Skip to content

armgit / BUI

Public Imported from GitHub
0

Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI

feat: slug & css

Preetham Pemmasanif156d59dd8a9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 58f7d62..3731984 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,15 @@ All notable changes to **blenderui** (BUI). The format follows
- **Text looks like Blender's:** Inter, Blender's UI font, is embedded and is the default face on every platform. The portable stb_truetype engine is now the default on Windows too. `-DBUI_TEXT_GDI=ON` (Rust: the `gdi-text` feature) restores GDI and system fonts. `BUI_TEXT_STB` and `portable-text` are now no-ops.
### Added
+- **Slug as a flag:** GPU text is Slug or the per-glyph atlas, chosen at build time (CMake `BUI_SLUG`, Rust feature `slug`, both on by default) or at run time (`BUI_gpu_set_slug`, `bui.set_slug`, `Application::slug` / `blenderui::set_slug`, `BUI_SLUG=1/0`).
+- **Optional props and keys** (Rust): `Option<T>` props and `children` may be left out in `rsx!`, and a missing required prop is a compile error that names it. `key={..}` ties a component's hook state to the key instead of its position. Struct components opt in with `#[derive(Props)]`.
+- **CSS** (Rust):
+ - **Applied at-rules:** `@container` size queries (`container-type`, `container-name`, `container`), `@font-face` (loads local font files) and `@property` initial values.
+ - **Images:** `background-image: url()` with `background-size`, `-position` (including `-x` / `-y`) and `-repeat`, plus the `background` shorthand; `object-fit` and `object-position` on `<img>`.
+ - **Font families:** `font-family` now selects the face (registered, installed, or generic `monospace` / `serif`).
+ - **Longhands and aliases:** logical border longhands, `text-wrap-mode`, `white-space-collapse`, `scale` and `all`.
+ - **Parsed (no effect yet):** about 100 more properties, including scroll margins and padding, overscroll, OpenType font features, masks and `contain-intrinsic-*`.
+ - **Coverage:** 207 of 745 W3C properties now render (was 176), 177 more parse (was 75), and CSS 2.1 is at 82 of 90.
- **Slug GPU text:** with the GPU renderer, glyphs are drawn from their outlines with Eric Lengyel's Slug algorithm: one instance per glyph, exact coverage in the pixel shader, cached curve and band textures, no CPU rasterization. `BUI_SLUG=0` falls back to per-glyph bitmaps in the GPU atlas (Blender's approach).
- **Components and hooks** (Rust, compatible with zopra, React and Leptos):
- `#[component]` turns a function into a component, with lowercase or uppercase names and `&str` props.
diff --git a/README.md b/README.md
index 875444b..506de8e 100644
--- a/README.md
+++ b/README.md
@@ -239,7 +239,7 @@ error: rsx!: `bg-sky-50O` is not a Tailwind utility; did you mean `bg-sky-500` o
| Windows | A native Win32 window in C: DPI-aware, vsync-paced animation, clipboard, cursors, window-manager features |
| tkinter syntax | **Complete**: every public tkinter and ttk name (7,846 of 7,846) |
| Components | 45 Blender components, including the color ramp and curve editors |
-| Rust | HTML (113/113 elements), Flexbox 12/12, Grid 23/23, CSS 2.1 80/90, math functions, `var()`, CSS Color 4/5, Selectors 4, `@layer`/`@media`/`@supports`/`@scope`, Tailwind v4, `rsx!`, `#[component]`, hooks, headless testing |
+| Rust | HTML (113/113 elements), Flexbox 12/12, Grid 23/23, CSS 2.1 82/90, math functions, `var()`, CSS Color 4/5, Selectors 4, `@layer`/`@media`/`@supports`/`@scope`/`@container`/`@font-face`/`@property`, background images, `object-fit`, Tailwind v4, `rsx!`, `#[component]` with optional props and `key`, hooks, headless testing |
| Rendering | Software raster (parallel, damage-tracked), GPU renderer (Direct3D 11), portable text engine |
| Packaging | [`blenderui` on PyPI](https://pypi.org/project/blenderui/), with a CI workflow for wheels on all platforms |
@@ -248,9 +248,9 @@ error: rsx!: `bg-sky-50O` is not a Tailwind utility; did you mean `bg-sky-500` o
| Area | What's missing |
|---|---|
| Qt syntax (~25%) | Model/view classes, docks, toolbars, splitters, Qt stylesheets ([details](docs/qt.md#coverage)) |
-| CSS (176 of 745 W3C properties render) | Rendering effects: `rotate`/`skew` transforms, `filter`/`backdrop-filter`, blend modes, `clip-path`, masks, `border-image`, non-solid borders. Also animations and transitions, background images, applying `@container`, `@font-face`. Most of the remaining W3C list is drafts, speech, print and SVG ([breakdown](docs/rust.md#coverage)) |
+| CSS (207 of 745 W3C properties render, 177 more parse) | Rendering effects: `rotate`/`skew` transforms, `filter`/`backdrop-filter`, blend modes, `clip-path`, masks, `border-image`, non-solid borders. Also animations and transitions. Most of the remaining W3C list is drafts, speech, print and SVG ([breakdown](docs/rust.md#coverage)) |
| Text | No text wrapping around floats; no right-to-left shaping |
-| Rust components | No optional props; no async resources (`use_resource`); no generic components |
+| Rust components | No async resources (`use_resource`); no generic components |
| Linux / macOS | They work through a fallback window (the stdlib Tk window shows BUI's frame), but they're less tested. No native window host and no GPU renderer yet |
| crates.io | The crates are ready to publish but not published yet; use the git dependency for now |
diff --git a/bindings/python/bui/__init__.py b/bindings/python/bui/__init__.py
index b74291c..ceb20cf 100644
--- a/bindings/python/bui/__init__.py
+++ b/bindings/python/bui/__init__.py
@@ -131,3 +131,11 @@ def set_gpu(on: bool = True) -> None:
software raster where no device exists. ``BUI_GPU=1``/``0`` overrides.
Per window: ``Tk(gpu=True)``."""
buipy.set_gpu(bool(on))
+
+
+def set_slug(on: bool = True) -> None:
+ """How the GPU renderer draws text. ``True`` (the default): Slug, glyph
+ outlines evaluated in the pixel shader, sharp at any size. ``False``: a
+ per-glyph bitmap atlas like Blender's, with less GPU work. Takes effect
+ on the next frame. ``BUI_SLUG=1``/``0`` overrides."""
+ buipy.set_slug(bool(on))
diff --git a/bindings/python/bui/__pycache__/__init__.cpython-314.pyc b/bindings/python/bui/__pycache__/__init__.cpython-314.pyc
index 5df0713..367ffce 100644
Binary files a/bindings/python/bui/__pycache__/__init__.cpython-314.pyc and b/bindings/python/bui/__pycache__/__init__.cpython-314.pyc differ
diff --git a/bindings/python/src/buipy_module.c b/bindings/python/src/buipy_module.c
index 5626898..66fd247 100644
--- a/bindings/python/src/buipy_module.c
+++ b/bindings/python/src/buipy_module.c
@@ -1154,6 +1154,17 @@ static PyObject *buipy_set_gpu(PyObject *self, PyObject *on)
Py_RETURN_NONE;
}
+static PyObject *buipy_set_slug(PyObject *self, PyObject *on)
+{
+ (void)self;
+ const int v = PyObject_IsTrue(on);
+ if (v < 0) {
+ return NULL;
+ }
+ BUI_gpu_set_slug(v);
+ Py_RETURN_NONE;
+}
+
static PyObject *buipy_gpu_default(PyObject *self, PyObject *noargs)
{
(void)self;
@@ -1253,6 +1264,8 @@ static PyMethodDef buipy_methods[] = {
{"set_gpu", buipy_set_gpu, METH_O,
"set_gpu(on): new native windows draw on the GPU (Direct3D 11). BUI_GPU=1/0 overrides."},
{"gpu_default", buipy_gpu_default, METH_NOARGS, "Whether new native windows use the GPU."},
+ {"set_slug", buipy_set_slug, METH_O,
+ "set_slug(on): GPU text from glyph outlines (Slug) or a glyph atlas. BUI_SLUG=1/0 overrides."},
{"draw_triangles", buipy_draw_triangles, METH_VARARGS, "draw_triangles([(x, y), ...], [(r, g, b, a), ...]): per-vertex colored triangles."},
{"draw_gradient", buipy_draw_gradient, METH_VARARGS, "draw_gradient(x, y, w, h, tl, tr, br, bl): bilinear corner-color rectangle."},
{"draw_hsv_circle", buipy_draw_hsv_circle, METH_VARARGS, "draw_hsv_circle(cx, cy, radius, value): Blender HSV color wheel."},
diff --git a/bindings/rust/bench/results.json b/bindings/rust/bench/results.json
index 12516bb..c1589f3 100644
--- a/bindings/rust/bench/results.json
+++ b/bindings/rust/bench/results.json
@@ -1,435 +1,15 @@
[
- {
- "app": "gpui",
- "cells": 100,
- "mode": "anim",
- "fps": 60.0,
- "cpu_pct": 28.2,
- "cpu_ms_per_frame": 4.696,
- "gpu_pct": 7.74527881392689,
- "ws_mb": 40.2,
- "peak_ws_mb": 40.2,
- "private_mb": 35.4,
- "gpu_mem_mb": 16.12890625,
- "first_frame_ms": 234
- },
- {
- "app": "gpui-fast",
- "cells": 100,
- "mode": "anim",
- "fps": 60.0,
- "cpu_pct": 16.0,
- "cpu_ms_per_frame": 2.675,
- "gpu_pct": 3.804781362567745,
- "ws_mb": 46.7,
- "peak_ws_mb": 46.7,
- "private_mb": 40.4,
- "gpu_mem_mb": 19.1484375,
- "first_frame_ms": 224
- },
- {
- "app": "blenderui",
- "cells": 100,
- "mode": "anim",
- "fps": 60.1,
- "cpu_pct": 27.7,
- "cpu_ms_per_frame": 4.616,
- "gpu_pct": null,
- "ws_mb": 20.7,
- "peak_ws_mb": 20.7,
- "private_mb": 11.7,
- "gpu_mem_mb": null,
- "first_frame_ms": 4
- },
- {
- "app": "blenderui-gpu",
- "cells": 100,
- "mode": "anim",
- "fps": 60.1,
- "cpu_pct": 7.2,
- "cpu_ms_per_frame": 1.192,
- "gpu_pct": 8.490680562219257,
- "ws_mb": 27.9,
- "peak_ws_mb": 27.9,
- "private_mb": 21.7,
- "gpu_mem_mb": 19.29296875,
- "first_frame_ms": 5
- },
- {
- "app": "gpui",
- "cells": 100,
- "mode": "one",
- "fps": 60.0,
- "cpu_pct": 21.1,
- "cpu_ms_per_frame": 3.516,
- "gpu_pct": 5.895781827760465,
- "ws_mb": 32.8,
- "peak_ws_mb": 32.9,
- "private_mb": 35.6,
- "gpu_mem_mb": 16.12890625,
- "first_frame_ms": 279
- },
- {
- "app": "gpui-fast",
- "cells": 100,
- "mode": "one",
- "fps": 60.0,
- "cpu_pct": 14.0,
- "cpu_ms_per_frame": 2.342,
- "gpu_pct": 2.541856576909325,
- "ws_mb": 34.5,
- "peak_ws_mb": 34.6,
- "private_mb": 39.9,
- "gpu_mem_mb": 19.1484375,
- "first_frame_ms": 213
- },
- {
- "app": "blenderui",
- "cells": 100,
- "mode": "one",
- "fps": 60.1,
- "cpu_pct": 26.5,
- "cpu_ms_per_frame": 4.414,
- "gpu_pct": null,
- "ws_mb": 19.7,
- "peak_ws_mb": 19.9,
- "private_mb": 10.7,
- "gpu_mem_mb": null,
- "first_frame_ms": 5
- },
- {
- "app": "blenderui-gpu",
- "cells": 100,
- "mode": "one",
- "fps": 60.1,
- "cpu_pct": 6.3,
- "cpu_ms_per_frame": 1.051,
- "gpu_pct": 5.594142989433645,
- "ws_mb": 25.1,
- "peak_ws_mb": 25.2,
- "private_mb": 20.4,
- "gpu_mem_mb": 18.78515625,
- "first_frame_ms": 6
- },
- {
- "app": "gpui",
- "cells": 100,
- "mode": "idle",
- "fps": 0.2,
- "cpu_pct": 1.4,
- "cpu_ms_per_frame": 82.208,
- "gpu_pct": 0.0,
- "ws_mb": 32.8,
- "peak_ws_mb": 32.9,
- "private_mb": 35.6,
- "gpu_mem_mb": 16.12890625,
- "first_frame_ms": 212
- },
- {
- "app": "gpui-fast",
- "cells": 100,
- "mode": "idle",
- "fps": 0.0,
- "cpu_pct": 0.0,
- "cpu_ms_per_frame": 0.0,
- "gpu_pct": 0.0,
- "ws_mb": 34.0,
- "peak_ws_mb": 34.0,
- "private_mb": 39.4,
- "gpu_mem_mb": 18.94921875,
- "first_frame_ms": 197
- },
- {
- "app": "blenderui",
- "cells": 100,
- "mode": "idle",
- "fps": 0.0,
- "cpu_pct": 0.0,
- "cpu_ms_per_frame": 0.0,
- "gpu_pct": null,
- "ws_mb": 19.4,
- "peak_ws_mb": 19.4,
- "private_mb": 9.9,
- "gpu_mem_mb": null,
- "first_frame_ms": 6
- },
- {
- "app": "blenderui-gpu",
- "cells": 100,
- "mode": "idle",
- "fps": 0.0,
- "cpu_pct": 0.0,
- "cpu_ms_per_frame": 0.0,
- "gpu_pct": 0.0,
- "ws_mb": 25.8,
- "peak_ws_mb": 25.8,
- "private_mb": 19.1,
- "gpu_mem_mb": 18.28515625,
- "first_frame_ms": 6
- },
- {
- "app": "blenderui (uncapped)",
- "cells": 100,
- "mode": "anim",
- "fps": 648.6,
- "cpu_pct": 315.0,
- "cpu_ms_per_frame": 4.857,
- "gpu_pct": null,
- "ws_mb": 20.7,
- "peak_ws_mb": 20.8,
- "private_mb": 11.9,
- "gpu_mem_mb": null,
- "first_frame_ms": 5
- },
- {
- "app": "blenderui-gpu (uncapped)",
- "cells": 100,
- "mode": "anim",
- "fps": 1491.2,
- "cpu_pct": 89.8,
- "cpu_ms_per_frame": 0.602,
- "gpu_pct": 92.07909147050972,
- "ws_mb": 28.3,
- "peak_ws_mb": 28.3,
- "private_mb": 22.2,
- "gpu_mem_mb": 19.546875,
- "first_frame_ms": 6
- },
- {
- "app": "gpui",
- "cells": 1000,
- "mode": "anim",
- "fps": 36.4,
- "cpu_pct": 100.9,
- "cpu_ms_per_frame": 27.726,
- "gpu_pct": 3.764205848581965,
- "ws_mb": 47.2,
- "peak_ws_mb": 47.5,
- "private_mb": 51.6,
- "gpu_mem_mb": 17.07421875,
- "first_frame_ms": 227
- },
- {
- "app": "gpui-fast",
- "cells": 1000,
- "mode": "anim",
- "fps": 49.2,
- "cpu_pct": 100.9,
- "cpu_ms_per_frame": 20.515,
- "gpu_pct": 5.504059756315993,
- "ws_mb": 44.5,
- "peak_ws_mb": 44.6,
- "private_mb": 51.2,
- "gpu_mem_mb": 19.89453125,
- "first_frame_ms": 200
- },
- {
- "app": "blenderui",
- "cells": 1000,
- "mode": "anim",
- "fps": 60.0,
- "cpu_pct": 61.2,
- "cpu_ms_per_frame": 10.201,
- "gpu_pct": null,
- "ws_mb": 23.8,
- "peak_ws_mb": 24.7,
- "private_mb": 14.9,
- "gpu_mem_mb": null,
- "first_frame_ms": 5
- },
- {
- "app": "blenderui-gpu",
- "cells": 1000,
- "mode": "anim",
- "fps": 60.0,
- "cpu_pct": 28.2,
- "cpu_ms_per_frame": 4.702,
- "gpu_pct": 9.046779328061197,
- "ws_mb": 34.5,
- "peak_ws_mb": 35.5,
- "private_mb": 29.2,
- "gpu_mem_mb": 21.69140625,
- "first_frame_ms": 6
- },
- {
- "app": "gpui",
- "cells": 1000,
- "mode": "one",
- "fps": 35.7,
- "cpu_pct": 100.9,
- "cpu_ms_per_frame": 28.257,
- "gpu_pct": 3.569115647625785,
- "ws_mb": 47.3,
- "peak_ws_mb": 47.6,
- "private_mb": 52.3,
- "gpu_mem_mb": 17.07421875,
- "first_frame_ms": 229
- },
- {
- "app": "gpui-fast",
- "cells": 1000,
- "mode": "one",
- "fps": 29.6,
- "cpu_pct": 59.1,
- "cpu_ms_per_frame": 19.99,
- "gpu_pct": 2.4599204070895526,
- "ws_mb": 44.5,
- "peak_ws_mb": 44.6,
- "private_mb": 51.8,
- "gpu_mem_mb": 19.89453125,
- "first_frame_ms": 197
- },
- {
- "app": "blenderui",
- "cells": 1000,
- "mode": "one",
- "fps": 60.1,
- "cpu_pct": 61.4,
- "cpu_ms_per_frame": 10.208,
- "gpu_pct": null,
- "ws_mb": 24.1,
- "peak_ws_mb": 25.0,
- "private_mb": 15.9,
- "gpu_mem_mb": null,
- "first_frame_ms": 4
- },
- {
- "app": "blenderui-gpu",
- "cells": 1000,
- "mode": "one",
- "fps": 60.0,
- "cpu_pct": 29.0,
- "cpu_ms_per_frame": 4.834,
- "gpu_pct": 8.746954225653713,
- "ws_mb": 34.3,
- "peak_ws_mb": 35.0,
- "private_mb": 28.4,
- "gpu_mem_mb": 21.5,
- "first_frame_ms": 5
- },
- {
- "app": "gpui",
- "cells": 1000,
- "mode": "idle",
- "fps": 0.0,
- "cpu_pct": 0.9,
- "cpu_ms_per_frame": 0.0,
- "gpu_pct": 0.0,
- "ws_mb": 46.4,
- "peak_ws_mb": 46.4,
- "private_mb": 50.9,
- "gpu_mem_mb": 17.07421875,
- "first_frame_ms": 204
- },
- {
- "app": "gpui-fast",
- "cells": 1000,
- "mode": "idle",
- "fps": 0.2,
- "cpu_pct": 0.4,
- "cpu_ms_per_frame": 25.054,
- "gpu_pct": 0.0,
- "ws_mb": 43.4,
- "peak_ws_mb": 43.8,
- "private_mb": 50.2,
- "gpu_mem_mb": 19.89453125,
- "first_frame_ms": 212
- },
- {
- "app": "blenderui",
- "cells": 1000,
- "mode": "idle",
- "fps": 0.3,
- "cpu_pct": 0.9,
- "cpu_ms_per_frame": 26.518,
- "gpu_pct": null,
- "ws_mb": 23.6,
- "peak_ws_mb": 23.7,
- "private_mb": 14.2,
- "gpu_mem_mb": null,
- "first_frame_ms": 6
- },
- {
- "app": "blenderui-gpu",
- "cells": 1000,
- "mode": "idle",
- "fps": 0.0,
- "cpu_pct": 0.0,
- "cpu_ms_per_frame": 0.0,
- "gpu_pct": 0.0,
- "ws_mb": 31.8,
- "peak_ws_mb": 31.9,
- "private_mb": 27.1,
- "gpu_mem_mb": 21.69140625,
- "first_frame_ms": 5
- },
- {
- "app": "blenderui (uncapped)",
- "cells": 1000,
- "mode": "anim",
- "fps": 202.4,
- "cpu_pct": 233.2,
- "cpu_ms_per_frame": 11.523,
- "gpu_pct": null,
- "ws_mb": 24.5,
- "peak_ws_mb": 24.9,
- "private_mb": 15.9,
- "gpu_mem_mb": null,
- "first_frame_ms": 4
- },
- {
- "app": "blenderui-gpu (uncapped)",
- "cells": 1000,
- "mode": "anim",
- "fps": 309.1,
- "cpu_pct": 101.8,
- "cpu_ms_per_frame": 3.292,
- "gpu_pct": 42.598707686330776,
- "ws_mb": 35.4,
- "peak_ws_mb": 35.9,
- "private_mb": 29.9,
- "gpu_mem_mb": 21.75390625,
- "first_frame_ms": 4
- },
- {
- "app": "gpui",
- "cells": 3000,
- "mode": "anim",
- "fps": 19.9,
- "cpu_pct": 100.6,
- "cpu_ms_per_frame": 50.471,
- "gpu_pct": 2.9571464808078,
- "ws_mb": 77.2,
- "peak_ws_mb": 78.0,
- "private_mb": 95.3,
- "gpu_mem_mb": 20.64453125,
- "first_frame_ms": 210
- },
- {
- "app": "gpui-fast",
- "cells": 3000,
- "mode": "anim",
- "fps": 31.5,
- "cpu_pct": 100.5,
- "cpu_ms_per_frame": 31.885,
- "gpu_pct": 4.385109321763488,
- "ws_mb": 64.9,
- "peak_ws_mb": 65.5,
- "private_mb": 85.3,
- "gpu_mem_mb": 23.47265625,
- "first_frame_ms": 193
- },
{
"app": "blenderui",
"cells": 3000,
"mode": "anim",
- "fps": 57.6,
- "cpu_pct": 126.7,
- "cpu_ms_per_frame": 21.979,
+ "fps": 56.3,
+ "cpu_pct": 131.1,
+ "cpu_ms_per_frame": 23.293,
"gpu_pct": null,
- "ws_mb": 30.2,
- "peak_ws_mb": 33.1,
- "private_mb": 26.9,
+ "ws_mb": 31.0,
+ "peak_ws_mb": 33.9,
+ "private_mb": 24.7,
"gpu_mem_mb": null,
"first_frame_ms": 5
},
@@ -437,99 +17,43 @@
"app": "blenderui-gpu",
"cells": 3000,
"mode": "anim",
- "fps": 59.9,
- "cpu_pct": 69.4,
- "cpu_ms_per_frame": 11.582,
- "gpu_pct": 10.990262499917524,
- "ws_mb": 39.6,
- "peak_ws_mb": 42.2,
- "private_mb": 38.0,
- "gpu_mem_mb": 20.80859375,
- "first_frame_ms": 5
- },
- {
- "app": "gpui",
- "cells": 3000,
- "mode": "one",
- "fps": 20.2,
- "cpu_pct": 100.6,
- "cpu_ms_per_frame": 49.685,
- "gpu_pct": 4.146866676585088,
- "ws_mb": 76.7,
- "peak_ws_mb": 77.4,
- "private_mb": 94.9,
- "gpu_mem_mb": 20.64453125,
- "first_frame_ms": 215
- },
- {
- "app": "gpui-fast",
- "cells": 3000,
- "mode": "one",
- "fps": 39.2,
- "cpu_pct": 100.7,
- "cpu_ms_per_frame": 25.715,
- "gpu_pct": 6.548003516690843,
- "ws_mb": 63.6,
- "peak_ws_mb": 64.6,
- "private_mb": 85.7,
- "gpu_mem_mb": 23.47265625,
- "first_frame_ms": 209
+ "fps": 47.8,
+ "cpu_pct": 100.8,
+ "cpu_ms_per_frame": 21.084,
+ "gpu_pct": 17.09916311167295,
+ "ws_mb": 42.5,
+ "peak_ws_mb": 45.9,
+ "private_mb": 46.7,
+ "gpu_mem_mb": 27.3828125,
+ "first_frame_ms": 6
},
{
"app": "blenderui",
"cells": 3000,
"mode": "one",
- "fps": 59.9,
- "cpu_pct": 127.6,
- "cpu_ms_per_frame": 21.29,
+ "fps": 58.3,
+ "cpu_pct": 132.7,
+ "cpu_ms_per_frame": 22.773,
"gpu_pct": null,
- "ws_mb": 30.1,
- "peak_ws_mb": 33.3,
- "private_mb": 23.9,
+ "ws_mb": 31.4,
+ "peak_ws_mb": 34.4,
+ "private_mb": 26.4,
"gpu_mem_mb": null,
- "first_frame_ms": 5
+ "first_frame_ms": 6
},
{
"app": "blenderui-gpu",
"cells": 3000,
"mode": "one",
- "fps": 60.1,
- "cpu_pct": 67.3,
- "cpu_ms_per_frame": 11.195,
- "gpu_pct": 10.188285266632718,
- "ws_mb": 39.2,
- "peak_ws_mb": 42.2,
- "private_mb": 36.4,
- "gpu_mem_mb": 20.80859375,
- "first_frame_ms": 10
- },
- {
- "app": "gpui",
- "cells": 3000,
- "mode": "idle",
- "fps": 0.0,
- "cpu_pct": 1.1,
- "cpu_ms_per_frame": 0.0,
- "gpu_pct": 0.0,
- "ws_mb": 74.8,
- "peak_ws_mb": 74.8,
- "private_mb": 92.5,
- "gpu_mem_mb": 20.64453125,
- "first_frame_ms": 205
- },
- {
- "app": "gpui-fast",
- "cells": 3000,
- "mode": "idle",
- "fps": 0.0,
- "cpu_pct": 0.1,
- "cpu_ms_per_frame": 0.0,
- "gpu_pct": 0.0,
- "ws_mb": 60.9,
- "peak_ws_mb": 61.0,
- "private_mb": 81.4,
- "gpu_mem_mb": 20.90625,
- "first_frame_ms": 202
+ "fps": 50.3,
+ "cpu_pct": 100.8,
+ "cpu_ms_per_frame": 20.045,
+ "gpu_pct": 17.95473784974835,
+ "ws_mb": 42.8,
+ "peak_ws_mb": 46.3,
+ "private_mb": 45.9,
+ "gpu_mem_mb": 27.3828125,
+ "first_frame_ms": 8
},
{
"app": "blenderui",
@@ -539,11 +63,11 @@
"cpu_pct": 0.1,
"cpu_ms_per_frame": 0.0,
"gpu_pct": null,
- "ws_mb": 27.9,
- "peak_ws_mb": 27.9,
- "private_mb": 21.4,
+ "ws_mb": 30.4,
+ "peak_ws_mb": 30.4,
+ "private_mb": 23.6,
"gpu_mem_mb": null,
- "first_frame_ms": 5
+ "first_frame_ms": 4
},
{
"app": "blenderui-gpu",
@@ -553,38 +77,38 @@
"cpu_pct": 0.1,
"cpu_ms_per_frame": 0.0,
"gpu_pct": 0.0,
- "ws_mb": 36.0,
- "peak_ws_mb": 36.0,
- "private_mb": 34.2,
- "gpu_mem_mb": 19.6171875,
+ "ws_mb": 41.6,
+ "peak_ws_mb": 41.6,
+ "private_mb": 44.5,
+ "gpu_mem_mb": 27.19140625,
"first_frame_ms": 8
},
{
"app": "blenderui (uncapped)",
"cells": 3000,
"mode": "anim",
- "fps": 75.5,
- "cpu_pct": 166.4,
- "cpu_ms_per_frame": 22.037,
+ "fps": 71.4,
+ "cpu_pct": 170.6,
+ "cpu_ms_per_frame": 23.891,
"gpu_pct": null,
- "ws_mb": 30.5,
- "peak_ws_mb": 32.5,
- "private_mb": 26.2,
+ "ws_mb": 31.9,
+ "peak_ws_mb": 35.2,
+ "private_mb": 28.7,
"gpu_mem_mb": null,
- "first_frame_ms": 4
+ "first_frame_ms": 5
},
{
"app": "blenderui-gpu (uncapped)",
"cells": 3000,
"mode": "anim",
- "fps": 94.0,
- "cpu_pct": 101.1,
- "cpu_ms_per_frame": 10.751,
- "gpu_pct": 14.692075994349425,
- "ws_mb": 39.7,
- "peak_ws_mb": 41.7,
- "private_mb": 36.8,
- "gpu_mem_mb": 20.83984375,
- "first_frame_ms": 9
+ "fps": 48.2,
+ "cpu_pct": 100.7,
+ "cpu_ms_per_frame": 20.915,
+ "gpu_pct": 16.9653188312799,
+ "ws_mb": 42.3,
+ "peak_ws_mb": 45.1,
+ "private_mb": 46.2,
+ "gpu_mem_mb": 27.3828125,
+ "first_frame_ms": 5
}
]
\ No newline at end of file
diff --git a/bindings/rust/blenderui-macros/src/component.rs b/bindings/rust/blenderui-macros/src/component.rs
index 8870242..2880da0 100644
--- a/bindings/rust/blenderui-macros/src/component.rs
+++ b/bindings/rust/blenderui-macros/src/component.rs
@@ -73,6 +73,7 @@ fn expand(input: TokenStream) -> Result<TokenStream, String> {
let mut fields = TokenStream::new();
let mut names = Vec::new();
let mut shadows = TokenStream::new();
+ let mut typed: Vec<(String, String)> = Vec::new();
for (n, ty) in &props {
let s = ty.to_string().replace(' ', "");
let field_ty = if s == "&str" || s == "&'staticstr" {
@@ -84,6 +85,7 @@ fn expand(input: TokenStream) -> Result<TokenStream, String> {
ty.clone()
};
fields.extend(ts(&format!("pub {n}:")));
+ typed.push((n.clone(), field_ty.to_string()));
fields.extend(field_ty);
fields.extend(ts(","));
names.push(n.clone());
@@ -99,13 +101,186 @@ fn expand(input: TokenStream) -> Result<TokenStream, String> {
let mut closure = ts("|| ::blenderui::element::IntoElement::into_any_element");
closure.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, body_expr(body)))]);
inner.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, closure))]);
- let mut method = ts("fn into_any_element(self) -> ::blenderui::element::AnyElement");
+ let mut method = ts("#[allow(unused_braces)] fn into_any_element(self) -> ::blenderui::element::AnyElement");
method.extend([TokenTree::Group(Group::new(Delimiter::Brace, inner))]);
out.extend(ts(&format!("impl ::blenderui::element::IntoElement for {name}")));
out.extend([TokenTree::Group(Group::new(Delimiter::Brace, method))]);
+ out.extend(builder(&name, &vis_string(&toks[..fn_at]), &typed)?);
Ok(out)
}
+fn vis_string(toks: &[TokenTree]) -> String {
+ let s: String = toks.iter().map(|t| t.to_string() + " ").collect();
+ match s.find("pub") {
+ Some(i) => {
+ let rest = &s[i..];
+ // `pub` or `pub (crate)`
+ let end = if rest[3..].trim_start().starts_with('(') { rest.find(')').map_or(3, |j| j + 1) } else { 3 };
+ rest[..end].to_string()
+ }
+ None => String::new(),
+ }
+}
+
+/// `#[derive(Props)]` on a struct component: the same props builder.
+pub fn derive_props(input: TokenStream) -> TokenStream {
+ let r = (|| -> Result<TokenStream, String> {
+ let toks: Vec<TokenTree> = input.into_iter().collect();
+ let at = toks.iter().position(|t| matches!(t, TokenTree::Ident(i) if i.to_string() == "struct"))
+ .ok_or("#[derive(Props)] goes on a struct")?;
+ let name = match toks.get(at + 1) {
+ Some(TokenTree::Ident(i)) => i.to_string(),
+ _ => return Err("#[derive(Props)]: expected a struct name".into()),
+ };
+ let body = match toks.get(at + 2) {
+ Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Brace => g.stream(),
+ _ => return Err("#[derive(Props)]: needs named fields (and no generics)".into()),
+ };
+ let vis = vis_string(&toks[..at]);
+ let mut fields = Vec::new();
+ let mut cur: Vec<TokenTree> = Vec::new();
+ let mut depth = 0i32;
+ let btoks: Vec<TokenTree> = body.into_iter().collect();
+ for (k, t) in btoks.iter().enumerate() {
+ match t {
+ TokenTree::Punct(p) if p.as_char() == '<' => depth += 1,
+ TokenTree::Punct(p) if p.as_char() == '>'
+ && !matches!(k.checked_sub(1).and_then(|j| btoks.get(j)), Some(TokenTree::Punct(q)) if q.as_char() == '-') => {
+ depth -= 1
+ }
+ TokenTree::Punct(p) if p.as_char() == ',' && depth == 0 => {
+ field(&mut cur, &mut fields)?;
+ continue;
+ }
+ _ => {}
+ }
+ cur.push(t.clone());
+ }
+ field(&mut cur, &mut fields)?;
+ builder(&name, &vis, &fields)
+ })();
+ r.unwrap_or_else(|e| format!("::core::compile_error!({e:?});").parse().unwrap())
+}
+
+/// One struct field (`#[attr] pub name: Type`) as (name, type).
+fn field(cur: &mut Vec<TokenTree>, fields: &mut Vec<(String, String)>) -> Result<(), String> {
+ let mut t: Vec<TokenTree> = Vec::new();
+ let mut k = 0;
+ while k < cur.len() {
+ match &cur[k] {
+ TokenTree::Punct(p) if p.as_char() == '#' => k += 2,
+ TokenTree::Ident(i) if i.to_string() == "pub" => {
+ k += 1;
+ if matches!(cur.get(k), Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Parenthesis) {
+ k += 1;
+ }
+ }
+ other => {
+ t.push(other.clone());
+ k += 1;
+ }
+ }
+ }
+ if !t.is_empty() {
+ let (n, ty) = prop(&t)?;
+ fields.push((n, ty.to_string()));
+ }
+ cur.clear();
+ Ok(())
+}
+
+/// The inner type of `Option<T>` (any path to Option), else None.
+fn option_inner(ty: &str) -> Option<String> {
+ let squashed: String = ty.chars().filter(|c| !c.is_whitespace()).collect();
+ let tail = squashed.strip_prefix("::").unwrap_or(&squashed);
+ let tail = tail.strip_prefix("std::option::").or_else(|| tail.strip_prefix("core::option::")).unwrap_or(tail);
+ if !tail.starts_with("Option<") || !tail.ends_with('>') {
+ return None;
+ }
+ let t = ty.trim_end();
+ let open = t.find('<')?;
+ Some(t[open + 1..t.len() - 1].to_string())
+}
+
+/// A typestate props builder (`<Name>::__builder()`): `Option<T>` props and
+/// `children` may be left out; leaving out any other prop is a compile
+/// error naming it (`Name_missing_<prop>` in the builder's type).
+fn builder(name: &str, vis: &str, fields: &[(String, String)]) -> Result<TokenStream, String> {
+ enum Kind {
+ Required(usize),
+ Optional(String),
+ Children,
+ }
+ let mut req = 0;
+ let kinds: Vec<Kind> = fields.iter().map(|(n, ty)| {
+ if let Some(inner) = option_inner(ty) {
+ Kind::Optional(inner)
+ } else if n == "children" {
+ Kind::Children
+ } else {
+ req += 1;
+ Kind::Required(req - 1)
+ }
+ }).collect();
+ let b = format!("__{name}Props");
+ let gens: Vec<String> = (0..req).map(|i| format!("__R{i}")).collect();
+ let g = gens.join(", ");
+ let missing: Vec<String> = fields.iter().zip(&kinds)
+ .filter(|(_, k)| matches!(k, Kind::Required(_)))
+ .map(|((n, _), _)| format!("{name}_missing_{n}")).collect();
+ let pd = "::core::marker::PhantomData";
+ // setters take `impl Into<T>` ("x" for a String prop), except numbers,
+ // where a generic would stop integer literals from inferring
+ let param = |ty: &str| {
+ const NUM: &[&str] = &["u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64",
+ "i128", "isize", "f32", "f64", "bool", "char"];
+ if NUM.contains(&ty.trim()) { ty.to_string() } else { format!("impl ::core::convert::Into<{ty}>") }
+ };
+ let mut out = String::new();
+ for m in &missing {
+ out += &format!("#[doc(hidden)] #[allow(non_camel_case_types)] {vis} struct {m};\n");
+ }
+ out += &format!("#[doc(hidden)] #[allow(non_camel_case_types, non_snake_case)] {vis} struct {b}<{g}> {{");
+ for ((n, ty), k) in fields.iter().zip(&kinds) {
+ match k {
+ Kind::Required(_) => out += &format!("{n}: ::core::option::Option<{ty}>,"),
+ _ => out += &format!("{n}: {ty},"),
+ }
+ }
+ out += &format!("__s: {pd}<({g}{})>, }}\n", if req == 1 { "," } else { "" });
+ let init: String = fields.iter().zip(&kinds).map(|((n, _), k)| match k {
+ Kind::Required(_) => format!("{n}: ::core::option::Option::None,"),
+ _ => format!("{n}: ::core::default::Default::default(),"),
+ }).collect();
+ out += &format!("#[allow(non_camel_case_types)] impl {name} {{ #[doc(hidden)] {vis} fn __builder() -> {b}<{}> {{ {b} {{ {init} __s: {pd} }} }} }}\n",
+ missing.join(", "));
+ out += &format!("#[allow(non_camel_case_types, non_snake_case)] impl<{g}> {b}<{g}> {{");
+ for ((n, ty), k) in fields.iter().zip(&kinds) {
+ match k {
+ Kind::Required(i) => {
+ let to: Vec<String> = gens.iter().enumerate()
+ .map(|(j, x)| if j == *i { "::blenderui::hooks::Set".to_string() } else { x.clone() }).collect();
+ let rest: String = fields.iter().filter(|(m, _)| m != n).map(|(m, _)| format!("{m}: self.{m},")).collect();
+ out += &format!("pub fn {n}(self, v: {}) -> {b}<{}> {{ {b} {{ {n}: ::core::option::Option::Some(v.into()), {rest} __s: {pd} }} }}",
+ param(ty), to.join(", "));
+ }
+ Kind::Optional(inner) => {
+ out += &format!("pub fn {n}(mut self, v: {}) -> Self {{ self.{n} = ::core::option::Option::Some(v.into()); self }}", param(inner));
+ }
+ Kind::Children => out += &format!("pub fn {n}(mut self, v: {ty}) -> Self {{ self.{n} = v; self }}"),
+ }
+ }
+ out += "}\n";
+ let set = vec!["::blenderui::hooks::Set"; req].join(", ");
+ let fin: String = fields.iter().zip(&kinds).map(|((n, _), k)| match k {
+ Kind::Required(_) => format!("{n}: match self.{n} {{ ::core::option::Option::Some(v) => v, ::core::option::Option::None => ::core::unreachable!() }},"),
+ _ => format!("{n}: self.{n},"),
+ }).collect();
+ out += &format!("impl ::blenderui::hooks::Complete for {b}<{set}> {{ type Props = {name}; fn finish(self) -> {name} {{ {name} {{ {fin} }} }} }}\n");
+ out.parse().map_err(|e| format!("#[component]: builder for {name}: {e:?}"))
+}
+
+
/// The body as an expression: a block, whose last expression may also be
/// bare markup (zopra lets a component end in `<div>..</div>`).
fn body_expr(body: Group) -> TokenStream {
diff --git a/bindings/rust/blenderui-macros/src/lib.rs b/bindings/rust/blenderui-macros/src/lib.rs
index aa41ad6..6b85afc 100644
--- a/bindings/rust/blenderui-macros/src/lib.rs
+++ b/bindings/rust/blenderui-macros/src/lib.rs
@@ -23,6 +23,13 @@ pub fn component(_attr: TokenStream, item: TokenStream) -> TokenStream {
/// JSX-style markup: `rsx! { <div class="p-4" onClick={|| ..}>"hi" {name}</div> }`.
/// See `rsx.rs` for the (uniform) lowering to builder calls.
+/// `#[derive(Props)]`: a props builder for a struct component, so `rsx!`
+/// can leave out its `Option<T>` fields and `children`.
+#[proc_macro_derive(Props)]
+pub fn derive_props(item: TokenStream) -> TokenStream {
+ component::derive_props(item)
+}
+
#[proc_macro]
pub fn rsx(input: TokenStream) -> TokenStream {
rsx::rsx(input)
diff --git a/bindings/rust/blenderui-macros/src/rsx.rs b/bindings/rust/blenderui-macros/src/rsx.rs
index 1c2365a..2e2ed93 100644
--- a/bindings/rust/blenderui-macros/src/rsx.rs
+++ b/bindings/rust/blenderui-macros/src/rsx.rs
@@ -6,7 +6,7 @@
//! | markup | becomes |
//! |--------------------------------|-------------------------------------------|
//! | `<div ...>` | `html::div()` (any tag; `<my-el>` -> `Div::new("my-el")`) |
-//! | `<Card a={x}>..</Card>` | `Card { a: x, children: vec![..] }` (components) |
+//! | `<Card a={x}>..</Card>` | `Card::__builder().a(x).children(vec![..])` (components; `Option` props may be left out) |
//! | `name="lit"` / bare `name` | `.attr("name", "lit")` (`class`, `style`, `id`: their methods) |
//! | `name={expr}` | `.name(expr)`: any builder method (`checked`, `w`, `hover` ...) |
//! | `onClick={|| ..}` | `.on_click(|_, _, _| ..)` (missing listener params added) |
@@ -213,7 +213,8 @@ impl P<'_> {
} else {
ts(&format!("::blenderui::html::{tag}()"))
};
- let mut fields = TokenStream::new(); // component props
+ let mut fields = TokenStream::new(); // component props: `.name(value)` builder calls
+ let mut key: Option<TokenStream> = None; // `key=`: hook identity
let mut classes: Vec<String> = Vec::new(); // bare utility attributes
loop {
match self.peek() {
@@ -226,7 +227,7 @@ impl P<'_> {
if !classes.is_empty() {
base.extend(ts(&format!(".class({:?})", classes.join(" "))));
}
- return Ok(if component { component_expr(&tag, fields, Vec::new()) } else { base });
+ return Ok(if component { component_expr(&tag, fields, Vec::new(), key) } else { keyed(base, key) });
}
Some(TokenTree::Punct(p)) if p.as_char() == '>' => {
self.i += 1;
@@ -264,18 +265,19 @@ impl P<'_> {
None => {}
}
}
- if component {
- fields.extend(ts(&format!("{}:", name.replace('-', "_"))));
- fields.extend(match value {
+ if name == "key" || component {
+ // component setters take `impl Into<T>`: literals go in as they are
+ let v = match value {
Some(TokenTree::Group(g)) => g.stream(),
- Some(t) => {
- let mut s = TokenStream::from(t);
- s.extend(ts(".into()"));
- s
- }
+ Some(t) => TokenStream::from(t),
None => ts("true"),
- });
- fields.extend(ts(","));
+ };
+ if name == "key" {
+ key = Some(v);
+ } else {
+ fields.extend(ts(&format!(".{}", name.replace('-', "_"))));
+ fields.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, v))]);
+ }
} else {
base.extend(attribute(&name, value)?);
}
@@ -287,12 +289,12 @@ impl P<'_> {
}
let kids = self.children_until(&tag)?;
if component {
- return Ok(component_expr(&tag, fields, kids));
+ return Ok(component_expr(&tag, fields, kids, key));
}
for k in kids {
base.extend(k.call());
}
- Ok(base)
+ Ok(keyed(base, key))
}
/// Children up to `</tag>` (or `</>` for fragments).
@@ -334,8 +336,25 @@ fn join_words(words: &[String]) -> String {
s
}
-/// `<Card a={x}>kids</Card>` -> `Card { a: x, children: vec![..] }`
-fn component_expr(tag: &str, mut fields: TokenStream, kids: Vec<Child>) -> TokenStream {
+/// `key={k}`: hooks under this element are identified by `k`, not position.
+fn keyed(el: TokenStream, key: Option<TokenStream>) -> TokenStream {
+ match key {
+ None => el,
+ Some(k) => {
+ let mut args = k;
+ args.extend(ts(","));
+ args.extend(el);
+ let mut out = ts("::blenderui::hooks::keyed");
+ out.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, args))]);
+ out
+ }
+ }
+}
+
+/// `<Card a={x}>kids</Card>` -> `build(Card::__builder().a(x).children(vec![..]))`:
+/// `Option` props and `children` may be left out (`#[component]` and
+/// `#[derive(Props)]` generate the builder).
+fn component_expr(tag: &str, mut fields: TokenStream, kids: Vec<Child>, key: Option<TokenStream>) -> TokenStream {
if !kids.is_empty() {
// { let mut v = Vec::new(); v.push(..); v.extend(..); v }
let mut body = ts("let mut __v: ::std::vec::Vec<::blenderui::element::AnyElement> = ::std::vec::Vec::new();");
@@ -356,13 +375,15 @@ fn component_expr(tag: &str, mut fields: TokenStream, kids: Vec<Child>) -> Token
body.extend(ts(";"));
}
body.extend(ts("__v"));
- fields.extend(ts("children:"));
- fields.extend([TokenTree::Group(Group::new(Delimiter::Brace, body))]);
- fields.extend(ts(","));
+ fields.extend(ts(".children"));
+ fields.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis,
+ TokenStream::from(TokenTree::Group(Group::new(Delimiter::Brace, body)))))]);
}
- let mut out = ts(tag);
- out.extend([TokenTree::Group(Group::new(Delimiter::Brace, fields))]);
- out
+ let mut chain = ts(&format!("{tag}::__builder()"));
+ chain.extend(fields);
+ let mut out = ts("::blenderui::hooks::build");
+ out.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, chain))]);
+ keyed(out, key)
}
/// `hover:class="..."`, `md:dark:style="..."`, `hover:color="red"`,
diff --git a/bindings/rust/blenderui-sys/Cargo.toml b/bindings/rust/blenderui-sys/Cargo.toml
index 4802ae4..76c04c6 100644
--- a/bindings/rust/blenderui-sys/Cargo.toml
+++ b/bindings/rust/blenderui-sys/Cargo.toml
@@ -17,6 +17,10 @@ include = ["src/**", "build.rs", "Cargo.toml", "csrc/**"]
# Windows' native GDI text engine (system fonts) instead of the portable
# engine (embedded Inter, GPU Slug glyphs).
gdi-text = []
+# GPU text drawn with Slug (glyph outlines in the pixel shader) by default;
+# without it, the per-glyph atlas. Switchable at runtime either way.
+slug = []
+default = ["slug"]
# Deprecated no-op: the portable engine is the default everywhere.
portable-text = []
diff --git a/bindings/rust/blenderui-sys/build.rs b/bindings/rust/blenderui-sys/build.rs
index 94b2bf1..f8e9b78 100644
--- a/bindings/rust/blenderui-sys/build.rs
+++ b/bindings/rust/blenderui-sys/build.rs
@@ -23,6 +23,7 @@ fn main() {
println!("cargo:rerun-if-env-changed=BUI_TEXT_GDI");
let dst = cmake::Config::new(&root)
.define("BUI_TEXT_GDI", if gdi { "ON" } else { "OFF" })
+ .define("BUI_SLUG", if std::env::var("CARGO_FEATURE_SLUG").is_ok() { "ON" } else { "OFF" })
.define("BUI_BUILD_TESTS", "OFF")
.define("BUI_BUILD_EXAMPLES", "OFF")
.define("BUI_BUILD_PYTHON_BINDINGS", "OFF")
diff --git a/bindings/rust/blenderui-sys/src/lib.rs b/bindings/rust/blenderui-sys/src/lib.rs
index a264cc7..7519f9a 100644
--- a/bindings/rust/blenderui-sys/src/lib.rs
+++ b/bindings/rust/blenderui-sys/src/lib.rs
@@ -105,6 +105,7 @@ pub struct BKCanvasItem {
pub text_flags: c_int,
pub clip_on: c_int,
pub clip: [c_float; 4],
+ pub family: *const c_char,
}
impl Default for BKCanvasItem {
@@ -249,6 +250,8 @@ unsafe extern "C" {
/// GPU rendering: default for new windows (BUI_GPU overrides).
pub fn BUI_gpu_set_default(on: c_int);
pub fn BUI_gpu_default() -> c_int;
+ pub fn BUI_gpu_set_slug(on: c_int);
+ pub fn BUI_gpu_slug() -> c_int;
pub fn BK_window_set_gpu(win: *mut BKWindow, on: c_int);
pub fn BK_window_gpu(win: *mut BKWindow) -> c_int;
pub fn BUI_text_add_font(family: *const c_char, flags: c_int, data: *const c_void,
diff --git a/bindings/rust/blenderui/Cargo.toml b/bindings/rust/blenderui/Cargo.toml
index d5d1618..05721be 100644
--- a/bindings/rust/blenderui/Cargo.toml
+++ b/bindings/rust/blenderui/Cargo.toml
@@ -11,7 +11,7 @@ categories = ["gui"]
readme = "README.md"
[dependencies]
-blenderui-sys = { path = "../blenderui-sys", version = "0.1.0" }
+blenderui-sys = { path = "../blenderui-sys", version = "0.1.0", default-features = false }
blenderui-macros = { path = "../blenderui-macros", version = "0.1.0" }
blenderui-tailwind = { path = "../blenderui-tailwind", version = "0.1.0" }
taffy = { version = "0.15", default-features = false, features = ["std", "taffy_tree", "flexbox", "flexbox_balance", "grid", "block_layout", "float_layout", "calc", "content_size"] }
@@ -23,5 +23,9 @@ png = "0.17"
# Draw text with Windows' native GDI engine (system fonts) instead of the
# default portable engine (embedded Inter, like Blender; Slug on the GPU).
gdi-text = ["blenderui-sys/gdi-text"]
+# GPU text with Slug by default (else the per-glyph atlas); see
+# `Application::slug` / `blenderui::set_slug` to switch at runtime.
+slug = ["blenderui-sys/slug"]
+default = ["slug"]
# Deprecated no-op: the portable engine is the default everywhere.
portable-text = ["blenderui-sys/portable-text"]
diff --git a/bindings/rust/blenderui/src/hooks.rs b/bindings/rust/blenderui/src/hooks.rs
index 29850ba..480f085 100644
--- a/bindings/rust/blenderui/src/hooks.rs
+++ b/bindings/rust/blenderui/src/hooks.rs
@@ -41,10 +41,12 @@ type Job = Box<dyn FnOnce()>;
struct Store {
slots: Vec<Slot>,
free: Vec<u32>,
- /// (window, call site, occurrence) -> slot
- keys: FnvMap<(usize, usize, u32), u32>,
- /// occurrences of each call site in the current render
- occ: FnvMap<usize, u32>,
+ /// (window, call site, key scope, occurrence) -> slot
+ keys: FnvMap<(usize, usize, u64, u32), u32>,
+ /// occurrences of each (call site, key scope) in the current render
+ occ: FnvMap<(usize, u64), u32>,
+ /// the keys of the keyed components being rendered, hashed together
+ scope: u64,
window: Option<usize>,
dirty: Vec<usize>,
jobs: Vec<Job>,
@@ -90,8 +92,8 @@ impl Store {
fn hook_slot(&mut self, site: &'static Location<'static>, init: impl FnOnce() -> Box<dyn Any>) -> (u32, u32) {
let window = self.window.unwrap_or(usize::MAX);
let site = site as *const Location as usize;
- let n = self.occ.entry(site).or_insert(0);
- let key = (window, site, *n);
+ let n = self.occ.entry((site, self.scope)).or_insert(0);
+ let key = (window, site, self.scope, *n);
*n += 1;
if let Some(&i) = self.keys.get(&key) {
let s = &mut self.slots[i as usize];
@@ -112,6 +114,7 @@ pub(crate) fn begin(window: usize) {
s.window = Some(window);
s.occ.clear();
s.ctx.clear();
+ s.scope = 0;
for slot in s.slots.iter_mut().filter(|x| x.window == window && x.hook) {
slot.seen = false;
}
@@ -498,3 +501,56 @@ pub fn component<R>(body: impl FnOnce() -> R) -> R {
/// Children of a component (`#[component] fn card(children: Children)`).
pub type Children = Vec<crate::element::AnyElement>;
+
+/// `<Item key={id} ../>`: a component whose hook state follows its key, not
+/// its position among its siblings (React's `key`). Without keys, removing
+/// the first item of a list hands its state to the next one.
+pub struct Keyed<E> {
+ key: u64,
+ inner: E,
+}
+
+/// Wraps `inner` so the hooks it runs are identified by `key` (`rsx!` does
+/// this for `key=` attributes).
+pub fn keyed<K: std::hash::Hash, E>(key: K, inner: E) -> Keyed<E> {
+ use std::hash::{BuildHasher, Hasher};
+ let mut h = std::hash::BuildHasherDefault::<std::collections::hash_map::DefaultHasher>::default().build_hasher();
+ key.hash(&mut h);
+ Keyed { key: h.finish(), inner }
+}
+
+impl<E: crate::element::IntoElement> crate::element::IntoElement for Keyed<E> {
+ fn into_any_element(self) -> crate::element::AnyElement {
+ let outer = with(|s| {
+ let outer = s.scope;
+ // nested keys combine: a keyed row inside a keyed list
+ s.scope = (outer ^ self.key).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(29) | 1;
+ outer
+ });
+ let el = self.inner.into_any_element();
+ with(|s| s.scope = outer);
+ el
+ }
+}
+
+/// A component's props, built field by field (`rsx!` calls the setters, then
+/// [`build`]). Implemented by `#[component]` and `#[derive(Props)]`
+/// builders once every required prop is set.
+#[diagnostic::on_unimplemented(
+ message = "a required prop is missing: `{Self}`",
+ label = "set the props named `missing_<prop>` in this builder's type",
+ note = "optional props are `Option<T>` (or `children`); every other prop must be given"
+)]
+pub trait Complete {
+ type Props;
+ fn finish(self) -> Self::Props;
+}
+
+/// A required prop that has been set (props builders' type state).
+#[doc(hidden)]
+pub struct Set;
+
+#[doc(hidden)]
+pub fn build<B: Complete>(builder: B) -> B::Props {
+ builder.finish()
+}
diff --git a/bindings/rust/blenderui/src/layout.rs b/bindings/rust/blenderui/src/layout.rs
index d83d29b..538cb56 100644
--- a/bindings/rust/blenderui/src/layout.rs
+++ b/bindings/rust/blenderui/src/layout.rs
@@ -101,11 +101,14 @@ pub(crate) struct StyleStore {
cache: FnvMap<u64, Vec<(StyleKey, StyleId)>>,
/// Custom property maps the styles point into (`Computed::vars`).
vars: crate::vars::Vars,
+ /// The author sheet whose `@property` initial values seed the root
+ /// style's variables.
+ seeded: u64,
}
impl Default for StyleStore {
fn default() -> Self {
- StyleStore { styles: vec![Computed::default()], cache: Default::default(), vars: Default::default() }
+ StyleStore { styles: vec![Computed::default()], cache: Default::default(), vars: Default::default(), seeded: 0 }
}
}
@@ -124,9 +127,31 @@ impl StyleStore {
self.styles.truncate(1);
self.cache.clear();
self.vars.clear();
+ self.seeded = 0;
}
}
+ /// `@property --x { initial-value: .. }`: registered properties hold
+ /// their initial value until something sets them (`var(--x)` finds it
+ /// without a fallback). Seeded into the root style once per sheet.
+ fn seed_properties(&mut self, sheet: &Stylesheet, hash: u64) {
+ if self.seeded == hash {
+ return;
+ }
+ self.seeded = hash;
+ let mut map: Vec<(Prop, Box<[crate::css::Tok]>)> = sheet.properties.iter()
+ .filter(|p| p.name.starts_with("--"))
+ .filter_map(|p| Some((Prop::custom(&p.name), crate::css::tokenize(p.initial.as_deref()?).into_boxed_slice())))
+ .collect();
+ map.sort_by_key(|e| e.0);
+ map.dedup_by_key(|e| e.0);
+ // styles computed against the old root variables are stale
+ self.styles.truncate(1);
+ self.cache.clear();
+ self.vars.clear();
+ self.styles[0].vars = if map.is_empty() { 0 } else { self.vars.add(map.into_boxed_slice()) };
+ }
+
fn add(&mut self, c: Computed) -> StyleId {
self.styles.push(c);
StyleId((self.styles.len() - 1) as u32)
@@ -309,6 +334,62 @@ pub(crate) struct LayoutCaches {
/// Measured text leaves: key -> box index, this frame.
text_box: FnvMap<Key, usize>,
tw: TwJit,
+ /// `@container`: query containers' content sizes from the last layout.
+ containers: Containers,
+}
+
+impl LayoutCaches {
+ /// After a layout: record query containers' sizes. True when the
+ /// window must render again (an `@container` query may match differently).
+ pub(crate) fn after_layout(&mut self, frame: &Frame) -> bool {
+ let queried = self.author.sheet.has_container_queries();
+ self.containers.update(frame, &self.styles, queried)
+ }
+}
+
+/// Query containers by element key: content-box size, `container-type`
+/// and names, from the previous layout (queries see last frame's sizes;
+/// a change re-renders once more).
+#[derive(Default)]
+pub(crate) struct Containers {
+ map: FnvMap<Key, (f32, f32, u8, Option<Box<str>>)>,
+ /// Hash of `map`, part of the selector-match memo.
+ generation: u64,
+ /// Consecutive re-renders caused by container size changes.
+ chain: u8,
+}
+
+impl Containers {
+ /// After a layout: record the containers; true when a re-render is needed.
+ fn update(&mut self, frame: &Frame, styles: &StyleStore, queried: bool) -> bool {
+ let mut map: FnvMap<Key, (f32, f32, u8, Option<Box<str>>)> = FnvMap::default();
+ for n in &frame.nodes {
+ let c = &styles[n.style];
+ if c.container_type != 0 && n.taffy.is_some() {
+ let b = crate::paint::content_box(c, n.bounds);
+ map.insert(n.key, (b.size.width, b.size.height, c.container_type, c.container_name.clone()));
+ }
+ }
+ let mut h = Fnv::default();
+ let mut keys: Vec<&Key> = map.keys().collect();
+ keys.sort_unstable();
+ for k in keys {
+ let (w, hh, t, _) = &map[k];
+ (k, w.to_bits(), hh.to_bits(), t).hash(&mut h);
+ }
+ let generation = h.finish();
+ let changed = generation != self.generation;
+ self.map = map;
+ self.generation = generation;
+ // a query may now match differently: render again (bounded, in case
+ // the result feeds back into the container's own size)
+ if changed && queried && self.chain < 3 {
+ self.chain += 1;
+ return true;
+ }
+ self.chain = 0;
+ false
+ }
}
/// Rule indices (`Rule::order`) in the UA and author sheets.
@@ -334,6 +415,7 @@ impl Default for LayoutCaches {
recon: Recon::default(),
text_box: FnvMap::default(),
tw: TwJit::default(),
+ containers: Containers::default(),
}
}
}
@@ -354,6 +436,7 @@ struct Builder<'a> {
next_tpos: (u32, u32),
author: &'a Stylesheet,
author_hash: u64,
+ containers: &'a Containers,
/// Media query results of the UA and author sheets this frame.
ua_media: Vec<bool>,
au_media: Vec<bool>,
@@ -399,6 +482,7 @@ struct NodeRef<'b> {
nodes: &'b [BoxNode],
els: &'b [ElData],
state: &'b UiState,
+ containers: &'b Containers,
i: usize,
}
@@ -418,6 +502,20 @@ impl NodeRef<'_> {
}
impl Subject for NodeRef<'_> {
+ fn container(&self, name: Option<&str>) -> Option<(f32, f32)> {
+ let mut cur = self.nodes[self.i].parent;
+ while let Some(p) = cur {
+ if let Some((w, h, ty, names)) = self.containers.map.get(&self.nodes[p].key) {
+ let named = name.is_none_or(|n| names.as_deref().is_some_and(|s| s.split(' ').any(|x| x == n)));
+ if named {
+ // an inline-size container has no queryable height
+ return Some((*w, if *ty == 2 { *h } else { f32::NAN }));
+ }
+ }
+ cur = self.nodes[p].parent;
+ }
+ None
+ }
fn tag(&self) -> &str {
self.el().map(|e| e.tag).unwrap_or("")
}
@@ -653,7 +751,7 @@ fn collect_styles(el: &AnyElement, css: &mut String, title: &mut Option<String>,
impl<'a> Builder<'a> {
fn subject(&self, i: usize) -> NodeRef<'_> {
- NodeRef { nodes: &self.nodes, els: &self.els, state: self.state, i }
+ NodeRef { nodes: &self.nodes, els: &self.els, state: self.state, containers: self.containers, i }
}
fn st(&self, i: usize) -> &Computed {
@@ -729,6 +827,7 @@ impl<'a> Builder<'a> {
let memo = {
let mut h = Fnv::default();
self.nodes[i].fp.hash(&mut h);
+ self.containers.generation.hash(&mut h);
self.viewport.0.to_bits().hash(&mut h);
self.viewport.1.to_bits().hash(&mut h);
h.finish()
@@ -1680,8 +1779,10 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca
let css_hash = fnv(&[css.as_bytes()]);
if css_hash != caches.author.hash {
caches.author = AuthorSheet { hash: css_hash, sheet: Stylesheet::parse(&css) };
+ load_font_faces(&caches.author.sheet);
}
caches.styles.begin_frame();
+ caches.styles.seed_properties(&caches.author.sheet, caches.author.hash);
// the taffy tree persists: drop last frame's duplicates, start a new stamp
for id in caches.recon.extra.drain(..) {
caches.taffy.remove(id);
@@ -1695,7 +1796,7 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca
caches.matched.map.clear();
caches.matched.author = caches.author.hash;
}
- let LayoutCaches { styles, text, images, author, taffy, box_of, acc, matched, recon, text_box, .. } = caches;
+ let LayoutCaches { styles, text, images, author, taffy, box_of, acc, matched, recon, text_box, containers, .. } = caches;
let mut b = Builder {
nodes,
els,
@@ -1706,6 +1807,7 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca
matched,
recon,
text_box,
+ containers,
changed: false,
next_tpos: (1, 1),
author: &author.sheet,
@@ -2039,3 +2141,22 @@ impl Frame {
}
}
}
+
+/// `@font-face`: registers each face's first `url()` that loads (paths are
+/// relative to the working directory), once per process. Styles computed
+/// before a face loaded are recomputed because the sheet changed.
+fn load_font_faces(sheet: &Stylesheet) {
+ static LOADED: std::sync::Mutex<Vec<(String, bool, bool)>> = std::sync::Mutex::new(Vec::new());
+ for face in &sheet.font_faces {
+ let key = (face.family.to_ascii_lowercase(), face.bold, face.italic);
+ if LOADED.lock().unwrap_or_else(|e| e.into_inner()).contains(&key) {
+ continue;
+ }
+ let loaded = face.src.iter().any(|path| {
+ std::fs::read(path).is_ok_and(|bytes| crate::add_font(&face.family, face.bold, face.italic, &bytes))
+ });
+ if loaded {
+ LOADED.lock().unwrap_or_else(|e| e.into_inner()).push(key);
+ }
+ }
+}
diff --git a/bindings/rust/blenderui/src/lib.rs b/bindings/rust/blenderui/src/lib.rs
index 72af72c..a6edc92 100644
--- a/bindings/rust/blenderui/src/lib.rs
+++ b/bindings/rust/blenderui/src/lib.rs
@@ -90,6 +90,10 @@ pub use blenderui_macros::rsx;
/// [`rsx!`] under its zopra / Leptos name.
pub use blenderui_macros::rsx as view;
+/// `#[derive(Props)]` on a struct component: `rsx!` may leave out its
+/// `Option<T>` fields and `children`, and names missing required ones.
+pub use blenderui_macros::Props;
+
pub mod calc;
pub mod color;
mod color4;
@@ -135,12 +139,28 @@ pub fn set_tailwind(on: bool) {
/// the data isn't a font.
pub fn add_font(family: &str, bold: bool, italic: bool, data: &[u8]) -> bool {
let fam = std::ffi::CString::new(family).unwrap_or_default();
+ text::register_family(family);
let flags = if bold { 1 } else { 0 } | if italic { 2 } else { 0 };
let len = data.len().min(i32::MAX as usize) as i32;
// SAFETY: the kit copies the bytes; both pointers are valid for the call.
unsafe { sys::BUI_text_add_font(fam.as_ptr(), flags, data.as_ptr().cast(), len) != 0 }
}
+/// How the GPU renderer draws text. `true`: Slug, glyph outlines evaluated
+/// in the pixel shader (sharp at any size; the default with the `slug`
+/// feature). `false`: a per-glyph bitmap atlas like Blender's (less GPU
+/// work). Takes effect on the next frame; `BUI_SLUG=1`/`0` overrides.
+pub fn set_slug(on: bool) {
+ // SAFETY: sets a global flag.
+ unsafe { sys::BUI_gpu_set_slug(on as std::os::raw::c_int) }
+}
+
+/// Whether GPU text is drawn with Slug (see [`set_slug`]).
+pub fn slug() -> bool {
+ // SAFETY: reads a global flag.
+ unsafe { sys::BUI_gpu_slug() != 0 }
+}
+
/// Everything an app needs: `use blenderui::prelude::*;`
pub mod prelude {
pub use crate::{css, rsx, tw, view, use_effect};
@@ -148,7 +168,7 @@ pub mod prelude {
create_signal, provide_context, signal, try_use_context, use_context, use_memo, use_signal, use_state,
Children, Effect, Memo, ReadSignal, RwSignal, Signal, WriteSignal,
};
- pub use blenderui_macros::component;
+ pub use blenderui_macros::{component, Props};
pub use crate::color::*;
pub use crate::element::*;
pub use crate::events::*;
diff --git a/bindings/rust/blenderui/src/paint.rs b/bindings/rust/blenderui/src/paint.rs
index 3047037..e5c9354 100644
--- a/bindings/rust/blenderui/src/paint.rs
+++ b/bindings/rust/blenderui/src/paint.rs
@@ -297,7 +297,7 @@ impl Painter {
Kind::Text { start, size, flags } => {
ci.type_ = sys::BK_ITEM_TEXT;
ci.size = size * scale;
- ci.text_flags = *flags;
+ (ci.family, ci.text_flags) = crate::text::family(*flags);
ci.anchor = sys::BK_ANCHOR_N | sys::BK_ANCHOR_W;
ci.text = self.text[*start as usize..].as_ptr().cast();
}
@@ -384,7 +384,8 @@ pub(crate) fn paint_frame(frame: &Frame, styles: &StyleStore, tc: &mut TextCache
/// only undecorated same-sized boxes in between (so nothing else can show).
fn redundant_background(frame: &Frame, styles: &StyleStore, n: &BoxNode) -> bool {
let c = &styles[n.style];
- if c.background.a < 1.0 || c.gradient.is_some() || !c.shadows.is_empty() {
+ if c.background.a < 1.0 || c.gradient.is_some() || !c.shadows.is_empty()
+ || c.images.as_ref().is_some_and(|i| i.bg_url.is_some()) {
return false;
}
let mut cur = n.parent;
@@ -467,7 +468,16 @@ fn paint_node(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, i: usize,
if let Content::Replaced(r) = &n.content {
let inner = content_box(c, b);
match r {
- Replaced::Image(img) => p.image(inner, img),
+ Replaced::Image(img) => match &c.images {
+ Some(st) if st.object_fit != crate::style::ObjectFit::Fill
+ || st.object_position != [crate::style::Pos::CENTER; 2] => {
+ let (x, y, w, h) = st.object_rect(
+ (inner.origin.x, inner.origin.y, inner.size.width, inner.size.height),
+ (img.width as f32, img.height as f32));
+ p.with_clip(inner, |p| p.image(rect(x, y, w, h), img));
+ }
+ _ => p.image(inner, img),
+ },
Replaced::Painted(f) => p.with_clip(inner, |p| f(inner, p)),
Replaced::Placeholder(tag) => {
p.fill(inner, crate::color::rgb(0x282828));
@@ -485,7 +495,7 @@ fn paint_node(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, i: usize,
}
}
-fn content_box(c: &Computed, b: Bounds<f32>) -> Bounds<f32> {
+pub(crate) fn content_box(c: &Computed, b: Bounds<f32>) -> Bounds<f32> {
let w = b.size.width;
let bw = border_widths(c, w);
let pd = c.layout.padding;
@@ -555,6 +565,9 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_ba
None if skip_background => {}
None => p.quad(b, r, c.background, Rgba::TRANSPARENT, 0.0),
}
+ if let Some(st) = c.images.as_deref().filter(|st| st.bg_url.is_some()) {
+ paint_background_image(p, c, st, b);
+ }
for s in c.shadows.iter().filter(|s| s.inset) {
let w = s.blur.max(1.0) + s.spread;
p.with_clip(b, |p| {
@@ -675,3 +688,45 @@ fn paint_scrollbars(n: &BoxNode, p: &mut Painter) {
Rgba::TRANSPARENT, 0.0);
}
}
+
+/// `background-image: url()` files (PNG), decoded once per process.
+fn background_file(url: &str) -> Option<Arc<Image>> {
+ static FILES: std::sync::Mutex<Option<HashMap<String, Option<Arc<Image>>>>> = std::sync::Mutex::new(None);
+ let mut files = FILES.lock().unwrap_or_else(|e| e.into_inner());
+ let files = files.get_or_insert_with(HashMap::new);
+ if let Some(i) = files.get(url) {
+ return i.clone();
+ }
+ let img = Image::from_png(url).map(Arc::new);
+ files.insert(url.to_owned(), img.clone());
+ img
+}
+
+/// A background image over the padding box: sized, positioned and tiled.
+fn paint_background_image(p: &mut Painter, c: &Computed, st: &crate::style::ImageStyle, b: Bounds<f32>) {
+ let Some(img) = st.bg_url.as_deref().and_then(background_file) else { return };
+ let bw = border_widths(c, b.size.width);
+ let (ax, ay) = (b.origin.x + bw[3], b.origin.y + bw[0]);
+ let (aw, ah) = (b.size.width - bw[1] - bw[3], b.size.height - bw[0] - bw[2]);
+ let (tw, th) = st.tile((aw, ah), (img.width as f32, img.height as f32));
+ if tw < 0.5 || th < 0.5 || aw <= 0.0 || ah <= 0.0 {
+ return;
+ }
+ let x0 = ax + st.bg_position[0].at(aw - tw);
+ let y0 = ay + st.bg_position[1].at(ah - th);
+ // first tile at or before the area's start, when repeating
+ let sx = if st.bg_repeat.0 { x0 - ((x0 - ax) / tw).ceil() * tw } else { x0 };
+ let sy = if st.bg_repeat.1 { y0 - ((y0 - ay) / th).ceil() * th } else { y0 };
+ let nx = if st.bg_repeat.0 { ((ax + aw - sx) / tw).ceil() as usize } else { 1 };
+ let ny = if st.bg_repeat.1 { ((ay + ah - sy) / th).ceil() as usize } else { 1 };
+ if nx.saturating_mul(ny) > 4096 {
+ return; // tiny tiles over a huge box: not worth thousands of quads
+ }
+ p.with_clip(rect(ax, ay, aw, ah), |p| {
+ for j in 0..ny {
+ for i in 0..nx {
+ p.image(rect(sx + i as f32 * tw, sy + j as f32 * th, tw, th), &img);
+ }
+ }
+ });
+}
diff --git a/bindings/rust/blenderui/src/selector.rs b/bindings/rust/blenderui/src/selector.rs
index 4ce4fa4..34aff27 100644
--- a/bindings/rust/blenderui/src/selector.rs
+++ b/bindings/rust/blenderui/src/selector.rs
@@ -1199,6 +1199,11 @@ struct Ctx {
}
impl Stylesheet {
+ /// Whether any rule sits under `@container`.
+ pub fn has_container_queries(&self) -> bool {
+ !self.containers.is_empty()
+ }
+
/// Parse CSS text.
pub fn parse(css: &str) -> Stylesheet {
let mut sheet = Stylesheet::default();
diff --git a/bindings/rust/blenderui/src/style.rs b/bindings/rust/blenderui/src/style.rs
index 0700c36..f47dea0 100644
--- a/bindings/rust/blenderui/src/style.rs
+++ b/bindings/rust/blenderui/src/style.rs
@@ -113,6 +113,113 @@ pub struct Shadow {
pub inset: bool,
}
+/// A position along one axis: `frac` of the free space plus `px`
+/// (`left` = 0, `center` = 0.5, `75%`, `10px`, `right 10px` ...).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Pos {
+ pub frac: f32,
+ pub px: f32,
+}
+
+impl Pos {
+ pub const START: Pos = Pos { frac: 0.0, px: 0.0 };
+ pub const CENTER: Pos = Pos { frac: 0.5, px: 0.0 };
+
+ /// Offset into `free` pixels of room.
+ pub fn at(self, free: f32) -> f32 {
+ free * self.frac + self.px
+ }
+}
+
+/// `object-fit`.
+#[derive(Clone, Copy, Debug, PartialEq, Default)]
+pub enum ObjectFit {
+ #[default]
+ Fill,
+ Contain,
+ Cover,
+ None,
+ ScaleDown,
+}
+
+/// `background-size`: a size is a fraction of the box plus pixels; `None` = auto.
+#[derive(Clone, Copy, Debug, PartialEq, Default)]
+pub enum BgSize {
+ #[default]
+ Auto,
+ Cover,
+ Contain,
+ Size(Option<Pos>, Option<Pos>),
+}
+
+/// Image placement: `object-*` for replaced content, `background-*` images.
+/// Boxed in [`Computed::images`]: most elements have neither.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ImageStyle {
+ pub object_fit: ObjectFit,
+ pub object_position: [Pos; 2],
+ pub bg_url: Option<std::sync::Arc<str>>,
+ pub bg_size: BgSize,
+ pub bg_position: [Pos; 2],
+ /// repeat along x, y
+ pub bg_repeat: (bool, bool),
+}
+
+impl Default for ImageStyle {
+ fn default() -> Self {
+ ImageStyle {
+ object_fit: ObjectFit::Fill,
+ object_position: [Pos::CENTER; 2],
+ bg_url: None,
+ bg_size: BgSize::Auto,
+ bg_position: [Pos::START; 2],
+ bg_repeat: (true, true),
+ }
+ }
+}
+
+impl ImageStyle {
+ /// Where an image of `natural` size goes in `area` with `object-fit` /
+ /// `object-position` (it may overflow `area`; clip to it).
+ pub fn object_rect(&self, area: (f32, f32, f32, f32), natural: (f32, f32)) -> (f32, f32, f32, f32) {
+ let (x, y, w, h) = area;
+ let (nw, nh) = (natural.0.max(1.0), natural.1.max(1.0));
+ let (dw, dh) = match self.object_fit {
+ ObjectFit::Fill => (w, h),
+ ObjectFit::None => (nw, nh),
+ ObjectFit::Contain | ObjectFit::Cover | ObjectFit::ScaleDown => {
+ let s = if self.object_fit == ObjectFit::Cover { (w / nw).max(h / nh) } else { (w / nw).min(h / nh) };
+ let s = if self.object_fit == ObjectFit::ScaleDown { s.min(1.0) } else { s };
+ (nw * s, nh * s)
+ }
+ };
+ (x + self.object_position[0].at(w - dw), y + self.object_position[1].at(h - dh), dw, dh)
+ }
+
+ /// One background tile's size for an image of `natural` size in `area`.
+ pub fn tile(&self, area: (f32, f32), natural: (f32, f32)) -> (f32, f32) {
+ let (w, h) = area;
+ let (nw, nh) = (natural.0.max(1.0), natural.1.max(1.0));
+ match self.bg_size {
+ BgSize::Auto => (nw, nh),
+ BgSize::Cover => {
+ let s = (w / nw).max(h / nh);
+ (nw * s, nh * s)
+ }
+ BgSize::Contain => {
+ let s = (w / nw).min(h / nh);
+ (nw * s, nh * s)
+ }
+ BgSize::Size(sx, sy) => match (sx.map(|p| p.at(w)), sy.map(|p| p.at(h))) {
+ (Some(a), Some(b)) => (a, b),
+ (Some(a), None) => (a, a * nh / nw),
+ (None, Some(b)) => (b * nw / nh, b),
+ (None, None) => (nw, nh),
+ },
+ }
+ }
+}
+
/// The style of one element after the cascade.
#[derive(Clone, Debug)]
pub struct Computed {
@@ -122,6 +229,12 @@ pub struct Computed {
// paint (not inherited)
pub background: Rgba,
pub gradient: Option<Gradient>,
+ /// `object-*` / `background-image: url()` placement (None: defaults).
+ pub images: Option<Box<ImageStyle>>,
+ /// `container-type`: 0 normal, 1 inline-size, 2 size.
+ pub container_type: u8,
+ /// `container-name` (space-separated names).
+ pub container_name: Option<Box<str>>,
pub border_color: [Rgba; 4],
pub border_drawn: [bool; 4],
pub radius: [Length; 4],
@@ -155,6 +268,8 @@ pub struct Computed {
pub small_caps: bool,
pub vertical_align: VAlign,
pub font_family: String,
+ /// The font family's engine id (see `text::font_id`); 0 = the UI font.
+ pub font_id: u16,
// tables, lists, quotes and text effects (inherited)
pub border_spacing: (f32, f32),
pub border_collapse: bool,
@@ -188,6 +303,9 @@ impl Default for Computed {
order: 0,
background: Rgba::TRANSPARENT,
gradient: None,
+ images: None,
+ container_type: 0,
+ container_name: None,
border_color: [Rgba::TRANSPARENT; 4],
border_drawn: [true; 4],
radius: [Length::Px(0.0); 4],
@@ -220,6 +338,7 @@ impl Default for Computed {
small_caps: false,
vertical_align: VAlign::Baseline,
font_family: String::new(),
+ font_id: 0,
border_spacing: (0.0, 0.0),
border_collapse: false,
caption_bottom: false,
@@ -255,6 +374,7 @@ impl Computed {
list_style: parent.list_style,
small_caps: parent.small_caps,
font_family: parent.font_family.clone(),
+ font_id: parent.font_id,
// text-decoration propagates to inline descendants in CSS
underline: parent.underline,
line_through: parent.line_through,
@@ -272,6 +392,10 @@ impl Computed {
}
}
+ fn images_mut(&mut self) -> &mut ImageStyle {
+ self.images.get_or_insert_with(Default::default)
+ }
+
/// Line box height in pixels.
pub fn line_px(&self) -> f32 {
match self.line_height {
@@ -308,6 +432,17 @@ pub fn apply(c: &mut Computed, parent: &Computed, u: Units, d: &Decl) -> bool {
return false;
}
if let [Tok::Ident(k)] = &*d.value {
+ if d.prop.name() == "all" {
+ let keep = (ctx.c.layout.direction, ctx.c.vars);
+ *ctx.c = match k.as_ref() {
+ "inherit" => ctx.parent.clone(),
+ "initial" => Computed::default(),
+ "unset" | "revert" | "revert-layer" => Computed::inherit(ctx.parent),
+ _ => return false,
+ };
+ (ctx.c.layout.direction, ctx.c.vars) = keep;
+ return true;
+ }
if matches!(k.as_ref(), "inherit" | "initial" | "unset" | "revert" | "revert-layer") {
return global_keyword(&mut ctx, d.prop.name(), k);
}
@@ -349,11 +484,10 @@ pub(crate) fn prop_index(name: &str) -> Prop {
/// Standard properties that parse and are accepted but have no effect in this
/// renderer (floats, bidi, generated content, background images, animation ...).
pub const ACCEPTED: &[&str] = &[
- "background-attachment", "background-position", "background-repeat", "background-size",
- "background-clip", "background-origin", "clip", "clip-path",
+ "background-attachment", "background-clip", "background-origin", "clip", "clip-path",
"counter-increment", "counter-reset", "counter-set", "unicode-bidi",
"writing-mode", "empty-cells", "list-style-image", "table-layout",
- "object-fit", "object-position", "filter", "backdrop-filter", "mix-blend-mode", "isolation",
+ "filter", "backdrop-filter", "mix-blend-mode", "isolation",
"transition", "transition-property", "transition-duration", "transition-timing-function",
"transition-delay", "animation", "animation-name", "animation-duration", "animation-delay",
"animation-iteration-count", "animation-direction", "animation-fill-mode",
@@ -367,6 +501,41 @@ pub const ACCEPTED: &[&str] = &[
"column-rule", "rotate", "transform-origin", "perspective", "backface-visibility",
"box-decoration-break", "image-rendering", "shape-outside", "text-underline-offset",
"text-decoration-thickness", "text-decoration-style", "text-justify", "line-break",
+ "all",
+ // scrolling
+ "scroll-margin", "scroll-margin-top", "scroll-margin-right", "scroll-margin-bottom",
+ "scroll-margin-left", "scroll-margin-block", "scroll-margin-block-start", "scroll-margin-block-end",
+ "scroll-margin-inline", "scroll-margin-inline-start", "scroll-margin-inline-end",
+ "scroll-padding", "scroll-padding-top", "scroll-padding-right", "scroll-padding-bottom",
+ "scroll-padding-left", "scroll-padding-block", "scroll-padding-block-start",
+ "scroll-padding-block-end", "scroll-padding-inline", "scroll-padding-inline-start",
+ "scroll-padding-inline-end", "scroll-snap-stop", "overscroll-behavior-x", "overscroll-behavior-y",
+ "overscroll-behavior-block", "overscroll-behavior-inline", "overflow-anchor", "scrollbar-color",
+ "scrollbar-gutter", "overflow-clip-margin",
+ // fonts: OpenType features and synthesis
+ "font-variant-ligatures", "font-variant-numeric", "font-variant-east-asian",
+ "font-variant-alternates", "font-variant-position", "font-variant-emoji", "font-synthesis",
+ "font-synthesis-weight", "font-synthesis-style", "font-synthesis-small-caps",
+ "font-synthesis-position", "font-optical-sizing", "font-size-adjust", "font-variation-settings",
+ "font-palette", "font-language-override", "font-width",
+ // text details
+ "text-wrap-style", "text-align-last", "text-underline-position", "text-decoration-skip-ink",
+ "text-emphasis", "text-emphasis-color", "text-emphasis-style", "text-emphasis-position",
+ "text-orientation", "text-combine-upright", "hanging-punctuation", "hyphenate-character",
+ "line-clamp", "-webkit-line-clamp", "text-size-adjust", "-webkit-text-size-adjust",
+ // sizing / containment / rendering hints
+ "contain-intrinsic-size", "contain-intrinsic-width", "contain-intrinsic-height",
+ "contain-intrinsic-block-size", "contain-intrinsic-inline-size", "content-visibility",
+ "field-sizing", "interpolate-size", "transition-behavior", "color-scheme", "forced-color-adjust",
+ "print-color-adjust", "color-adjust", "image-orientation", "image-resolution",
+ "transform-box", "transform-style", "perspective-origin", "zoom", "caret", "caret-shape",
+ "background-blend-mode", "column-span", "column-fill", "column-rule-color", "column-rule-style",
+ "column-rule-width",
+ // masking
+ "mask", "mask-image", "mask-mode", "mask-repeat", "mask-position", "mask-clip", "mask-origin",
+ "mask-size", "mask-composite", "mask-type", "mask-border", "mask-border-source",
+ "mask-border-slice", "mask-border-width", "mask-border-outset", "mask-border-repeat",
+ "mask-border-mode",
];
/// Implemented or accepted.
@@ -375,6 +544,9 @@ pub fn is_supported(name: &str) -> bool {
}
fn global_keyword(ctx: &mut Ctx, name: &str, keyword: &str) -> bool {
+ if name == "font-family" {
+ global_keyword(ctx, "-bui-font-id", keyword);
+ }
let src = if keyword == "inherit" || (keyword == "unset" && is_inherited(name)) {
ctx.parent.clone()
} else {
@@ -397,6 +569,7 @@ fn global_keyword(ctx: &mut Ctx, name: &str, keyword: &str) -> bool {
"background-color" => background, "opacity" => opacity, "display" => display,
"width" => layout.size.width, "height" => layout.size.height,
"font-family" => font_family, "accent-color" => accent,
+ "-bui-font-id" => font_id,
}
}
@@ -1233,15 +1406,6 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
c.c.layout.contain = bits;
true
}),
- h("scrollbar-width", |c, v| {
- c.c.layout.scrollbar_width = match kw(v) {
- Some("auto") => 0.0, // overlay scrollbars, like the kit's
- Some("thin") => 0.0,
- Some("none") => 0.0,
- _ => return false,
- };
- true
- }),
h("box-sizing", |c, v| {
c.c.layout.box_sizing = match kw(v) {
Some("content-box") => BoxSizing::ContentBox,
@@ -1564,13 +1728,141 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
h("background-image", |c, v| match kw(v) {
Some("none") => {
c.c.gradient = None;
+ if let Some(i) = c.c.images.as_mut() {
+ i.bg_url = None;
+ }
true
}
- _ => v.first().and_then(|t| gradient(c, t)).map(|g| c.c.gradient = Some(g)).is_some(),
+ _ => {
+ // the first url() and the first gradient of the layer list
+ let mut ok = false;
+ for t in v {
+ match t {
+ Tok::Func(fx) if fx.name == "url" => {
+ if let Some(Tok::Str(u)) = fx.args.first().and_then(|a| a.first()) {
+ if c.c.images.as_ref().is_none_or(|i| i.bg_url.is_none()) || !ok {
+ c.c.images_mut().bg_url = Some(u.as_ref().into());
+ }
+ ok = true;
+ }
+ }
+ _ => {
+ if let Some(g) = gradient(c, t) {
+ c.c.gradient.get_or_insert(g);
+ ok = true;
+ }
+ }
+ }
+ }
+ ok
+ }
+ }),
+ h("background-size", |c, v| {
+ let first = v.split(|t| matches!(t, Tok::Comma)).next().unwrap_or(&[]);
+ let size = match (kw(first), first) {
+ (Some("cover"), _) => BgSize::Cover,
+ (Some("contain"), _) => BgSize::Contain,
+ (_, [a]) => BgSize::Size(size_pos(c, a), None),
+ (_, [a, b]) => BgSize::Size(size_pos(c, a), size_pos(c, b)),
+ _ => return false,
+ };
+ let size = match size {
+ BgSize::Size(None, None) => BgSize::Auto,
+ s => s,
+ };
+ c.c.images_mut().bg_size = size;
+ true
+ }),
+ h("background-position", |c, v| {
+ let first = v.split(|t| matches!(t, Tok::Comma)).next().unwrap_or(&[]);
+ position(c, first).map(|p| c.c.images_mut().bg_position = p).is_some()
+ }),
+ h("background-position-x", |c, v| axis_pos(c, v, 0).map(|p| c.c.images_mut().bg_position[0] = p).is_some()),
+ h("background-position-y", |c, v| axis_pos(c, v, 1).map(|p| c.c.images_mut().bg_position[1] = p).is_some()),
+ h("background-repeat", |c, v| {
+ let words: Vec<&str> = v.iter().take_while(|t| !matches!(t, Tok::Comma)).filter_map(Tok::ident).collect();
+ let rep = |w: &str| matches!(w, "repeat" | "space" | "round");
+ let r = match words.as_slice() {
+ ["repeat-x"] => (true, false),
+ ["repeat-y"] => (false, true),
+ [a] => (rep(a), rep(a)),
+ [a, b] => (rep(a), rep(b)),
+ _ => return false,
+ };
+ c.c.images_mut().bg_repeat = r;
+ true
+ }),
+ h("object-fit", |c, v| {
+ c.c.images_mut().object_fit = match kw(v) {
+ Some("fill") => ObjectFit::Fill,
+ Some("contain") => ObjectFit::Contain,
+ Some("cover") => ObjectFit::Cover,
+ Some("none") => ObjectFit::None,
+ Some("scale-down") => ObjectFit::ScaleDown,
+ _ => return false,
+ };
+ true
+ }),
+ h("container-type", |c, v| {
+ c.c.container_type = match kw(v) {
+ Some("normal") | Some("scroll-state") => 0,
+ Some("inline-size") => 1,
+ Some("size") => 2,
+ _ => return false,
+ };
+ true
+ }),
+ h("container-name", |c, v| {
+ let names: Vec<&str> = v.iter().filter_map(Tok::ident).collect();
+ c.c.container_name = match names.as_slice() {
+ [] => return false,
+ ["none"] => None,
+ n => Some(n.join(" ").into()),
+ };
+ true
+ }),
+ h("container", |c, v| {
+ // <name>+ [/ <type>]
+ let mut parts = v.split(|t| matches!(t, Tok::Slash));
+ let names = parts.next().unwrap_or(&[]);
+ let ok = delegate(c, "container-name", names);
+ match parts.next() {
+ Some(ty) => ok && delegate(c, "container-type", ty),
+ None => ok,
+ }
}),
+ h("object-position", |c, v| position(c, v).map(|p| c.c.images_mut().object_position = p).is_some()),
h("background", |c, v| {
- let mut ok = false;
+ // the first layer's image, position / size and repeat, then the colour
+ let layer = v.split(|t| matches!(t, Tok::Comma)).next().unwrap_or(&[]);
+ if let Some(k) = layer.iter().position(|t| matches!(t, Tok::Slash)) {
+ let size: Vec<Tok> = layer[k + 1..].iter().take_while(|t| length(t).is_some()
+ || matches!(t.ident(), Some("auto" | "cover" | "contain"))).cloned().take(2).collect();
+ delegate(c, "background-size", &size);
+ }
+ let pos: Vec<Tok> = layer.iter().take_while(|t| !matches!(t, Tok::Slash))
+ .filter(|t| length(t).is_some() && !matches!(t, Tok::Num(_))
+ || matches!(t.ident(), Some("left" | "right" | "top" | "bottom" | "center")))
+ .cloned().collect();
+ if !pos.is_empty() {
+ delegate(c, "background-position", &pos);
+ }
+ let reps: Vec<Tok> = layer.iter().filter(|t| matches!(t.ident(),
+ Some("repeat" | "no-repeat" | "repeat-x" | "repeat-y" | "space" | "round"))).cloned().collect();
+ if !reps.is_empty() {
+ delegate(c, "background-repeat", &reps);
+ }
+ let mut ok = !pos.is_empty() || !reps.is_empty();
for t in v {
+ if let Tok::Func(fx) = t {
+ if fx.name == "url" {
+ if let Some(Tok::Str(u)) = fx.args.first().and_then(|a| a.first()) {
+ c.c.images_mut().bg_url = Some(u.as_ref().into());
+ ok = true;
+ }
+ continue;
+ }
+ }
if let Some(g) = gradient(c, t) {
c.c.gradient = Some(g);
ok = true;
@@ -1597,6 +1889,25 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
h("border-inline-end", |c, v| border_sides(c, v, &[1])),
h("border-block-start", |c, v| border_sides(c, v, &[0])),
h("border-block-end", |c, v| border_sides(c, v, &[2])),
+ // logical longhands (horizontal-tb: block = top/bottom, inline = left/right)
+ h("border-block-color", |c, v| pair(c, v, "border-top-color", "border-bottom-color")),
+ h("border-block-style", |c, v| pair(c, v, "border-top-style", "border-bottom-style")),
+ h("border-block-width", |c, v| pair(c, v, "border-top-width", "border-bottom-width")),
+ h("border-inline-color", |c, v| pair(c, v, "border-left-color", "border-right-color")),
+ h("border-inline-style", |c, v| pair(c, v, "border-left-style", "border-right-style")),
+ h("border-inline-width", |c, v| pair(c, v, "border-left-width", "border-right-width")),
+ h("border-block-start-color", |c, v| delegate(c, "border-top-color", v)),
+ h("border-block-start-style", |c, v| delegate(c, "border-top-style", v)),
+ h("border-block-start-width", |c, v| delegate(c, "border-top-width", v)),
+ h("border-block-end-color", |c, v| delegate(c, "border-bottom-color", v)),
+ h("border-block-end-style", |c, v| delegate(c, "border-bottom-style", v)),
+ h("border-block-end-width", |c, v| delegate(c, "border-bottom-width", v)),
+ h("border-inline-start-color", |c, v| delegate(c, "border-left-color", v)),
+ h("border-inline-start-style", |c, v| delegate(c, "border-left-style", v)),
+ h("border-inline-start-width", |c, v| delegate(c, "border-left-width", v)),
+ h("border-inline-end-color", |c, v| delegate(c, "border-right-color", v)),
+ h("border-inline-end-style", |c, v| delegate(c, "border-right-style", v)),
+ h("border-inline-end-width", |c, v| delegate(c, "border-right-width", v)),
h("border-width", |c, v| per_side(v, |i, t| border_width_tok(c, t).map(|w| set_border_width(c, i, w)).is_some())),
h("border-top-width", |c, v| v.first().and_then(|t| border_width_tok(c, t)).map(|w| set_border_width(c, 0, w)).is_some()),
h("border-right-width", |c, v| v.first().and_then(|t| border_width_tok(c, t)).map(|w| set_border_width(c, 1, w)).is_some()),
@@ -1690,6 +2001,15 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
}
ok
}),
+ h("scale", |c, v| {
+ c.c.scale = match (kw(v), v.first()) {
+ (Some("none"), _) => 1.0,
+ (_, Some(Tok::Num(n))) => *n,
+ (_, Some(Tok::Pct(p))) => *p / 100.0,
+ _ => return false,
+ };
+ true
+ }),
h("translate", |c, v| {
let l = lengths(v).unwrap_or_default();
c.c.translate = (*l.first().unwrap_or(&Length::Px(0.0)), *l.get(1).unwrap_or(&Length::Px(0.0)));
@@ -1705,6 +2025,7 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
}),
h("font-family", |c, v| {
c.c.font_family = v.iter().map(tok_text).collect::<Vec<_>>().join(" ");
+ c.c.font_id = crate::text::font_id(&c.c.font_family);
true
}),
h("font-variant", |c, v| {
@@ -1737,6 +2058,7 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
}
i += 1;
c.c.font_family = v[i..].iter().map(tok_text).collect::<Vec<_>>().join(" ");
+ c.c.font_id = crate::text::font_id(&c.c.font_family);
return true;
} else {
return false;
@@ -1781,6 +2103,31 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
}
true
}),
+ // CSS Text 4 longhands of white-space: wrapping and collapsing
+ h("text-wrap-mode", |c, v| {
+ use WhiteSpace::*;
+ c.c.white_space = match (kw(v), c.c.white_space) {
+ (Some("wrap"), NoWrap) => Normal,
+ (Some("wrap"), Pre) => PreWrap,
+ (Some("wrap"), w) => w,
+ (Some("nowrap"), Normal | PreLine) => NoWrap,
+ (Some("nowrap"), PreWrap) => Pre,
+ (Some("nowrap"), w) => w,
+ _ => return false,
+ };
+ true
+ }),
+ h("white-space-collapse", |c, v| {
+ use WhiteSpace::*;
+ let wraps = !matches!(c.c.white_space, NoWrap | Pre);
+ c.c.white_space = match kw(v) {
+ Some("collapse" | "discard") => if wraps { Normal } else { NoWrap },
+ Some("preserve" | "break-spaces" | "preserve-spaces") => if wraps { PreWrap } else { Pre },
+ Some("preserve-breaks") => if wraps { PreLine } else { Pre },
+ _ => return false,
+ };
+ true
+ }),
h("text-transform", |c, v| {
c.c.text_transform = match kw(v) {
Some("none") => TextTransform::None,
@@ -1935,6 +2282,82 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
]
};
+/// A `<position>` (`center`, `left 10px top`, `25% 75%`, `right 8px bottom 4px` ...)
+/// as x and y.
+fn position(c: &Ctx, v: &[Tok]) -> Option<[Pos; 2]> {
+ let kwp = |s: &str| match s {
+ "left" | "top" => Some(0.0),
+ "center" => Some(0.5),
+ "right" | "bottom" => Some(1.0),
+ _ => None,
+ };
+ let val = |t: &Tok| -> Option<Pos> {
+ match length(t)? {
+ Length::Percent(p) => Some(Pos { frac: p / 100.0, px: 0.0 }),
+ l => l.to_px(&c.u).map(|px| Pos { frac: 0.0, px }),
+ }
+ };
+ let mut x: Option<Pos> = None;
+ let mut y: Option<Pos> = None;
+ let mut i = 0;
+ let mut pending_center = 0;
+ while i < v.len() {
+ let t = &v[i];
+ if let Some(word) = t.ident() {
+ let f = kwp(word)?;
+ // `right 10px`: an offset from that edge
+ let off = v.get(i + 1).filter(|n| n.ident().is_none()).and_then(val);
+ let p = match off {
+ Some(o) => {
+ i += 1;
+ if f == 1.0 { Pos { frac: 1.0 - o.frac, px: -o.px } } else { o }
+ }
+ None => Pos { frac: f, px: 0.0 },
+ };
+ match word {
+ "left" | "right" => x = Some(p),
+ "top" | "bottom" => y = Some(p),
+ _ => pending_center += 1,
+ }
+ } else {
+ let p = val(t)?;
+ if x.is_none() && pending_center == 0 {
+ x = Some(p);
+ } else {
+ y = Some(p);
+ }
+ }
+ i += 1;
+ }
+ for _ in 0..pending_center {
+ if x.is_none() {
+ x = Some(Pos::CENTER);
+ } else if y.is_none() {
+ y = Some(Pos::CENTER);
+ }
+ }
+ if x.is_none() && y.is_none() {
+ return None;
+ }
+ Some([x.unwrap_or(Pos::CENTER), y.unwrap_or(Pos::CENTER)])
+}
+
+/// `background-position-x` / `-y`.
+fn axis_pos(c: &Ctx, v: &[Tok], axis: usize) -> Option<Pos> {
+ let first: Vec<Tok> = v.iter().take_while(|t| !matches!(t, Tok::Comma)).cloned().collect();
+ let p = position(c, &first)?;
+ // a lone keyword/length lands on x; for -y take it from whichever axis it went to
+ Some(if axis == 0 || matches!(first.first().and_then(Tok::ident), Some("top" | "bottom")) { p[axis] } else { p[0] })
+}
+
+/// One `background-size` component: `auto` is None.
+fn size_pos(c: &Ctx, t: &Tok) -> Option<Pos> {
+ match length(t)? {
+ Length::Percent(p) => Some(Pos { frac: p / 100.0, px: 0.0 }),
+ l => l.to_px(&c.u).map(|px| Pos { frac: 0.0, px }),
+ }
+}
+
fn pair(c: &mut Ctx, v: &[Tok], a: &str, b: &str) -> bool {
let (x, y) = match v {
[one] => (one.clone(), one.clone()),
diff --git a/bindings/rust/blenderui/src/text.rs b/bindings/rust/blenderui/src/text.rs
index baf87d1..2a3ff62 100644
--- a/bindings/rust/blenderui/src/text.rs
+++ b/bindings/rust/blenderui/src/text.rs
@@ -4,9 +4,74 @@
use crate::style::Computed;
use blenderui_sys as sys;
-/// Font flags for a style (bold / italic; decorations are painted as lines).
+/// Font flags for a style (bold / italic; decorations are painted as lines),
+/// with the font family's id above [`FAMILY_SHIFT`].
pub(crate) fn flags(c: &Computed) -> i32 {
(if c.bold() { sys::BUI_FONT_BOLD } else { 0 }) | (if c.italic { sys::BUI_FONT_ITALIC } else { 0 })
+ | ((c.font_id as i32) << FAMILY_SHIFT)
+}
+
+/// Font flags live in the low byte; the family id above it.
+pub(crate) const FAMILY_SHIFT: i32 = 8;
+
+/// Families by id (0 = the UI font, ""), leaked: canvas items point at them.
+static FAMILIES: std::sync::Mutex<Vec<&'static std::ffi::CStr>> = std::sync::Mutex::new(Vec::new());
+/// Families registered with `add_font` / `@font-face` (lowercase).
+static REGISTERED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
+
+pub(crate) fn register_family(name: &str) {
+ let mut r = REGISTERED.lock().unwrap_or_else(|e| e.into_inner());
+ let n = name.to_ascii_lowercase();
+ if !r.contains(&n) {
+ r.push(n);
+ }
+}
+
+/// The id of a `font-family` list: its first registered family, else its
+/// first generic one, else its first entry (the engine finds installed
+/// fonts by name, and falls back to the UI font). 0 = the UI font.
+pub(crate) fn font_id(list: &str) -> u16 {
+ let names: Vec<String> = list.split(',').map(|n| n.trim().trim_matches(['"', '\'']).trim().to_string())
+ .filter(|n| !n.is_empty()).collect();
+ let registered = REGISTERED.lock().unwrap_or_else(|e| e.into_inner());
+ let generic = |n: &str| match n.to_ascii_lowercase().as_str() {
+ "sans-serif" | "system-ui" | "ui-sans-serif" | "-apple-system" | "blinkmacsystemfont" | "inter" => Some(""),
+ "monospace" | "ui-monospace" => Some("monospace"),
+ "serif" | "ui-serif" => Some("serif"),
+ _ => None,
+ };
+ let pick = names.iter().find(|n| registered.contains(&n.to_ascii_lowercase())).cloned()
+ .or_else(|| names.iter().find_map(|n| generic(n)).map(str::to_string))
+ .or_else(|| names.first().cloned())
+ .unwrap_or_default();
+ drop(registered);
+ if pick.is_empty() {
+ return 0;
+ }
+ let mut f = FAMILIES.lock().unwrap_or_else(|e| e.into_inner());
+ if f.is_empty() {
+ f.push(c"");
+ }
+ if let Some(i) = f.iter().position(|c| c.to_bytes().eq_ignore_ascii_case(pick.as_bytes())) {
+ return i as u16;
+ }
+ if f.len() >= 0x7fff {
+ return 0;
+ }
+ let c = std::ffi::CString::new(pick).unwrap_or_default();
+ f.push(Box::leak(c.into_boxed_c_str()));
+ (f.len() - 1) as u16
+}
+
+/// The family name for `flags` (a static C string) and the engine's flags.
+pub(crate) fn family(flags: i32) -> (*const std::os::raw::c_char, i32) {
+ let id = (flags >> FAMILY_SHIFT) as usize;
+ let low = flags & ((1 << FAMILY_SHIFT) - 1);
+ if id == 0 {
+ return (c"".as_ptr(), low);
+ }
+ let f = FAMILIES.lock().unwrap_or_else(|e| e.into_inner());
+ (f.get(id).map_or(c"".as_ptr(), |c| c.as_ptr()), low)
}
type Widths = crate::style::FnvMap<Box<str>, f32>;
@@ -29,9 +94,10 @@ impl TextCache {
return w;
}
let mut w = 0.0f32;
- // SAFETY: pointers are valid for the call; "" selects the UI font.
+ let (fam, low) = family(flags);
+ // SAFETY: pointers are valid for the call (families are 'static).
let ok = unsafe {
- sys::BUI_text_measure(c"".as_ptr(), flags, size, s.as_ptr().cast(), s.len() as i32, &mut w)
+ sys::BUI_text_measure(fam, low, size, s.as_ptr().cast(), s.len() as i32, &mut w)
};
if ok == 0 {
w = s.chars().count() as f32 * size * 0.55; // no native text engine
diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rs
index 622c7ca..0b3beb8 100644
--- a/bindings/rust/blenderui/src/window.rs
+++ b/bindings/rust/blenderui/src/window.rs
@@ -220,6 +220,7 @@ pub struct WindowOptions {
pub struct Application {
headless: bool,
gpu: Option<bool>,
+ slug: Option<bool>,
}
impl Default for Application {
@@ -231,7 +232,7 @@ impl Default for Application {
impl Application {
/// Native windows.
pub fn new() -> Application {
- Application { headless: false, gpu: None }
+ Application { headless: false, gpu: None, slug: None }
}
/// Draw every window on the GPU (Direct3D 11 on Windows): the same
@@ -243,10 +244,19 @@ impl Application {
self
}
+ /// How the GPU renderer draws text: `true` for Slug (glyph outlines in
+ /// the pixel shader, sharp at any size), `false` for a per-glyph bitmap
+ /// atlas like Blender's (less GPU work). Defaults to the `slug` feature;
+ /// `BUI_SLUG=1`/`0` overrides. See also [`crate::set_slug`].
+ pub fn slug(mut self, on: bool) -> Application {
+ self.slug = Some(on);
+ self
+ }
+
/// Off-screen windows (tests, screenshots, CI): nothing is shown, the
/// `simulate_*` and `draw` methods drive it.
pub fn headless() -> Application {
- Application { headless: true, gpu: None }
+ Application { headless: true, gpu: None, slug: None }
}
/// Run `f`, then the event loop until every window is closed.
@@ -258,6 +268,9 @@ impl Application {
if let Some(on) = self.gpu {
unsafe { sys::BUI_gpu_set_default(on as c_int) };
}
+ if let Some(on) = self.slug {
+ crate::set_slug(on);
+ }
let mut app = App::create(headless);
f(&mut app);
app.flush();
@@ -879,6 +892,8 @@ impl Window {
let recycle = self.frame.take().unwrap_or_default();
let frame = layout(root, vp, &self.state, &mut self.caches, recycle,
&mut |key, spec| widgets.ensure(canvas, key, spec, scale));
+ // `@container`: sizes changed under a query: render once more
+ let container_changed = self.caches.after_layout(&frame);
let p = &mut self.painter;
p.reset();
{
@@ -914,6 +929,9 @@ impl Window {
prof::frame_done();
// state of components that didn't render is freed; effects run now
crate::hooks::end();
+ if container_changed {
+ self.dirty = true;
+ }
}
// -- events ------------------------------------------------------------------------------
diff --git a/bindings/rust/blenderui/tests/hooks.rs b/bindings/rust/blenderui/tests/hooks.rs
index 8c7094b..9e7a87c 100644
--- a/bindings/rust/blenderui/tests/hooks.rs
+++ b/bindings/rust/blenderui/tests/hooks.rs
@@ -111,3 +111,67 @@ fn hooks_state_effects_context() {
assert!(has(cx, "alice-liked"), "Alice kept hers");
});
}
+
+// optional props: `note` may be left out in markup
+#[component]
+fn Row(name: &str, note: Option<String>) {
+ let (n, set_n) = use_state(0usize);
+ let note = note.unwrap_or_default();
+ rsx! {
+ <div id={name.to_string()} class="h-2" onClick={move || set_n(n() + 1)} data-note={note}>
+ {if n() > 0 { <div id={format!("{name}-clicked-{}", n())} class="h-1" /> }}
+ </div>
+ }
+}
+
+struct List {
+ items: Vec<&'static str>,
+ keyed: bool,
+}
+
+impl Render for List {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ let keyed = self.keyed;
+ rsx! {
+ <body style="margin: 0">
+ {for name in self.items.clone() {
+ if keyed {
+ rsx! { <Row key={name} name={name} /> }.into_any_element()
+ } else {
+ rsx! { <Row name={name} note={"plain".to_string()} /> }.into_any_element()
+ }
+ }}
+ </body>
+ }
+ }
+}
+
+#[test]
+fn keys_and_optional_props() {
+ for keyed in [true, false] {
+ Application::headless().run(|cx| {
+ let win = cx.open_window(WindowOptions::default(), |_, cx| {
+ cx.new(|_| List { items: vec!["a", "b", "c"], keyed })
+ }).unwrap();
+ let id = win.id;
+ cx.draw(id);
+ let b = cx.element_bounds(id, "b").unwrap();
+ cx.simulate_click(id, b.origin.x + 2.0, b.origin.y + 1.0);
+ cx.draw(id);
+ assert!(cx.element_bounds(id, "b-clicked-1").is_some());
+ // remove "a": with keys, b keeps its state; without, state follows position
+ win.root().update(cx, |l, cx| {
+ l.items.remove(0);
+ cx.notify();
+ });
+ cx.draw(id);
+ let b_kept = cx.element_bounds(id, "b-clicked-1").is_some();
+ let c_got = cx.element_bounds(id, "c-clicked-1").is_some();
+ if keyed {
+ assert!(b_kept && !c_got, "keyed: state follows the key");
+ } else {
+ assert!(!b_kept && c_got, "unkeyed: state follows the position (React semantics)");
+ }
+ });
+ }
+}
diff --git a/bindings/rust/blenderui/tests/modern_css.rs b/bindings/rust/blenderui/tests/modern_css.rs
index ecf795d..88f9fa2 100644
--- a/bindings/rust/blenderui/tests/modern_css.rs
+++ b/bindings/rust/blenderui/tests/modern_css.rs
@@ -288,3 +288,100 @@ fn tailwind_classes() {
assert_eq!(rect(cx, w, "f1").3, 4.0, "[&>*]: arbitrary variant");
});
}
+
+/// A page whose stylesheet is built at run time.
+struct DynPage {
+ css: String,
+ body: fn() -> Div,
+}
+
+impl Render for DynPage {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ (self.body)().child(style().child(self.css.clone()))
+ }
+}
+
+/// A 2x1 PNG: red, blue (for image placement checks).
+fn tile_png() -> String {
+ let path = std::env::temp_dir().join("bui_test_tile.png");
+ let f = std::fs::File::create(&path).unwrap();
+ let mut e = png::Encoder::new(f, 2, 1);
+ e.set_color(png::ColorType::Rgba);
+ e.set_depth(png::BitDepth::Eight);
+ e.write_header().unwrap().write_image_data(&[255, 0, 0, 255, 0, 0, 255, 255]).unwrap();
+ path.to_string_lossy().replace('\\', "/")
+}
+
+#[test]
+fn property_initial_logical_borders_container_queries() {
+ Application::headless().run(|cx| {
+ let w = page(cx, 600.0, 300.0, "
+ @property --size { syntax: '<length>'; inherits: false; initial-value: 40px }
+ body { margin: 0 }
+ #p { width: var(--size); height: 5px }
+ #lb { box-sizing: content-box; width: 10px; height: 10px;
+ border-inline-style: solid; border-inline-width: 3px 5px;
+ border-block-start-width: 2px; border-block-start-style: solid }
+ .wide { container-type: inline-size; width: 300px }
+ .narrow { container: side / inline-size; width: 100px }
+ .cq { width: 10px; height: 5px }
+ @container (min-width: 200px) { .cq { width: 50px } }
+ @container side (max-width: 150px) { .cq { width: 20px } }
+ ", || {
+ body()
+ .child(div().id("p"))
+ .child(div().id("lb"))
+ .child(div().class("wide").child(div().class("cq").id("cq1")))
+ .child(div().class("narrow").child(div().class("cq").id("cq2")))
+ });
+ assert_eq!(rect(cx, w, "p").2, 40.0, "@property initial-value");
+ let lb = rect(cx, w, "lb");
+ assert_eq!((lb.2, lb.3), (18.0, 12.0), "logical border longhands");
+ cx.draw(w);
+ assert_eq!(rect(cx, w, "cq1").2, 50.0, "@container (min-width: 200px)");
+ assert_eq!(rect(cx, w, "cq2").2, 20.0, "named @container");
+ });
+}
+
+#[test]
+fn object_fit_and_background_images() {
+ let png = tile_png();
+ Application::headless().run(|cx| {
+ let css = format!("
+ body {{ margin: 0; background: #000 }}
+ #img {{ width: 100px; height: 100px; object-fit: contain; display: block }}
+ #bg {{ width: 40px; height: 40px; background: url('{png}') no-repeat right bottom / 20px 10px }}
+ #rep {{ width: 40px; height: 4px; background-image: url('{png}'); background-size: 4px 4px }}
+ ");
+ fn body_fn() -> Div {
+ let png = std::env::temp_dir().join("bui_test_tile.png").to_string_lossy().replace('\\', "/");
+ body().child(img().id("img").src(png)).child(div().id("bg")).child(div().id("rep"))
+ }
+ let win = open(cx, 200.0, 200.0, DynPage { css, body: body_fn });
+ let (pw, _, px) = cx.draw(win.id);
+ let at = |x: usize, y: usize| px[y * pw + x] & 0xffffff;
+ // contain: a 2:1 image in 100x100 is 100x50, centred (rows 25..75)
+ assert_eq!(at(25, 10), 0x000000, "letterbox above");
+ assert_eq!(at(25, 50), 0xff0000, "left half red");
+ assert_eq!(at(75, 50), 0x0000ff, "right half blue");
+ // background: 20x10 at the bottom right of the 40x40 box (y 100..140)
+ assert_eq!(at(5, 105), 0x000000);
+ assert_eq!(at(25, 135), 0xff0000);
+ assert_eq!(at(35, 135), 0x0000ff);
+ // repeated 4px tiles across 40px: red, blue alternating every 2px
+ assert_eq!(at(1, 141), 0xff0000);
+ assert_eq!(at(3, 141), 0x0000ff);
+ assert_eq!(at(37, 141), 0xff0000, "tile 36..40: red half");
+ assert_eq!(at(39, 141), 0x0000ff, "tile 36..40: blue half");
+ });
+}
+
+#[test]
+fn css_aliases_parse() {
+ use blenderui::style::is_supported;
+ for p in ["text-wrap-mode", "white-space-collapse", "scale", "border-block-color", "overscroll-behavior-x",
+ "scroll-margin-top", "font-variant-numeric", "mask-image", "container-type", "background-position-x",
+ "all"] {
+ assert!(is_supported(p), "{p}");
+ }
+}
diff --git a/bindings/rust/blenderui/tests/rsx.rs b/bindings/rust/blenderui/tests/rsx.rs
index 7378c55..76f765c 100644
--- a/bindings/rust/blenderui/tests/rsx.rs
+++ b/bindings/rust/blenderui/tests/rsx.rs
@@ -3,6 +3,7 @@
use blenderui::prelude::*;
/// A component: a struct with props and children.
+#[derive(Props)]
struct Card {
title: SharedString,
children: Vec<AnyElement>,
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 62785a5..5ab25a0 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -31,6 +31,7 @@ cmake --build build
| `BUI_BUILD_UI` | `OFF` | Compile Blender's original `ui/` sources as well (not needed for the kit) |
| `BUI_BUILD_QT_BACKEND` | `OFF` | The C++ Qt/QPainter render-sink backend (needs Qt 5/6 Widgets) |
| `BUI_WARNINGS_AS_ERRORS` | `OFF` | `-Werror` / `/WX` |
+| `BUI_SLUG` | `ON` | GPU text from glyph outlines (Slug) by default; `OFF` makes the glyph atlas the default (switchable at run time either way) |
| `BUI_TEXT_GDI` | `OFF` | Use Windows' GDI text engine and system fonts instead of the portable engine (embedded Inter, Slug on the GPU) |
## 2. Use it from Python
@@ -83,7 +84,7 @@ shared (`bui.host`).
| `BUI_GPU=1` | Draw native windows on the GPU (Direct3D 11). `BUI_GPU=0` forces the software raster. Overrides `bui.set_gpu()` / `.gpu(true)` |
| `BUI_GPU_DEBUG=1` | Print why the GPU renderer could not start |
| `BUI_FONT`, `BUI_FONT_DIR` | A font file to replace the embedded Inter UI font, and an extra font folder |
-| `BUI_SLUG` | `0` draws GPU text from a per-glyph bitmap atlas instead of glyph outlines (Slug) |
+| `BUI_SLUG` | `0` draws GPU text from a per-glyph bitmap atlas instead of glyph outlines (Slug); `1` forces Slug. Overrides `bui.set_slug()` / `.slug()` / `BUI_gpu_set_slug()` |
| `BUI_PROFILE=1` | Print per-phase frame times (raster and present) |
## Window hosts
@@ -110,6 +111,16 @@ Native windows draw on the CPU by default. To draw them on the GPU
| C | `BUI_gpu_set_default(1)` or `BK_window_set_gpu(win, 1)` |
| Any app, no code change | `BUI_GPU=1` |
+GPU text is drawn with Slug (from glyph outlines, sharp at any size) or from
+a per-glyph bitmap atlas like Blender's (about half the GPU work):
+
+| Where | Slug (default) / atlas |
+|---|---|
+| Python | `bui.set_slug(True)` / `bui.set_slug(False)` |
+| Rust | `Application::new().slug(..)`, `blenderui::set_slug(..)`, or build without the default `slug` feature |
+| C | `BUI_gpu_set_slug(1 / 0)`, or CMake `-DBUI_SLUG=OFF` for the atlas by default |
+| Any app | `BUI_SLUG=1` / `BUI_SLUG=0` |
+
Both renderers draw the same pixels. The GPU uses far less CPU per frame
(about 2-4x less in the
[benchmark](../bindings/rust/bench/README.md)), but the process needs about
diff --git a/docs/rust.md b/docs/rust.md
index 69935e0..d8072fb 100644
--- a/docs/rust.md
+++ b/docs/rust.md
@@ -121,7 +121,7 @@ The lowering is uniform, so the whole API is reachable without special cases:
- `name="text"` sets an HTML attribute, except `class`, `style` and `id`, which call their methods.
- `name={expr}` calls the builder method of that name: `w={px(10.)}`, `hover={|s| s.bg(red())}`.
- `onClick` becomes `.on_click`, and closures may omit the `(event, window, cx)` parameters.
-- **Components:** an uppercase tag builds a struct, so `<Card title="x">..</Card>` becomes `Card { title: "x".into(), children: .. }`.
+- **Components:** a component tag builds its props through a builder, so `<Card title="x">..</Card>` becomes `Card::__builder().title("x").children(..)`. `#[component]` generates the builder; a hand-written struct component needs `#[derive(Props)]`. `key={..}` on any component ties its hook state to the key.
- **Fragments:** `<>..</>` is a `display: contents` wrapper.
Tailwind utilities can also be written as bare attributes (UnoCSS calls this "attributify"). They become classes at compile time:
@@ -198,12 +198,13 @@ These are the hooks and their counterparts in other frameworks:
How it behaves:
- **Signals:** signals are `Copy` handles. They don't need `cx`, and writing one re-renders its window.
-- **Hook identity:** like React, a hook's state is tied to its call site and to the order in which components render. Removing a component from the middle of a list shifts the state of the components after it.
+- **Hook identity:** like React, a hook's state is tied to its call site and to the order in which components render. In lists, give components a `key` (`<Row key={item.id} ../>`) so their state follows the item: without keys, removing an item from the middle shifts the state of the ones after it.
- **Components:** `#[component]` turns `fn name(props)` into a props struct with that name. Uppercase and lowercase names both work in `rsx!`, as does a body that ends in markup.
+- **Optional props:** `Option<T>` props (and `children`) may be left out in `rsx!`; they are `None`. Leaving out any other prop is a compile error naming it (`a required prop is missing: ... Row_missing_name`). Struct components get the same with `#[derive(Props)]`.
- **Lifetime:** a component's state is freed when it stops rendering.
- **Implementation:** there is no `Rc` or `RefCell` anywhere in it.
-Not supported yet: optional props (pass every prop; use `Option<T>` for optional values), async resources (`use_resource`) and generic components.
+Not supported yet: async resources (`use_resource`) and generic components.
## Elements
@@ -410,9 +411,9 @@ From `cargo test --test parity -- --nocapture`:
| Area | Coverage |
| ------------------------------------- | -------------------------------------------------------------------------------- |
| HTML elements (WHATWG index) | **113 / 113** constructible, plus `svg` / `math` roots; 9 are Blender widgets |
-| CSS properties | **180** change layout or rendering; **81** more parse but have no effect |
-| W3C property index (745 properties) | **176** rendered (24%), **75** parsed without effect (10%), **494** not recognized (66%): most of these are drafts, speech, paged media and SVG |
-| CSS 2.1, screen properties | **80 / 90** rendered, 90 / 90 parsed |
+| CSS properties | **210** change layout or rendering; **185** more parse but have no effect |
+| W3C property index (745 properties) | **207** rendered (28%), **177** parsed without effect (24%), **361** not recognized (48%): most of these are drafts, speech, paged media and SVG |
+| CSS 2.1, screen properties | **82 / 90** rendered, 90 / 90 parsed |
| Flexbox | **12 / 12** |
| Grid | **23 / 23** (including `grid-template-areas` and named lines) |
| Tailwind CSS v4 | Classes compile on first use (v4 theme, variants, arbitrary values); `tw!` checks them at compile time |
@@ -428,18 +429,20 @@ div().class(tw!("grid grid-cols-3 gap-4 md:grid-cols-6 hover:bg-sky-500/50"))
div().style("width: calc(100% - 2 * var(--gap)); background: color-mix(in oklch, var(--brand) 60%, white)")
```
-The CSS 2.1 properties that parse without effect: `clip`, `counter-increment`, `counter-reset`, `empty-cells`, `table-layout`, `unicode-bidi`, `list-style-image` and `background-attachment` / `-position` / `-repeat` (there are no background images; gradients are supported).
+The CSS 2.1 properties that parse without effect: `clip`, `counter-increment`, `counter-reset`, `empty-cells`, `table-layout`, `unicode-bidi`, `list-style-image` and `background-attachment`.
+
+Also supported: `background-image: url()` (PNG) with `background-size` / `-position` (`-x` / `-y`) / `-repeat`, `object-fit` / `object-position`, logical border longhands (`border-inline-width` ...), `text-wrap-mode`, `white-space-collapse`, `scale`, `all`, `@container` size queries (`container-type`, `container-name`), `@font-face` (local font files) and `@property` initial values.
How much is left, against all 745 properties in the
[W3C index](https://www.w3.org/Style/CSS/all-properties.en.html):
| | Properties | Share |
|---|---:|---:|
-| Change layout or rendering | 176 | 24% |
-| Parsed, no effect yet | 75 | 10% |
-| Not recognized | 494 | 66% |
+| Change layout or rendering | 207 | 28% |
+| Parsed, no effect yet | 177 | 24% |
+| Not recognized | 361 | 48% |
-The 494 unrecognized properties break down as:
+The 361 unrecognized properties break down as:
| Group | Properties |
|---|---:|
@@ -449,19 +452,18 @@ The 494 unrecognized properties break down as:
| Speech and aural | 31 |
| Animation triggers and scroll-driven animation | 26 |
| Paged media, regions, rhythm and others | ~25 |
-| Scroll snap margins and padding | 23 |
-| Masking | 18 |
-| Everything else | ~215 |
+| Everything else | ~100 |
The everyday screen CSS is much further along: Flexbox 12/12, Grid 23/23 and
-CSS 2.1 80/90. The largest remaining gaps among common properties are visual
-effects (transforms, filters, blend modes, `clip-path`), animations and
-transitions, and background images.
+CSS 2.1 82/90. The largest remaining gaps among common properties are visual
+effects (transforms, filters, blend modes, `clip-path`, masks) and
+animations and transitions.
Not done yet:
-- **Parsed, not applied:** `@container` (queries parse, no container sizes yet), `@font-face`, `@keyframes`, transitions and animations.
+- **Parsed, not applied:** `@keyframes`, transitions and animations; scroll snapping and OpenType font features.
+- **`@container` timing:** queries use the container's size from the previous layout; when it changes, the window renders once more.
- **Rendering effects:** 2D/3D `rotate` / `skew` transforms, `filter` / `backdrop-filter`, blend modes, `clip-path`, masks, `border-image` and border styles other than solid.
-- **The rest of the W3C property index:** about 490 entries this engine doesn't know, mostly drafts, speech and paged media.
+- **The rest of the W3C property index:** about 360 entries this engine doesn't know, mostly drafts, speech, paged media and SVG.
- **Box sizing:** the default is `border-box` (like Tailwind's preflight), not CSS's `content-box`.
## Performance vs gpui
@@ -516,16 +518,24 @@ blenderui::add_font("Brand", false, false, include_bytes!("Brand-Regular.ttf"));
With `.gpu(true)`, glyphs are drawn straight from their outlines using
Eric Lengyel's [Slug](https://github.com/EricLengyel/Slug) algorithm: one
quad per glyph, exact coverage computed in the pixel shader, and no glyph
-bitmaps. `BUI_SLUG=0` switches to a per-glyph bitmap atlas (Blender's
-approach) instead. The `gdi-text` feature uses Windows' GDI engine and
-system fonts.
+bitmaps. The alternative is a per-glyph bitmap atlas (Blender's approach):
+about half the GPU work, but bitmaps per size. Choose with:
+
+| | Slug (default) | Glyph atlas |
+|---|---|---|
+| Build time | `slug` feature (default) | `default-features = false` |
+| Run time | `Application::new().slug(true)` / `blenderui::set_slug(true)` | `.slug(false)` / `set_slug(false)` |
+| Environment (overrides) | `BUI_SLUG=1` | `BUI_SLUG=0` |
+
+The `gdi-text` feature uses Windows' GDI engine and system fonts.
## Limitations
- **Floats** place block boxes, but text does not wrap around them; `direction: rtl`
lays boxes out right to left, but text itself is not shaped right to left.
-- **One font face**: the UI font in regular, bold and italic. `font-family`
- is parsed but `monospace` text uses the UI font.
+- **Fonts**: `font-family` picks a face per element (registered, `@font-face`,
+ installed or generic `monospace` / `serif`); there is no per-glyph fallback
+ between faces of a list.
- **Effects and animation**: see "Not done yet" under [Coverage](#coverage).
- **Transforms**: `translate` only; `scale()` and `rotate()` are ignored.
- **Inline boxes** paint their background per word; borders and padding on
diff --git a/docs/tkinter.md b/docs/tkinter.md
index 0ba2574..a9845f8 100644
--- a/docs/tkinter.md
+++ b/docs/tkinter.md
@@ -93,7 +93,8 @@ root = tk.Tk(gpu=True)
The pixels are the same, but rendering uses far less CPU, which helps busy
`Canvas` scenes most. For apps you run unchanged
(`python -m bui.tksyntax app.py`), set `BUI_GPU=1` instead, or call
-`bui.set_gpu(True)` before the first `Tk()`. The first frames draw on the
+`bui.set_gpu(True)` before the first `Tk()` (and `bui.set_slug(False)` for
+the glyph-atlas text path instead of Slug). The first frames draw on the
CPU while the device starts. If no GPU is available, the window stays on
the software raster.
diff --git a/gpu/CMakeLists.txt b/gpu/CMakeLists.txt
index 6d29f8a..2ef9e8b 100644
--- a/gpu/CMakeLists.txt
+++ b/gpu/CMakeLists.txt
@@ -28,6 +28,10 @@ endif()
# ClearType-style hinting, no Slug). BUI_TEXT_STB is kept as a no-op.
option(BUI_TEXT_GDI "Use the native GDI text engine on Windows" OFF)
option(BUI_TEXT_STB "Deprecated: the portable engine is the default" ON)
+# GPU text: Slug (glyph outlines in the pixel shader) or the per-glyph atlas.
+# Runtime: BUI_gpu_set_slug() / BUI_SLUG=1|0; this sets the default.
+option(BUI_SLUG "GPU renderer draws text with Slug by default (else a glyph atlas)" ON)
+target_compile_definitions(bui_gpu PRIVATE BUI_SLUG_DEFAULT=$<BOOL:${BUI_SLUG}>)
if(BUI_TEXT_GDI)
target_compile_definitions(bui_gpu PRIVATE BUI_TEXT_GDI=1)
endif()
diff --git a/gpu/include/GPU_raster.h b/gpu/include/GPU_raster.h
index 38799c5..88da064 100644
--- a/gpu/include/GPU_raster.h
+++ b/gpu/include/GPU_raster.h
@@ -212,6 +212,12 @@ int BUI_raster_is_gpu(const BuiRaster *r);
* BUI_GPU environment variable (1/0). Off by default. */
void BUI_gpu_set_default(int on);
int BUI_gpu_default(void);
+/* How the GPU renderer draws text: 1 = Slug (glyph outlines evaluated in the
+ * pixel shader; sharp at any size), 0 = per-glyph bitmap atlas (Blender's
+ * approach; less GPU work). Takes effect on the next frame. Default: the
+ * BUI_SLUG build option (ON), overridden by the BUI_SLUG variable (1/0). */
+void BUI_gpu_set_slug(int on);
+int BUI_gpu_slug(void);
/* A BuiGpuSink that renders into `r` (user pointer is the raster). */
const BuiGpuSink *BUI_raster_sink(BuiRaster *r);
diff --git a/gpu/intern/gpu_d3d11.c b/gpu/intern/gpu_d3d11.c
index c2a0b4d..d2e3c9d 100644
--- a/gpu/intern/gpu_d3d11.c
+++ b/gpu/intern/gpu_d3d11.c
@@ -618,10 +618,8 @@ static int slug_tex(BuiGpu *g, DXGI_FORMAT fmt, ID3D11Texture2D **r_tex,
int bui_gpu_slug_on(BuiGpu *g)
{
if (g->slug == 0) {
- const char *env = getenv("BUI_SLUG");
g->slug = -1;
- if (!(env && env[0] == '0') &&
- slug_tex(g, DXGI_FORMAT_R32G32B32A32_FLOAT, &g->curve_tex, &g->curve_srv) &&
+ if (slug_tex(g, DXGI_FORMAT_R32G32B32A32_FLOAT, &g->curve_tex, &g->curve_srv) &&
slug_tex(g, DXGI_FORMAT_R32G32_UINT, &g->band_tex, &g->band_srv) &&
(g->slug_map = (SlugGlyph *)calloc(SLUG_MAP, sizeof(SlugGlyph))) != NULL)
{
diff --git a/gpu/intern/gpu_d3d11.h b/gpu/intern/gpu_d3d11.h
index b24d9d3..b6f8266 100644
--- a/gpu/intern/gpu_d3d11.h
+++ b/gpu/intern/gpu_d3d11.h
@@ -56,8 +56,9 @@ BuiGpuInst *bui_gpu_inst(BuiGpu *g, int kind, int x0, int y0, int x1, int y1);
* Returns 0 when it can't be placed. */
int bui_gpu_mask(BuiGpu *g, const void *key, unsigned gen, const uint8_t *mask, int w, int h,
int *r_x, int *r_y);
-/* Slug text (Eric Lengyel's algorithm): 1 when glyph outlines are
- * rendered on the GPU (default; BUI_SLUG=0 turns it off). */
+/* Slug text (Eric Lengyel's algorithm): 1 when this device can render
+ * glyph outlines (creates the curve/band textures on first call). Whether
+ * it is used is BUI_gpu_slug(). */
int bui_gpu_slug_on(BuiGpu *g);
/* Curve/band data for glyph `glyph` of font face `face` (uploaded on first
* use): its box in font units, the band transform (instance c1) and its
diff --git a/gpu/intern/gpu_raster.c b/gpu/intern/gpu_raster.c
index 3c48eb9..e09cb2c 100644
--- a/gpu/intern/gpu_raster.c
+++ b/gpu/intern/gpu_raster.c
@@ -239,6 +239,25 @@ int BUI_gpu_default(void)
return g_gpu_default > 0;
}
+#ifndef BUI_SLUG_DEFAULT
+# define BUI_SLUG_DEFAULT 1
+#endif
+static int g_slug = -1;
+
+void BUI_gpu_set_slug(int on)
+{
+ g_slug = on ? 1 : 0;
+}
+
+int BUI_gpu_slug(void)
+{
+ const char *env = getenv("BUI_SLUG");
+ if (env && env[0]) {
+ return env[0] == '1' || env[0] == 'y' || env[0] == 'Y' || env[0] == 't' || env[0] == 'T';
+ }
+ return g_slug >= 0 ? g_slug : BUI_SLUG_DEFAULT;
+}
+
int BUI_raster_gpu_attach(BuiRaster *r, void *window_handle, int wait)
{
if (r->gpu || r->gpu_pending) {
@@ -1962,7 +1981,7 @@ static int gpu_text_glyphs(BuiRaster *r, TextRun *e, float x, float y, const flo
}
const FontSlot *fs = &g_fonts[e->font];
const float ox = floorf(x + 0.5f), base = floorf(y + 0.5f);
- const int slug = bui_gpu_slug_on(r->gpu);
+ const int slug = BUI_gpu_slug() && bui_gpu_slug_on(r->gpu);
const int passes = embolden > 0.0f ? 1 + (int)(embolden + 0.5f) : 1; /* synthetic bold */
for (int i = 0; i < e->ng; i++) {
const float pen = ox + e->gx[i];
@@ -2543,7 +2562,12 @@ static int face_find(const char *family, int style, int *r_have)
/* 1. registered fonts: exact style, then any style of the family */
for (int pass = 0; pass < 2; pass++) {
for (int i = 0; i < g_reg_count; i++) {
- if ((ieq(g_regs[i].family, family) || (!family[0] && i == 0)) &&
+# ifdef BUI_NO_INTER
+ const int default_face = !family[0] && i == 0; /* no embedded UI font */
+# else
+ const int default_face = 0;
+# endif
+ if ((ieq(g_regs[i].family, family) || default_face) &&
(pass == 1 || g_regs[i].style == style))
{
*r_have = g_regs[i].style;
diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.h
index f6419a1..d56cb96 100644
--- a/kit/include/BUI_kit.h
+++ b/kit/include/BUI_kit.h
@@ -215,6 +215,8 @@ typedef struct BKCanvasItem {
int text_flags; /* BUI_FONT_BOLD | ITALIC | UNDERLINE */
int clip_on; /* clip the item to `clip` (x, y, w, h in canvas space) */
float clip[4];
+ const char *family; /* text font family; NULL = the UI font. Not copied:
+ it must outlive the item (e.g. a static string) */
} BKCanvasItem;
void BK_canvas_set_item(BKNode *canvas, const BKCanvasItem *item); /* insert or replace by id */
void BK_canvas_add_item(BKNode *canvas, const BKCanvasItem *item);
diff --git a/kit/intern/kit_frame.c b/kit/intern/kit_frame.c
index 4a10854..84e0dd6 100644
--- a/kit/intern/kit_frame.c
+++ b/kit/intern/kit_frame.c
@@ -917,7 +917,7 @@ static bool citem_bbox(const CItem *ci, float b[4])
}
const float size = it->size > 0 ? it->size : bk_font_size();
float tw = 0;
- BUI_text_measure("", it->text_flags, size, ci->text, (int)strlen(ci->text), &tw);
+ BUI_text_measure(it->family ? it->family : "", it->text_flags, size, ci->text, (int)strlen(ci->text), &tw);
const float x = p[0] - anchor_off(it->anchor, (int)tw, BK_ANCHOR_W, BK_ANCHOR_E);
const float asc = size * 0.72f;
const float base = p[1] + asc - anchor_off(it->anchor, (int)asc, BK_ANCHOR_N, BK_ANCHOR_S);
@@ -1216,7 +1216,7 @@ static void canvas_item_draw(BuiRaster *r, const CItem *ci, float ox, float oy,
const int len = (int)strlen(ci->text);
float tw = 0;
if (!(it->anchor & BK_ANCHOR_W)) { /* the width only moves centred / right text */
- BUI_text_measure("", it->text_flags, size, ci->text, len, &tw);
+ BUI_text_measure(it->family ? it->family : "", it->text_flags, size, ci->text, len, &tw);
}
float x = ox + p[0], y = oy + p[1];
x -= anchor_off(it->anchor, (int)tw, BK_ANCHOR_W, BK_ANCHOR_E);
@@ -1228,7 +1228,7 @@ static void canvas_item_draw(BuiRaster *r, const CItem *ci, float ox, float oy,
BUI_raster_text_run(r, prep->tx, prep->ty, prep->run, c);
}
else {
- BUI_raster_set_font(r, "", it->text_flags);
+ BUI_raster_set_font(r, it->family ? it->family : "", it->text_flags);
BUI_raster_text(r, floorf(x + 0.5f), floorf(y + 0.5f), ci->text, len, size, c);
}
break;
@@ -1326,7 +1326,7 @@ static bool item_prepare(const CItem *ci, float ox, float oy, ItemPrep *pp)
if (it->type == BK_ITEM_TEXT && ci->text && it->ncoords >= 2) {
const float size = it->size > 0 ? it->size : bk_font_size();
float tw = 0;
- pp->run = BUI_text_prepare("", it->text_flags, size, ci->text, (int)strlen(ci->text), &tw);
+ pp->run = BUI_text_prepare(it->family ? it->family : "", it->text_flags, size, ci->text, (int)strlen(ci->text), &tw);
float x = ox + p[0], y = oy + p[1];
x -= anchor_off(it->anchor, (int)tw, BK_ANCHOR_W, BK_ANCHOR_E);
const float asc = size * 0.72f;