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: optimization for perf

Preetham Pemmasani59e12ed2c409
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e6a6179..518e173 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,13 +29,43 @@ All notable changes to **blenderui** (BUI). The format follows
`presented_frames`, and `BUI_PROFILE=1` per-phase timings.
- `bindings/rust/bench`: blenderui vs gpui vs gpui-fast benchmark (FPS, CPU, GPU, RAM).
+- Rust: `css!` (crate `blenderui-macros`) checks CSS blocks at compile time;
+ `.style()` takes its output or run-time text.
+
+### Changed
+- Rust: no `Rc` / `RefCell`. Frames are index-linked arenas reused across
+ frames, styles live in a per-window store, listeners are owned `Box`es.
+ `Entity<T>` is a `Copy` handle into an app-owned slot map: `read`
+ returns `&T`, `WeakEntity::upgrade` became `upgrade_in(cx)`, and
+ `cx.release(entity)` drops a value. Elements are no longer `Clone`.
+- Rust: style methods resolve property names at compile time (a `const`
+ property table) and build typed values without formatting or parsing.
+
### Performance
+- Kit canvas (tkinter, Qt, Rust): every item type rasterizes in parallel
+ (lines, arcs and outlines included); item edits redraw only the item's old
+ and new boxes; items are found by id through a hash index; replacing an
+ item reuses its buffers. tkinter: 2000 items, one moving: 9.4 → 0.08 ms
+ render per frame; all moving: 11.1 → 3.6 ms.
+- tkinter facade: colors parsed once; lines delete only arrowheads they made.
+- Rust: frame-to-frame reuse: selector matches memoized by element
+ fingerprint, a persistent taffy tree reconciled by key (unchanged subtrees
+ keep their cached layout). 3000 elements of which one changes: 42 % less
+ CPU per frame than when all change.
+- Rust: fewer allocations: 32-byte tokens, smaller elements with inline
+ children, reused painter / text buffer / layout scratch, stack-backed
+ small lists.
- Fill-only rounded canvas rects use the span-filling rounded-rect routine
(about 2.5× faster).
- Left-anchored canvas text is no longer measured before drawing.
- Rust crate: style sharing between identical elements, interned and typed
CSS values, an indexed stylesheet, allocation-free text measuring.
- Animating 3000 elements went from 12 to about 33 fps (same session: gpui-fast 0.1.13 29.7 fps, gpui 0.2.2 22.8 fps).
+ Animating 3000 elements went from 12 to about 50 fps, at 29 ms CPU per
+ frame (from 40).
+- Lone text runs fold into their box as one layout leaf. Canvas raster
+ threads adapt to the frame deadline, items are bucketed by band, and
+ `BK_canvas_put_item` / `BK_canvas_truncate` update a canvas in place
+ (the latter invalidates once).
### Changed
- The C sources build with MSVC (`/utf-8`, no `typeof` / `[[nodiscard]]`
diff --git a/README.md b/README.md
index c30faa9..41cfd4f 100644
--- a/README.md
+++ b/README.md
@@ -45,7 +45,7 @@ Right: an unmodified tkinter program (<code>examples/tk_unchanged_app.py</code>)
- [Blender components](#blender-components)
- [Rust (gpui syntax, HTML and CSS)](#rust-gpui-syntax-html-and-css)
- [How it works](#how-it-works)
-- [Performance](#performance)
+- [Performance](#performance) (including [blenderui vs gpui](#rust-blenderui-vs-gpui))
- [Roadmap: more languages and platforms](#roadmap-more-languages-and-platforms)
- [Packaging](#packaging)
- [Documentation](#documentation)
@@ -77,7 +77,7 @@ Right: an unmodified tkinter program (<code>examples/tk_unchanged_app.py</code>)
| Component library (`bui.components`) | ✅ Working | 45 Blender components, including editors (color ramp, curves) and templates |
| C++ / Qt render-sink backends | ✅ Working | For embedding BUI drawing into your own renderer ([INTEGRATION.md](INTEGRATION.md)) |
| Packaging (`pip install blenderui`) | ✅ Published | [`blenderui` 0.1.0 on PyPI](https://pypi.org/project/blenderui/): a prebuilt wheel for Windows / CPython 3.12, and a source package that other platforms compile on install (needs CMake and a C compiler). Prebuilt wheels for all platforms come from CI on the next tagged release ([docs/publishing.md](docs/publishing.md)) |
-| **Rust** (`blenderui` crate) | ✅ **Working** | gpui syntax (`Render`, `Context`, `Entity`, `cx.listener`, ~1,300 `Styled` methods) over **113/113 HTML elements** and CSS: **173 properties rendered** (+87 parsed without effect), CSS 2.1 screen properties 76/90 rendered (90/90 parsed), Flexbox 12/12, Grid 22/23. Layout by [taffy](https://github.com/DioxusLabs/taffy). Native window on Windows, headless rendering everywhere. Fastest in a 3000-element full-animation benchmark: 32.6 fps vs gpui-fast 29.7 and gpui 22.8, with about half their memory ([benchmark](bindings/rust/bench/README.md)). [docs/rust.md](docs/rust.md) |
+| **Rust** (`blenderui` crate) | ✅ **Working** | gpui syntax (`Render`, `Context`, `Entity`, `cx.listener`, ~1,300 `Styled` methods) over **113/113 HTML elements** and CSS: **173 properties rendered** (+87 parsed without effect), CSS 2.1 screen properties 76/90 rendered (90/90 parsed), Flexbox 12/12, Grid 22/23. Layout by [taffy](https://github.com/DioxusLabs/taffy). Native window on Windows, headless rendering everywhere. Animating 3000 elements: 57.5 fps on 27 ms CPU per frame (same session: gpui-fast 50.5 fps, gpui 18.9 fps), with about half their memory and a 6 ms first frame ([benchmark](bindings/rust/bench/README.md)). [docs/rust.md](docs/rust.md) |
| **egui integration** | 🗺️ Planned | BUI panels drawn inside egui (raster → `egui::TextureHandle`, input forwarded) and a Blender-styled `egui::Visuals` theme. Builds on the Rust crate |
| **WebAssembly build** | 🗺️ Planned | The kit compiled with Emscripten: the raster blits to `<canvas>` (damage rectangles only), DOM events feed `BK_press` / `BK_key` |
| **React** (`@blenderui/react`) | 🗺️ Planned | A JSX reconciler over the WASM build (`<Panel>`, `<NumberSlider>` ...); `@blenderui/web` for plain JS/TS, N-API for Node |
@@ -315,6 +315,45 @@ Measured on the full component demo (520×900) on a desktop CPU:
The test suite enforces a 120 Hz budget: full frames under 8.3 ms, and
interaction frames under 1 ms.
+### Rust: blenderui vs gpui
+
+The same UI built with the `blenderui` crate and with
+[gpui](https://crates.io/crates/gpui) 0.2.2 (Zed's GPU-rendered framework): a
+1000×800 window of N rounded, labelled cells that all change every frame.
+Ryzen 7 5800U laptop on mains power, 60 Hz display, release builds, both apps
+in the same session, median of 3 runs
+([method and full data](bindings/rust/bench/README.md)).
+
+| | blenderui | gpui |
+|---|---:|---:|
+| FPS, 3000 animated cells | **57.5** | 18.9 |
+| FPS, 1000 / 100 animated cells | 60 / 60 (display cap; 157 / 529 uncapped) | 60 / 60 |
+| CPU per frame, 3000 cells | **27.3 ms** | 53.1 ms + GPU |
+| CPU per frame, 1000 cells | **13.7 ms** | 14.7 ms + GPU |
+| CPU per frame, 100 cells | 5.1 ms | **3.4 ms** + GPU |
+| RAM (working set), 3000 / 1000 / 100 cells | **31 / 23 / 20 MB** | 76 / 46 / 32 MB, plus 16-21 MB GPU memory |
+| First frame after launch | **~6 ms** | ~250 ms |
+| Idle CPU | **0 %** | 0.7-1.4 % |
+
+blenderui wins everything except CPU per frame on very small scenes, where
+gpui's GPU does the drawing. With only one of 3000 cells changing per frame
+(a later, power-limited session for both apps), blenderui ran at 54 fps and
+gpui at 11 fps. Against [gpui-fast](https://github.com/longbridge/gpui-fast),
+a faster gpui fork, blenderui leads on frame rate in the heavy scene, memory
+and startup, while gpui-fast uses less CPU per frame; see the
+[benchmark](bindings/rust/bench/README.md).
+
+### tkinter canvas
+
+[`bindings/python/bench/tk_canvas_bench.py`](bindings/python/bench/tk_canvas_bench.py) (2000 rectangles, ovals, lines, polygons, arcs and
+labels on one tkinter-syntax `Canvas`, rendered headless):
+
+| Per frame | before | now |
+|---|---:|---:|
+| Render, every item moved | 11.1 ms | **3.6 ms** (parallel raster for all item types) |
+| Render, one item moved | 9.4 ms | **0.08 ms** (only the item's old and new boxes redraw) |
+| Python, 2000 `Canvas.move` calls | 22.5 ms | **15.0 ms** (cached colors, O(1) item lookup) |
+
## Roadmap: more languages and platforms
BUI's core is plain C with a small, stable surface (`kit/include/BUI_kit.h`
diff --git a/bindings/python/bench/tk_canvas_bench.py b/bindings/python/bench/tk_canvas_bench.py
new file mode 100644
index 0000000..d308cdd
--- /dev/null
+++ b/bindings/python/bench/tk_canvas_bench.py
@@ -0,0 +1,61 @@
+"""tkinter syntax on BUI: canvas frame cost, rendered headless.
+
+ py bench/tk_canvas_bench.py [items] [all|one]
+
+Each frame moves every item (`all`) or one item (`one`) with Canvas.move,
+then renders (damage only). Prints ms per frame: Python (the tkinter facade)
+and render (the C kit).
+"""
+
+import sys
+import time
+
+import bui # noqa: F401 (locates buipy)
+import buipy
+from bui.tksyntax import Canvas, Tk
+
+N = int(sys.argv[1]) if len(sys.argv) > 1 else 2000
+MODE = sys.argv[2] if len(sys.argv) > 2 else "all"
+W, H = 1000, 800
+
+root = Tk()
+cv = Canvas(root, width=W, height=H, bg="#303030", highlightthickness=0)
+cv.pack()
+items = []
+cols = 50
+for k in range(N):
+ x, y = (k % cols) * 20 + 2, (k // cols) * 20 % (H - 20) + 2
+ kind = k % 6
+ if kind == 0:
+ i = cv.create_rectangle(x, y, x + 16, y + 16, fill="#4772b3", outline="#e6e6e6")
+ elif kind == 1:
+ i = cv.create_oval(x, y, x + 16, y + 16, fill="#e6a23c")
+ elif kind == 2:
+ i = cv.create_line(x, y, x + 16, y + 16, fill="#78aef0", width=2)
+ elif kind == 3:
+ i = cv.create_polygon(x, y + 16, x + 8, y, x + 16, y + 16, fill="#6aa84f", outline="#ffffff")
+ elif kind == 4:
+ i = cv.create_arc(x, y, x + 16, y + 16, start=0, extent=270, fill="#c27ba0")
+ else:
+ i = cv.create_text(x + 8, y + 8, text=str(k % 100), fill="#ffffff")
+ items.append(i)
+
+ctx = root._ctx
+r = buipy.Raster(W, H)
+ctx.render(W, H, r, True)
+frames, t_py, t_render = 120, 0.0, 0.0
+for f in range(frames):
+ d = 1 if f % 2 == 0 else -1
+ t0 = time.perf_counter()
+ if MODE == "all":
+ for i in items:
+ cv.move(i, d, 0)
+ else:
+ cv.move(items[f % N], d, 0)
+ t1 = time.perf_counter()
+ ctx.render(W, H, r, False)
+ t2 = time.perf_counter()
+ t_py += t1 - t0
+ t_render += t2 - t1
+print(f"items={N} mode={MODE}: python {t_py / frames * 1000:.2f} ms/frame, "
+ f"render {t_render / frames * 1000:.2f} ms/frame")
diff --git a/bindings/python/bui/tksyntax/__pycache__/_core.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/_core.cpython-314.pyc
index d2f545e..fa5d3a8 100644
Binary files a/bindings/python/bui/tksyntax/__pycache__/_core.cpython-314.pyc and b/bindings/python/bui/tksyntax/__pycache__/_core.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/_widgets.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/_widgets.cpython-314.pyc
index b795648..d8c9cc2 100644
Binary files a/bindings/python/bui/tksyntax/__pycache__/_widgets.cpython-314.pyc and b/bindings/python/bui/tksyntax/__pycache__/_widgets.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/_core.py b/bindings/python/bui/tksyntax/_core.py
index 6e36c21..b3a3fe5 100644
--- a/bindings/python/bui/tksyntax/_core.py
+++ b/bindings/python/bui/tksyntax/_core.py
@@ -77,11 +77,27 @@ _NAMED_COLORS = {
}
+_COLOR_CACHE = {}
+
+
def color(value):
"""A Tk color (``#rgb``, ``#rrggbb``, ``#rrrrggggbbbb``, a name, or an
- RGB(A) tuple) as RGBA floats; None for "" / None."""
+ RGB(A) tuple) as RGBA floats; None for "" / None. Color strings are
+ parsed once (canvases re-send their items' colors on every change)."""
if value is None or value == "":
return None
+ if isinstance(value, str):
+ hit = _COLOR_CACHE.get(value)
+ if hit is None:
+ hit = _parse_color(value)
+ if len(_COLOR_CACHE) > 4096:
+ _COLOR_CACHE.clear()
+ _COLOR_CACHE[value] = hit
+ return hit
+ return _parse_color(value)
+
+
+def _parse_color(value):
if isinstance(value, (tuple, list)):
v = tuple(float(c) / (255.0 if max(value) > 1 else 1.0) for c in value)
return v + (1.0,) if len(v) == 3 else v
diff --git a/bindings/python/bui/tksyntax/_widgets.py b/bindings/python/bui/tksyntax/_widgets.py
index 3959dce..bc91614 100644
--- a/bindings/python/bui/tksyntax/_widgets.py
+++ b/bindings/python/bui/tksyntax/_widgets.py
@@ -1324,10 +1324,11 @@ _SUB = 1 << 24 # kit ids of an item's parts (line arrows)
class _Item:
- __slots__ = ("id", "type", "coords", "tags", "opts")
+ __slots__ = ("id", "type", "coords", "tags", "opts", "arrows")
def __init__(self, iid, kind, coords, tags, opts):
self.id, self.type, self.coords, self.tags, self.opts = iid, kind, coords, tags, opts
+ self.arrows = 0 # bit k: arrowhead sub-item k exists in the kit
def _flat(coords):
@@ -1502,8 +1503,10 @@ class Canvas(Widget, XView, YView):
poly = [tip[0], tip[1], bx - uy * wing, by + ux * wing,
tip[0] - ux * a, tip[1] - uy * a, bx + uy * wing, by - ux * wing]
self._node.canvas_set(kid, 3, poly, fill=ink, hidden=hidden)
- else:
+ item.arrows |= 1 << k
+ elif item.arrows & (1 << k): # only delete what was created
self._node.canvas_delete(kid)
+ item.arrows &= ~(1 << k)
def _place_window(self, item):
w = item.opts.get("window")
diff --git a/bindings/python/tests/test_render.py b/bindings/python/tests/test_render.py
index 2ce8c1f..511f897 100644
--- a/bindings/python/tests/test_render.py
+++ b/bindings/python/tests/test_render.py
@@ -250,6 +250,68 @@ def test_after_cancel():
root.destroy()
+def test_canvas_damage_matches_full_redraw():
+ """Canvas edits redraw only the items' old and new boxes; the result must
+ equal redrawing everything, for every item type and kind of edit."""
+ import random
+ from bui.tksyntax import Canvas, Tk
+
+ W, H = 320, 220
+ root = Tk()
+ cv = Canvas(root, width=W, height=H, bg="#303030", highlightthickness=0)
+ cv.pack()
+ rnd = random.Random(7)
+
+ def make(k):
+ x, y = rnd.randrange(0, W - 40), rnd.randrange(0, H - 30)
+ kind = k % 7
+ if kind == 0:
+ return cv.create_rectangle(x, y, x + 30, y + 20, fill="#4772b3", outline="#e6e6e6", width=2)
+ if kind == 1:
+ return cv.create_oval(x, y, x + 24, y + 24, fill="#e6a23c")
+ if kind == 2:
+ return cv.create_line(x, y, x + 30, y + 18, x + 10, y + 25, fill="#78aef0", width=3)
+ if kind == 3:
+ return cv.create_polygon(x, y + 20, x + 12, y, x + 24, y + 20, fill="#6aa84f", outline="#ffffff")
+ if kind == 4:
+ return cv.create_arc(x, y, x + 26, y + 26, start=30, extent=240, fill="#c27ba0", outline="#ffffff")
+ if kind == 5:
+ return cv.create_text(x + 10, y + 10, text="label %d" % k, fill="#ffffff", anchor="nw")
+ return cv.create_text(x + 15, y + 10, text="ctr", fill="#ffff00")
+
+ items = [make(k) for k in range(40)]
+ ctx = root._ctx
+ live = buipy.Raster(W, H)
+ ctx.render(W, H, live, True)
+ for step in range(80):
+ i = rnd.choice(items)
+ op = step % 6
+ if op == 0:
+ cv.move(i, rnd.randint(-15, 15), rnd.randint(-15, 15))
+ elif op == 1:
+ if cv.type(i) in ("text",):
+ cv.itemconfigure(i, text="changed text %d" % step)
+ else:
+ cv.itemconfigure(i, fill=rnd.choice(["#ff0000", "#00ff00", "#2020ff"]))
+ elif op == 2:
+ cv.delete(i)
+ items.remove(i)
+ items.append(make(step))
+ elif op == 3:
+ cv.tag_raise(i)
+ elif op == 4:
+ cv.tag_lower(i)
+ else:
+ x, y = rnd.randrange(0, W - 40), rnd.randrange(0, H - 30)
+ n = len(cv.coords(i))
+ cv.coords(i, *([x, y, x + 20, y + 14, x + 5, y + 20][:n] if n <= 6 else cv.coords(i)))
+ ctx.render(W, H, live, False) # damage only
+ full = buipy.Raster(W, H)
+ ctx.render(W, H, full, True) # everything
+ assert live.ppm(0, 0, W, H) == full.ppm(0, 0, W, H), "step %d (op %d): damage redraw differs" % (step, op)
+ root.destroy()
+
+
def main() -> int:
tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
for t in tests:
diff --git a/bindings/rust/Cargo.lock b/bindings/rust/Cargo.lock
index 25ed81f..568eaf4 100644
--- a/bindings/rust/Cargo.lock
+++ b/bindings/rust/Cargo.lock
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
-version = 3
+version = 4
[[package]]
name = "adler2"
@@ -30,12 +30,18 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
name = "blenderui"
version = "0.1.0"
dependencies = [
+ "blenderui-macros",
"blenderui-sys",
"paste",
"png",
+ "smallvec",
"taffy",
]
+[[package]]
+name = "blenderui-macros"
+version = "0.1.0"
+
[[package]]
name = "blenderui-sys"
version = "0.1.0"
@@ -226,6 +232,12 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "smallvec"
+version = "1.16.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
+
[[package]]
name = "syn"
version = "3.0.9"
diff --git a/bindings/rust/Cargo.toml b/bindings/rust/Cargo.toml
index ffda08c..45f8d01 100644
--- a/bindings/rust/Cargo.toml
+++ b/bindings/rust/Cargo.toml
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
-members = ["blenderui-sys", "blenderui"]
+members = ["blenderui-sys", "blenderui-macros", "blenderui"]
exclude = ["bench"]
[workspace.package]
diff --git a/bindings/rust/bench/Cargo.lock b/bindings/rust/bench/Cargo.lock
index 6d14522..76b7860 100644
--- a/bindings/rust/bench/Cargo.lock
+++ b/bindings/rust/bench/Cargo.lock
@@ -715,12 +715,18 @@ dependencies = [
name = "blenderui"
version = "0.1.0"
dependencies = [
+ "blenderui-macros",
"blenderui-sys",
"paste",
"png 0.17.16",
+ "smallvec",
"taffy 0.6.3",
]
+[[package]]
+name = "blenderui-macros"
+version = "0.1.0"
+
[[package]]
name = "blenderui-sys"
version = "0.1.0"
diff --git a/bindings/rust/bench/README.md b/bindings/rust/bench/README.md
index 5b5b0a1..1accdc1 100644
--- a/bindings/rust/bench/README.md
+++ b/bindings/rust/bench/README.md
@@ -13,6 +13,9 @@ with a centred number), built with the same element tree in both
- **anim**: every frame changes every cell's colour and number, and the view
calls `window.request_animation_frame()`. That's the worst case: full
re-render, re-layout and re-paint every frame.
+- **one**: every frame re-renders the whole scene, but only one cell actually
+ changes: closer to a real UI (a hover, a ticking value), where reusing the
+ previous frame's work pays off.
- **idle**: the scene renders once and then nothing changes.
- **blenderui (uncapped)**: animation without vsync pacing (`--uncapped`).
@@ -42,31 +45,32 @@ Every configuration ran 3 times, and the table shows the medians.
Ryzen 7 5800U (8 cores / 16 threads, laptop, plugged in), AMD Radeon iGPU,
60 Hz display, Windows 11, release builds. All three apps ran back to back in
-one session, 3 runs each, medians shown.
+one session, 3 runs each, medians shown. This is after blenderui's
+arena / compile-time rework (no `Rc` / `RefCell`).
| App | Cells | Mode | FPS | CPU % (1 core = 100) | CPU ms / frame | GPU 3D % | RAM working set MB | Private MB | GPU memory MB | First frame ms |
|---|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|
-| gpui | 100 | anim | 60.1 | 18.8 | 3.12 | 5.4 | 33.5 | 35.8 | 16.1 | 225 |
-| gpui-fast | 100 | anim | 60.0 | 8.1 | 1.35 | 2.2 | 35.6 | 40.3 | 19.1 | 206 |
-| blenderui | 100 | anim | 60.1 | 38.1 | 6.33 | 0 | 22.3 | 12.9 | 0 | 7 |
-| gpui | 100 | idle | 0.0 | 1.1 | 0 | 0.0 | 33.3 | 35.4 | 16.1 | 219 |
-| gpui-fast | 100 | idle | 0.0 | 0.1 | 0 | 0.0 | 34.4 | 39.4 | 18.8 | 201 |
-| blenderui | 100 | idle | 0.1 | 0.2 | 0 | - | 19.9 | 9.9 | 0 | 6 |
-| blenderui (uncapped) | 100 | anim | 494.1 | 259.2 | 5.25 | 0 | 22.9 | 13.4 | 0 | 7 |
-| gpui | 1000 | anim | 60.1 | 94.1 | 15.66 | 6.8 | 47.9 | 52.0 | 17.1 | 223 |
-| gpui-fast | 1000 | anim | 60.0 | 49.7 | 8.27 | 7.9 | 44.8 | 51.1 | 19.9 | 203 |
-| blenderui | 1000 | anim | 60.1 | 99.7 | 16.59 | 0 | 26.8 | 17.8 | 0 | 8 |
-| gpui | 1000 | idle | 0.3 | 3.7 | 0 | 0.8 | 47.0 | 51.1 | 17.1 | 219 |
-| gpui-fast | 1000 | idle | 0.2 | 0.5 | 0 | 0.0 | 44.1 | 50.3 | 19.9 | 200 |
-| blenderui | 1000 | idle | 0.0 | 0.1 | 0 | - | 22.8 | 12.8 | 0 | 5 |
-| blenderui (uncapped) | 1000 | anim | 96.7 | 165.4 | 16.85 | 0 | 27.3 | 17.6 | 0 | 7 |
-| gpui | 3000 | anim | 22.8 | 100.6 | 44.09 | 4.2 | 77.5 | 94.9 | 20.6 | 215 |
-| gpui-fast | 3000 | anim | 29.7 | 54.7 | 18.42 | 4.5 | 64.7 | 85.3 | 23.5 | 213 |
-| blenderui | 3000 | anim | 32.6 | 129.7 | 39.67 | 0 | 36.3 | 31.6 | 0 | 5 |
-| gpui | 3000 | idle | 0.0 | 0.9 | 0 | 0.0 | 75.2 | 92.3 | 20.6 | 233 |
-| gpui-fast | 3000 | idle | 0.0 | 0.1 | 0 | 0.0 | 61.6 | 81.4 | 20.9 | 201 |
-| blenderui | 3000 | idle | 0.2 | 1.0 | 0 | - | 27.8 | 19.3 | 0 | 6 |
-| blenderui (uncapped) | 3000 | anim | 31.4 | 128.6 | 40.97 | 0 | 35.4 | 37.8 | 0 | 6 |
+| gpui | 100 | anim | 60.1 | 20.3 | 3.38 | 5.2 | 31.7 | 35.3 | 16.1 | 257 |
+| gpui-fast | 100 | anim | 60.0 | 7.8 | 1.30 | 3.3 | 33.6 | 39.9 | 19.1 | 258 |
+| blenderui | 100 | anim | 60.0 | 30.3 | 5.05 | 0 | 19.6 | 11.4 | 0 | 6 |
+| gpui | 100 | idle | 0.0 | 0.7 | 0 | 0.0 | 31.4 | 34.9 | 16.1 | 274 |
+| gpui-fast | 100 | idle | 0.0 | 0.0 | 0 | 0.0 | 32.5 | 39.0 | 18.8 | 254 |
+| blenderui | 100 | idle | 0.0 | 0.0 | 0 | - | 17.8 | 9.5 | 0 | 6 |
+| blenderui (uncapped) | 100 | anim | 529.3 | 329.9 | 6.24 | 0 | 19.8 | 11.8 | 0 | 7 |
+| gpui | 1000 | anim | 60.1 | 88.4 | 14.73 | 6.1 | 46.0 | 51.7 | 17.1 | 275 |
+| gpui-fast | 1000 | anim | 60.0 | 40.4 | 6.74 | 7.2 | 43.4 | 50.9 | 19.9 | 262 |
+| blenderui | 1000 | anim | 59.8 | 81.8 | 13.67 | 0 | 23.4 | 15.6 | 0 | 7 |
+| gpui | 1000 | idle | 0.0 | 1.4 | 0 | 0.0 | 47.1 | 50.9 | 17.1 | 261 |
+| gpui-fast | 1000 | idle | 0.0 | 0.0 | 0 | 0.0 | 42.1 | 49.8 | 19.1 | 262 |
+| blenderui | 1000 | idle | 0.0 | 0.0 | 0 | - | 21.6 | 13.5 | 0 | 6 |
+| blenderui (uncapped) | 1000 | anim | 156.9 | 236.4 | 14.82 | 0 | 23.7 | 15.9 | 0 | 6 |
+| gpui | 3000 | anim | 18.9 | 100.5 | 53.07 | 2.5 | 75.9 | 95.4 | 20.6 | 251 |
+| gpui-fast | 3000 | anim | 50.5 | 101.2 | 20.05 | 6.6 | 63.7 | 85.3 | 23.5 | 243 |
+| blenderui | 3000 | anim | 57.5 | 157.1 | 27.33 | 0 | 31.2 | 27.9 | 0 | 6 |
+| gpui | 3000 | idle | 0.0 | 1.0 | 0 | 0.0 | 73.6 | 92.1 | 20.6 | 252 |
+| gpui-fast | 3000 | idle | 0.0 | 0.1 | 0 | 0.0 | 59.7 | 80.9 | 20.9 | 254 |
+| blenderui | 3000 | idle | 0.0 | 0.0 | 0 | - | 26.9 | 21.7 | 0 | 6 |
+| blenderui (uncapped) | 3000 | anim | 58.1 | 168.0 | 28.90 | 0 | 31.3 | 28.3 | 0 | 6 |
blenderui has no GPU counter instances (shown as 0): it draws on the CPU. `CPU %`
counts all threads, so above 100 means more than one core.
@@ -75,18 +79,31 @@ counts all threads, so above 100 means more than one core.
| Animated cells | blenderui | gpui-fast | gpui |
|---|---:|---:|---:|
-| 100 | 60 (500 uncapped) | 60 | 60 |
-| 1000 | 60 (97 uncapped) | 60 | 60 |
-| 3000 | **32.6** | 29.7 | 22.8 |
-| CPU ms / frame at 3000 | 39.7 | **18.4** (+GPU) | 44.1 (+GPU) |
-| RAM working set at 3000 | **36 MB** | 65 MB (+24 MB GPU) | 78 MB (+21 MB GPU) |
-| First frame | **~6 ms** | ~205 ms | ~220 ms |
-
-- **FPS:** at the display cap (100 and 1000 cells) all three tie at 60. At 3000 cells blenderui is fastest: 10 % ahead of gpui-fast (per-run ranges 30.3-32.9 vs 29.7-29.9) and 43 % ahead of gpui. Uncapped, blenderui reaches 97 fps at 1000 cells; the gpui apps can't run uncapped.
-- **CPU efficiency: gpui-fast is best,** about 2× less CPU per frame than blenderui on the large scene, plus a little GPU. Its 3000-cell frame rate is held back by something other than CPU (it uses half a core), while blenderui uses 1.3 cores to get there.
-- **Memory and startup: blenderui wins clearly.** It uses 1.8-2.2× less working set and 2.7-3.2× less private memory, holds no GPU memory, and shows its first frame about 35× sooner.
-- **Idle:** blenderui and gpui-fast both use about 0.1 % CPU; gpui uses about 1 %.
-- **gpui across sessions:** at 1000 cells it measured 51 fps in an earlier session and 60 in this one, which is why these numbers come from one session.
+| 100 | 60 fps, 5.1 ms CPU/frame (529 uncapped) | 60 fps, **1.3 ms** + GPU | 60 fps, 3.4 ms + GPU |
+| 1000 | 60 fps, 13.7 ms (157 uncapped) | 60 fps, **6.7 ms** + GPU | 60 fps, 14.7 ms + GPU |
+| 3000 | **57.5 fps**, 27.3 ms | 50.5 fps, **20.1 ms** + GPU | 18.9 fps, 53.1 ms + GPU |
+| RAM working set (3000) | **31 MB** | 64 MB + 24 MB GPU | 76 MB + 21 MB GPU |
+| First frame | **~6 ms** | ~250 ms | ~260 ms |
+| Idle CPU | **0.0 %** | 0.0-0.1 % | 0.7-1.4 % |
+
+- **Frame rate:** blenderui is fastest at 3000 cells in this session (57.5 vs gpui-fast 50.5; per-run ranges 57.4-58.6 vs 49.9-51.6). Smaller scenes hit the 60 Hz cap in all three. gpui-fast's 3000-cell frame rate varies a lot between sessions on this laptop (29.7, 59.8 and 50.5 fps in three sessions), so compare within a session only.
+- **CPU efficiency:** gpui-fast still does the least CPU work per frame (plus GPU work). The gap at 3000 cells has narrowed from 2.1× to 1.4×.
+- **Memory and startup:** blenderui uses about half the RAM of either gpui and no GPU memory, and starts about 40× faster.
+
+## Frame-to-frame reuse (mode `one`)
+
+Measured in a later session while the laptop was charging from a low battery,
+so everything (all three apps) ran slower than in the table above; only
+same-session comparisons are meaningful:
+
+| 3000 cells, same session | blenderui | gpui-fast | gpui |
+|---|---:|---:|---:|
+| all cells change (`anim`) | 36.8 fps, 47.7 ms CPU/frame | 31.3 fps, 27.4 ms + GPU | 11.3 fps, 89.2 ms + GPU |
+| one cell changes (`one`) | **54.0 fps, 27.5 ms** | 29.4 fps, 16.3 ms + GPU | 11.3 fps, 89.1 ms + GPU |
+
+blenderui spends 42 % less CPU per frame when little changes (38 % at 1000
+cells). gpui-fast was capped near 30 fps throughout that session (its GPU in a
+low-power state), so its frame rate there says little.
## Caveats
@@ -111,4 +128,33 @@ The first version of this benchmark had blenderui at 29 fps (1000 cells) and 12
| **No overdraw:** a background identical to the one under it isn't painted, and the kit skips its clear when the page is opaque | `paint.rs`, `kit_core.c` | about 1 ms |
| **Frame pacing:** animation frames rebuild right before the render (`BK_window_request_frame`). A frame that is already late doesn't wait for another vblank | `kit_window.c`, `window.rs` | removes 10 ms timer and vsync quantisation stalls |
+Second round (lower CPU per frame without costing RAM, startup, idle or fps):
+
+| Change | Where | Effect |
+|---|---|---|
+| **Adaptive raster threads:** the fewest threads that still meet the frame deadline, and all of them when it can't be met | `kit_frame.c` | 1000 cells: 17.4 → 14.3 ms CPU/frame; 100 cells drawn serially |
+| **Lone text folded into its box:** one measured layout leaf instead of a text leaf (or one per word) | `layout.rs` | 3000 cells: boxes 5.0 → 2.5 ms, taffy 7.0 → 1.9 ms; pixel-identical |
+| **Items bucketed by band** once instead of every band scanning the list | `kit_frame.c` | about 1.5 ms CPU at 3000 cells |
+| **Allocation-free style-sharing probe** (hash the inputs, compare in place) | `layout.rs` | cascade 3.5 → 2.5 ms |
+| **In-place canvas updates** (`BK_canvas_put_item` / `BK_canvas_truncate` reuse buffers and invalidate once) and inline painter coordinates | `kit_frame.c`, `paint.rs` | hand-off 1.25 → 0.30 ms |
+
+Third round (no `Rc` / `RefCell`, work moved to compile time):
+
+| Change | Effect at 3000 cells |
+|---|---|
+| Property names resolved at compile time (`const` table), typed values without formatting or parsing, `css!` | element building 3.5 → 3.1 ms |
+| Frames as index-linked arenas reused across frames; words as byte ranges; no per-node strings or `Rc`s | build 7.3 → 4.1 ms, boxes 2.8 → 1.4 ms, dropping the old frame 1.4 → 0.03 ms |
+| Styles in a per-window store addressed by `StyleId` | the cascade probe compares ids |
+| Matched rules and declarations in stack-backed small vectors; rule index without key strings | cascade 2.8 → 2.5 ms |
+| Text widths, images, the author sheet and the taffy tree cached in the window | fewer allocations everywhere |
+
+Fourth round (reuse across frames, fewer allocations):
+
+| Change | Effect |
+|---|---|
+| Matched rules memoized by an element fingerprint (parent, previous sibling, tag, id, attributes, position, state) | selector matching runs once per distinct element |
+| A persistent taffy tree reconciled by key; text leaves keyed by a text hash; changed subtrees marked dirty explicitly | taffy's cache skips everything that didn't change: taffy time halves at 3000 cells when one cell changes |
+| `Tok` 56 → 32 bytes (function tokens boxed); `Div` ~470 → ~150 bytes (listeners and state styles allocated on use, children inline) | less memory traffic, one allocation less per element |
+| Painter, text buffer, layout scratch, box index table reused across frames; small lists on the stack | allocations per frame no longer grow with text items |
+
Still single-threaded and the largest remaining costs are the cascade, box tree and taffy layout (about 20 ms at 3000 cells): incremental restyling and layout would be the next step.
diff --git a/bindings/rust/bench/bui-bench/src/main.rs b/bindings/rust/bench/bui-bench/src/main.rs
index ce865aa..4a8f013 100644
--- a/bindings/rust/bench/bui-bench/src/main.rs
+++ b/bindings/rust/bench/bui-bench/src/main.rs
@@ -34,14 +34,14 @@ impl Render for Scene {
div()
.w(px(w))
.h(px(h))
- .bg(rgb(measure::cell_color(i, t)))
+ .bg(rgb(measure::cell_color(i, cfg.t_for(i, t))))
.rounded(px(3.0))
.flex()
.items_center()
.justify_center()
.text_size(px(font))
.text_color(rgb(0xffffff))
- .child(measure::cell_label(i, t))
+ .child(measure::cell_label(i, cfg.t_for(i, t)))
})))
}
}
diff --git a/bindings/rust/bench/common/measure.rs b/bindings/rust/bench/common/measure.rs
index e78a76e..26ad393 100644
--- a/bindings/rust/bench/common/measure.rs
+++ b/bindings/rust/bench/common/measure.rs
@@ -15,6 +15,8 @@ pub static FRAMES: AtomicU64 = AtomicU64::new(0);
pub struct Config {
pub cells: usize,
pub animate: bool,
+ /// `--mode one`: every frame re-renders, but only cell 0 changes.
+ pub one: bool,
pub warmup: f64,
pub seconds: f64,
pub width: f32,
@@ -30,7 +32,8 @@ impl Config {
};
Config {
cells: get("--cells", "100").parse().unwrap(),
- animate: get("--mode", "anim") == "anim",
+ animate: matches!(get("--mode", "anim").as_str(), "anim" | "one"),
+ one: get("--mode", "anim") == "one",
warmup: get("--warmup", "3").parse().unwrap(),
seconds: get("--seconds", "10").parse().unwrap(),
width: 1000.0,
@@ -73,6 +76,13 @@ pub fn cell_label(i: usize, t: u64) -> String {
format!("{}", (i as u64 * 13 + t) % 1000)
}
+impl Config {
+ /// The frame number cell `i` shows: all cells follow `t`, or only cell 0 (`--mode one`).
+ pub fn t_for(&self, i: usize, t: u64) -> u64 {
+ if self.one && i != 0 { 0 } else { t }
+ }
+}
+
pub fn frame() -> u64 {
FRAMES.fetch_add(1, Ordering::Relaxed)
}
@@ -142,6 +152,7 @@ fn memory() -> MemCounters {
/// Start the measuring thread. `name` labels the JSON line.
pub fn start(name: &'static str, cfg: &Config) {
let (warmup, secs, cells, animate) = (cfg.warmup, cfg.seconds, cfg.cells, cfg.animate);
+ let mode = if cfg.one { "one" } else if animate { "anim" } else { "idle" };
let launched = Instant::now();
std::thread::spawn(move || {
// time to first frame
@@ -176,7 +187,7 @@ pub fn start(name: &'static str, cfg: &Config) {
"{{\"app\":\"{name}\",\"cells\":{cells},\"mode\":\"{}\",\"fps\":{:.1},\"cpu_pct\":{:.1},\
\"cpu_ms_per_frame\":{:.3},\"ws_mb\":{:.1},\"peak_ws_mb\":{:.1},\"private_mb\":{:.1},\
\"first_frame_ms\":{:.0}}}",
- if animate { "anim" } else { "idle" },
+ mode,
frames as f64 / wall.as_secs_f64(),
cpu.as_secs_f64() / wall.as_secs_f64() * 100.0,
if frames > 0 { cpu.as_secs_f64() * 1000.0 / frames as f64 } else { 0.0 },
diff --git a/bindings/rust/bench/gpui-bench/src/scene.rs b/bindings/rust/bench/gpui-bench/src/scene.rs
index bed7a84..bbd0528 100644
--- a/bindings/rust/bench/gpui-bench/src/scene.rs
+++ b/bindings/rust/bench/gpui-bench/src/scene.rs
@@ -37,14 +37,14 @@ impl Render for Scene {
div()
.w(px(w))
.h(px(h))
- .bg(rgb(measure::cell_color(i, t)))
+ .bg(rgb(measure::cell_color(i, cfg.t_for(i, t))))
.rounded(px(3.0))
.flex()
.items_center()
.justify_center()
.text_size(px(font))
.text_color(rgb(0xffffff))
- .child(measure::cell_label(i, t))
+ .child(measure::cell_label(i, cfg.t_for(i, t)))
}))
}
}
diff --git a/bindings/rust/bench/results.json b/bindings/rust/bench/results.json
index c10ccd2..6a187e2 100644
--- a/bindings/rust/bench/results.json
+++ b/bindings/rust/bench/results.json
@@ -3,41 +3,83 @@
"app": "gpui",
"cells": 100,
"mode": "anim",
- "fps": 60.1,
- "cpu_pct": 18.8,
- "cpu_ms_per_frame": 3.124,
- "gpu_pct": 5.430223331602986,
- "ws_mb": 33.5,
- "peak_ws_mb": 33.5,
- "private_mb": 35.8,
+ "fps": 60.0,
+ "cpu_pct": 18.3,
+ "cpu_ms_per_frame": 3.046,
+ "gpu_pct": 2.160049611054961,
+ "ws_mb": 33.6,
+ "peak_ws_mb": 33.6,
+ "private_mb": 35.6,
"gpu_mem_mb": 16.12890625,
- "first_frame_ms": 225
+ "first_frame_ms": 299
},
{
"app": "gpui-fast",
"cells": 100,
"mode": "anim",
- "fps": 60.0,
- "cpu_pct": 8.1,
- "cpu_ms_per_frame": 1.346,
- "gpu_pct": 2.22759138111008,
- "ws_mb": 35.6,
- "peak_ws_mb": 35.6,
- "private_mb": 40.3,
+ "fps": 60.1,
+ "cpu_pct": 7.6,
+ "cpu_ms_per_frame": 1.323,
+ "gpu_pct": 1.7367879010844638,
+ "ws_mb": 35.3,
+ "peak_ws_mb": 35.3,
+ "private_mb": 40.2,
"gpu_mem_mb": 19.1484375,
- "first_frame_ms": 206
+ "first_frame_ms": 295
},
{
"app": "blenderui",
"cells": 100,
"mode": "anim",
- "fps": 60.1,
- "cpu_pct": 38.1,
- "cpu_ms_per_frame": 6.334,
+ "fps": 59.9,
+ "cpu_pct": 36.8,
+ "cpu_ms_per_frame": 6.168,
"gpu_pct": null,
- "ws_mb": 22.3,
- "peak_ws_mb": 22.7,
- "private_mb": 12.9,
+ "ws_mb": 21.2,
+ "peak_ws_mb": 21.2,
+ "private_mb": 11.6,
+ "gpu_mem_mb": null,
+ "first_frame_ms": 9
+ },
+ {
+ "app": "gpui",
+ "cells": 100,
+ "mode": "one",
+ "fps": 60.0,
+ "cpu_pct": 12.9,
+ "cpu_ms_per_frame": 2.149,
+ "gpu_pct": 2.0736485199869437,
+ "ws_mb": 33.4,
+ "peak_ws_mb": 33.4,
+ "private_mb": 35.4,
+ "gpu_mem_mb": 16.12890625,
+ "first_frame_ms": 340
+ },
+ {
+ "app": "gpui-fast",
+ "cells": 100,
+ "mode": "one",
+ "fps": 29.7,
+ "cpu_pct": 4.2,
+ "cpu_ms_per_frame": 1.355,
+ "gpu_pct": 0.9146514374982673,
+ "ws_mb": 34.8,
+ "peak_ws_mb": 35.0,
+ "private_mb": 39.8,
+ "gpu_mem_mb": 19.1484375,
+ "first_frame_ms": 278
+ },
+ {
+ "app": "blenderui",
+ "cells": 100,
+ "mode": "one",
+ "fps": 59.9,
+ "cpu_pct": 37.6,
+ "cpu_ms_per_frame": 6.292,
+ "gpu_pct": null,
+ "ws_mb": 20.4,
+ "peak_ws_mb": 20.6,
+ "private_mb": 10.9,
"gpu_mem_mb": null,
"first_frame_ms": 7
},
@@ -49,248 +91,332 @@
"cpu_pct": 1.1,
"cpu_ms_per_frame": 0.0,
"gpu_pct": 0.0,
- "ws_mb": 33.3,
- "peak_ws_mb": 33.3,
- "private_mb": 35.4,
+ "ws_mb": 33.1,
+ "peak_ws_mb": 33.1,
+ "private_mb": 35.1,
"gpu_mem_mb": 16.12890625,
- "first_frame_ms": 219
+ "first_frame_ms": 274
},
{
"app": "gpui-fast",
"cells": 100,
"mode": "idle",
"fps": 0.0,
- "cpu_pct": 0.1,
+ "cpu_pct": 0.0,
"cpu_ms_per_frame": 0.0,
"gpu_pct": 0.0,
- "ws_mb": 34.4,
- "peak_ws_mb": 34.4,
- "private_mb": 39.4,
+ "ws_mb": 34.1,
+ "peak_ws_mb": 34.1,
+ "private_mb": 39.2,
"gpu_mem_mb": 18.7578125,
- "first_frame_ms": 201
+ "first_frame_ms": 246
},
{
"app": "blenderui",
"cells": 100,
"mode": "idle",
- "fps": 0.1,
- "cpu_pct": 0.2,
- "cpu_ms_per_frame": 17.651,
+ "fps": 0.0,
+ "cpu_pct": 0.0,
+ "cpu_ms_per_frame": 0.0,
"gpu_pct": null,
- "ws_mb": 19.9,
- "peak_ws_mb": 19.9,
- "private_mb": 9.9,
+ "ws_mb": 19.7,
+ "peak_ws_mb": 19.7,
+ "private_mb": 9.7,
"gpu_mem_mb": null,
- "first_frame_ms": 6
+ "first_frame_ms": 8
},
{
"app": "blenderui (uncapped)",
"cells": 100,
"mode": "anim",
- "fps": 494.1,
- "cpu_pct": 259.2,
- "cpu_ms_per_frame": 5.251,
+ "fps": 288.9,
+ "cpu_pct": 322.2,
+ "cpu_ms_per_frame": 11.155,
"gpu_pct": null,
- "ws_mb": 22.9,
- "peak_ws_mb": 23.3,
- "private_mb": 13.4,
+ "ws_mb": 21.3,
+ "peak_ws_mb": 21.5,
+ "private_mb": 11.9,
"gpu_mem_mb": null,
- "first_frame_ms": 7
+ "first_frame_ms": 16
},
{
"app": "gpui",
"cells": 1000,
"mode": "anim",
- "fps": 60.1,
- "cpu_pct": 94.1,
- "cpu_ms_per_frame": 15.662,
- "gpu_pct": 6.799581583082019,
- "ws_mb": 47.9,
- "peak_ws_mb": 48.3,
- "private_mb": 52.0,
+ "fps": 54.8,
+ "cpu_pct": 92.0,
+ "cpu_ms_per_frame": 16.789,
+ "gpu_pct": 3.3781059655571912,
+ "ws_mb": 47.6,
+ "peak_ws_mb": 48.2,
+ "private_mb": 51.5,
"gpu_mem_mb": 17.07421875,
- "first_frame_ms": 223
+ "first_frame_ms": 344
},
{
"app": "gpui-fast",
"cells": 1000,
"mode": "anim",
- "fps": 60.0,
- "cpu_pct": 49.7,
- "cpu_ms_per_frame": 8.274,
- "gpu_pct": 7.941114150402417,
- "ws_mb": 44.8,
- "peak_ws_mb": 45.1,
- "private_mb": 51.1,
+ "fps": 29.7,
+ "cpu_pct": 27.5,
+ "cpu_ms_per_frame": 9.231,
+ "gpu_pct": 1.505138613040445,
+ "ws_mb": 44.7,
+ "peak_ws_mb": 44.9,
+ "private_mb": 50.9,
"gpu_mem_mb": 19.89453125,
- "first_frame_ms": 203
+ "first_frame_ms": 394
},
{
"app": "blenderui",
"cells": 1000,
"mode": "anim",
- "fps": 60.1,
- "cpu_pct": 99.7,
- "cpu_ms_per_frame": 16.588,
+ "fps": 54.8,
+ "cpu_pct": 150.5,
+ "cpu_ms_per_frame": 27.466,
"gpu_pct": null,
- "ws_mb": 26.8,
- "peak_ws_mb": 29.2,
- "private_mb": 17.8,
+ "ws_mb": 24.9,
+ "peak_ws_mb": 25.5,
+ "private_mb": 16.0,
"gpu_mem_mb": null,
- "first_frame_ms": 8
+ "first_frame_ms": 12
},
{
"app": "gpui",
"cells": 1000,
- "mode": "idle",
- "fps": 0.3,
- "cpu_pct": 3.7,
- "cpu_ms_per_frame": 83.632,
- "gpu_pct": 0.7863746532776426,
- "ws_mb": 47.0,
- "peak_ws_mb": 47.2,
- "private_mb": 51.1,
+ "mode": "one",
+ "fps": 44.3,
+ "cpu_pct": 100.0,
+ "cpu_ms_per_frame": 22.046,
+ "gpu_pct": 2.5052906138400513,
+ "ws_mb": 46.2,
+ "peak_ws_mb": 46.4,
+ "private_mb": 51.7,
"gpu_mem_mb": 17.07421875,
- "first_frame_ms": 219
+ "first_frame_ms": 345
+ },
+ {
+ "app": "gpui-fast",
+ "cells": 1000,
+ "mode": "one",
+ "fps": 29.4,
+ "cpu_pct": 27.1,
+ "cpu_ms_per_frame": 9.113,
+ "gpu_pct": 1.8060058098129863,
+ "ws_mb": 44.9,
+ "peak_ws_mb": 44.9,
+ "private_mb": 51.6,
+ "gpu_mem_mb": 19.89453125,
+ "first_frame_ms": 300
+ },
+ {
+ "app": "blenderui",
+ "cells": 1000,
+ "mode": "one",
+ "fps": 59.5,
+ "cpu_pct": 101.7,
+ "cpu_ms_per_frame": 17.131,
+ "gpu_pct": null,
+ "ws_mb": 24.7,
+ "peak_ws_mb": 25.5,
+ "private_mb": 15.8,
+ "gpu_mem_mb": null,
+ "first_frame_ms": 10
+ },
+ {
+ "app": "gpui",
+ "cells": 1000,
+ "mode": "idle",
+ "fps": 0.0,
+ "cpu_pct": 1.0,
+ "cpu_ms_per_frame": 0.0,
+ "gpu_pct": 0.0,
+ "ws_mb": 47.3,
+ "peak_ws_mb": 47.3,
+ "private_mb": 51.3,
+ "gpu_mem_mb": 17.51171875,
+ "first_frame_ms": 387
},
{
"app": "gpui-fast",
"cells": 1000,
"mode": "idle",
- "fps": 0.2,
- "cpu_pct": 0.5,
- "cpu_ms_per_frame": 15.09,
+ "fps": 0.0,
+ "cpu_pct": 0.0,
+ "cpu_ms_per_frame": 0.0,
"gpu_pct": 0.0,
- "ws_mb": 44.1,
- "peak_ws_mb": 44.6,
- "private_mb": 50.3,
+ "ws_mb": 43.7,
+ "peak_ws_mb": 43.7,
+ "private_mb": 50.1,
"gpu_mem_mb": 19.89453125,
- "first_frame_ms": 200
+ "first_frame_ms": 277
},
{
"app": "blenderui",
"cells": 1000,
"mode": "idle",
"fps": 0.0,
- "cpu_pct": 0.1,
+ "cpu_pct": 0.0,
"cpu_ms_per_frame": 0.0,
"gpu_pct": null,
- "ws_mb": 22.8,
- "peak_ws_mb": 22.8,
- "private_mb": 12.8,
+ "ws_mb": 23.4,
+ "peak_ws_mb": 23.4,
+ "private_mb": 13.6,
"gpu_mem_mb": null,
- "first_frame_ms": 5
+ "first_frame_ms": 10
},
{
"app": "blenderui (uncapped)",
"cells": 1000,
"mode": "anim",
- "fps": 96.7,
- "cpu_pct": 165.4,
- "cpu_ms_per_frame": 16.847,
+ "fps": 86.6,
+ "cpu_pct": 239.3,
+ "cpu_ms_per_frame": 27.625,
"gpu_pct": null,
- "ws_mb": 27.3,
- "peak_ws_mb": 29.5,
- "private_mb": 17.6,
+ "ws_mb": 25.1,
+ "peak_ws_mb": 25.6,
+ "private_mb": 16.0,
"gpu_mem_mb": null,
- "first_frame_ms": 7
+ "first_frame_ms": 12
},
{
"app": "gpui",
"cells": 3000,
"mode": "anim",
- "fps": 22.8,
- "cpu_pct": 100.6,
- "cpu_ms_per_frame": 44.093,
- "gpu_pct": 4.1647137724058325,
- "ws_mb": 77.5,
- "peak_ws_mb": 78.4,
- "private_mb": 94.9,
+ "fps": 11.3,
+ "cpu_pct": 100.5,
+ "cpu_ms_per_frame": 89.241,
+ "gpu_pct": 1.0648015763039103,
+ "ws_mb": 77.8,
+ "peak_ws_mb": 78.6,
+ "private_mb": 93.7,
"gpu_mem_mb": 20.64453125,
- "first_frame_ms": 215
+ "first_frame_ms": 583
},
{
"app": "gpui-fast",
"cells": 3000,
"mode": "anim",
- "fps": 29.7,
- "cpu_pct": 54.7,
- "cpu_ms_per_frame": 18.419,
- "gpu_pct": 4.54098209237542,
- "ws_mb": 64.7,
- "peak_ws_mb": 65.8,
- "private_mb": 85.3,
+ "fps": 31.3,
+ "cpu_pct": 91.8,
+ "cpu_ms_per_frame": 27.417,
+ "gpu_pct": 2.254235548767074,
+ "ws_mb": 64.9,
+ "peak_ws_mb": 65.5,
+ "private_mb": 85.1,
"gpu_mem_mb": 23.47265625,
- "first_frame_ms": 213
+ "first_frame_ms": 498
},
{
"app": "blenderui",
"cells": 3000,
"mode": "anim",
- "fps": 32.6,
- "cpu_pct": 129.7,
- "cpu_ms_per_frame": 39.667,
+ "fps": 36.8,
+ "cpu_pct": 175.8,
+ "cpu_ms_per_frame": 47.7,
+ "gpu_pct": null,
+ "ws_mb": 30.7,
+ "peak_ws_mb": 33.2,
+ "private_mb": 26.1,
+ "gpu_mem_mb": null,
+ "first_frame_ms": 11
+ },
+ {
+ "app": "gpui",
+ "cells": 3000,
+ "mode": "one",
+ "fps": 11.3,
+ "cpu_pct": 100.5,
+ "cpu_ms_per_frame": 89.116,
+ "gpu_pct": 1.0455488689161836,
+ "ws_mb": 77.9,
+ "peak_ws_mb": 78.7,
+ "private_mb": 95.1,
+ "gpu_mem_mb": 20.64453125,
+ "first_frame_ms": 556
+ },
+ {
+ "app": "gpui-fast",
+ "cells": 3000,
+ "mode": "one",
+ "fps": 29.4,
+ "cpu_pct": 62.1,
+ "cpu_ms_per_frame": 16.341,
+ "gpu_pct": 2.313129568589991,
+ "ws_mb": 64.2,
+ "peak_ws_mb": 64.2,
+ "private_mb": 85.6,
+ "gpu_mem_mb": 23.47265625,
+ "first_frame_ms": 358
+ },
+ {
+ "app": "blenderui",
+ "cells": 3000,
+ "mode": "one",
+ "fps": 54.0,
+ "cpu_pct": 148.4,
+ "cpu_ms_per_frame": 27.488,
"gpu_pct": null,
- "ws_mb": 36.3,
- "peak_ws_mb": 43.4,
- "private_mb": 31.6,
+ "ws_mb": 31.6,
+ "peak_ws_mb": 33.9,
+ "private_mb": 27.2,
"gpu_mem_mb": null,
- "first_frame_ms": 5
+ "first_frame_ms": 15
},
{
"app": "gpui",
"cells": 3000,
"mode": "idle",
"fps": 0.0,
- "cpu_pct": 0.9,
+ "cpu_pct": 1.0,
"cpu_ms_per_frame": 0.0,
"gpu_pct": 0.0,
- "ws_mb": 75.2,
- "peak_ws_mb": 75.2,
- "private_mb": 92.3,
+ "ws_mb": 75.0,
+ "peak_ws_mb": 75.0,
+ "private_mb": 91.8,
"gpu_mem_mb": 20.64453125,
- "first_frame_ms": 233
+ "first_frame_ms": 409
},
{
"app": "gpui-fast",
"cells": 3000,
"mode": "idle",
"fps": 0.0,
- "cpu_pct": 0.1,
+ "cpu_pct": 0.0,
"cpu_ms_per_frame": 0.0,
"gpu_pct": 0.0,
- "ws_mb": 61.6,
- "peak_ws_mb": 61.6,
- "private_mb": 81.4,
- "gpu_mem_mb": 20.90625,
- "first_frame_ms": 201
+ "ws_mb": 62.0,
+ "peak_ws_mb": 62.1,
+ "private_mb": 81.6,
+ "gpu_mem_mb": 23.47265625,
+ "first_frame_ms": 359
},
{
"app": "blenderui",
"cells": 3000,
"mode": "idle",
- "fps": 0.2,
- "cpu_pct": 1.0,
- "cpu_ms_per_frame": 49.36,
+ "fps": 0.0,
+ "cpu_pct": 0.0,
+ "cpu_ms_per_frame": 0.0,
"gpu_pct": null,
- "ws_mb": 27.8,
- "peak_ws_mb": 28.1,
- "private_mb": 19.3,
+ "ws_mb": 30.3,
+ "peak_ws_mb": 30.3,
+ "private_mb": 23.1,
"gpu_mem_mb": null,
- "first_frame_ms": 6
+ "first_frame_ms": 7
},
{
"app": "blenderui (uncapped)",
"cells": 3000,
"mode": "anim",
- "fps": 31.4,
- "cpu_pct": 128.6,
- "cpu_ms_per_frame": 40.966,
+ "fps": 34.7,
+ "cpu_pct": 173.0,
+ "cpu_ms_per_frame": 50.11,
"gpu_pct": null,
- "ws_mb": 35.4,
- "peak_ws_mb": 42.9,
- "private_mb": 37.8,
+ "ws_mb": 30.8,
+ "peak_ws_mb": 33.7,
+ "private_mb": 25.9,
"gpu_mem_mb": null,
- "first_frame_ms": 6
+ "first_frame_ms": 9
}
]
\ No newline at end of file
diff --git a/bindings/rust/bench/results.md b/bindings/rust/bench/results.md
index d36f7c5..2e2db85 100644
--- a/bindings/rust/bench/results.md
+++ b/bindings/rust/bench/results.md
@@ -1,23 +1,32 @@
| App | Cells | Mode | FPS | CPU % (1 core = 100) | CPU ms / frame | GPU 3D % | RAM working set MB | Private MB | GPU memory MB | First frame ms |
|---|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|
-| gpui | 100 | anim | 60.1 | 18.8 | 3.12 | 5.4 | 33.5 | 35.8 | 16.1 | 225 |
-| gpui-fast | 100 | anim | 60.0 | 8.1 | 1.35 | 2.2 | 35.6 | 40.3 | 19.1 | 206 |
-| blenderui | 100 | anim | 60.1 | 38.1 | 6.33 | - | 22.3 | 12.9 | - | 7 |
-| gpui | 100 | idle | 0.0 | 1.1 | - | 0.0 | 33.3 | 35.4 | 16.1 | 219 |
-| gpui-fast | 100 | idle | 0.0 | 0.1 | - | 0.0 | 34.4 | 39.4 | 18.8 | 201 |
-| blenderui | 100 | idle | 0.1 | 0.2 | - | - | 19.9 | 9.9 | - | 6 |
-| blenderui (uncapped) | 100 | anim | 494.1 | 259.2 | 5.25 | - | 22.9 | 13.4 | - | 7 |
-| gpui | 1000 | anim | 60.1 | 94.1 | 15.66 | 6.8 | 47.9 | 52.0 | 17.1 | 223 |
-| gpui-fast | 1000 | anim | 60.0 | 49.7 | 8.27 | 7.9 | 44.8 | 51.1 | 19.9 | 203 |
-| blenderui | 1000 | anim | 60.1 | 99.7 | 16.59 | - | 26.8 | 17.8 | - | 8 |
-| gpui | 1000 | idle | 0.3 | 3.7 | - | 0.8 | 47.0 | 51.1 | 17.1 | 219 |
-| gpui-fast | 1000 | idle | 0.2 | 0.5 | - | 0.0 | 44.1 | 50.3 | 19.9 | 200 |
-| blenderui | 1000 | idle | 0.0 | 0.1 | - | - | 22.8 | 12.8 | - | 5 |
-| blenderui (uncapped) | 1000 | anim | 96.7 | 165.4 | 16.85 | - | 27.3 | 17.6 | - | 7 |
-| gpui | 3000 | anim | 22.8 | 100.6 | 44.09 | 4.2 | 77.5 | 94.9 | 20.6 | 215 |
-| gpui-fast | 3000 | anim | 29.7 | 54.7 | 18.42 | 4.5 | 64.7 | 85.3 | 23.5 | 213 |
-| blenderui | 3000 | anim | 32.6 | 129.7 | 39.67 | - | 36.3 | 31.6 | - | 5 |
-| gpui | 3000 | idle | 0.0 | 0.9 | - | 0.0 | 75.2 | 92.3 | 20.6 | 233 |
-| gpui-fast | 3000 | idle | 0.0 | 0.1 | - | 0.0 | 61.6 | 81.4 | 20.9 | 201 |
-| blenderui | 3000 | idle | 0.2 | 1.0 | - | - | 27.8 | 19.3 | - | 6 |
-| blenderui (uncapped) | 3000 | anim | 31.4 | 128.6 | 40.97 | - | 35.4 | 37.8 | - | 6 |
+| gpui | 100 | anim | 60.0 | 18.3 | 3.05 | 2.2 | 33.6 | 35.6 | 16.1 | 299 |
+| gpui-fast | 100 | anim | 60.1 | 7.6 | 1.32 | 1.7 | 35.3 | 40.2 | 19.1 | 295 |
+| blenderui | 100 | anim | 59.9 | 36.8 | 6.17 | - | 21.2 | 11.6 | - | 9 |
+| gpui | 100 | one | 60.0 | 12.9 | 2.15 | 2.1 | 33.4 | 35.4 | 16.1 | 340 |
+| gpui-fast | 100 | one | 29.7 | 4.2 | 1.35 | 0.9 | 34.8 | 39.8 | 19.1 | 278 |
+| blenderui | 100 | one | 59.9 | 37.6 | 6.29 | - | 20.4 | 10.9 | - | 7 |
+| gpui | 100 | idle | 0.0 | 1.1 | - | 0.0 | 33.1 | 35.1 | 16.1 | 274 |
+| gpui-fast | 100 | idle | 0.0 | 0.0 | - | 0.0 | 34.1 | 39.2 | 18.8 | 246 |
+| blenderui | 100 | idle | 0.0 | 0.0 | - | - | 19.7 | 9.7 | - | 8 |
+| blenderui (uncapped) | 100 | anim | 288.9 | 322.2 | 11.15 | - | 21.3 | 11.9 | - | 16 |
+| gpui | 1000 | anim | 54.8 | 92.0 | 16.79 | 3.4 | 47.6 | 51.5 | 17.1 | 344 |
+| gpui-fast | 1000 | anim | 29.7 | 27.5 | 9.23 | 1.5 | 44.7 | 50.9 | 19.9 | 394 |
+| blenderui | 1000 | anim | 54.8 | 150.5 | 27.47 | - | 24.9 | 16.0 | - | 12 |
+| gpui | 1000 | one | 44.3 | 100.0 | 22.05 | 2.5 | 46.2 | 51.7 | 17.1 | 345 |
+| gpui-fast | 1000 | one | 29.4 | 27.1 | 9.11 | 1.8 | 44.9 | 51.6 | 19.9 | 300 |
+| blenderui | 1000 | one | 59.5 | 101.7 | 17.13 | - | 24.7 | 15.8 | - | 10 |
+| gpui | 1000 | idle | 0.0 | 1.0 | - | 0.0 | 47.3 | 51.3 | 17.5 | 387 |
+| gpui-fast | 1000 | idle | 0.0 | 0.0 | - | 0.0 | 43.7 | 50.1 | 19.9 | 277 |
+| blenderui | 1000 | idle | 0.0 | 0.0 | - | - | 23.4 | 13.6 | - | 10 |
+| blenderui (uncapped) | 1000 | anim | 86.6 | 239.3 | 27.62 | - | 25.1 | 16.0 | - | 12 |
+| gpui | 3000 | anim | 11.3 | 100.5 | 89.24 | 1.1 | 77.8 | 93.7 | 20.6 | 583 |
+| gpui-fast | 3000 | anim | 31.3 | 91.8 | 27.42 | 2.3 | 64.9 | 85.1 | 23.5 | 498 |
+| blenderui | 3000 | anim | 36.8 | 175.8 | 47.70 | - | 30.7 | 26.1 | - | 11 |
+| gpui | 3000 | one | 11.3 | 100.5 | 89.12 | 1.0 | 77.9 | 95.1 | 20.6 | 556 |
+| gpui-fast | 3000 | one | 29.4 | 62.1 | 16.34 | 2.3 | 64.2 | 85.6 | 23.5 | 358 |
+| blenderui | 3000 | one | 54.0 | 148.4 | 27.49 | - | 31.6 | 27.2 | - | 15 |
+| gpui | 3000 | idle | 0.0 | 1.0 | - | 0.0 | 75.0 | 91.8 | 20.6 | 409 |
+| gpui-fast | 3000 | idle | 0.0 | 0.0 | - | 0.0 | 62.0 | 81.6 | 23.5 | 359 |
+| blenderui | 3000 | idle | 0.0 | 0.0 | - | - | 30.3 | 23.1 | - | 7 |
+| blenderui (uncapped) | 3000 | anim | 34.7 | 173.0 | 50.11 | - | 30.8 | 25.9 | - | 9 |
diff --git a/bindings/rust/bench/run.py b/bindings/rust/bench/run.py
index ce81a3f..c831508 100644
--- a/bindings/rust/bench/run.py
+++ b/bindings/rust/bench/run.py
@@ -79,7 +79,7 @@ def main():
a = ap.parse_args()
configs = []
for cells in map(int, a.cells.split(",")):
- for mode in ("anim", "idle"):
+ for mode in ("anim", "one", "idle"):
for app in a.apps.split(","):
configs.append((app, cells, mode, ()))
if "blenderui" in a.apps.split(","):
@@ -107,7 +107,7 @@ def main():
print("|---|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|")
for label, cells, mode, v in results:
print(f"| {label} | {cells} | {mode} | {f(v['fps'])} | {f(v['cpu_pct'])} | "
- f"{f(v['cpu_ms_per_frame'], 2) if mode == 'anim' else '-'} | {f(v['gpu_pct'])} | "
+ f"{f(v['cpu_ms_per_frame'], 2) if mode != 'idle' else '-'} | {f(v['gpu_pct'])} | "
f"{f(v['ws_mb'])} | {f(v['private_mb'])} | {f(v['gpu_mem_mb'])} | {f(v['first_frame_ms'], 0)} |")
diff --git a/bindings/rust/blenderui-macros/Cargo.toml b/bindings/rust/blenderui-macros/Cargo.toml
new file mode 100644
index 0000000..52544c6
--- /dev/null
+++ b/bindings/rust/blenderui-macros/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "blenderui-macros"
+description = "Compile-time CSS for blenderui: the css! macro"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+repository.workspace = true
+rust-version.workspace = true
+
+[lib]
+proc-macro = true
diff --git a/bindings/rust/blenderui-macros/src/lib.rs b/bindings/rust/blenderui-macros/src/lib.rs
new file mode 100644
index 0000000..ce680c7
--- /dev/null
+++ b/bindings/rust/blenderui-macros/src/lib.rs
@@ -0,0 +1,130 @@
+//! `css!`: CSS declaration blocks checked and resolved at compile time.
+//!
+//! ```ignore
+//! div().style(css!("display: flex; gap: 4px; border-left: 3px solid #4772b3"))
+//! ```
+//!
+//! The block is split into declarations when the program compiles. Every
+//! property becomes `const { Prop::named("...") }`, so an unknown property is
+//! a compile error, and each value is tokenized once for the whole program.
+//! The expansion is an array of `Decl`s, so nothing is parsed per frame.
+
+use proc_macro::{TokenStream, TokenTree};
+
+#[proc_macro]
+pub fn css(input: TokenStream) -> TokenStream {
+ match expand(input) {
+ Ok(code) => code.parse().expect("css!: generated code"),
+ Err(msg) => format!("::core::compile_error!({msg:?})").parse().unwrap(),
+ }
+}
+
+fn expand(input: TokenStream) -> Result<String, String> {
+ let mut tokens = input.into_iter();
+ let lit = match (tokens.next(), tokens.next()) {
+ (Some(TokenTree::Literal(l)), None) => l.to_string(),
+ _ => return Err("css! takes one string literal".into()),
+ };
+ let text = unquote(&lit).ok_or("css! takes one string literal")?;
+ let mut decls = Vec::new();
+ for part in split_top(&strip_comments(&text), ';') {
+ let part = part.trim();
+ if part.is_empty() {
+ continue;
+ }
+ let (name, value) = part.split_once(':').ok_or_else(|| format!("css!: expected `property: value` in `{part}`"))?;
+ let name = name.trim().to_ascii_lowercase();
+ if name.is_empty() {
+ return Err(format!("css!: missing property name in `{part}`"));
+ }
+ let mut value = value.trim();
+ let mut important = false;
+ if let Some(v) = value.strip_suffix("!important") {
+ value = v.trim_end();
+ important = true;
+ }
+ if value.is_empty() {
+ return Err(format!("css!: missing value for `{name}`"));
+ }
+ decls.push(format!(
+ "::blenderui::css::Decl {{ \
+ prop: const {{ ::blenderui::css::Prop::named({name:?}) }}, \
+ value: {{ \
+ static V: ::std::sync::OnceLock<::std::boxed::Box<[::blenderui::css::Tok]>> = \
+ ::std::sync::OnceLock::new(); \
+ ::blenderui::css::Value::Static(V.get_or_init(|| \
+ ::blenderui::css::tokenize({value:?}).into_boxed_slice())) \
+ }}, \
+ important: {important} \
+ }}"
+ ));
+ }
+ Ok(format!("[{}]", decls.join(", ")))
+}
+
+/// The contents of a (raw) string literal, escapes resolved.
+fn unquote(lit: &str) -> Option<String> {
+ if let Some(rest) = lit.strip_prefix('r') {
+ let hashes = rest.len() - rest.trim_start_matches('#').len();
+ let inner = &rest[hashes..];
+ let inner = inner.strip_prefix('"')?;
+ let inner = inner.strip_suffix(&"#".repeat(hashes))?.strip_suffix('"')?;
+ return Some(inner.to_owned());
+ }
+ let inner = lit.strip_prefix('"')?.strip_suffix('"')?;
+ let mut out = String::with_capacity(inner.len());
+ let mut chars = inner.chars();
+ while let Some(c) = chars.next() {
+ if c != '\\' {
+ out.push(c);
+ continue;
+ }
+ match chars.next()? {
+ 'n' => out.push('\n'),
+ 't' => out.push('\t'),
+ 'r' => out.push('\r'),
+ '0' => out.push('\0'),
+ '\n' => {
+ // line continuation: skip leading whitespace on the next line
+ let rest: String = chars.by_ref().skip_while(|c| c.is_whitespace()).collect();
+ out.push_str(&unquote(&format!("\"{rest}\""))?);
+ return Some(out);
+ }
+ other => out.push(other),
+ }
+ }
+ Some(out)
+}
+
+fn strip_comments(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ let mut rest = s;
+ while let Some(start) = rest.find("/*") {
+ out.push_str(&rest[..start]);
+ rest = rest[start + 2..].find("*/").map(|e| &rest[start + 2 + e + 2..]).unwrap_or("");
+ }
+ out.push_str(rest);
+ out
+}
+
+/// Split at `sep` outside parentheses and quotes.
+fn split_top(s: &str, sep: char) -> Vec<&str> {
+ let mut parts = Vec::new();
+ let (mut depth, mut quote, mut start) = (0i32, None::<char>, 0);
+ for (k, c) in s.char_indices() {
+ match (quote, c) {
+ (Some(q), _) if c == q => quote = None,
+ (Some(_), _) => {}
+ (None, '"' | '\'') => quote = Some(c),
+ (None, '(' | '[') => depth += 1,
+ (None, ')' | ']') => depth -= 1,
+ (None, _) if c == sep && depth == 0 => {
+ parts.push(&s[start..k]);
+ start = k + c.len_utf8();
+ }
+ _ => {}
+ }
+ }
+ parts.push(&s[start..]);
+ parts
+}
diff --git a/bindings/rust/blenderui-sys/src/lib.rs b/bindings/rust/blenderui-sys/src/lib.rs
index 56beced..64cd8aa 100644
--- a/bindings/rust/blenderui-sys/src/lib.rs
+++ b/bindings/rust/blenderui-sys/src/lib.rs
@@ -184,6 +184,8 @@ unsafe extern "C" {
// canvas display list
pub fn BK_canvas_set_item(canvas: *mut BKNode, item: *const BKCanvasItem);
pub fn BK_canvas_add_item(canvas: *mut BKNode, item: *const BKCanvasItem);
+ pub fn BK_canvas_put_item(canvas: *mut BKNode, index: c_int, item: *const BKCanvasItem);
+ pub fn BK_canvas_truncate(canvas: *mut BKNode, count: c_int);
pub fn BK_canvas_delete(canvas: *mut BKNode, id: c_int);
pub fn BK_canvas_count(canvas: *mut BKNode) -> c_int;
diff --git a/bindings/rust/blenderui/Cargo.toml b/bindings/rust/blenderui/Cargo.toml
index 3315df6..bb8abc9 100644
--- a/bindings/rust/blenderui/Cargo.toml
+++ b/bindings/rust/blenderui/Cargo.toml
@@ -12,6 +12,8 @@ readme = "README.md"
[dependencies]
blenderui-sys = { path = "../blenderui-sys", version = "0.1.0" }
+blenderui-macros = { path = "../blenderui-macros", version = "0.1.0" }
taffy = { version = "0.6", default-features = false, features = ["std", "flexbox", "grid", "block_layout", "taffy_tree", "content_size"] }
paste = "1"
+smallvec = { version = "1", features = ["union", "const_generics"] }
png = "0.17"
diff --git a/bindings/rust/blenderui/examples/golden.rs b/bindings/rust/blenderui/examples/golden.rs
new file mode 100644
index 0000000..e6a720a
--- /dev/null
+++ b/bindings/rust/blenderui/examples/golden.rs
@@ -0,0 +1,59 @@
+//! Renders a fixed scene off-screen to a PNG, for pixel comparisons between
+//! builds: `cargo run --release --example golden -- out.png`.
+
+use blenderui::prelude::*;
+
+struct Scene;
+
+impl Render for Scene {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ body()
+ .m_0()
+ .child(style().child(".hdr { color: #e6a23c; } li:nth-child(2) { color: #78aef0 } .box:hover { opacity: 0.5 }"))
+ .child(
+ div().flex().flex_wrap().gap(px(2.0)).p(px(2.0)).children((0..120).map(|i| {
+ let d = div().w(px(70.0)).h(px(28.0)).bg(rgb(0x4772b3 + (i as u32 * 0x010203) % 0x303030))
+ .rounded(px(3.0)).text_size(px(11.0)).text_color(white());
+ let d = match i % 5 {
+ 0 => d.flex().items_center().justify_center(),
+ 1 => d.flex().flex_col().justify_end(),
+ 2 => d.text_center(),
+ 3 => d.p(px(3.0)),
+ _ => d.flex().justify_end().items_end().px_1(),
+ };
+ d.child(format!("{i} cell"))
+ })),
+ )
+ .child(div().class("hdr").p_2().child(h2().child("Heading")).child(
+ p().child("Plain text with ").child(b().child("bold")).child(", ").child(i().child("italic"))
+ .child(" and a ").child(a().href("#").child("link")).child(" that wraps across lines in a narrow box.")
+ .w(px(260.0)),
+ ))
+ .child(ul().child(li().child("one")).child(li().child("two")).child(li().child("three")))
+ .child(table().child(tbody().children((0..3).map(|r| {
+ tr().child(td().child(format!("r{r}"))).child(td().child("value")).child(td().child(format!("{}", r * 7)))
+ }))))
+ .child(div().class("box").size(px(40.0)).bg(rgb(0xe6a23c)).shadow_md().rounded_md())
+ }
+}
+
+fn main() {
+ let path = std::env::args().nth(1).expect("output path");
+ Application::headless().run(move |cx| {
+ let opts = WindowOptions {
+ window_bounds: Some(WindowBounds::Windowed(Bounds {
+ origin: point(px(0.0), px(0.0)),
+ size: size(px(1000.0), px(800.0)),
+ })),
+ ..Default::default()
+ };
+ let w = cx.open_window(opts, |_, cx| cx.new(|_| Scene)).unwrap();
+ let (width, height, pixels) = cx.draw(w.id);
+ let rgba: Vec<u8> = pixels.iter().flat_map(|p| [(p >> 16) as u8, (p >> 8) as u8, *p as u8, 255]).collect();
+ let file = std::io::BufWriter::new(std::fs::File::create(&path).unwrap());
+ let mut enc = png::Encoder::new(file, width as u32, height as u32);
+ enc.set_color(png::ColorType::Rgba);
+ enc.set_depth(png::BitDepth::Eight);
+ enc.write_header().unwrap().write_image_data(&rgba).unwrap();
+ });
+}
diff --git a/bindings/rust/blenderui/src/css.rs b/bindings/rust/blenderui/src/css.rs
index 5158c68..9765890 100644
--- a/bindings/rust/blenderui/src/css.rs
+++ b/bindings/rust/blenderui/src/css.rs
@@ -9,22 +9,36 @@ use std::borrow::Cow;
// ==========================================================================
// Tokens
+/// Text inside tokens: borrowed from the binary for values known at compile
+/// time, owned for parsed CSS.
+pub type CssStr = Cow<'static, str>;
+
/// A CSS component value.
#[derive(Clone, Debug, PartialEq)]
pub enum Tok {
Num(f32),
- Dim(f32, String),
+ Dim(f32, CssStr),
Pct(f32),
- Ident(String),
- Hash(String),
- Str(String),
- /// `name(args)`, arguments split at top-level commas.
- Func(String, Vec<Vec<Tok>>),
+ Ident(CssStr),
+ Hash(CssStr),
+ Str(CssStr),
+ /// `name(args)`, arguments split at top-level commas. Boxed: functions
+ /// are rare and this keeps every token at 32 bytes.
+ Func(Box<FuncTok>),
+ /// A color given as a value (typed style methods: `.bg(rgb(..))`).
+ Color(crate::color::Rgba),
Comma,
Slash,
Delim(char),
}
+/// A CSS function call: `rgb(1, 2, 3)`, `repeat(3, 1fr)` ...
+#[derive(Clone, Debug, PartialEq)]
+pub struct FuncTok {
+ pub name: CssStr,
+ pub args: Vec<Vec<Tok>>,
+}
+
impl Tok {
pub(crate) fn ident(&self) -> Option<&str> {
match self {
@@ -32,6 +46,41 @@ impl Tok {
_ => None,
}
}
+
+ /// A length as the token CSS text would produce (`40px`, `50%`, `auto`).
+ pub const fn length(l: crate::geometry::Length) -> Tok {
+ use crate::geometry::Length;
+ match l {
+ Length::Px(v) => Tok::Dim(v, Cow::Borrowed("px")),
+ Length::Rem(v) => Tok::Dim(v, Cow::Borrowed("rem")),
+ Length::Em(v) => Tok::Dim(v, Cow::Borrowed("em")),
+ Length::Vw(v) => Tok::Dim(v, Cow::Borrowed("vw")),
+ Length::Vh(v) => Tok::Dim(v, Cow::Borrowed("vh")),
+ Length::Percent(v) => Tok::Pct(v),
+ Length::Auto => Tok::Ident(Cow::Borrowed("auto")),
+ }
+ }
+}
+
+impl std::hash::Hash for Tok {
+ fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
+ std::mem::discriminant(self).hash(h);
+ match self {
+ Tok::Num(v) | Tok::Pct(v) => v.to_bits().hash(h),
+ Tok::Dim(v, u) => {
+ v.to_bits().hash(h);
+ u.hash(h);
+ }
+ Tok::Ident(s) | Tok::Hash(s) | Tok::Str(s) => s.hash(h),
+ Tok::Func(fx) => {
+ fx.name.hash(h);
+ fx.args.hash(h);
+ }
+ Tok::Color(c) => [c.r, c.g, c.b, c.a].map(f32::to_bits).hash(h),
+ Tok::Delim(c) => c.hash(h),
+ Tok::Comma | Tok::Slash => {}
+ }
+ }
}
/// Tokenize a CSS value (no selectors or blocks).
@@ -51,11 +100,11 @@ pub fn tokenize(s: &str) -> Vec<Tok> {
i += 1;
} else if c == '"' || c == '\'' {
let end = s[i + 1..].find(c).map(|e| i + 1 + e).unwrap_or(s.len());
- out.push(Tok::Str(s[i + 1..end].to_string()));
+ out.push(Tok::Str(s[i + 1..end].to_string().into()));
i = end + 1;
} else if c == '#' {
let end = scan_name(s, i + 1);
- out.push(Tok::Hash(s[i + 1..end].to_ascii_lowercase()));
+ out.push(Tok::Hash(s[i + 1..end].to_ascii_lowercase().into()));
i = end;
} else if c.is_ascii_digit()
|| (c == '.' && b.get(i + 1).is_some_and(|d| d.is_ascii_digit()))
@@ -81,7 +130,7 @@ pub fn tokenize(s: &str) -> Vec<Tok> {
} else {
let unit_end = scan_name(s, end);
if unit_end > end {
- out.push(Tok::Dim(v, s[end..unit_end].to_ascii_lowercase()));
+ out.push(Tok::Dim(v, s[end..unit_end].to_ascii_lowercase().into()));
} else {
out.push(Tok::Num(v));
}
@@ -94,14 +143,14 @@ pub fn tokenize(s: &str) -> Vec<Tok> {
let close = matching_paren(s, end);
let inner = &s[end + 1..close];
let args = if name == "url" {
- vec![vec![Tok::Str(inner.trim().trim_matches(['"', '\'']).to_string())]]
+ vec![vec![Tok::Str(inner.trim().trim_matches(['"', '\'']).to_string().into())]]
} else {
split_top(inner, ',').into_iter().map(tokenize).collect()
};
- out.push(Tok::Func(name, args));
+ out.push(Tok::Func(Box::new(FuncTok { name: name.into(), args })));
i = (close + 1).min(s.len());
} else {
- out.push(Tok::Ident(name));
+ out.push(Tok::Ident(name.into()));
i = end;
}
} else {
@@ -167,52 +216,161 @@ pub(crate) fn split_top(s: &str, sep: char) -> Vec<&str> {
// ==========================================================================
// Declarations
-/// One `property: value` declaration.
-#[derive(Clone, Debug, PartialEq)]
-pub struct Decl {
- pub prop: Cow<'static, str>,
- /// Tokens, shared: equal value strings tokenize once per thread.
- pub value: std::sync::Arc<[Tok]>,
- pub important: bool,
+/// A CSS property, as an index into the property table (`style::HANDLERS`,
+/// then `style::ACCEPTED`). Style methods resolve it at compile time with
+/// [`Prop::named`]; parsed CSS with [`Prop::lookup`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct Prop(pub(crate) u16);
+
+const fn str_eq(a: &str, b: &str) -> bool {
+ let (a, b) = (a.as_bytes(), b.as_bytes());
+ if a.len() != b.len() {
+ return false;
+ }
+ let mut i = 0;
+ while i < a.len() {
+ if a[i] != b[i] {
+ return false;
+ }
+ i += 1;
+ }
+ true
}
-/// Tokenize through a per-thread cache (style methods repeat the same values
-/// every render: `.w(px(40.0))` is "40px" a thousand times).
-fn tokenize_cached(value: &str) -> std::sync::Arc<[Tok]> {
- use std::cell::RefCell;
- use std::collections::HashMap;
- thread_local! {
- static CACHE: RefCell<HashMap<String, std::sync::Arc<[Tok]>>> = RefCell::new(HashMap::new());
+impl Prop {
+ /// Not a property this engine knows.
+ pub const UNKNOWN: Prop = Prop(u16::MAX);
+ /// A custom property (`--name`): accepted, no effect.
+ pub const CUSTOM: Prop = Prop(u16::MAX - 1);
+
+ /// The property called `name`, evaluated at compile time in `const`
+ /// contexts (an unknown name there is a compile error).
+ pub const fn named(name: &str) -> Prop {
+ let h = crate::style::HANDLERS;
+ let mut i = 0;
+ while i < h.len() {
+ if str_eq(h[i].0, name) {
+ return Prop(i as u16);
+ }
+ i += 1;
+ }
+ let a = crate::style::ACCEPTED;
+ let mut j = 0;
+ while j < a.len() {
+ if str_eq(a[j], name) {
+ return Prop((h.len() + j) as u16);
+ }
+ j += 1;
+ }
+ let b = name.as_bytes();
+ if b.len() > 2 && b[0] == b'-' && b[1] == b'-' {
+ return Prop::CUSTOM;
+ }
+ panic!("unknown CSS property")
+ }
+
+ /// The property called `name` (lowercase), at run time.
+ pub fn lookup(name: &str) -> Prop {
+ crate::style::prop_index(name)
}
- CACHE.with(|c| {
- if let Some(t) = c.borrow().get(value) {
- return t.clone();
+
+ /// The property's name ("" for unknown and custom properties).
+ pub fn name(self) -> &'static str {
+ let (h, a) = (crate::style::HANDLERS, crate::style::ACCEPTED);
+ let i = self.0 as usize;
+ if i < h.len() {
+ h[i].0
+ } else if i - h.len() < a.len() && self != Prop::CUSTOM && self != Prop::UNKNOWN {
+ a[i - h.len()]
+ } else {
+ ""
}
- let t: std::sync::Arc<[Tok]> = tokenize(value).into();
- let mut c = c.borrow_mut();
- if c.len() > 50_000 {
- c.clear();
+ }
+}
+
+impl std::fmt::Display for Prop {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(self.name())
+ }
+}
+
+/// A declaration's tokens: one inline token (typed style methods), a slice
+/// parsed once for the whole program (fixed style methods), or parsed CSS.
+#[derive(Clone, Debug)]
+pub enum Value {
+ One(Tok),
+ Static(&'static [Tok]),
+ Owned(Box<[Tok]>),
+}
+
+impl std::ops::Deref for Value {
+ type Target = [Tok];
+ fn deref(&self) -> &[Tok] {
+ match self {
+ Value::One(t) => std::slice::from_ref(t),
+ Value::Static(s) => s,
+ Value::Owned(b) => b,
+ }
+ }
+}
+
+impl PartialEq for Value {
+ fn eq(&self, o: &Value) -> bool {
+ match (self, o) {
+ (Value::Static(a), Value::Static(b)) if std::ptr::eq(*a, *b) => true,
+ _ => **self == **o,
}
- c.insert(value.to_owned(), t.clone());
- t
- })
+ }
+}
+
+impl std::hash::Hash for Value {
+ fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
+ (**self).hash(h)
+ }
+}
+
+/// One `property: value` declaration.
+#[derive(Clone, Debug, PartialEq, Hash)]
+pub struct Decl {
+ pub prop: Prop,
+ pub value: Value,
+ pub important: bool,
}
impl Decl {
- pub fn new(prop: impl Into<Cow<'static, str>>, value: &str) -> Decl {
+ /// A cheap hash for style sharing: fixed values (parsed once, unique per
+ /// program) by address, others by content. Equal declarations may hash
+ /// differently across variants; that only costs a cache miss.
+ pub(crate) fn probe_hash<H: std::hash::Hasher>(&self, h: &mut H) {
+ use std::hash::Hash;
+ self.prop.hash(h);
+ self.important.hash(h);
+ match &self.value {
+ Value::Static(s) => (s.as_ptr() as usize).hash(h),
+ v => (**v).hash(h),
+ }
+ }
+
+ /// Parse `value` for `prop` (the run-time path: `.css()`, stylesheets).
+ pub fn new(prop: impl AsRef<str>, value: &str) -> Decl {
let mut value = value.trim();
let mut important = false;
if let Some(v) = value.strip_suffix("!important") {
value = v.trim_end();
important = true;
}
- let prop = prop.into();
+ let prop = prop.as_ref();
let prop = if prop.bytes().any(|b| b.is_ascii_uppercase()) {
- Cow::Owned(prop.to_ascii_lowercase())
+ Prop::lookup(&prop.to_ascii_lowercase())
} else {
- prop
+ Prop::lookup(prop)
};
- Decl { prop, value: tokenize_cached(value), important }
+ Decl { prop, value: Value::Owned(tokenize(value).into_boxed_slice()), important }
+ }
+
+ /// A declaration with one already-typed token (no parsing).
+ pub const fn one(prop: Prop, value: Tok) -> Decl {
+ Decl { prop, value: Value::One(value), important: false }
}
}
@@ -273,6 +431,14 @@ enum Combinator {
Sibling,
}
+/// Where a rule is filed in a stylesheet's index.
+enum Bucket {
+ Id(String),
+ Class(String),
+ Tag(String),
+ Universal,
+}
+
/// A complex selector: compounds joined by combinators (stored right to left).
#[derive(Clone, Debug, PartialEq)]
pub struct Selector {
@@ -354,18 +520,18 @@ impl Selector {
}
/// The bucket a rule is filed under: its subject's id, class, tag, or "*".
- fn bucket(&self) -> String {
+ fn bucket(&self) -> Bucket {
let subject = &self.parts[0].0;
subject.iter().find_map(|s| match s {
- Simple::Id(i) => Some(format!("#{i}")),
+ Simple::Id(i) => Some(Bucket::Id(i.clone())),
_ => None,
}).or_else(|| subject.iter().find_map(|s| match s {
- Simple::Class(c) => Some(format!(".{c}")),
+ Simple::Class(c) => Some(Bucket::Class(c.clone())),
_ => None,
})).or_else(|| subject.iter().find_map(|s| match s {
- Simple::Tag(t) => Some(t.to_ascii_lowercase()),
+ Simple::Tag(t) => Some(Bucket::Tag(t.to_ascii_lowercase())),
_ => None,
- })).unwrap_or_else(|| "*".into())
+ })).unwrap_or(Bucket::Universal)
}
pub fn matches<S: Subject + Clone>(&self, el: &S) -> bool {
@@ -609,11 +775,18 @@ impl Media {
#[derive(Clone, Debug, Default)]
pub struct Stylesheet {
pub rules: Vec<Rule>,
- /// Rule indices by subject id / class / tag / "*" (rebuilt when `rules` changes length).
- index: std::collections::HashMap<String, Vec<usize>>,
+ /// Rule indices by the subject's id / class / tag, or universal (rebuilt
+ /// when `rules` changes length). Looked up by `&str`: no key building.
+ by_id: std::collections::HashMap<String, Vec<usize>>,
+ by_class: std::collections::HashMap<String, Vec<usize>>,
+ by_tag: std::collections::HashMap<String, Vec<usize>>,
+ universal: Vec<usize>,
indexed: usize,
}
+/// Rules matching one element: on the stack for the usual handful.
+pub(crate) type Matches<'a> = smallvec::SmallVec<[&'a Rule; 8]>;
+
impl Stylesheet {
/// Parse CSS text (rules, `@media` blocks; other at-rules are skipped).
pub fn parse(css: &str) -> Stylesheet {
@@ -624,9 +797,17 @@ impl Stylesheet {
}
fn reindex(&mut self) {
- self.index.clear();
+ self.by_id.clear();
+ self.by_class.clear();
+ self.by_tag.clear();
+ self.universal.clear();
for (k, r) in self.rules.iter().enumerate() {
- self.index.entry(r.selector.bucket()).or_default().push(k);
+ match r.selector.bucket() {
+ Bucket::Id(s) => self.by_id.entry(s).or_default().push(k),
+ Bucket::Class(s) => self.by_class.entry(s).or_default().push(k),
+ Bucket::Tag(s) => self.by_tag.entry(s).or_default().push(k),
+ Bucket::Universal => self.universal.push(k),
+ }
}
self.indexed = self.rules.len();
}
@@ -656,24 +837,34 @@ impl Stylesheet {
/// Declarations of every matching rule, in cascade order.
pub fn matching<'a, S: Subject + Clone>(&'a self, el: &S, viewport: (f32, f32))
-> Vec<&'a Rule> {
+ self.matches(el, viewport).into_vec()
+ }
+
+ /// [`Self::matching`] without heap allocation for the usual few rules.
+ pub(crate) fn matches<'a, S: Subject + Clone>(&'a self, el: &S, viewport: (f32, f32)) -> Matches<'a> {
let ok = |r: &&Rule| r.media.as_ref().is_none_or(|m| m.applies(viewport)) && r.selector.matches(el);
- let mut hits: Vec<&Rule> = if self.indexed != self.rules.len() {
+ let mut hits: Matches<'a> = if self.indexed != self.rules.len() {
self.rules.iter().filter(ok).collect() // `rules` edited by hand: scan all
} else {
- let mut cand: Vec<usize> = Vec::new();
- let mut take = |key: &str| {
- if let Some(v) = self.index.get(key) {
- cand.extend_from_slice(v);
- }
+ let mut cand: smallvec::SmallVec<[usize; 16]> = smallvec::SmallVec::new();
+ cand.extend_from_slice(&self.universal);
+ let tag = el.tag();
+ let found = if tag.bytes().any(|b| b.is_ascii_uppercase()) {
+ self.by_tag.get(&tag.to_ascii_lowercase())
+ } else {
+ self.by_tag.get(tag)
};
- take("*");
- take(&el.tag().to_ascii_lowercase());
- if let Some(id) = el.id() {
- take(&format!("#{id}"));
+ if let Some(v) = found {
+ cand.extend_from_slice(v);
+ }
+ if let Some(v) = el.id().and_then(|id| self.by_id.get(id)) {
+ cand.extend_from_slice(v);
}
if let Some(classes) = el.class_attr() {
for c in classes.split_whitespace() {
- take(&format!(".{c}"));
+ if let Some(v) = self.by_class.get(c) {
+ cand.extend_from_slice(v);
+ }
}
}
cand.sort_unstable();
@@ -711,7 +902,8 @@ mod tests {
let t = tokenize("1px solid rgb(255, 0, 0) 50% -2.5rem #abc 'x'");
assert_eq!(t[0], Tok::Dim(1.0, "px".into()));
assert_eq!(t[1], Tok::Ident("solid".into()));
- assert!(matches!(&t[2], Tok::Func(n, args) if n == "rgb" && args.len() == 3));
+ assert!(matches!(&t[2], Tok::Func(fx) if fx.name == "rgb" && fx.args.len() == 3));
+ assert_eq!(std::mem::size_of::<Tok>(), 32);
assert_eq!(t[3], Tok::Pct(50.0));
assert_eq!(t[4], Tok::Dim(-2.5, "rem".into()));
assert_eq!(t[5], Tok::Hash("abc".into()));
@@ -723,6 +915,7 @@ mod tests {
let d = parse_declarations("color: red; padding: 4px 8px !important; /* c */ ;");
assert_eq!(d.len(), 2);
assert!(d[1].important && d[1].value.len() == 2);
+ assert_eq!(d[0].prop, Prop::named("color"));
}
#[test]
diff --git a/bindings/rust/blenderui/src/element.rs b/bindings/rust/blenderui/src/element.rs
index 0c5793b..826a688 100644
--- a/bindings/rust/blenderui/src/element.rs
+++ b/bindings/rust/blenderui/src/element.rs
@@ -1,7 +1,7 @@
//! Elements: one [`Div`] type for every HTML tag, built gpui-style.
use std::borrow::Cow;
-use std::rc::Rc;
+use std::sync::Arc;
use crate::css::Decl;
pub use crate::styled::Styled;
@@ -15,12 +15,13 @@ pub type SharedString = Cow<'static, str>;
/// state across renders.
pub type ElementId = SharedString;
-pub(crate) type Listener<E> = Rc<dyn Fn(&E, &mut Window, &mut App)>;
+/// An event listener, owned by its element (moved into the frame, never shared).
+pub(crate) type Listener<E> = Box<dyn Fn(&E, &mut Window, &mut App)>;
/// Custom painting (gpui's `canvas()` element).
-pub(crate) type PaintFn = Rc<dyn Fn(crate::geometry::Bounds<f32>, &mut crate::paint::Painter)>;
+pub(crate) type PaintFn = Box<dyn Fn(crate::geometry::Bounds<f32>, &mut crate::paint::Painter)>;
-#[derive(Clone, Default)]
+#[derive(Default)]
pub(crate) struct Listeners {
pub click: Vec<Listener<ClickEvent>>,
pub mouse_down: Vec<(Option<MouseButton>, Listener<MouseDownEvent>)>,
@@ -36,25 +37,32 @@ pub(crate) struct Listeners {
/// An element: a tag, its attributes, styles, children and listeners.
/// `div()`, `span()`, `button()` ... all build one of these.
-#[derive(Clone)]
pub struct Div {
pub(crate) tag: &'static str,
pub(crate) id: Option<ElementId>,
pub(crate) attrs: Vec<(SharedString, SharedString)>,
pub(crate) decls: Vec<Decl>,
- pub(crate) hover: Vec<Decl>,
- pub(crate) active: Vec<Decl>,
- pub(crate) focus: Vec<Decl>,
+ /// `:hover` / `:active` / `:focus` styles, allocated only when used.
+ pub(crate) states: Option<Box<StateDecls>>,
pub(crate) children: Vec<AnyElement>,
- pub(crate) listeners: Listeners,
+ /// Allocated only when the element has a listener.
+ pub(crate) listeners: Option<Box<Listeners>>,
pub(crate) paint: Option<PaintFn>,
- pub(crate) image: Option<Rc<crate::paint::Image>>,
+ pub(crate) image: Option<Arc<crate::paint::Image>>,
+}
+
+/// Styles for interaction states (`.hover(|s| ...)` ...).
+#[derive(Default)]
+pub(crate) struct StateDecls {
+ pub hover: Vec<Decl>,
+ pub active: Vec<Decl>,
+ pub focus: Vec<Decl>,
}
-/// Anything that can be a child: an element or a text run.
-#[derive(Clone)]
+/// Anything that can be a child: an element or a text run. Elements are
+/// stored inline (no box per element).
pub enum AnyElement {
- Element(Box<Div>),
+ Element(Div),
Text(SharedString),
}
@@ -65,7 +73,7 @@ pub trait IntoElement {
impl IntoElement for Div {
fn into_any_element(self) -> AnyElement {
- AnyElement::Element(Box::new(self))
+ AnyElement::Element(self)
}
}
impl IntoElement for AnyElement {
@@ -96,16 +104,22 @@ impl Div {
id: None,
attrs: Vec::new(),
decls: Vec::new(),
- hover: Vec::new(),
- active: Vec::new(),
- focus: Vec::new(),
+ states: None,
children: Vec::new(),
- listeners: Listeners::default(),
+ listeners: None,
paint: None,
image: None,
}
}
+ fn listeners_mut(&mut self) -> &mut Listeners {
+ self.listeners.get_or_insert_with(Default::default)
+ }
+
+ fn states_mut(&mut self) -> &mut StateDecls {
+ self.states.get_or_insert_with(Default::default)
+ }
+
/// The HTML tag name.
pub fn tag(&self) -> &'static str {
self.tag
@@ -199,76 +213,83 @@ impl Div {
/// Image pixels for `<img>`: RGBA, `width * height * 4` bytes.
pub fn image_rgba(mut self, width: u32, height: u32, rgba: Vec<u8>) -> Self {
- self.image = Some(Rc::new(crate::paint::Image { width, height, rgba }));
+ // (shared image data: see `image`)
+ self.image = Some(Arc::new(crate::paint::Image { width, height, rgba }));
+ self
+ }
+
+ /// Show shared image pixels (cheap to pass every frame).
+ pub fn image(mut self, image: Arc<crate::paint::Image>) -> Self {
+ self.image = Some(image);
self
}
// -- events ----------------------------------------------------------------------------
/// Click (press and release on this element); bubbles to ancestors.
pub fn on_click(mut self, f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self {
- self.listeners.click.push(Rc::new(f));
+ self.listeners_mut().click.push(Box::new(f));
self
}
pub fn on_mouse_down(mut self, button: MouseButton,
f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self {
- self.listeners.mouse_down.push((Some(button), Rc::new(f)));
+ self.listeners_mut().mouse_down.push((Some(button), Box::new(f)));
self
}
pub fn on_any_mouse_down(mut self,
f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self {
- self.listeners.mouse_down.push((None, Rc::new(f)));
+ self.listeners_mut().mouse_down.push((None, Box::new(f)));
self
}
pub fn on_mouse_up(mut self, button: MouseButton,
f: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static) -> Self {
- self.listeners.mouse_up.push((Some(button), Rc::new(f)));
+ self.listeners_mut().mouse_up.push((Some(button), Box::new(f)));
self
}
pub fn on_mouse_move(mut self,
f: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static) -> Self {
- self.listeners.mouse_move.push(Rc::new(f));
+ self.listeners_mut().mouse_move.push(Box::new(f));
self
}
/// Called with `true` when the pointer enters, `false` when it leaves.
pub fn on_hover(mut self, f: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
- self.listeners.hover.push(Rc::new(f));
+ self.listeners_mut().hover.push(Box::new(f));
self
}
pub fn on_scroll_wheel(mut self,
f: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static) -> Self {
- self.listeners.scroll.push(Rc::new(f));
+ self.listeners_mut().scroll.push(Box::new(f));
self
}
pub fn on_key_down(mut self, f: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static) -> Self {
- self.listeners.key_down.push(Rc::new(f));
+ self.listeners_mut().key_down.push(Box::new(f));
self
}
pub fn on_key_up(mut self, f: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) -> Self {
- self.listeners.key_up.push(Rc::new(f));
+ self.listeners_mut().key_up.push(Box::new(f));
self
}
/// Form controls: the committed value changed (`change` in HTML).
pub fn on_change(mut self, f: impl Fn(&ChangeEvent, &mut Window, &mut App) + 'static) -> Self {
- self.listeners.change.push(Rc::new(f));
+ self.listeners_mut().change.push(Box::new(f));
self
}
/// Form controls: every edit (`input` in HTML).
pub fn on_input(mut self, f: impl Fn(&ChangeEvent, &mut Window, &mut App) + 'static) -> Self {
- self.listeners.input.push(Rc::new(f));
+ self.listeners_mut().input.push(Box::new(f));
self
}
// -- state styles (gpui's .hover(|s| ...), CSS :hover / :active / :focus) ----------------
pub fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
- self.hover.extend(f(StyleRefinement::default()).decls);
+ self.states_mut().hover.extend(f(StyleRefinement::default()).decls);
self
}
pub fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
- self.active.extend(f(StyleRefinement::default()).decls);
+ self.states_mut().active.extend(f(StyleRefinement::default()).decls);
self
}
pub fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
- self.focus.extend(f(StyleRefinement::default()).decls);
+ self.states_mut().focus.extend(f(StyleRefinement::default()).decls);
self
}
}
@@ -281,6 +302,10 @@ pub struct StyleRefinement {
impl Styled for Div {
fn decls_mut(&mut self) -> &mut Vec<Decl> {
+ // one allocation for a typical element's handful of style calls
+ if self.decls.capacity() == 0 {
+ self.decls.reserve(8);
+ }
&mut self.decls
}
}
@@ -337,6 +362,6 @@ impl FluentBuilder for StyleRefinement {}
pub fn canvas(paint: impl Fn(crate::geometry::Bounds<f32>, &mut crate::paint::Painter) + 'static)
-> Div {
let mut d = Div::new("canvas");
- d.paint = Some(Rc::new(paint));
+ d.paint = Some(Box::new(paint));
d
}
diff --git a/bindings/rust/blenderui/src/layout.rs b/bindings/rust/blenderui/src/layout.rs
index 34e05ea..0f838ac 100644
--- a/bindings/rust/blenderui/src/layout.rs
+++ b/bindings/rust/blenderui/src/layout.rs
@@ -5,39 +5,146 @@
//! boxes); inline elements own their words for painting and hit testing.
//! * Flex and grid containers get text runs as measured, wrapping leaves.
//! * Tables map onto flex rows and columns, lists paint their markers.
+//!
+//! Everything lives in flat arenas owned by the window and reused every
+//! frame: boxes and element data in [`Frame`], computed styles in
+//! [`StyleStore`] (shared between identical elements), the taffy tree, text
+//! widths and images. Boxes refer to each other by index; nothing is
+//! reference-counted.
-use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
-use std::rc::Rc;
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
use taffy::prelude::*;
use taffy::style::Overflow;
-use crate::css::{Decl, Rule, Stylesheet, Subject};
-use crate::element::{AnyElement, Div, Listeners, PaintFn, ParentElement};
+use crate::css::{Decl, Prop, Rule, Stylesheet, Subject};
+use crate::element::{AnyElement, Div, Listeners, PaintFn, ParentElement, SharedString};
use crate::geometry::{rect, Bounds, Units};
use crate::html::{tag_kind, ua_stylesheet, TagKind};
-use crate::paint::Image;
-use crate::style::{apply, Computed, DisplayKind, TextAlign, TextTransform, VAlign, WhiteSpace};
-use crate::text;
+use crate::paint::{Image, ImageCache};
+use crate::prof::{span, Phase};
+use crate::style::{apply, Computed, DisplayKind, Fnv, FnvMap, TextAlign, TextTransform, VAlign, WhiteSpace};
+use crate::text::{self, TextCache};
use crate::widgets::WidgetSpec;
+// ==========================================================================
+// Keys
+
+/// An element's identity across frames: a hash of its `.id()`, or of its
+/// parent's key, tag and position.
+pub(crate) type Key = u64;
+
+fn fnv(parts: &[&[u8]]) -> u64 {
+ let mut h = Fnv::default();
+ for p in parts {
+ h.write(p);
+ h.write(&[0xff]);
+ }
+ h.finish()
+}
+
+/// The key of the element with `.id(id)`.
+pub(crate) fn id_key(id: &str) -> Key {
+ fnv(&[b"#", id.as_bytes()])
+}
+
+fn child_key(parent: Key, tag: &str, n: usize) -> Key {
+ fnv(&[&parent.to_le_bytes(), tag.as_bytes(), &(n as u64).to_le_bytes()])
+}
+
+/// The key of the `<html>` element.
+pub(crate) const ROOT_KEY: Key = 0x68746d6c; // "html"
+
/// Interaction state the cascade reads (`:hover`, `:active`, `:focus`, `details[open]`).
#[derive(Default)]
pub(crate) struct UiState {
- pub hovered: HashSet<String>,
- pub active: HashSet<String>,
- pub focused: Option<String>,
- pub details_open: HashMap<String, bool>,
- pub scroll: HashMap<String, (f32, f32)>,
- pub checked: HashMap<String, bool>,
+ pub hovered: HashSet<Key>,
+ pub active: HashSet<Key>,
+ pub focused: Option<Key>,
+ /// The focused element and its ancestors (`:focus-within`).
+ pub focus_path: HashSet<Key>,
+ /// The `.id()` of the focused element.
+ pub focused_id: Option<String>,
+ pub details_open: HashMap<Key, bool>,
+ pub scroll: HashMap<Key, (f32, f32)>,
+ pub checked: HashMap<Key, bool>,
+}
+
+// ==========================================================================
+// Styles
+
+/// A computed style in a [`StyleStore`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub(crate) struct StyleId(u32);
+
+/// The style everything inherits from at the root.
+pub(crate) const ROOT_STYLE: StyleId = StyleId(0);
+
+/// What a computed style depends on (style sharing).
+struct StyleKey {
+ parent: StyleId,
+ viewport: (u32, u32),
+ author: u64,
+ rules: Vec<usize>,
+ decls: Vec<Decl>,
+ fixup: u8,
}
+/// Computed styles, shared by every element with the same inputs and kept
+/// across frames (browsers call this style sharing). Elements refer to them
+/// by [`StyleId`].
+pub(crate) struct StyleStore {
+ styles: Vec<Computed>,
+ cache: FnvMap<u64, Vec<(StyleKey, StyleId)>>,
+}
+
+impl Default for StyleStore {
+ fn default() -> Self {
+ StyleStore { styles: vec![Computed::default()], cache: Default::default() }
+ }
+}
+
+impl std::ops::Index<StyleId> for StyleStore {
+ type Output = Computed;
+ fn index(&self, id: StyleId) -> &Computed {
+ &self.styles[id.0 as usize]
+ }
+}
+
+impl StyleStore {
+ /// Before building a frame: drop everything when the store has grown
+ /// large (ids from the previous frame are not used after this).
+ fn begin_frame(&mut self) {
+ if self.styles.len() > 20_000 {
+ self.styles.truncate(1);
+ self.cache.clear();
+ }
+ }
+
+ fn add(&mut self, c: Computed) -> StyleId {
+ self.styles.push(c);
+ StyleId((self.styles.len() - 1) as u32)
+ }
+}
+
+/// The author stylesheet (all `<style>` elements), reparsed only when its text changes.
+#[derive(Default)]
+pub(crate) struct AuthorSheet {
+ hash: u64,
+ sheet: Stylesheet,
+}
+
+// ==========================================================================
+// Boxes
+
/// What a box holds.
pub(crate) enum Content {
Element,
- /// A word (or pre-formatted line) inside a line container.
- Word(String),
+ /// A word (or pre-formatted line) inside a line container: bytes
+ /// `start..end` of the text of box `src`.
+ Word { src: u32, start: u32, end: u32 },
/// A whole text run in a flex/grid container (wraps when measured).
Text(String),
LineBreak,
@@ -48,28 +155,40 @@ pub(crate) enum Content {
}
pub(crate) enum Replaced {
- Image(Rc<Image>),
+ Image(Arc<Image>),
Painted(PaintFn),
Placeholder(&'static str),
}
-/// The element-level data kept from a `Div` after building.
+/// The element-level data kept from a `Div` after building (moved, not copied).
pub(crate) struct ElData {
pub tag: &'static str,
- pub id: Option<String>,
- pub attrs: Vec<(String, String)>,
- pub listeners: Listeners,
+ pub id: Option<SharedString>,
+ pub attrs: Vec<(SharedString, SharedString)>,
+ pub listeners: Option<Box<Listeners>>,
}
+const NONE: u32 = u32::MAX;
+
pub(crate) struct BoxNode {
pub parent: Option<usize>,
- pub kids: Vec<usize>,
+ /// Element and text children, linked (words / breaks / line boxes point
+ /// at their parent but aren't linked into its list).
+ first: u32,
+ last: u32,
+ next: u32,
+ prev: u32,
pub content: Content,
- pub el: Option<Rc<ElData>>,
+ /// Index into [`Frame::els`].
+ el: u32,
/// The element this box belongs to (itself, or the inline element of a word).
pub owner: usize,
- pub style: Rc<Computed>,
- pub key: String,
+ pub style: StyleId,
+ pub key: Key,
+ /// What selectors can see of this element (its tag, id, attributes,
+ /// position and state, chained through its parent and previous sibling):
+ /// equal fingerprints match the same rules.
+ fp: u64,
pub taffy: Option<NodeId>,
pub pos: (usize, usize),
pub marker: Option<String>,
@@ -80,83 +199,133 @@ pub(crate) struct BoxNode {
pub visible: bool,
pub scroll_range: (f32, f32),
pub scroll_pos: (f32, f32),
+ /// This element is one layout leaf measuring its lone text child (that box).
+ pub fold: Option<usize>,
+ /// This text run is laid out by its parent (`fold`), not by its own node.
+ pub folded: bool,
}
-impl BoxNode {
- pub(crate) fn attr(&self, name: &str) -> Option<&str> {
- self.el.as_ref()?.attrs.iter().find(|(n, _)| n == name).map(|(_, v)| v.as_str())
- }
-}
-
-/// A laid-out frame.
+/// A laid-out frame. The arenas are reused by the next frame.
+#[derive(Default)]
pub(crate) struct Frame {
pub nodes: Vec<BoxNode>,
+ els: Vec<ElData>,
pub title: Option<String>,
- by_key: std::cell::OnceCell<HashMap<String, usize>>,
+ by_key: std::cell::OnceCell<HashMap<Key, usize>>,
+}
+
+/// Measure contexts of taffy leaves. Compared across frames: an unchanged
+/// context keeps the leaf's cached layout.
+#[derive(PartialEq)]
+pub(crate) enum Measure {
+ /// Text of the box registered under `key` this frame (already
+ /// whitespace-processed and transformed); `hash` identifies the text.
+ Text { key: Key, hash: u64, size: f32, flags: i32, line: f32, nowrap: bool },
+}
+
+/// The persistent taffy tree's nodes by box key (with the frame they were
+/// last used in). Reconciling instead of rebuilding lets taffy's cache skip
+/// every subtree whose style, content and children didn't change.
+#[derive(Default)]
+struct Recon {
+ map: FnvMap<Key, (NodeId, u32)>,
+ stamp: u32,
+ /// Nodes for duplicate keys this frame: removed next frame.
+ extra: Vec<NodeId>,
}
-enum Measure {
- /// The text of box `node` (already whitespace-processed and transformed).
- Text { node: usize, size: f32, flags: i32, line: f32, nowrap: bool },
+/// Everything layout keeps across frames, owned by the window.
+pub(crate) struct LayoutCaches {
+ pub styles: StyleStore,
+ pub text: TextCache,
+ pub images: ImageCache,
+ pub author: AuthorSheet,
+ pub taffy: TaffyTree<Measure>,
+ /// Box index of each taffy node (by slot), rebuilt in place each frame.
+ box_of: Vec<u32>,
+ /// Scratch for `finish`.
+ acc: Vec<Option<Bounds<f32>>>,
+ /// Matched rules by element fingerprint (+ viewport): selector matching
+ /// runs once per distinct element, not every frame.
+ matched: MatchCache,
+ recon: Recon,
+ /// Measured text leaves: key -> box index, this frame.
+ text_box: FnvMap<Key, usize>,
+}
+
+/// Rule indices (`Rule::order`) in the UA and author sheets.
+type RuleIds = smallvec::SmallVec<[u32; 8]>;
+
+#[derive(Default)]
+struct MatchCache {
+ map: FnvMap<u64, (RuleIds, RuleIds)>,
+ author: u64,
+}
+
+impl Default for LayoutCaches {
+ fn default() -> Self {
+ LayoutCaches {
+ styles: StyleStore::default(),
+ text: TextCache::default(),
+ images: ImageCache::default(),
+ author: AuthorSheet::default(),
+ taffy: TaffyTree::new(),
+ box_of: Vec::new(),
+ acc: Vec::new(),
+ matched: MatchCache::default(),
+ recon: Recon::default(),
+ text_box: FnvMap::default(),
+ }
+ }
}
struct Builder<'a> {
nodes: Vec<BoxNode>,
- taffy: TaffyTree<Measure>,
- author: Stylesheet,
+ els: Vec<ElData>,
+ taffy: &'a mut TaffyTree<Measure>,
+ styles: &'a mut StyleStore,
+ text: &'a mut TextCache,
+ images: &'a mut ImageCache,
+ matched: &'a mut MatchCache,
+ recon: &'a mut Recon,
+ text_box: &'a mut FnvMap<Key, usize>,
+ /// Set when a node changed while building the current subtree.
+ changed: bool,
+ author: &'a Stylesheet,
author_hash: u64,
state: &'a UiState,
viewport: (f32, f32),
title: Option<String>,
- widgets: &'a mut dyn FnMut(&str, &WidgetSpec) -> (f32, f32),
+ widgets: &'a mut dyn FnMut(Key, &WidgetSpec) -> (f32, f32),
}
-// -- style sharing ---------------------------------------------------------------------
+/// Child box indices / layout nodes being assembled: on the stack for the usual few.
+type Kids = smallvec::SmallVec<[usize; 8]>;
+type NodeList = smallvec::SmallVec<[NodeId; 8]>;
-/// What a computed style depends on. Holding the parent `Rc` and the value
-/// `Arc`s keeps their addresses unique while the entry lives, so they are
-/// compared by pointer.
-struct StyleKey {
- parent: Rc<Computed>,
- viewport: (u32, u32),
- author: u64,
- rules: Vec<usize>,
- decls: Vec<(std::borrow::Cow<'static, str>, std::sync::Arc<[crate::css::Tok]>, bool)>,
- fixup: u8,
+/// The slot index of a taffy node (dense from 0 after `TaffyTree::clear`).
+fn slot(id: NodeId) -> usize {
+ (u64::from(id) & 0xffff_ffff) as usize
}
-impl PartialEq for StyleKey {
- fn eq(&self, o: &Self) -> bool {
- Rc::ptr_eq(&self.parent, &o.parent)
- && self.viewport == o.viewport
- && self.author == o.author
- && self.fixup == o.fixup
- && self.rules == o.rules
- && self.decls.len() == o.decls.len()
- && self.decls.iter().zip(&o.decls).all(|(a, b)| {
- a.2 == b.2 && std::sync::Arc::ptr_eq(&a.1, &b.1) && a.0 == b.0
- })
- }
-}
-impl Eq for StyleKey {}
-
-impl std::hash::Hash for StyleKey {
- fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
- (Rc::as_ptr(&self.parent) as usize).hash(h);
- self.viewport.hash(h);
- self.author.hash(h);
- self.fixup.hash(h);
- self.rules.hash(h);
- for (p, v, imp) in &self.decls {
- p.hash(h);
- (std::sync::Arc::as_ptr(v) as *const () as usize).hash(h);
- imp.hash(h);
- }
- }
+/// Children of box `i` in the arena `nodes`.
+fn kids(nodes: &[BoxNode], i: usize) -> impl Iterator<Item = usize> + '_ {
+ let mut k = nodes[i].first;
+ std::iter::from_fn(move || {
+ (k != NONE).then(|| {
+ let cur = k as usize;
+ k = nodes[cur].next;
+ cur
+ })
+ })
}
-thread_local! {
- static STYLES: RefCell<crate::style::FnvMap<StyleKey, Rc<Computed>>> = RefCell::new(Default::default());
+fn el_attr<'a>(nodes: &[BoxNode], els: &'a [ElData], i: usize, name: &str) -> Option<&'a str> {
+ let e = nodes[i].el;
+ if e == NONE {
+ return None;
+ }
+ els[e as usize].attrs.iter().rev().find(|(n, _)| n == name).map(|(_, v)| v.as_ref())
}
// -- selector subject -------------------------------------------------------------------
@@ -164,45 +333,58 @@ thread_local! {
#[derive(Clone)]
struct NodeRef<'b> {
nodes: &'b [BoxNode],
+ els: &'b [ElData],
state: &'b UiState,
i: usize,
}
+impl NodeRef<'_> {
+ fn el(&self) -> Option<&ElData> {
+ let e = self.nodes[self.i].el;
+ (e != NONE).then(|| &self.els[e as usize])
+ }
+ fn own_attr(&self, name: &str) -> Option<&str> {
+ el_attr(self.nodes, self.els, self.i, name)
+ }
+}
+
impl Subject for NodeRef<'_> {
fn tag(&self) -> &str {
- self.nodes[self.i].el.as_ref().map(|e| e.tag).unwrap_or("")
+ self.el().map(|e| e.tag).unwrap_or("")
}
fn id(&self) -> Option<&str> {
- self.nodes[self.i].el.as_ref()?.id.as_deref()
+ self.el()?.id.as_deref()
}
fn has_class(&self, class: &str) -> bool {
- self.nodes[self.i].attr("class").is_some_and(|c| c.split_whitespace().any(|w| w == class))
+ self.own_attr("class").is_some_and(|c| c.split_whitespace().any(|w| w == class))
}
fn attr(&self, name: &str) -> Option<&str> {
let n = &self.nodes[self.i];
- if name == "open" && n.el.as_ref().is_some_and(|e| e.tag == "details") {
+ if name == "open" && self.tag() == "details" {
return self.state.details_open.get(&n.key).copied()
- .unwrap_or(n.attr("open").is_some()).then_some("");
+ .unwrap_or(self.own_attr("open").is_some()).then_some("");
}
- n.attr(name)
+ self.own_attr(name)
}
fn state(&self, pseudo: &str) -> bool {
- let n = &self.nodes[self.i];
+ let key = self.nodes[self.i].key;
match pseudo {
- "hover" => self.state.hovered.contains(&n.key),
- "active" => self.state.active.contains(&n.key),
- "focus" | "focus-visible" => self.state.focused.as_deref() == Some(n.key.as_str()),
- "focus-within" => self.state.focused.as_deref().is_some_and(|f| f.starts_with(&n.key)),
- "checked" => self.state.checked.get(&n.key).copied().unwrap_or(n.attr("checked").is_some()),
- "disabled" => n.attr("disabled").is_some(),
- "enabled" => n.attr("disabled").is_none(),
- "link" | "any-link" => self.tag() == "a" && n.attr("href").is_some(),
- "required" => n.attr("required").is_some(),
- "optional" => n.attr("required").is_none(),
- "read-only" => n.attr("readonly").is_some(),
- "read-write" => n.attr("readonly").is_none(),
+ "hover" => self.state.hovered.contains(&key),
+ "active" => self.state.active.contains(&key),
+ "focus" | "focus-visible" => self.state.focused == Some(key),
+ "focus-within" => self.state.focus_path.contains(&key),
+ "checked" => self.state.checked.get(&key).copied().unwrap_or(self.own_attr("checked").is_some()),
+ "disabled" => self.own_attr("disabled").is_some(),
+ "enabled" => self.own_attr("disabled").is_none(),
+ "link" | "any-link" => self.tag() == "a" && self.own_attr("href").is_some(),
+ "required" => self.own_attr("required").is_some(),
+ "optional" => self.own_attr("required").is_none(),
+ "read-only" => self.own_attr("readonly").is_some(),
+ "read-write" => self.own_attr("readonly").is_none(),
"open" => self.attr("open").is_some(),
- "placeholder-shown" => n.attr("placeholder").is_some() && n.attr("value").is_none_or(str::is_empty),
+ "placeholder-shown" => {
+ self.own_attr("placeholder").is_some() && self.own_attr("value").is_none_or(str::is_empty)
+ }
_ => false,
}
}
@@ -210,17 +392,20 @@ impl Subject for NodeRef<'_> {
self.nodes[self.i].parent.map(|p| NodeRef { i: p, ..self.clone() })
}
fn prev_sibling(&self) -> Option<Self> {
- let p = self.nodes[self.i].parent?;
- let sibs = &self.nodes[p].kids;
- let k = sibs.iter().position(|&s| s == self.i)?;
- sibs[..k].iter().rev().find(|&&s| self.nodes[s].el.is_some())
- .map(|&s| NodeRef { i: s, ..self.clone() })
+ let mut k = self.nodes[self.i].prev;
+ while k != NONE {
+ if self.nodes[k as usize].el != NONE {
+ return Some(NodeRef { i: k as usize, ..self.clone() });
+ }
+ k = self.nodes[k as usize].prev;
+ }
+ None
}
fn position(&self) -> (usize, usize) {
self.nodes[self.i].pos
}
fn is_empty(&self) -> bool {
- self.nodes[self.i].kids.is_empty()
+ self.nodes[self.i].first == NONE
}
}
@@ -243,71 +428,156 @@ fn collect_styles(el: &AnyElement, css: &mut String, title: &mut Option<String>)
}
}
-impl Builder<'_> {
+impl<'a> Builder<'a> {
fn subject(&self, i: usize) -> NodeRef<'_> {
- NodeRef { nodes: &self.nodes, state: self.state, i }
+ NodeRef { nodes: &self.nodes, els: &self.els, state: self.state, i }
}
- /// The computed style of element `i`, shared with every earlier element
- /// that had the same parent style, matched rules and declarations
- /// (browsers call this style sharing). `fixup` adjusts `display` for
- /// widgets and flex/grid items before the result is cached.
- fn cascade(&self, i: usize, div: &Div, parent: &Rc<Computed>, fixup: u8) -> Rc<Computed> {
- let _s = crate::prof::span(" cascade");
- let subj = self.subject(i);
- let ua = ua_stylesheet().matching(&subj, self.viewport);
- let au = self.author.matching(&subj, self.viewport);
+ fn st(&self, i: usize) -> &Computed {
+ &self.styles[self.nodes[i].style]
+ }
+
+ fn attr(&self, i: usize, name: &str) -> Option<&str> {
+ el_attr(&self.nodes, &self.els, i, name)
+ }
+
+ /// The computed style of element `i`, shared with every element (this
+ /// frame or earlier) that had the same parent style, matched rules and
+ /// declarations. `fixup` adjusts `display` for widgets and flex/grid
+ /// items before the result is shared.
+ fn cascade(&mut self, i: usize, div: &Div, parent: StyleId, fixup: u8) -> StyleId {
+ let _s = span(Phase::Cascade);
+ let (ua, au) = self.matched_rules(i);
let decls = self.declared(i, div, &ua, &au);
+ let viewport = (self.viewport.0.to_bits(), self.viewport.1.to_bits());
+ let rule_ids = || ua.iter().map(|r| *r as *const Rule as usize).chain(au.iter().map(|r| r.order));
+ // probe without building a key: hash the inputs, compare in place
+ let hash = {
+ let mut h = Fnv::default();
+ parent.hash(&mut h);
+ viewport.hash(&mut h);
+ self.author_hash.hash(&mut h);
+ fixup.hash(&mut h);
+ for r in rule_ids() {
+ r.hash(&mut h);
+ }
+ for d in &decls {
+ d.probe_hash(&mut h);
+ }
+ h.finish()
+ };
+ let same = |k: &StyleKey| {
+ k.parent == parent
+ && k.viewport == viewport
+ && k.author == self.author_hash
+ && k.fixup == fixup
+ && k.rules.len() == ua.len() + au.len()
+ && k.rules.iter().copied().eq(rule_ids())
+ && k.decls.len() == decls.len()
+ && k.decls.iter().zip(&decls).all(|(a, d)| a == *d)
+ };
+ if let Some(&(_, id)) = self.styles.cache.get(&hash).and_then(|b| b.iter().find(|(k, _)| same(k))) {
+ return id;
+ }
let key = StyleKey {
- parent: parent.clone(),
- viewport: (self.viewport.0.to_bits(), self.viewport.1.to_bits()),
+ parent,
+ viewport,
author: self.author_hash,
- rules: ua.iter().map(|r| *r as *const Rule as usize).chain(au.iter().map(|r| r.order)).collect(),
- decls: decls.iter().map(|d| (d.prop.clone(), d.value.clone(), d.important)).collect(),
+ rules: rule_ids().collect(),
+ decls: decls.iter().map(|d| (*d).clone()).collect(),
fixup,
};
- if let Some(hit) = STYLES.with(|c| c.borrow().get(&key).cloned()) {
- return hit;
- }
let mut c = self.compute(parent, &decls);
match fixup {
1 if c.display == DisplayKind::Inline => c.display = DisplayKind::InlineBlock,
2 if c.display == DisplayKind::Inline => c.display = DisplayKind::Block,
_ => {}
}
- let c = Rc::new(c);
- STYLES.with(|cache| {
- let mut cache = cache.borrow_mut();
- if cache.len() > 20_000 {
- cache.clear();
+ let id = self.styles.add(c);
+ self.styles.cache.entry(hash).or_default().push((key, id));
+ id
+ }
+
+ /// The UA and author rules matching element `i`: from the memo when an
+ /// element with the same fingerprint was matched before.
+ fn matched_rules(&mut self, i: usize) -> (crate::css::Matches<'static>, crate::css::Matches<'a>) {
+ let ua_sheet = ua_stylesheet();
+ let author: &'a Stylesheet = self.author;
+ let memo = {
+ let mut h = Fnv::default();
+ self.nodes[i].fp.hash(&mut h);
+ self.viewport.0.to_bits().hash(&mut h);
+ self.viewport.1.to_bits().hash(&mut h);
+ h.finish()
+ };
+ if let Some((u, a)) = self.matched.map.get(&memo) {
+ return (u.iter().map(|&k| &ua_sheet.rules[k as usize]).collect(),
+ a.iter().map(|&k| &author.rules[k as usize]).collect());
+ }
+ let subj = self.subject(i);
+ let ua = ua_sheet.matches(&subj, self.viewport);
+ let au = author.matches(&subj, self.viewport);
+ self.matched.map.insert(memo, (ua.iter().map(|r| r.order as u32).collect(),
+ au.iter().map(|r| r.order as u32).collect()));
+ (ua, au)
+ }
+
+ /// The fingerprint of element `i` (see [`BoxNode::fp`]).
+ fn fingerprint(&self, i: usize) -> u64 {
+ let n = &self.nodes[i];
+ let mut h = Fnv::default();
+ n.parent.map(|p| self.nodes[p].fp).unwrap_or(0).hash(&mut h);
+ // the previous element sibling (text in between doesn't count)
+ let mut k = n.prev;
+ while k != NONE && self.nodes[k as usize].el == NONE {
+ k = self.nodes[k as usize].prev;
+ }
+ (if k == NONE { 0 } else { self.nodes[k as usize].fp }).hash(&mut h);
+ n.pos.hash(&mut h);
+ if let Some(e) = (n.el != NONE).then(|| &self.els[n.el as usize]) {
+ e.tag.hash(&mut h);
+ e.id.as_deref().hash(&mut h);
+ for (a, v) in &e.attrs {
+ a.hash(&mut h);
+ v.hash(&mut h);
}
- cache.insert(key, c.clone());
- });
- c
+ }
+ let st = self.state;
+ let key = n.key;
+ (st.hovered.contains(&key), st.active.contains(&key), st.focused == Some(key),
+ st.focus_path.contains(&key), st.checked.get(&key).copied(), st.details_open.get(&key).copied())
+ .hash(&mut h);
+ h.finish()
}
/// Every declaration that applies to element `i`, in cascade order.
- fn declared<'d>(&self, i: usize, div: &'d Div, ua: &[&'d Rule], au: &[&'d Rule]) -> Vec<&'d Decl> {
- let key = &self.nodes[i].key;
- let mut decls: Vec<&Decl> = Vec::new();
+ fn declared<'d>(&self, i: usize, div: &'d Div, ua: &[&'d Rule], au: &[&'d Rule])
+ -> smallvec::SmallVec<[&'d Decl; 24]> {
+ let key = self.nodes[i].key;
+ let mut decls = smallvec::SmallVec::new();
decls.extend(ua.iter().flat_map(|r| r.decls.iter()));
decls.extend(au.iter().flat_map(|r| r.decls.iter()));
decls.extend(div.decls.iter());
- if self.state.hovered.contains(key) {
- decls.extend(div.hover.iter());
- }
- if self.state.active.contains(key) {
- decls.extend(div.active.iter());
- }
- if self.state.focused.as_deref() == Some(key.as_str()) {
- decls.extend(div.focus.iter());
+ if let Some(st) = &div.states {
+ if self.state.hovered.contains(&key) {
+ decls.extend(st.hover.iter());
+ }
+ if self.state.active.contains(&key) {
+ decls.extend(st.active.iter());
+ }
+ if self.state.focused == Some(key) {
+ decls.extend(st.focus.iter());
+ }
}
decls
}
- fn compute(&self, parent: &Computed, decls: &[&Decl]) -> Computed {
+ fn compute(&self, parent: StyleId, decls: &[&Decl]) -> Computed {
+ let parent = &self.styles[parent];
let mut c = Computed::inherit(parent);
- let font_first = |d: &&Decl| d.prop == "font-size" || d.prop == "font";
+ const FONT_SIZE: Prop = Prop::named("font-size");
+ const FONT: Prop = Prop::named("font");
+ let font_first = |d: &&Decl| d.prop == FONT_SIZE || d.prop == FONT;
for important in [false, true] {
// font-size first: em lengths in the other properties depend on it
for d in decls.iter().filter(|d| d.important == important && font_first(d)) {
@@ -327,17 +597,27 @@ impl Builder<'_> {
Units { font_size, viewport: self.viewport }
}
- fn push(&mut self, parent: Option<usize>, content: Content, owner: Option<usize>,
- style: Rc<Computed>, key: String) -> usize {
+ /// A new box. `link`: append it to its parent's child list (elements and
+ /// text); words, breaks and line boxes only point at their parent.
+ fn push(&mut self, parent: Option<usize>, content: Content, owner: Option<usize>, style: StyleId,
+ key: Key, link: bool) -> usize {
let i = self.nodes.len();
+ let prev = match parent {
+ Some(p) if link => self.nodes[p].last,
+ _ => NONE,
+ };
self.nodes.push(BoxNode {
parent,
- kids: Vec::new(),
+ first: NONE,
+ last: NONE,
+ next: NONE,
+ prev,
content,
- el: None,
+ el: NONE,
owner: owner.unwrap_or(i),
style,
key,
+ fp: 0,
taffy: None,
pos: (1, 1),
marker: None,
@@ -347,49 +627,75 @@ impl Builder<'_> {
visible: true,
scroll_range: (0.0, 0.0),
scroll_pos: (0.0, 0.0),
+ fold: None,
+ folded: false,
});
- if let Some(p) = parent {
- self.nodes[p].kids.push(i);
+ if let (Some(p), true) = (parent, link) {
+ if prev == NONE {
+ self.nodes[p].first = i as u32;
+ } else {
+ self.nodes[prev as usize].next = i as u32;
+ }
+ self.nodes[p].last = i as u32;
}
i
}
+ /// Remove the last box (an element that turned out not to render).
+ fn pop(&mut self) {
+ let n = self.nodes.pop().expect("a box to pop");
+ if let Some(p) = n.parent {
+ let i = self.nodes.len() as u32;
+ if self.nodes[p].last == i {
+ self.nodes[p].last = n.prev;
+ if n.prev == NONE {
+ self.nodes[p].first = NONE;
+ } else {
+ self.nodes[n.prev as usize].next = NONE;
+ }
+ }
+ }
+ if n.el != NONE && n.el as usize == self.els.len() - 1 {
+ self.els.pop();
+ }
+ }
+
/// Build an element; returns its index (None when not rendered).
- fn element(&mut self, mut div: Div, parent: Option<usize>, key: String, pos: (usize, usize))
- -> Option<usize> {
- let parent_style = parent.map(|p| self.nodes[p].style.clone())
- .unwrap_or_else(|| root_parent());
- let i = self.push(parent, Content::Element, None, parent_style.clone(), key);
+ fn element(&mut self, mut div: Div, parent: Option<usize>, key: Key, pos: (usize, usize)) -> Option<usize> {
+ let parent_style = parent.map(|p| self.nodes[p].style).unwrap_or(ROOT_STYLE);
+ let i = self.push(parent, Content::Element, None, parent_style, key, true);
self.nodes[i].pos = pos;
- self.nodes[i].el = Some(Rc::new(ElData {
+ self.nodes[i].el = self.els.len() as u32;
+ self.els.push(ElData {
tag: div.tag,
- id: div.id.as_ref().map(|s| s.to_string()),
- attrs: div.attrs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
+ id: div.id.take(),
+ attrs: std::mem::take(&mut div.attrs),
listeners: std::mem::take(&mut div.listeners),
- }));
+ });
+ self.nodes[i].fp = self.fingerprint(i);
let kind = tag_kind(div.tag);
// widgets and replaced elements are atomic inlines; flex/grid items are blockified
let fixup = if kind == TagKind::Widget || kind == TagKind::Replaced {
1
- } else if parent.is_some_and(|p| matches!(self.nodes[p].style.display,
+ } else if parent.is_some_and(|p| matches!(self.st(p).display,
DisplayKind::Flex | DisplayKind::InlineFlex
| DisplayKind::Grid | DisplayKind::InlineGrid)) {
2
} else {
0
};
- let style = self.cascade(i, &div, &parent_style, fixup);
- if style.display == DisplayKind::None || kind == TagKind::Metadata {
- self.nodes.pop();
- if let Some(p) = parent {
- self.nodes[p].kids.pop();
- }
+ let style = self.cascade(i, &div, parent_style, fixup);
+ if self.styles[style].display == DisplayKind::None || kind == TagKind::Metadata {
+ self.pop();
return None;
}
self.nodes[i].style = style;
+ // attributes moved into ElData: widgets read them back through the arena
+ div.attrs = Vec::new();
match kind {
TagKind::Widget => {
- let spec = WidgetSpec::from_element(&div, &self.nodes[i].key, self.state);
+ let spec = WidgetSpec::from_element(&div, self.els.last().map(|e| &e.attrs[..]).unwrap_or(&[]),
+ key, self.state);
if let Some(spec) = spec {
self.nodes[i].content = Content::Widget(spec);
} else {
@@ -400,7 +706,7 @@ impl Builder<'_> {
let r = if let Some(f) = div.paint.take() {
Replaced::Painted(f)
} else if let Some(img) = div.image.take().or_else(|| {
- div.get_attr("src").and_then(crate::paint::load_image)
+ self.attr(i, "src").map(str::to_owned).and_then(|s| self.images.load(&s))
}) {
Replaced::Image(img)
} else {
@@ -420,7 +726,7 @@ impl Builder<'_> {
}
}
if div.tag == "q" {
- let (open, close) = self.nodes[i].style.quotes.clone()
+ let (open, close) = self.st(i).quotes.clone()
.unwrap_or_else(|| ("\u{201c}".into(), "\u{201d}".into()));
children.insert(0, AnyElement::Text(open.into()));
children.push(AnyElement::Text(close.into()));
@@ -434,41 +740,43 @@ impl Builder<'_> {
/// Children of element `i`: elements and text, keyed by position.
fn children(&mut self, i: usize, mut children: Vec<AnyElement>) {
// list markers: painted outside the box, or inline text when `inside`
- if self.nodes[i].style.display == DisplayKind::ListItem {
- let ls = self.nodes[i].style.list_style;
- let tag = self.nodes[i].el.as_ref().map(|e| e.tag).unwrap_or("");
+ if self.st(i).display == DisplayKind::ListItem {
+ let ls = self.st(i).list_style;
+ let tag = self.subject(i).tag().to_owned();
let marker = if tag == "summary" {
let details = self.nodes[i].parent.unwrap_or(i);
Some(if self.subject(details).attr("open").is_some() { "\u{25be}" } else { "\u{25b8}" }.into())
} else {
let idx = self.nodes[i].pos.0 + self.nodes[i].parent
- .and_then(|p| self.nodes[p].attr("start"))
+ .and_then(|p| self.attr(p, "start"))
.and_then(|s| s.parse::<usize>().ok()).map(|s| s - 1).unwrap_or(0);
ls.marker(idx)
};
match marker {
- Some(m) if self.nodes[i].style.marker_inside => {
+ Some(m) if self.st(i).marker_inside => {
children.insert(0, AnyElement::Text(format!("{m}\u{a0}").into()));
}
m => self.nodes[i].marker = m,
}
}
let count = children.iter().filter(|c| matches!(c, AnyElement::Element(_))).count();
- let mut k = 0;
+ let (mut k, mut n) = (0, 0);
+ let parent_key = self.nodes[i].key;
for child in children {
+ n += 1;
match child {
AnyElement::Element(d) => {
k += 1;
let key = match &d.id {
- Some(id) => format!("#{id}"),
- None => format!("{}/{}{}", self.nodes[i].key, d.tag, k),
+ Some(id) => id_key(id),
+ None => child_key(parent_key, d.tag, k),
};
- self.element(*d, Some(i), key, (k, count));
+ self.element(d, Some(i), key, (k, count));
}
AnyElement::Text(t) => {
- let key = format!("{}/t{}", self.nodes[i].key, self.nodes[i].kids.len());
- let style = self.nodes[i].style.clone();
- self.push(Some(i), Content::Text(t.into_owned()), Some(i), style, key);
+ let style = self.nodes[i].style;
+ self.push(Some(i), Content::Text(t.into_owned()), Some(i), style,
+ child_key(parent_key, "#text", n), true);
}
}
}
@@ -478,14 +786,13 @@ impl Builder<'_> {
fn is_block_level(&self, i: usize) -> bool {
match &self.nodes[i].content {
- Content::Element => !self.nodes[i].style.display.is_inline_level(),
- Content::Widget(_) | Content::Replaced(_) => false,
+ Content::Element => !self.st(i).display.is_inline_level(),
_ => false,
}
}
fn base_style(&self, i: usize) -> Style {
- let c = &self.nodes[i].style;
+ let c = self.st(i);
let mut s = c.layout.clone();
s.display = match c.display {
DisplayKind::Flex | DisplayKind::InlineFlex => Display::Flex,
@@ -513,7 +820,7 @@ impl Builder<'_> {
_ => Display::Block,
};
if c.display == DisplayKind::TableCell && s.size.width == Dimension::Auto {
- let span = self.nodes[i].attr("colspan").and_then(|v| v.parse::<f32>().ok()).unwrap_or(1.0);
+ let span = self.attr(i, "colspan").and_then(|v| v.parse::<f32>().ok()).unwrap_or(1.0);
s.flex_grow = span;
s.flex_shrink = 1.0;
s.flex_basis = Dimension::Percent(0.0);
@@ -538,19 +845,101 @@ impl Builder<'_> {
s
}
+ /// The taffy node for `key` with this style, measure context and
+ /// children: last frame's node, updated only where something differs
+ /// (which marks it dirty), or a new one.
+ fn node(&mut self, key: Key, style: Style, ctx: Option<Measure>, children: &[NodeId]) -> NodeId {
+ let stamp = self.recon.stamp;
+ let reuse = match self.recon.map.get_mut(&key) {
+ Some((id, st)) if *st != stamp => {
+ *st = stamp;
+ Some(*id)
+ }
+ _ => None,
+ };
+ let t = &mut *self.taffy;
+ if let Some(id) = reuse {
+ if t.style(id).map(|s| *s != style).unwrap_or(true) {
+ let _ = t.set_style(id, style);
+ self.changed = true;
+ }
+ let same_kids = t.child_count(id) == children.len()
+ && children.iter().enumerate().all(|(k, c)| t.child_at_index(id, k).ok() == Some(*c));
+ if !same_kids {
+ let _ = t.set_children(id, children);
+ self.changed = true;
+ }
+ if t.get_node_context(id) != ctx.as_ref() {
+ let _ = t.set_node_context(id, ctx);
+ self.changed = true;
+ }
+ return id;
+ }
+ let id = match ctx {
+ Some(m) => t.new_leaf_with_context(style, m).unwrap(),
+ None => t.new_with_children(style, children).unwrap(),
+ };
+ self.changed = true;
+ match self.recon.map.entry(key) {
+ std::collections::hash_map::Entry::Occupied(_) => self.recon.extra.push(id), // duplicate key
+ std::collections::hash_map::Entry::Vacant(v) => {
+ v.insert((id, stamp));
+ }
+ }
+ id
+ }
+
fn leaf(&mut self, i: usize, style: Style) -> NodeId {
- let id = self.taffy.new_leaf(style).unwrap();
+ let id = self.node(self.nodes[i].key, style, None, &[]);
self.nodes[i].taffy = Some(id);
id
}
- /// The taffy node for box `i` (and its subtree).
+ /// Replace the text of box `k` by its whitespace-processed, transformed form.
+ fn transform_text(&mut self, k: usize, c: StyleId) {
+ let (tt, ws) = (self.styles[c].text_transform, self.styles[c].white_space);
+ if let Content::Text(t) = &self.nodes[k].content {
+ if let std::borrow::Cow::Owned(s) = transform(t, tt, ws) {
+ self.nodes[k].content = Content::Text(s);
+ }
+ }
+ }
+
+ /// The measure context for the text of box `node`, registered under `key`.
+ fn text_measure(&mut self, key: Key, node: usize, c: StyleId, nowrap: bool) -> Measure {
+ self.text_box.insert(key, node);
+ let hash = match &self.nodes[node].content {
+ Content::Text(t) => fnv(&[t.as_bytes()]),
+ _ => 0,
+ };
+ let c = &self.styles[c];
+ Measure::Text { key, hash, size: c.font_size, flags: text::flags(c), line: c.line_px(), nowrap }
+ }
+
+ /// The taffy node for box `i` (and its subtree). Marks it dirty when
+ /// anything below changed (taffy's own propagation follows parent links,
+ /// which reconciling can leave stale).
fn layout_node(&mut self, i: usize) -> NodeId {
- let base = self.base_style(i);
- let c = self.nodes[i].style.clone();
+ let outer = std::mem::replace(&mut self.changed, false);
+ let id = self.layout_node_inner(i);
+ if self.changed {
+ let _ = self.taffy.mark_dirty(id);
+ }
+ self.changed |= outer;
+ id
+ }
+
+ fn layout_node_inner(&mut self, i: usize) -> NodeId {
+ let mut base = self.base_style(i);
+ if i == 0 {
+ // the root fills the viewport
+ base.min_size = Size { width: Dimension::Length(self.viewport.0),
+ height: Dimension::Length(self.viewport.1) };
+ }
+ let sid = self.nodes[i].style;
match &self.nodes[i].content {
Content::Widget(spec) => {
- let (w, h) = (self.widgets)(&self.nodes[i].key, spec);
+ let (w, h) = (self.widgets)(self.nodes[i].key, spec);
let mut s = base;
if s.size.width == Dimension::Auto {
s.size.width = Dimension::Length(w);
@@ -565,7 +954,7 @@ impl Builder<'_> {
Replaced::Image(img) => (img.width as f32, img.height as f32),
_ => (300.0, 150.0),
};
- let attr = |n: &str| self.nodes[i].attr(n).and_then(|v| v.trim_end_matches("px").parse::<f32>().ok());
+ let attr = |n: &str| self.attr(i, n).and_then(|v| v.trim_end_matches("px").parse::<f32>().ok());
let mut s = base;
let (aw, ah) = (attr("width"), attr("height"));
if s.size.width == Dimension::Auto {
@@ -587,178 +976,245 @@ impl Builder<'_> {
flex_shrink: 0.0, ..Default::default() };
return self.leaf(i, s);
}
- Content::Text(t) => {
+ Content::Text(_) => {
// a text run as a flex/grid item: measured, wrapping. The box
// keeps the transformed text, so paint draws what was measured.
- if let std::borrow::Cow::Owned(s) = transform(t, c.text_transform, c.white_space) {
- self.nodes[i].content = Content::Text(s);
- }
- let m = Measure::Text {
- node: i,
- size: c.font_size,
- flags: text::flags(&c),
- line: c.line_px(),
- nowrap: matches!(c.white_space, WhiteSpace::NoWrap | WhiteSpace::Pre),
- };
- let id = self.taffy.new_leaf_with_context(Style::default(), m).unwrap();
+ self.transform_text(i, sid);
+ let nowrap = matches!(self.styles[sid].white_space, WhiteSpace::NoWrap | WhiteSpace::Pre);
+ let key = self.nodes[i].key;
+ let m = self.text_measure(key, i, sid, nowrap);
+ let id = self.node(key, Style::default(), Some(m), &[]);
self.nodes[i].taffy = Some(id);
return id;
}
_ => {}
}
+ if let Some(k) = self.foldable_text(i) {
+ // one leaf for the box and its text: the text is measured as the
+ // box's content and placed inside it after layout
+ self.transform_text(k, sid);
+ let nowrap = self.styles[sid].white_space == WhiteSpace::NoWrap;
+ let key = self.nodes[i].key;
+ let m = self.text_measure(key, k, sid, nowrap);
+ let mut s = base;
+ s.display = Display::Block;
+ let id = self.node(key, s, Some(m), &[]);
+ self.nodes[i].taffy = Some(id);
+ self.nodes[i].fold = Some(k);
+ self.nodes[k].folded = true;
+ return id;
+ }
+ let c = self.styles[sid].clone_display();
let flex_like = matches!(c.display, DisplayKind::Flex | DisplayKind::InlineFlex
| DisplayKind::Grid | DisplayKind::InlineGrid
| DisplayKind::Table | DisplayKind::TableRowGroup
| DisplayKind::TableRow);
- let kids = self.nodes[i].kids.clone();
- let mut kids = kids;
- kids.sort_by_key(|&k| {
- let st = &self.nodes[k].style;
+ let mut list: Kids = kids(&self.nodes, i).collect();
+ let ordered = |b: &Builder, k: usize| {
+ let st = b.st(k);
if st.display == DisplayKind::TableCaption && st.caption_bottom { i32::MAX } else { st.order }
- });
- let mut out: Vec<NodeId> = Vec::new();
+ };
+ if list.iter().any(|&k| ordered(self, k) != 0) {
+ list.sort_by_key(|&k| ordered(self, k));
+ }
+ let mut out: NodeList = NodeList::new();
if flex_like {
- for k in kids {
+ for k in list {
if let Content::Text(t) = &self.nodes[k].content {
- if t.trim().is_empty() && self.nodes[k].style.white_space == WhiteSpace::Normal {
+ if t.trim().is_empty() && self.st(k).white_space == WhiteSpace::Normal {
continue;
}
}
- out.extend(self.child_nodes(k));
+ self.child_nodes(k, &mut out);
}
- let id = self.taffy.new_with_children(base, &out).unwrap();
+ let id = self.node(self.nodes[i].key, base, None, &out);
self.nodes[i].taffy = Some(id);
return id;
}
// block container: runs of inline content become line boxes
- let all_inline = kids.iter().all(|&k| !self.is_block_level(k));
- if all_inline {
- let mut line = Vec::new();
- self.inline_items(&kids, i, &mut line, true);
- let id = self.taffy.new_with_children(Self::line_style(&c, base), &line).unwrap();
+ if list.iter().all(|&k| !self.is_block_level(k)) {
+ self.inline_items(&list, i, &mut out, true);
+ let line = Self::line_style(&self.styles[sid], base);
+ let id = self.node(self.nodes[i].key, line, None, &out);
self.nodes[i].taffy = Some(id);
return id;
}
- let mut run: Vec<usize> = Vec::new();
- for k in kids {
+ let mut run: Kids = Kids::new();
+ for k in list {
if self.is_block_level(k) {
self.flush_run(i, &mut run, &mut out);
- out.extend(self.child_nodes(k));
+ self.child_nodes(k, &mut out);
} else {
run.push(k);
}
}
self.flush_run(i, &mut run, &mut out);
- let id = self.taffy.new_with_children(base, &out).unwrap();
+ let id = self.node(self.nodes[i].key, base, None, &out);
self.nodes[i].taffy = Some(id);
id
}
- fn child_nodes(&mut self, k: usize) -> Vec<NodeId> {
- if self.nodes[k].style.display == DisplayKind::Contents {
- let kids = self.nodes[k].kids.clone();
- return kids.into_iter().flat_map(|c| self.child_nodes(c)).collect();
+ /// The lone text child of element `i`, when laying the pair out as one
+ /// measured leaf gives the same result as two nodes (or a line of words).
+ fn foldable_text(&self, i: usize) -> Option<usize> {
+ let n = &self.nodes[i];
+ if !matches!(n.content, Content::Element) || n.first == NONE || n.first != n.last {
+ return None;
+ }
+ let k = n.first as usize;
+ match &self.nodes[k].content {
+ Content::Text(t) if !t.trim().is_empty() => {}
+ _ => return None,
+ }
+ let c = self.st(i);
+ let s = &c.layout;
+ let display_ok = match c.display {
+ DisplayKind::Block | DisplayKind::InlineBlock | DisplayKind::ListItem
+ | DisplayKind::TableCell | DisplayKind::TableCaption => true,
+ DisplayKind::Flex | DisplayKind::InlineFlex => {
+ s.flex_wrap == FlexWrap::NoWrap
+ && matches!(s.flex_direction, FlexDirection::Row | FlexDirection::Column)
+ }
+ _ => false,
+ };
+ (display_ok
+ && c.letter_spacing == 0.0
+ && c.word_spacing == 0.0
+ && c.text_indent == crate::geometry::Length::Px(0.0)
+ && c.vertical_align == VAlign::Baseline
+ && !c.small_caps
+ && matches!(c.white_space, WhiteSpace::Normal | WhiteSpace::NoWrap)
+ && s.overflow.x == Overflow::Visible
+ && s.overflow.y == Overflow::Visible)
+ .then_some(k)
+ }
+
+ fn child_nodes(&mut self, k: usize, out: &mut NodeList) {
+ if self.st(k).display == DisplayKind::Contents {
+ let list: Kids = kids(&self.nodes, k).collect();
+ for c in list {
+ self.child_nodes(c, out);
+ }
+ return;
}
- vec![self.layout_node(k)]
+ out.push(self.layout_node(k));
}
/// An anonymous line box for inline content between blocks.
- fn flush_run(&mut self, parent: usize, run: &mut Vec<usize>, out: &mut Vec<NodeId>) {
+ fn flush_run(&mut self, parent: usize, run: &mut Kids, out: &mut NodeList) {
let only_space = run.iter().all(|&k| matches!(&self.nodes[k].content,
Content::Text(t) if t.trim().is_empty()));
if run.is_empty() || only_space {
run.clear();
return;
}
- let style = self.nodes[parent].style.clone();
- let key = format!("{}/anon{}", self.nodes[parent].key, out.len());
- let anon = self.push(None, Content::Anon, Some(parent), style.clone(), key);
- self.nodes[anon].parent = Some(parent);
- let mut line = Vec::new();
- let items: Vec<usize> = std::mem::take(run);
+ let style = self.nodes[parent].style;
+ let key = child_key(self.nodes[parent].key, "#anon", out.len());
+ let anon = self.push(Some(parent), Content::Anon, Some(parent), style, key, false);
+ let mut line = NodeList::new();
+ let items: Kids = std::mem::take(run);
self.inline_items(&items, parent, &mut line, true);
- let id = self.taffy.new_with_children(Self::line_style(&style, Style::default()), &line).unwrap();
+ let ls = Self::line_style(&self.styles[style], Style::default());
+ let id = self.node(key, ls, None, &line);
+ if self.changed {
+ let _ = self.taffy.mark_dirty(id);
+ }
self.nodes[anon].taffy = Some(id);
out.push(id);
}
/// Flatten inline content into line items: words, atomic inline boxes, breaks.
- fn inline_items(&mut self, kids: &[usize], owner: usize, line: &mut Vec<NodeId>, first: bool) {
+ fn inline_items(&mut self, list: &[usize], owner: usize, line: &mut NodeList, first: bool) {
let mut first_word = first;
- for &k in kids {
+ for &k in list {
match &self.nodes[k].content {
Content::Text(_) => {
- let Content::Text(t) = std::mem::replace(&mut self.nodes[k].content, Content::Anon) else {
- unreachable!()
- };
- let words = self.words(k, owner, &t, first_word);
- self.nodes[k].content = Content::Text(t);
- if !words.is_empty() {
+ let n = line.len();
+ self.words(k, owner, first_word, line);
+ if line.len() > n {
first_word = false;
}
- line.extend(words);
}
- Content::Element if self.nodes[k].style.display == DisplayKind::Inline
- || self.nodes[k].style.display == DisplayKind::Contents => {
- let kids = self.nodes[k].kids.clone();
- self.inline_items(&kids, k, line, first_word);
+ Content::Element if matches!(self.st(k).display, DisplayKind::Inline | DisplayKind::Contents) => {
+ let inner: Kids = kids(&self.nodes, k).collect();
+ self.inline_items(&inner, k, line, first_word);
first_word = false;
}
_ => {
- line.extend(self.child_nodes(k));
+ self.child_nodes(k, line);
first_word = false;
}
}
}
}
- /// Word boxes for a text node, with the style of its inline owner.
- fn words(&mut self, text_node: usize, owner: usize, t: &str, first: bool) -> Vec<NodeId> {
- let c = self.nodes[owner].style.clone();
- let text = transform(t, c.text_transform, c.white_space);
- let flags = text::flags(&c);
+ /// Word boxes for text box `src`, with the style of its inline owner. The
+ /// box keeps the processed text; words are byte ranges into it.
+ fn words(&mut self, src: usize, owner: usize, first: bool, line: &mut NodeList) {
+ let sid = self.nodes[owner].style;
+ let c = &self.styles[sid];
+ let (ws, tt, size, letter, word_sp) = (c.white_space, c.text_transform, c.font_size, c.letter_spacing, c.word_spacing);
+ let flags = text::flags(c);
let line_h = c.line_px();
- let space = text::width(" ", c.font_size, flags) + c.word_spacing;
- let mut pieces: Vec<(String, bool, bool)> = Vec::new(); // text, trailing space, forced break after
- match c.white_space {
+ let indent = if first { c.text_indent.resolve(&self.units(size), 0.0) } else { 0.0 };
+ // the processed text, kept in the box
+ let Content::Text(raw) = std::mem::replace(&mut self.nodes[src].content, Content::Anon) else { return };
+ let mut text = match transform(&raw, tt, ws) {
+ std::borrow::Cow::Borrowed(_) => raw,
+ std::borrow::Cow::Owned(s) => s,
+ };
+ if ws == WhiteSpace::NoWrap {
+ text = collapse(&text);
+ }
+ // pieces: byte range, trailing space, forced break after
+ let mut pieces: smallvec::SmallVec<[(usize, usize, bool, bool); 16]> = smallvec::SmallVec::new();
+ let base = text.as_ptr() as usize;
+ let range = |w: &str| (w.as_ptr() as usize - base, w.as_ptr() as usize - base + w.len());
+ match ws {
WhiteSpace::Pre | WhiteSpace::PreWrap | WhiteSpace::PreLine => {
let lines: Vec<&str> = text.split('\n').collect();
for (n, l) in lines.iter().enumerate() {
let brk = n + 1 < lines.len();
- if c.white_space == WhiteSpace::Pre {
- pieces.push((l.to_string(), false, brk));
+ if ws == WhiteSpace::Pre {
+ let (a, b) = range(l);
+ pieces.push((a, b, false, brk));
} else {
- let ws: Vec<&str> = l.split_whitespace().collect();
- if ws.is_empty() {
- pieces.push((String::new(), false, brk));
+ let words: Vec<&str> = l.split_whitespace().collect();
+ if words.is_empty() {
+ let (a, _) = range(l);
+ pieces.push((a, a, false, brk));
}
- for (j, w) in ws.iter().enumerate() {
- pieces.push((w.to_string(), j + 1 < ws.len(), brk && j + 1 == ws.len()));
+ for (j, w) in words.iter().enumerate() {
+ let (a, b) = range(w);
+ pieces.push((a, b, j + 1 < words.len(), brk && j + 1 == words.len()));
}
}
}
}
- WhiteSpace::NoWrap => pieces.push((collapse(&text), false, false)),
+ WhiteSpace::NoWrap => pieces.push((0, text.len(), false, false)),
WhiteSpace::Normal => {
let lead = text.starts_with(char::is_whitespace) && !first;
- let ws: Vec<&str> = text.split_whitespace().collect();
+ let words: Vec<&str> = text.split_whitespace().collect();
let trail = text.ends_with(char::is_whitespace);
- for (j, w) in ws.iter().enumerate() {
- let space_after = j + 1 < ws.len() || trail;
- let word = if j == 0 && lead { format!(" {w}") } else { w.to_string() };
- pieces.push((word, space_after, false));
+ for (j, w) in words.iter().enumerate() {
+ let (mut a, b) = range(w);
+ if j == 0 && lead {
+ a -= 1; // one leading space, drawn with the word
+ }
+ pieces.push((a, b, j + 1 < words.len() || trail, false));
}
}
}
- let indent = if first { c.text_indent.resolve(&self.units(c.font_size), 0.0) } else { 0.0 };
- let mut ids = Vec::new();
- for (n, (word, trailing, brk)) in pieces.into_iter().enumerate() {
- let w = text::width(&word, c.font_size, flags)
- + c.letter_spacing * word.chars().count() as f32
+ let space = self.text.width(" ", size, flags) + word_sp;
+ let src_key = self.nodes[src].key;
+ for (n, &(a, b, trailing, brk)) in pieces.iter().enumerate() {
+ let piece = &text[a..b];
+ // a leading space becomes a plain space for measuring and drawing
+ let w = self.text.width(piece, size, flags)
+ + letter * piece.chars().count() as f32
+ if trailing { space } else { 0.0 };
- let key = format!("{}/w{}", self.nodes[text_node].key, n);
- let node = self.push(Some(owner), Content::Word(word), Some(owner), c.clone(), key);
- self.nodes[node].parent = Some(owner);
+ let content = Content::Word { src: src as u32, start: a as u32, end: b as u32 };
+ let node = self.push(Some(owner), content, Some(owner), sid, child_key(src_key, "#w", n), false);
let s = Style {
size: Size { width: Dimension::Length(w.ceil()), height: Dimension::Length(line_h) },
flex_shrink: 0.0,
@@ -766,23 +1222,42 @@ impl Builder<'_> {
..Rect::zero() },
..Default::default()
};
- ids.push(self.leaf(node, s));
+ line.push(self.leaf(node, s));
if brk {
- let b = self.push(Some(owner), Content::LineBreak, Some(owner), c.clone(),
- format!("{}/br{}", self.nodes[text_node].key, n));
- ids.push(self.leaf(b, Style {
+ let br = self.push(Some(owner), Content::LineBreak, Some(owner), sid,
+ child_key(src_key, "#br", n), false);
+ line.push(self.leaf(br, Style {
size: Size { width: Dimension::Percent(1.0), height: Dimension::Length(0.0) },
flex_shrink: 0.0,
..Default::default()
}));
}
}
- ids
+ self.nodes[src].content = Content::Text(text);
}
}
+impl Computed {
+ /// The few fields `layout_node` reads after building children (avoids
+ /// holding a borrow of the style store across recursion).
+ fn clone_display(&self) -> DisplayOnly {
+ DisplayOnly { display: self.display }
+ }
+}
+
+struct DisplayOnly {
+ display: DisplayKind,
+}
+
fn collapse(s: &str) -> String {
- s.split_whitespace().collect::<Vec<_>>().join(" ")
+ let mut out = String::with_capacity(s.len());
+ for w in s.split_whitespace() {
+ if !out.is_empty() {
+ out.push(' ');
+ }
+ out.push_str(w);
+ }
+ out
}
/// Whitespace processing and `text-transform`; borrows when nothing changes.
@@ -808,22 +1283,45 @@ fn transform(s: &str, t: TextTransform, ws: WhiteSpace) -> std::borrow::Cow<'_,
})
}
-/// Build, cascade and lay out `root` in a `viewport` (logical pixels).
-pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState,
- widgets: &mut dyn FnMut(&str, &WidgetSpec) -> (f32, f32)) -> Frame {
+/// Build, cascade and lay out `root` in a `viewport` (logical pixels),
+/// reusing the arenas of `recycle` (the previous frame) and `caches`.
+pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, caches: &mut LayoutCaches,
+ recycle: Frame, widgets: &mut dyn FnMut(Key, &WidgetSpec) -> (f32, f32)) -> Frame {
let mut css = String::new();
let mut title = None;
collect_styles(&root, &mut css, &mut title);
+ let css_hash = fnv(&[css.as_bytes()]);
+ if css_hash != caches.author.hash {
+ caches.author = AuthorSheet { hash: css_hash, sheet: Stylesheet::parse(&css) };
+ }
+ caches.styles.begin_frame();
+ // the taffy tree persists: drop last frame's duplicates, start a new stamp
+ for id in caches.recon.extra.drain(..) {
+ let _ = caches.taffy.remove(id);
+ }
+ caches.recon.stamp = caches.recon.stamp.wrapping_add(1);
+ caches.text_box.clear();
+ let Frame { mut nodes, mut els, .. } = recycle;
+ nodes.clear();
+ els.clear();
+ if caches.matched.author != caches.author.hash || caches.matched.map.len() > 50_000 {
+ 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 mut b = Builder {
- nodes: Vec::new(),
- taffy: TaffyTree::new(),
- author: Stylesheet::parse(&css),
- author_hash: {
- use std::hash::{Hash, Hasher};
- let mut h = std::collections::hash_map::DefaultHasher::new();
- css.hash(&mut h);
- h.finish()
- },
+ nodes,
+ els,
+ taffy,
+ styles,
+ text,
+ images,
+ matched,
+ recon,
+ text_box,
+ changed: false,
+ author: &author.sheet,
+ author_hash: author.hash,
state,
viewport,
title,
@@ -831,42 +1329,48 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState,
};
// the document: <html><body> unless the app built them itself
let root_div = match root {
- AnyElement::Element(d) if d.tag == "html" => *d,
- AnyElement::Element(d) if d.tag == "body" => crate::html::html().child(*d),
+ AnyElement::Element(d) if d.tag == "html" => d,
+ AnyElement::Element(d) if d.tag == "body" => crate::html::html().child(d),
other => {
let mut body = crate::html::body();
body.children.push(other);
crate::html::html().child(body)
}
};
- let span = crate::prof::span("build");
- let root = match b.element(root_div, None, "html".into(), (1, 1)) {
+ let s = span(Phase::Build);
+ let root = match b.element(root_div, None, ROOT_KEY, (1, 1)) {
Some(r) => r,
- None => b.push(None, Content::Element, None, root_parent(), "html".into()),
+ None => b.push(None, Content::Element, None, ROOT_STYLE, ROOT_KEY, false),
};
- drop(span);
- let span = crate::prof::span("boxes");
+ drop(s);
+ let s = span(Phase::Boxes);
let root_id = b.layout_node(root);
- drop(span);
- let span = crate::prof::span("taffy");
- // the root fills the viewport
- let mut rs = b.taffy.style(root_id).unwrap().clone();
- rs.min_size = Size { width: Dimension::Length(viewport.0), height: Dimension::Length(viewport.1) };
- b.taffy.set_style(root_id, rs).unwrap();
+ drop(s);
+ let s = span(Phase::Taffy);
+ // nodes not used this frame
+ let stamp = b.recon.stamp;
+ let taffy_ref = &mut *b.taffy;
+ b.recon.map.retain(|_, (id, st)| {
+ if *st == stamp {
+ return true;
+ }
+ let _ = taffy_ref.remove(*id);
+ false
+ });
let avail = Size { width: AvailableSpace::Definite(viewport.0),
height: AvailableSpace::Definite(viewport.1) };
- let nodes = &b.nodes;
- b.taffy
+ let Builder { nodes, els, taffy, styles, text: tc, title, text_box, .. } = b;
+ taffy
.compute_layout_with_measure(root_id, avail, |known, available, _id, ctx, _style| {
match ctx {
- Some(Measure::Text { node, size, flags, line, nowrap }) => {
- let text = match &nodes[*node].content {
- Content::Text(t) => t.as_str(),
+ Some(Measure::Text { key, size, flags, line, nowrap, .. }) => {
+ let text = match text_box.get(key).map(|&k| &nodes[k].content) {
+ Some(Content::Text(t)) => t.as_str(),
_ => "",
};
if !text.contains([' ', '\n']) {
// one word: no wrapping to do
- let w = text::width(text, *size, *flags);
+ let w = tc.width(text, *size, *flags);
return Size { width: known.width.unwrap_or(w.ceil()),
height: known.height.unwrap_or(*line) };
}
@@ -875,9 +1379,8 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState,
AvailableSpace::MinContent => 0.0,
AvailableSpace::MaxContent => f32::INFINITY,
});
- let lines = text::wrap(text, *size, *flags,
- if *nowrap { f32::INFINITY } else { max_w });
- let w = lines.iter().map(|l| text::width(l, *size, *flags)).fold(0.0, f32::max);
+ let lines = tc.wrap(text, *size, *flags, if *nowrap { f32::INFINITY } else { max_w });
+ let w = lines.iter().map(|l| tc.width(l, *size, *flags)).fold(0.0, f32::max);
Size { width: known.width.unwrap_or(w.ceil()),
height: known.height.unwrap_or(*line * lines.len().max(1) as f32) }
}
@@ -885,14 +1388,22 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState,
}
})
.unwrap();
- drop(span);
- let _span = crate::prof::span("place");
- let mut frame = Frame { nodes: b.nodes, title: b.title, by_key: Default::default() };
- let by_taffy: HashMap<NodeId, usize> = frame.nodes.iter().enumerate()
- .filter_map(|(i, n)| n.taffy.map(|t| (t, i))).collect();
- let mut walk = Walk { t: &b.taffy, by_taffy: &by_taffy, state, vp: viewport };
+ drop(s);
+ let _s = span(Phase::Place);
+ let mut frame = Frame { nodes, els, title, by_key: Default::default() };
+ box_of.clear();
+ for (i, n) in frame.nodes.iter().enumerate() {
+ if let Some(t) = n.taffy {
+ let s = slot(t);
+ if s >= box_of.len() {
+ box_of.resize(s + 1, NONE);
+ }
+ box_of[s] = i as u32;
+ }
+ }
+ let mut walk = Walk { t: taffy, box_of, state, vp: viewport, styles, text: tc };
walk.place(&mut frame.nodes, root_id, 0.0, 0.0, None);
- finish(&mut frame.nodes);
+ finish(&mut frame.nodes, styles, acc);
frame
}
@@ -900,9 +1411,11 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState,
/// be anonymous); translate and scroll offsets shift whole subtrees.
struct Walk<'a> {
t: &'a TaffyTree<Measure>,
- by_taffy: &'a HashMap<NodeId, usize>,
+ box_of: &'a [u32],
state: &'a UiState,
vp: (f32, f32),
+ styles: &'a StyleStore,
+ text: &'a mut TextCache,
}
impl Walk<'_> {
@@ -915,12 +1428,12 @@ impl Walk<'_> {
let (w, h) = (l.size.width, l.size.height);
let mut child_clip = clip;
let (mut sx, mut sy) = (0.0, 0.0);
- if let Some(&i) = self.by_taffy.get(&id) {
- let st = nodes[i].style.clone();
+ if let Some(i) = self.box_of.get(slot(id)).filter(|&&b| b != NONE).map(|&b| b as usize) {
+ let st = &self.styles[nodes[i].style];
let u = Units { font_size: st.font_size, viewport: self.vp };
x += st.translate.0.resolve(&u, w);
y += st.translate.1.resolve(&u, h);
- if matches!(nodes[i].content, Content::Word(_)) {
+ if matches!(nodes[i].content, Content::Word { .. }) {
y += match st.vertical_align {
VAlign::Sub => st.font_size * 0.25,
VAlign::Super => -st.font_size * 0.35,
@@ -951,79 +1464,159 @@ impl Walk<'_> {
nodes[i].scroll_pos = (sx, sy);
}
}
+ if let Some(k) = nodes[i].fold {
+ place_folded_text(nodes, i, k, rect(x, y, w, h), &l, self.styles, self.text);
+ }
}
- let kids = self.t.children(id).unwrap_or_default();
- for k in kids {
+ let n = self.t.child_count(id);
+ for c in 0..n {
+ let k = self.t.child_at_index(id, c).unwrap();
self.place(nodes, k, x - sx, y - sy, child_clip);
}
}
}
+/// Put a folded text run where its own flex item / line box would have gone:
+/// inside the content box, aligned like a lone flex item (or by `text-align`
+/// in a block, which paint applies across the full width).
+fn place_folded_text(nodes: &mut [BoxNode], i: usize, k: usize, b: Bounds<f32>, l: &taffy::Layout,
+ styles: &StyleStore, tc: &mut TextCache) {
+ let c = &styles[nodes[i].style];
+ let cb = rect(b.origin.x + l.border.left + l.padding.left, b.origin.y + l.border.top + l.padding.top,
+ (b.size.width - l.border.left - l.border.right - l.padding.left - l.padding.right).max(0.0),
+ (b.size.height - l.border.top - l.border.bottom - l.padding.top - l.padding.bottom).max(0.0));
+ let Content::Text(t) = &nodes[k].content else { return };
+ let flags = text::flags(c);
+ let line = c.line_px();
+ let (tw, th) = if !t.contains([' ', '\n']) {
+ (tc.width(t, c.font_size, flags).ceil(), line)
+ } else {
+ let max = if c.white_space == WhiteSpace::NoWrap { f32::INFINITY } else { cb.size.width + 0.5 };
+ let lines = tc.wrap(t, c.font_size, flags, max);
+ let w = lines.iter().map(|s| tc.width(s, c.font_size, flags)).fold(0.0, f32::max);
+ (w.ceil(), line * lines.len().max(1) as f32)
+ };
+ let tw = if c.white_space == WhiteSpace::NoWrap { tw } else { tw.min(cb.size.width) };
+ let s = &c.layout;
+ // offset of a box of `size` in `room` for a start / center / end choice
+ let at = |room: f32, size: f32, pos: u8| match pos {
+ 1 => (room - size) / 2.0,
+ 2 => room - size,
+ _ => 0.0,
+ };
+ let justify = match s.justify_content {
+ Some(JustifyContent::Center | JustifyContent::SpaceAround | JustifyContent::SpaceEvenly) => 1,
+ Some(JustifyContent::End | JustifyContent::FlexEnd) => 2,
+ _ => 0,
+ };
+ let align = match s.align_items {
+ Some(AlignItems::Center) => 1,
+ Some(AlignItems::End | AlignItems::FlexEnd) => 2,
+ _ => 0,
+ };
+ let stretch = matches!(s.align_items, None | Some(AlignItems::Stretch));
+ let tb = match c.display {
+ DisplayKind::Flex | DisplayKind::InlineFlex if s.flex_direction == FlexDirection::Row => {
+ rect(cb.origin.x + at(cb.size.width, tw, justify), cb.origin.y + at(cb.size.height, th, align), tw, th)
+ }
+ DisplayKind::Flex | DisplayKind::InlineFlex => {
+ let w = if stretch { cb.size.width } else { tw };
+ rect(cb.origin.x + at(cb.size.width, w, align), cb.origin.y + at(cb.size.height, th, justify), w, th)
+ }
+ _ => rect(cb.origin.x, cb.origin.y, cb.size.width, th), // block: text-align at paint
+ };
+ nodes[k].bounds = tb;
+}
+
/// Inherited opacity / visibility (parents precede children in the arena),
-/// and bounds of inline elements: the union of their pieces (children follow
-/// parents, so a reverse pass sees them first).
-fn finish(nodes: &mut [BoxNode]) {
+/// and bounds of boxes without a layout node (inline elements): the union of
+/// their pieces (children follow parents, so a reverse pass sees them first).
+fn finish(nodes: &mut [BoxNode], styles: &StyleStore, acc: &mut Vec<Option<Bounds<f32>>>) {
for i in 0..nodes.len() {
let (po, pv, pc) = match nodes[i].parent {
Some(p) => (nodes[p].opacity, nodes[p].visible, nodes[p].clip),
None => (1.0, true, None),
};
+ let st = &styles[nodes[i].style];
let own = matches!(nodes[i].content, Content::Element | Content::Widget(_) | Content::Replaced(_));
- nodes[i].opacity = if own { po * nodes[i].style.opacity } else { po };
- nodes[i].visible = pv && nodes[i].style.visible;
+ nodes[i].opacity = if own { po * st.opacity } else { po };
+ nodes[i].visible = pv && st.visible;
if nodes[i].taffy.is_none() {
nodes[i].clip = pc;
}
}
+ acc.clear();
+ acc.resize(nodes.len(), None);
for i in (0..nodes.len()).rev() {
- if nodes[i].taffy.is_some() || nodes[i].kids.is_empty() {
- continue;
- }
- let mut acc: Option<Bounds<f32>> = None;
- for &c in &nodes[i].kids {
- let cb = nodes[c].bounds;
- if cb.size.width <= 0.0 && cb.size.height <= 0.0 {
- continue;
+ if nodes[i].taffy.is_none() {
+ if let Some(a) = acc[i] {
+ nodes[i].bounds = a;
}
- acc = Some(match acc {
- None => cb,
- Some(a) => {
- let x0 = a.origin.x.min(cb.origin.x);
- let y0 = a.origin.y.min(cb.origin.y);
- let x1 = (a.origin.x + a.size.width).max(cb.origin.x + cb.size.width);
- let y1 = (a.origin.y + a.size.height).max(cb.origin.y + cb.size.height);
- rect(x0, y0, x1 - x0, y1 - y0)
- }
- });
}
- if let Some(a) = acc {
- nodes[i].bounds = a;
+ let Some(p) = nodes[i].parent else { continue };
+ if nodes[p].taffy.is_some() {
+ continue;
}
+ let cb = nodes[i].bounds;
+ if cb.size.width <= 0.0 && cb.size.height <= 0.0 {
+ continue;
+ }
+ acc[p] = Some(match acc[p] {
+ None => cb,
+ Some(a) => {
+ let x0 = a.origin.x.min(cb.origin.x);
+ let y0 = a.origin.y.min(cb.origin.y);
+ let x1 = (a.origin.x + a.size.width).max(cb.origin.x + cb.size.width);
+ let y1 = (a.origin.y + a.size.height).max(cb.origin.y + cb.size.height);
+ rect(x0, y0, x1 - x0, y1 - y0)
+ }
+ });
}
}
impl Frame {
/// Element boxes by key, built on first use (events and tests need it,
/// rendering doesn't).
- pub(crate) fn by_key(&self) -> &HashMap<String, usize> {
+ pub(crate) fn by_key(&self) -> &HashMap<Key, usize> {
self.by_key.get_or_init(|| {
- self.nodes.iter().enumerate().filter(|(_, n)| n.el.is_some())
- .map(|(i, n)| (n.key.clone(), i)).collect()
+ self.nodes.iter().enumerate().filter(|(_, n)| n.el != NONE).map(|(i, n)| (n.key, i)).collect()
})
}
+ /// The element data of box `i`.
+ pub(crate) fn el(&self, i: usize) -> Option<&ElData> {
+ let e = self.nodes[i].el;
+ (e != NONE).then(|| &self.els[e as usize])
+ }
+
+ pub(crate) fn attr(&self, i: usize, name: &str) -> Option<&str> {
+ el_attr(&self.nodes, &self.els, i, name)
+ }
+
+ /// The text a box draws: a text run's text, or a word's slice of it.
+ pub(crate) fn text(&self, i: usize) -> &str {
+ match &self.nodes[i].content {
+ Content::Text(t) => t,
+ Content::Word { src, start, end } => match &self.nodes[*src as usize].content {
+ Content::Text(t) => &t[*start as usize..*end as usize],
+ _ => "",
+ },
+ _ => "",
+ }
+ }
+
/// Element boxes from the root down to the topmost box under (x, y).
- pub(crate) fn hit_path(&self, x: f32, y: f32) -> Vec<usize> {
+ pub(crate) fn hit_path(&self, x: f32, y: f32, styles: &StyleStore) -> Vec<usize> {
let mut best: Option<(i32, usize)> = None;
for (i, n) in self.nodes.iter().enumerate() {
- if !n.visible || !n.style.pointer_events || n.taffy.is_none() {
+ if !n.visible || n.taffy.is_none() || !styles[n.style].pointer_events {
continue;
}
if n.clip.is_some_and(|c| !c.contains(x, y)) || !n.bounds.contains(x, y) {
continue;
}
// later boxes paint over earlier ones; z-index lifts a subtree
- let z = self.z_of(i);
+ let z = self.z_of(i, styles);
if best.is_none_or(|(bz, _)| z >= bz) {
best = Some((z, i));
}
@@ -1031,7 +1624,7 @@ impl Frame {
let mut path = Vec::new();
let mut cur = best.map(|(_, b)| self.nodes[b].owner);
while let Some(i) = cur {
- if self.nodes[i].el.is_some() {
+ if self.nodes[i].el != NONE {
path.push(i);
}
cur = self.nodes[i].parent;
@@ -1041,9 +1634,9 @@ impl Frame {
}
/// The effective stacking level of a box (its nearest z-index).
- pub(crate) fn z_of(&self, mut i: usize) -> i32 {
+ pub(crate) fn z_of(&self, mut i: usize, styles: &StyleStore) -> i32 {
loop {
- if let Some(z) = self.nodes[i].style.z_index {
+ if let Some(z) = styles[self.nodes[i].style].z_index {
return z;
}
match self.nodes[i].parent {
@@ -1053,10 +1646,3 @@ impl Frame {
}
}
}
-
-/// The style the root element inherits from: one shared value, so the root's
-/// style (and through it everything below) can be reused across frames.
-fn root_parent() -> Rc<Computed> {
- thread_local! { static ROOT: Rc<Computed> = Rc::new(Computed::default()); }
- ROOT.with(Rc::clone)
-}
diff --git a/bindings/rust/blenderui/src/lib.rs b/bindings/rust/blenderui/src/lib.rs
index 6d1a5fd..f9ac240 100644
--- a/bindings/rust/blenderui/src/lib.rs
+++ b/bindings/rust/blenderui/src/lib.rs
@@ -42,6 +42,19 @@
//! * **Rendering**: Blender's widget drawing; form controls are Blender's own
//! widgets (number fields, sliders, dropdowns, text fields ...).
+// lets `css!` (which names `::blenderui::...`) work inside this crate too
+extern crate self as blenderui;
+
+/// A CSS declaration block checked and resolved at compile time:
+/// `div().style(css!("display: flex; gap: 4px"))`. An unknown property is a
+/// compile error:
+///
+/// ```compile_fail
+/// use blenderui::prelude::*;
+/// let _ = div().style(css!("colr: red"));
+/// ```
+pub use blenderui_macros::css;
+
pub mod color;
pub mod css;
pub mod element;
@@ -64,17 +77,18 @@ pub use element::*;
pub use events::*;
pub use geometry::{point, px, relative, rems, size, Bounds, Length, Pixels, Point, Rems, Size};
pub use paint::{Image, Painter};
-pub use styled::{FontWeight, Styled};
+pub use styled::{FontWeight, StyleBlock, Styled};
pub use window::*;
/// Everything an app needs: `use blenderui::prelude::*;`
pub mod prelude {
+ pub use crate::css;
pub use crate::color::*;
pub use crate::element::*;
pub use crate::events::*;
pub use crate::geometry::{point, px, relative, rems, size, Bounds, Length, Pixels, Point, Rems, Size};
pub use crate::html::*;
pub use crate::paint::{Image, Painter};
- pub use crate::styled::{FontWeight, Styled};
+ pub use crate::styled::{FontWeight, StyleBlock, Styled};
pub use crate::window::*;
}
diff --git a/bindings/rust/blenderui/src/paint.rs b/bindings/rust/blenderui/src/paint.rs
index afe4bd6..135aad9 100644
--- a/bindings/rust/blenderui/src/paint.rs
+++ b/bindings/rust/blenderui/src/paint.rs
@@ -1,18 +1,16 @@
//! Painting: a frame of laid-out boxes becomes one display list on the kit
//! canvas. [`Painter`] is also what `canvas(|bounds, painter| ...)` draws with.
-use std::cell::RefCell;
use std::collections::HashMap;
-use std::ffi::CString;
-use std::rc::Rc;
+use std::sync::Arc;
use taffy::prelude::*;
use crate::color::Rgba;
use crate::geometry::{rect, Bounds, Units};
-use crate::layout::{BoxNode, Content, Frame, Replaced};
+use crate::layout::{BoxNode, Content, Frame, Replaced, StyleStore};
use crate::style::{Computed, DisplayKind, TextAlign, WhiteSpace};
-use crate::text;
+use crate::text::{self, TextCache};
use blenderui_sys as sys;
/// RGBA pixels for `<img>` / `img().image_rgba(...)`.
@@ -65,18 +63,22 @@ impl Image {
}
}
-thread_local! {
- static IMAGES: RefCell<HashMap<String, Option<Rc<Image>>>> = RefCell::new(HashMap::new());
+/// Decoded `<img src>` files, kept by the window (each file is decoded once).
+#[derive(Default)]
+pub(crate) struct ImageCache {
+ files: HashMap<String, Option<Arc<Image>>>,
}
-/// `src` of an `<img>`: PNG files, decoded once.
-pub(crate) fn load_image(src: &str) -> Option<Rc<Image>> {
- IMAGES.with(|m| {
- m.borrow_mut()
- .entry(src.to_owned())
- .or_insert_with(|| Image::from_png(src).map(Rc::new))
- .clone()
- })
+impl ImageCache {
+ /// `src` of an `<img>`: PNG files.
+ pub(crate) fn load(&mut self, src: &str) -> Option<Arc<Image>> {
+ if let Some(i) = self.files.get(src) {
+ return i.clone();
+ }
+ let img = Image::from_png(src).map(Arc::new);
+ self.files.insert(src.to_owned(), img.clone());
+ img
+ }
}
#[derive(Clone)]
@@ -86,14 +88,41 @@ enum Kind {
Line { width: f32 },
Polygon,
Arc { start: f32, extent: f32 },
- Text { text: CString, size: f32, flags: i32 },
- Image(Rc<Image>),
+ /// `start..end` of the painter's text arena (NUL-terminated there).
+ Text { start: u32, size: f32, flags: i32 },
+ Image(Arc<Image>),
+}
+
+/// Coordinates: up to four inline (rects, ovals, text, images), more on the heap.
+#[derive(Clone)]
+enum Coords {
+ Inline([f32; 4], u8),
+ Heap(Vec<f32>),
+}
+
+impl Coords {
+ fn of(v: &[f32]) -> Coords {
+ if v.len() <= 4 {
+ let mut a = [0.0; 4];
+ a[..v.len()].copy_from_slice(v);
+ Coords::Inline(a, v.len() as u8)
+ } else {
+ Coords::Heap(v.to_vec())
+ }
+ }
+
+ fn as_slice(&self) -> &[f32] {
+ match self {
+ Coords::Inline(a, n) => &a[..*n as usize],
+ Coords::Heap(v) => v,
+ }
+ }
}
#[derive(Clone)]
struct Item {
kind: Kind,
- coords: Vec<f32>,
+ coords: Coords,
fill: Rgba,
clip: Option<Bounds<f32>>,
}
@@ -109,16 +138,26 @@ struct Item {
#[derive(Default)]
pub struct Painter {
items: Vec<Item>,
+ /// Every text item's bytes, NUL-terminated, back to back.
+ text: Vec<u8>,
clip: Option<Bounds<f32>>,
opacity: f32,
}
impl Painter {
pub(crate) fn new() -> Painter {
- Painter { items: Vec::new(), clip: None, opacity: 1.0 }
+ Painter { items: Vec::new(), text: Vec::new(), clip: None, opacity: 1.0 }
+ }
+
+ /// Empty for the next frame, keeping the buffers.
+ pub(crate) fn reset(&mut self) {
+ self.items.clear();
+ self.text.clear();
+ self.clip = None;
+ self.opacity = 1.0;
}
- fn push(&mut self, kind: Kind, coords: Vec<f32>, fill: Rgba) {
+ fn push(&mut self, kind: Kind, coords: Coords, fill: Rgba) {
let fill = fill.opacity(self.opacity);
let kind = match kind {
Kind::Rect { radius, outline, width } => {
@@ -130,8 +169,8 @@ impl Painter {
self.items.push(Item { kind, coords, fill, clip: self.clip });
}
- fn corners(b: Bounds<f32>) -> Vec<f32> {
- vec![b.origin.x, b.origin.y, b.origin.x + b.size.width, b.origin.y + b.size.height]
+ fn corners(b: Bounds<f32>) -> Coords {
+ Coords::Inline([b.origin.x, b.origin.y, b.origin.x + b.size.width, b.origin.y + b.size.height], 4)
}
/// A filled rectangle (gpui's `paint_quad(fill(bounds, color))`).
@@ -164,12 +203,14 @@ impl Painter {
/// A polyline through `points`.
pub fn line(&mut self, points: &[(f32, f32)], color: impl Into<Rgba>, width: f32) {
- self.push(Kind::Line { width }, points.iter().flat_map(|&(x, y)| [x, y]).collect(), color.into());
+ let v: Vec<f32> = points.iter().flat_map(|&(x, y)| [x, y]).collect();
+ self.push(Kind::Line { width }, Coords::of(&v), color.into());
}
/// A filled polygon (gpui's `paint_path`).
pub fn polygon(&mut self, points: &[(f32, f32)], color: impl Into<Rgba>) {
- self.push(Kind::Polygon, points.iter().flat_map(|&(x, y)| [x, y]).collect(), color.into());
+ let v: Vec<f32> = points.iter().flat_map(|&(x, y)| [x, y]).collect();
+ self.push(Kind::Polygon, Coords::of(&v), color.into());
}
/// A pie slice: degrees counter-clockwise from 3 o'clock.
@@ -184,13 +225,15 @@ impl Painter {
pub(crate) fn styled_text(&mut self, x: f32, y: f32, text: &str, size: f32, flags: i32, color: Rgba) {
if !text.trim().is_empty() {
- let text = CString::new(text).unwrap_or_else(|_| CString::new(text.replace('\0', "")).unwrap_or_default());
- self.push(Kind::Text { text, size, flags }, vec![x, y], color);
+ let start = self.text.len() as u32;
+ self.text.extend(text.bytes().filter(|&b| b != 0));
+ self.text.push(0);
+ self.push(Kind::Text { start, size, flags }, Coords::Inline([x, y, 0.0, 0.0], 2), color);
}
}
/// An image scaled to `bounds`.
- pub fn image(&mut self, bounds: Bounds<f32>, image: &Rc<Image>) {
+ pub fn image(&mut self, bounds: Bounds<f32>, image: &Arc<Image>) {
self.push(Kind::Image(image.clone()), Self::corners(bounds), Rgba::TRANSPARENT);
}
@@ -207,10 +250,22 @@ impl Painter {
/// Replace the canvas display list with these items, scaled to device pixels.
pub(crate) fn flush(&self, canvas: *mut sys::BKNode, scale: f32) {
- // SAFETY: `canvas` is a live kit canvas node owned by the window.
- unsafe { sys::BK_canvas_delete(canvas, -1) };
+ let mut heap: Vec<f32> = Vec::new();
+ let mut count: i32 = 0;
for it in &self.items {
- let mut coords: Vec<f32> = it.coords.iter().map(|v| v * scale).collect();
+ let src = it.coords.as_slice();
+ let mut inline = [0.0f32; 4];
+ let coords: &mut [f32] = if src.len() <= 4 {
+ for (d, s) in inline.iter_mut().zip(src) {
+ *d = s * scale;
+ }
+ &mut inline[..src.len()]
+ } else {
+ heap.clear();
+ heap.extend(src.iter().map(|v| v * scale));
+ &mut heap[..]
+ };
+ let mut ncoords = coords.len();
let mut ci = sys::BKCanvasItem { fill: it.fill.to_array(), ..Default::default() };
let mut _keep_px = None;
match &it.kind {
@@ -239,12 +294,12 @@ impl Painter {
ci.start = *start;
ci.extent = *extent;
}
- Kind::Text { text, size, flags } => {
+ Kind::Text { start, size, flags } => {
ci.type_ = sys::BK_ITEM_TEXT;
ci.size = size * scale;
ci.text_flags = *flags;
ci.anchor = sys::BK_ANCHOR_N | sys::BK_ANCHOR_W;
- ci.text = text.as_ptr();
+ ci.text = self.text[*start as usize..].as_ptr().cast();
}
Kind::Image(img) => {
let w = (coords[2] - coords[0]).round().max(1.0) as u32;
@@ -258,7 +313,7 @@ impl Painter {
ci.rgba = px.as_ptr();
ci.iw = w as i32;
ci.ih = h as i32;
- coords.truncate(2);
+ ncoords = 2;
_keep_px = Some(px);
}
}
@@ -268,10 +323,14 @@ impl Painter {
c.size.height * scale];
}
ci.coords = coords.as_ptr();
- ci.ncoords = coords.len() as i32;
- // SAFETY: every pointer in `ci` outlives the call; the kit copies them.
- unsafe { sys::BK_canvas_add_item(canvas, &ci) };
+ ci.ncoords = ncoords as i32;
+ // SAFETY: every pointer in `ci` outlives the call; the kit copies
+ // them into the slot's existing buffers.
+ unsafe { sys::BK_canvas_put_item(canvas, count, &ci) };
+ count += 1;
}
+ // SAFETY: `canvas` is a live kit canvas node owned by the window.
+ unsafe { sys::BK_canvas_truncate(canvas, count) };
}
}
@@ -298,9 +357,12 @@ fn radius_px(c: &Computed, b: Bounds<f32>, vp: (f32, f32)) -> f32 {
}
/// Paint every box of `frame`, in stacking order.
-pub(crate) fn paint_frame(frame: &Frame, p: &mut Painter, vp: (f32, f32)) {
+pub(crate) fn paint_frame(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, p: &mut Painter,
+ vp: (f32, f32)) {
let mut order: Vec<usize> = (0..frame.nodes.len()).collect();
- order.sort_by_key(|&i| frame.z_of(i)); // stable: tree order within a level
+ if frame.nodes.iter().any(|n| styles[n.style].z_index.is_some()) {
+ order.sort_by_key(|&i| frame.z_of(i, styles)); // stable: tree order within a level
+ }
for i in order {
let n = &frame.nodes[i];
if !n.visible || n.opacity <= 0.0 {
@@ -308,7 +370,7 @@ pub(crate) fn paint_frame(frame: &Frame, p: &mut Painter, vp: (f32, f32)) {
}
p.opacity = n.opacity;
p.clip = n.clip;
- paint_node(frame, n, p, vp);
+ paint_node(frame, styles, tc, i, p, vp);
}
p.opacity = 1.0;
p.clip = None;
@@ -317,15 +379,15 @@ pub(crate) fn paint_frame(frame: &Frame, p: &mut Painter, vp: (f32, f32)) {
/// A background that repaints exactly the pixels already under it: an opaque
/// plain fill with the colour and bounds of the nearest painted ancestor, with
/// only undecorated same-sized boxes in between (so nothing else can show).
-fn redundant_background(frame: &Frame, n: &BoxNode) -> bool {
- let c = &*n.style;
+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() {
return false;
}
let mut cur = n.parent;
while let Some(i) = cur {
let a = &frame.nodes[i];
- let ac = &*a.style;
+ let ac = &styles[a.style];
if a.bounds != n.bounds || a.taffy.is_none() || !ac.shadows.is_empty() || ac.gradient.is_some()
|| a.opacity < 1.0 || a.clip.is_some() != n.clip.is_some()
{
@@ -342,73 +404,72 @@ fn redundant_background(frame: &Frame, n: &BoxNode) -> bool {
false
}
-fn paint_node(frame: &Frame, n: &BoxNode, p: &mut Painter, vp: (f32, f32)) {
- let c = &*n.style;
+fn paint_node(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, i: usize, p: &mut Painter,
+ vp: (f32, f32)) {
+ let n = &frame.nodes[i];
+ let c = &styles[n.style];
let b = n.bounds;
match &n.content {
- Content::Word(w) => {
+ Content::Word { .. } => {
// inline element backgrounds paint per line fragment (here: per word)
let owner = &frame.nodes[n.owner];
if owner.taffy.is_none() {
- p.fill(b, owner.style.background);
+ p.fill(b, styles[owner.style].background);
}
- paint_text_line(p, c, w, b.origin.x, b.origin.y, b.size.height, None);
+ paint_text_line(p, tc, c, frame.text(i), b.origin.x, b.origin.y, b.size.height, None);
}
// a text run as a flex/grid item (in line boxes its words paint instead)
- Content::Text(t) if n.taffy.is_some() => {
+ Content::Text(t) if n.taffy.is_some() || n.folded => {
let flags = text::flags(c);
let nowrap = matches!(c.white_space, WhiteSpace::NoWrap | WhiteSpace::Pre);
if !c.ellipsis && !t.contains([' ', '\n']) {
// one word: one line (the common label case)
- let lw = text::width(t, c.font_size, flags);
+ let lw = tc.width(t, c.font_size, flags);
let x = match c.text_align {
TextAlign::Center => b.origin.x + (b.size.width - lw) / 2.0,
TextAlign::Right => b.origin.x + b.size.width - lw,
_ => b.origin.x,
};
- paint_text_line(p, c, t, x, b.origin.y, c.line_px(), Some(lw));
+ paint_text_line(p, tc, c, t, x, b.origin.y, c.line_px(), Some(lw));
return;
}
let lines = if nowrap {
vec![t.clone()]
} else {
- text::wrap(t, c.font_size, flags, b.size.width + 0.5)
+ tc.wrap(t, c.font_size, flags, b.size.width + 0.5)
};
let lh = c.line_px();
for (k, line) in lines.iter().enumerate() {
- let line = if c.ellipsis { text::ellipsize(line, c.font_size, flags, b.size.width) }
+ let line = if c.ellipsis { tc.ellipsize(line, c.font_size, flags, b.size.width) }
else { line.clone() };
- let lw = text::width(&line, c.font_size, flags);
+ let lw = tc.width(&line, c.font_size, flags);
let x = match c.text_align {
TextAlign::Center => b.origin.x + (b.size.width - lw) / 2.0,
TextAlign::Right => b.origin.x + b.size.width - lw,
_ => b.origin.x,
};
- paint_text_line(p, c, &line, x, b.origin.y + lh * k as f32, lh, Some(lw));
+ paint_text_line(p, tc, c, &line, x, b.origin.y + lh * k as f32, lh, Some(lw));
}
}
Content::Element | Content::Replaced(_) if n.taffy.is_some() => {
- paint_box(n, p, vp, redundant_background(frame, n));
+ paint_box(n, c, p, vp, redundant_background(frame, styles, n));
if let Some(m) = &n.marker {
let bw = border_widths(c, b.size.width);
let pad = lp(c.layout.padding.top, b.size.width);
let flags = text::flags(c);
- let mw = text::width(m, c.font_size, flags);
- paint_text_line(p, c, m, b.origin.x - mw - 6.0, b.origin.y + bw[0] + pad, c.line_px(),
+ let mw = tc.width(m, c.font_size, flags);
+ paint_text_line(p, tc, c, m, b.origin.x - mw - 6.0, b.origin.y + bw[0] + pad, c.line_px(),
Some(mw));
}
if let Content::Replaced(r) = &n.content {
let inner = content_box(c, b);
match r {
Replaced::Image(img) => p.image(inner, img),
- Replaced::Painted(f) => {
- let f = f.clone();
- p.with_clip(inner, |p| f(inner, p));
- }
+ Replaced::Painted(f) => p.with_clip(inner, |p| f(inner, p)),
Replaced::Placeholder(tag) => {
p.fill(inner, crate::color::rgb(0x282828));
- let label = n.attr("alt").unwrap_or(tag);
- let w = text::width(label, c.font_size, 0);
+ let label = frame.attr(i, "alt").unwrap_or(tag);
+ let w = tc.width(label, c.font_size, 0);
p.styled_text(inner.origin.x + (inner.size.width - w) / 2.0,
inner.origin.y + (inner.size.height - c.font_size) / 2.0,
label, c.font_size, 0, crate::color::rgb(0x8a8a8a));
@@ -431,11 +492,13 @@ fn content_box(c: &Computed, b: Bounds<f32>) -> Bounds<f32> {
}
/// One line of text in a line box of height `lh`, with decorations.
-fn paint_text_line(p: &mut Painter, c: &Computed, s: &str, x: f32, y: f32, lh: f32, width: Option<f32>) {
+#[allow(clippy::too_many_arguments)]
+fn paint_text_line(p: &mut Painter, tc: &mut TextCache, c: &Computed, s: &str, x: f32, y: f32, lh: f32,
+ width: Option<f32>) {
let flags = text::flags(c);
let size = c.font_size;
let top = y + ((lh - size) / 2.0).max(0.0);
- let s = if c.small_caps { s.to_uppercase() } else { s.to_owned() };
+ let s: std::borrow::Cow<str> = if c.small_caps { s.to_uppercase().into() } else { s.into() };
let size_draw = if c.small_caps { size * 0.8 } else { size };
if let Some(sh) = c.text_shadow {
p.styled_text(x + sh.x, top + sh.y, &s, size_draw, flags, sh.color);
@@ -445,13 +508,13 @@ fn paint_text_line(p: &mut Painter, c: &Computed, s: &str, x: f32, y: f32, lh: f
for ch in s.chars() {
let t = ch.to_string();
p.styled_text(cx, top, &t, size_draw, flags, c.color);
- cx += text::width(&t, size_draw, flags) + c.letter_spacing;
+ cx += tc.width(&t, size_draw, flags) + c.letter_spacing;
}
} else {
p.styled_text(x, top, &s, size_draw, flags, c.color);
}
if c.underline || c.line_through || c.overline {
- let w = width.unwrap_or_else(|| text::width(s.trim_end(), size_draw, flags));
+ let w = width.unwrap_or_else(|| tc.width(s.trim_end(), size_draw, flags));
let thick = (size / 14.0).max(1.0);
let dc = c.decoration_color.unwrap_or(c.color);
let mut deco = |yy: f32| p.fill(rect(x, yy, w, thick), dc);
@@ -468,8 +531,7 @@ fn paint_text_line(p: &mut Painter, c: &Computed, s: &str, x: f32, y: f32, lh: f
}
/// Shadows, background, borders and outline of an element box.
-fn paint_box(n: &BoxNode, p: &mut Painter, vp: (f32, f32), skip_background: bool) {
- let c = &*n.style;
+fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_background: bool) {
let b = n.bounds;
if matches!(c.display, DisplayKind::Contents) || b.size.width <= 0.0 && b.size.height <= 0.0 {
return;
diff --git a/bindings/rust/blenderui/src/prof.rs b/bindings/rust/blenderui/src/prof.rs
index 8ec217b..8ebea23 100644
--- a/bindings/rust/blenderui/src/prof.rs
+++ b/bindings/rust/blenderui/src/prof.rs
@@ -1,41 +1,59 @@
//! `BUI_PROFILE=1`: per-phase frame timings, averaged and printed to stderr
//! every 60 frames. Costs one thread-local bool check when off.
-use std::cell::RefCell;
+use std::cell::Cell;
use std::time::Instant;
+/// The timed phases of a frame.
+#[derive(Clone, Copy)]
+pub(crate) enum Phase {
+ FrameInterval,
+ Render,
+ Cascade,
+ Build,
+ Boxes,
+ Taffy,
+ Place,
+ Paint,
+ Flush,
+ Widgets,
+}
+
+const NAMES: [&str; 10] = [
+ "frame interval", "render", " cascade", "build", "boxes", "taffy", "place", "paint", "flush",
+ "widgets+hover",
+];
+
thread_local! {
static ON: bool = std::env::var_os("BUI_PROFILE").is_some();
- static ACC: RefCell<(Vec<(&'static str, f64)>, u32)> = const { RefCell::new((Vec::new(), 0)) };
+ static ACC: [Cell<f64>; 10] = const { [const { Cell::new(0.0) }; 10] };
+ static FRAMES: Cell<u32> = const { Cell::new(0) };
}
pub(crate) fn on() -> bool {
ON.with(|o| *o)
}
-/// Times its scope into the phase `name`.
-pub(crate) struct Span(Option<(&'static str, Instant)>);
+/// Times its scope into a phase.
+pub(crate) struct Span(Option<(Phase, Instant)>);
-pub(crate) fn span(name: &'static str) -> Span {
- Span(on().then(|| (name, Instant::now())))
+pub(crate) fn span(phase: Phase) -> Span {
+ Span(on().then(|| (phase, Instant::now())))
}
impl Drop for Span {
fn drop(&mut self) {
- if let Some((name, t)) = self.0 {
- add(name, t.elapsed().as_secs_f64() * 1000.0);
+ if let Some((phase, t)) = self.0 {
+ add(phase, t.elapsed().as_secs_f64() * 1000.0);
}
}
}
-/// Add `ms` to phase `name`.
-pub(crate) fn add(name: &'static str, ms: f64) {
+/// Add `ms` to a phase.
+pub(crate) fn add(phase: Phase, ms: f64) {
ACC.with(|a| {
- let mut a = a.borrow_mut();
- match a.0.iter_mut().find(|(n, _)| *n == name) {
- Some(e) => e.1 += ms,
- None => a.0.push((name, ms)),
- }
+ let c = &a[phase as usize];
+ c.set(c.get() + ms);
});
}
@@ -44,14 +62,19 @@ pub(crate) fn frame_done() {
if !on() {
return;
}
- ACC.with(|a| {
- let mut a = a.borrow_mut();
- a.1 += 1;
- if a.1 == 60 {
- let line: Vec<String> = a.0.iter().map(|(n, ms)| format!("{n} {:.2}", ms / 60.0)).collect();
- eprintln!("frame ms: {}", line.join(" "));
- a.0.clear();
- a.1 = 0;
- }
+ let n = FRAMES.with(|f| {
+ f.set(f.get() + 1);
+ f.get()
+ });
+ if n < 60 {
+ return;
+ }
+ FRAMES.with(|f| f.set(0));
+ let line: Vec<String> = ACC.with(|a| {
+ NAMES.iter().zip(a.iter())
+ .filter(|(_, c)| c.get() > 0.0)
+ .map(|(name, c)| format!("{name} {:.2}", c.replace(0.0) / 60.0))
+ .collect()
});
+ eprintln!("frame ms: {}", line.join(" "));
}
diff --git a/bindings/rust/blenderui/src/style.rs b/bindings/rust/blenderui/src/style.rs
index 8d410c0..b891a5c 100644
--- a/bindings/rust/blenderui/src/style.rs
+++ b/bindings/rust/blenderui/src/style.rs
@@ -12,7 +12,7 @@ use taffy::prelude::*;
use taffy::style::Overflow;
use crate::color::{parse_color, Rgba};
-use crate::css::{Decl, Tok};
+use crate::css::{Decl, Prop, Tok};
use crate::geometry::{Length, Units};
// ==========================================================================
@@ -283,18 +283,34 @@ type Handler = fn(&mut Ctx, &[Tok]) -> bool;
/// Apply one declaration; false when the property or value isn't understood.
pub fn apply(c: &mut Computed, parent: &Computed, u: Units, d: &Decl) -> bool {
let mut ctx = Ctx { c, parent, u };
- let name = d.prop.as_ref();
+ if d.prop == Prop::CUSTOM {
+ return true; // custom properties are accepted (no var() substitution)
+ }
+ if d.prop == Prop::UNKNOWN {
+ return false;
+ }
if let [Tok::Ident(k)] = &*d.value {
- if matches!(k.as_str(), "inherit" | "initial" | "unset" | "revert" | "revert-layer") {
- return global_keyword(&mut ctx, name, k);
+ if matches!(k.as_ref(), "inherit" | "initial" | "unset" | "revert" | "revert-layer") {
+ return global_keyword(&mut ctx, d.prop.name(), k);
}
}
- if name.starts_with("--") {
- return true; // custom properties are accepted (no var() substitution)
+ match HANDLERS.get(d.prop.0 as usize) {
+ Some((_, h)) => h(&mut ctx, &d.value),
+ None => true, // accepted, no effect
}
- match handlers().get(name) {
- Some(h) => h(&mut ctx, &d.value),
- None => ACCEPTED.contains(&name),
+}
+
+/// The property index of `name` (run-time lookup for parsed CSS).
+pub(crate) fn prop_index(name: &str) -> Prop {
+ static MAP: OnceLock<FnvMap<&'static str, u16>> = OnceLock::new();
+ let map = MAP.get_or_init(|| {
+ HANDLERS.iter().map(|(n, _)| *n).chain(ACCEPTED.iter().copied()).enumerate()
+ .map(|(i, n)| (n, i as u16)).collect()
+ });
+ match map.get(name) {
+ Some(&i) => Prop(i),
+ None if name.starts_with("--") => Prop::CUSTOM,
+ None => Prop::UNKNOWN,
}
}
@@ -405,7 +421,7 @@ pub(crate) fn length(t: &Tok) -> Option<Length> {
Tok::Num(v) if *v == 0.0 => Length::Px(0.0),
Tok::Pct(p) => Length::Percent(*p),
Tok::Ident(s) if s == "auto" => Length::Auto,
- Tok::Dim(v, unit) => match unit.as_str() {
+ Tok::Dim(v, unit) => match unit.as_ref() {
"px" => Length::Px(*v),
"rem" => Length::Rem(*v),
"em" => Length::Em(*v),
@@ -421,8 +437,8 @@ pub(crate) fn length(t: &Tok) -> Option<Length> {
"q" => Length::Px(*v * 96.0 / 101.6),
_ => return None,
},
- Tok::Func(f, args) if matches!(f.as_str(), "calc" | "min" | "max" | "clamp") => {
- return calc(f, args)
+ Tok::Func(fx) if matches!(fx.name.as_ref(), "calc" | "min" | "max" | "clamp") => {
+ return calc(&fx.name, &fx.args)
}
_ => return None,
})
@@ -461,12 +477,14 @@ pub(crate) fn tok_text(t: &Tok) -> String {
Tok::Num(v) => format!("{v}"),
Tok::Dim(v, u) => format!("{v}{u}"),
Tok::Pct(v) => format!("{v}%"),
- Tok::Ident(s) => s.clone(),
+ Tok::Ident(s) => s.to_string(),
Tok::Hash(h) => format!("#{h}"),
- Tok::Str(s) => s.clone(),
- Tok::Func(n, args) => format!(
- "{n}({})",
- args.iter()
+ Tok::Str(s) => s.to_string(),
+ Tok::Color(c) => c.to_css(),
+ Tok::Func(fx) => format!(
+ "{}({})",
+ fx.name,
+ fx.args.iter()
.map(|a| a.iter().map(tok_text).collect::<Vec<_>>().join(" "))
.collect::<Vec<_>>()
.join(",")
@@ -479,12 +497,13 @@ pub(crate) fn tok_text(t: &Tok) -> String {
pub(crate) fn color(t: &Tok, current: Rgba) -> Option<Rgba> {
match t {
+ Tok::Color(c) => Some(*c),
Tok::Ident(s) if s == "currentcolor" => Some(current),
- Tok::Ident(s) if matches!(s.as_str(), "canvas" | "field") => Some(crate::color::rgb(0x282828)),
- Tok::Ident(s) if matches!(s.as_str(), "canvastext" | "fieldtext" | "buttontext") => {
+ Tok::Ident(s) if matches!(s.as_ref(), "canvas" | "field") => Some(crate::color::rgb(0x282828)),
+ Tok::Ident(s) if matches!(s.as_ref(), "canvastext" | "fieldtext" | "buttontext") => {
Some(crate::color::rgb(0xe6e6e6))
}
- Tok::Ident(s) if matches!(s.as_str(), "linktext" | "highlight") => {
+ Tok::Ident(s) if matches!(s.as_ref(), "linktext" | "highlight") => {
Some(crate::color::rgb(0x4772b3))
}
Tok::Hash(_) | Tok::Ident(_) | Tok::Func(..) => parse_color(&tok_text(t)),
@@ -710,13 +729,13 @@ fn track_max(ctx: &Ctx, t: &Tok) -> Option<MaxTrackSizingFunction> {
fn track(ctx: &Ctx, t: &Tok) -> Option<NonRepeatedTrackSizingFunction> {
match t {
- Tok::Func(f, args) if f == "minmax" && args.len() == 2 => Some(MinMax {
- min: track_min(ctx, args[0].first()?)?,
- max: track_max(ctx, args[1].first()?)?,
+ Tok::Func(fx) if fx.name == "minmax" && fx.args.len() == 2 => Some(MinMax {
+ min: track_min(ctx, fx.args[0].first()?)?,
+ max: track_max(ctx, fx.args[1].first()?)?,
}),
- Tok::Func(f, args) if f == "fit-content" => Some(MinMax {
+ Tok::Func(fx) if fx.name == "fit-content" => Some(MinMax {
min: MinTrackSizingFunction::Auto,
- max: MaxTrackSizingFunction::FitContent(lp(ctx, length(args.first()?.first()?)?)),
+ max: MaxTrackSizingFunction::FitContent(lp(ctx, length(fx.args.first()?.first()?)?)),
}),
_ => Some(MinMax { min: track_min(ctx, t)?, max: track_max(ctx, t)? }),
}
@@ -729,7 +748,8 @@ fn track_list(ctx: &Ctx, v: &[Tok]) -> Option<Vec<TrackSizingFunction>> {
let mut out = Vec::new();
for t in v {
match t {
- Tok::Func(f, args) if f == "repeat" && args.len() >= 2 => {
+ Tok::Func(fx) if fx.name == "repeat" && fx.args.len() >= 2 => {
+ let args = &fx.args;
let rep = match args[0].first()? {
Tok::Num(n) => GridTrackRepetition::Count(*n as u16),
Tok::Ident(s) if s == "auto-fill" => GridTrackRepetition::AutoFill,
@@ -771,7 +791,8 @@ fn grid_line(v: &[Tok]) -> Option<Line<GridPlacement>> {
// -- backgrounds, shadows, fonts -----------------------------------------------------------
fn gradient(ctx: &Ctx, t: &Tok) -> Option<Gradient> {
- let Tok::Func(f, args) = t else { return None };
+ let Tok::Func(fx) = t else { return None };
+ let (f, args) = (&fx.name, &fx.args);
let radial = f.contains("radial");
if !f.contains("gradient") {
return None;
@@ -781,7 +802,7 @@ fn gradient(ctx: &Ctx, t: &Tok) -> Option<Gradient> {
if let Some(a) = args.first() {
match a.first() {
Some(Tok::Dim(v, u)) if u == "deg" || u == "turn" || u == "rad" => {
- angle = match u.as_str() {
+ angle = match u.as_ref() {
"turn" => v * 360.0,
"rad" => v.to_degrees(),
_ => *v,
@@ -877,7 +898,7 @@ fn font_size(ctx: &Ctx, t: &Tok) -> Option<f32> {
fn font_weight(ctx: &Ctx, t: &Tok) -> Option<u16> {
Some(match t {
Tok::Num(n) => *n as u16,
- Tok::Ident(s) => match s.as_str() {
+ Tok::Ident(s) => match s.as_ref() {
"normal" => 400,
"bold" => 700,
"bolder" => (ctx.parent.weight + 300).min(900),
@@ -1010,7 +1031,9 @@ macro_rules! side_handlers {
};
}
-static HANDLERS: &[(&str, Handler)] = &{
+/// The property table. A `const`, so style methods resolve property names to
+/// indices at compile time ([`Prop::named`]).
+pub(crate) const HANDLERS: &[(&str, Handler)] = &{
const fn h(n: &'static str, f: Handler) -> (&'static str, Handler) {
(n, f)
}
@@ -1413,9 +1436,10 @@ static HANDLERS: &[(&str, Handler)] = &{
let mut ok = true;
for t in v {
match t {
- Tok::Func(f, args) => {
+ Tok::Func(fx) => {
+ let (f, args) = (&fx.name, &fx.args);
let arg = |i: usize| args.get(i).and_then(|a| a.first()).and_then(length);
- match f.as_str() {
+ match f.as_ref() {
"translate" => {
c.c.translate = (arg(0).unwrap_or_default(), arg(1).unwrap_or(Length::Px(0.0)))
}
@@ -1570,7 +1594,7 @@ static HANDLERS: &[(&str, Handler)] = &{
}),
h("quotes", |c, v| {
let strs: Vec<&str> = v.iter().filter_map(|t| match t {
- Tok::Str(s) => Some(s.as_str()),
+ Tok::Str(s) => Some(s.as_ref()),
_ => None,
}).collect();
match (kw(v), strs.as_slice()) {
diff --git a/bindings/rust/blenderui/src/styled.rs b/bindings/rust/blenderui/src/styled.rs
index 670ff31..92ce061 100644
--- a/bindings/rust/blenderui/src/styled.rs
+++ b/bindings/rust/blenderui/src/styled.rs
@@ -2,60 +2,23 @@
//! pushes a declaration that the one CSS property table applies.
use crate::color::Rgba;
-use std::cell::RefCell;
-use std::sync::Arc;
-
-use crate::css::{parse_declarations, tokenize, Decl, Tok};
+use crate::css::{parse_declarations, tokenize, Decl, Prop, Tok, Value};
use crate::geometry::Length;
-pub(crate) fn css_len(l: Length) -> String {
- match l {
- Length::Px(v) => format!("{v}px"),
- Length::Rem(v) => format!("{v}rem"),
- Length::Em(v) => format!("{v}em"),
- Length::Percent(v) => format!("{v}%"),
- Length::Vw(v) => format!("{v}vw"),
- Length::Vh(v) => format!("{v}vh"),
- Length::Auto => "auto".into(),
- }
-}
-/// Tokens for a typed value, cached by its bits (no string formatting or
-/// parsing on the hot path). A miss tokenizes the same CSS text the string
-/// path would, so handlers see identical tokens.
-fn cached_tokens(key: (u8, [u32; 4]), css: impl FnOnce() -> String) -> Arc<[Tok]> {
- thread_local! {
- static CACHE: RefCell<crate::style::FnvMap<(u8, [u32; 4]), Arc<[Tok]>>> = RefCell::new(Default::default());
- }
- CACHE.with(|c| {
- if let Some(t) = c.borrow().get(&key) {
- return t.clone();
- }
- let t: Arc<[Tok]> = tokenize(&css()).into();
- let mut c = c.borrow_mut();
- if c.len() > 50_000 {
- c.clear();
- }
- c.insert(key, t.clone());
- t
- })
-}
-
-pub(crate) fn len_tokens(l: Length) -> Arc<[Tok]> {
- let (tag, v) = match l {
- Length::Px(v) => (0, v),
- Length::Rem(v) => (1, v),
- Length::Em(v) => (2, v),
- Length::Percent(v) => (3, v),
- Length::Vw(v) => (4, v),
- Length::Vh(v) => (5, v),
- Length::Auto => (6, 0.0),
+/// `prop!("padding")`: the property index, resolved at compile time.
+macro_rules! prop {
+ ($name:literal) => {
+ const { Prop::named($name) }
};
- cached_tokens((tag, [v.to_bits(), 0, 0, 0]), || css_len(l))
}
-pub(crate) fn color_tokens(c: Rgba) -> Arc<[Tok]> {
- cached_tokens((7, [c.r.to_bits(), c.g.to_bits(), c.b.to_bits(), c.a.to_bits()]), || c.to_css())
+/// A fixed value, tokenized once for the whole program.
+macro_rules! fixed_value {
+ ($css:literal) => {{
+ static V: std::sync::OnceLock<Box<[Tok]>> = std::sync::OnceLock::new();
+ Value::Static(V.get_or_init(|| tokenize($css).into_boxed_slice()))
+ }};
}
impl Rgba {
@@ -66,6 +29,32 @@ impl Rgba {
}
}
+/// What `.style()` accepts: `css!` output (compile time) or CSS text (run time).
+pub trait StyleBlock {
+ fn push_into(self, out: &mut Vec<Decl>);
+}
+
+impl<const N: usize> StyleBlock for [Decl; N] {
+ fn push_into(self, out: &mut Vec<Decl>) {
+ out.extend(self);
+ }
+}
+impl StyleBlock for &str {
+ fn push_into(self, out: &mut Vec<Decl>) {
+ out.extend(parse_declarations(self));
+ }
+}
+impl StyleBlock for String {
+ fn push_into(self, out: &mut Vec<Decl>) {
+ out.extend(parse_declarations(&self));
+ }
+}
+impl StyleBlock for &String {
+ fn push_into(self, out: &mut Vec<Decl>) {
+ out.extend(parse_declarations(self));
+ }
+}
+
/// Font weights (gpui's `FontWeight`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FontWeight(pub u16);
@@ -88,8 +77,8 @@ macro_rules! scale {
($name:ident: $($prop:literal),+) => {
paste::paste! {
fn $name(self, length: impl Into<Length>) -> Self {
- let v = len_tokens(length.into());
- self$(.css_tokens($prop, v.clone()))+
+ let v = Tok::length(length.into());
+ self$(.decl(Decl::one(prop!($prop), v.clone())))+
}
fn [<$name _0>](self) -> Self { self.$name(Length::Px(0.0)) }
fn [<$name _0p5>](self) -> Self { self.$name(Length::Rem(0.125)) }
@@ -145,10 +134,13 @@ macro_rules! fractions {
};
}
-/// Methods that set one fixed declaration: `flex() => display: flex`.
+/// Methods that set one fixed declaration: `flex() => display: flex`. The
+/// property index is resolved at compile time and the value parsed once.
macro_rules! fixed {
($($name:ident => $prop:literal : $value:literal),* $(,)?) => {
- $(fn $name(self) -> Self { self.css($prop, $value) })*
+ $(fn $name(self) -> Self {
+ self.decl(Decl { prop: prop!($prop), value: fixed_value!($value), important: false })
+ })*
};
}
@@ -156,22 +148,24 @@ macro_rules! fixed {
pub trait Styled: Sized {
fn decls_mut(&mut self) -> &mut Vec<Decl>;
- /// One CSS declaration: `.css("grid-template-columns", "1fr 2fr")`.
+ /// One CSS declaration, parsed at run time:
+ /// `.css("grid-template-columns", "1fr 2fr")`.
fn css(mut self, property: &'static str, value: impl AsRef<str>) -> Self {
self.decls_mut().push(Decl::new(property, value.as_ref()));
self
}
- /// A declaration with already-tokenized value (the typed methods' fast path).
- #[doc(hidden)]
- fn css_tokens(mut self, property: &'static str, value: Arc<[Tok]>) -> Self {
- self.decls_mut().push(Decl { prop: property.into(), value, important: false });
+ /// A declaration built by the caller (typed values, no parsing).
+ fn decl(mut self, d: Decl) -> Self {
+ self.decls_mut().push(d);
self
}
- /// A CSS declaration block: `.style("display: flex; gap: 4px")`.
- fn style(mut self, block: impl AsRef<str>) -> Self {
- self.decls_mut().extend(parse_declarations(block.as_ref()));
+ /// A CSS declaration block: `.style(css!("display: flex; gap: 4px"))`
+ /// (checked and resolved at compile time) or `.style("...")` (parsed
+ /// at run time, for text built at run time).
+ fn style(mut self, block: impl StyleBlock) -> Self {
+ block.push_into(self.decls_mut());
self
}
@@ -268,7 +262,7 @@ pub trait Styled: Sized {
}
fn order(self, n: i32) -> Self {
- self.css("order", n.to_string())
+ self.decl(Decl::one(prop!("order"), Tok::Num(n as f32)))
}
// -- grid -------------------------------------------------------------------------------
@@ -282,45 +276,45 @@ pub trait Styled: Sized {
self.css("grid-column", format!("span {n}"))
}
fn col_span_full(self) -> Self {
- self.css("grid-column", "1 / -1")
+ self.decl(Decl { prop: prop!("grid-column"), value: fixed_value!("1 / -1"), important: false })
}
fn col_start(self, n: i16) -> Self {
- self.css("grid-column-start", n.to_string())
+ self.decl(Decl::one(prop!("grid-column-start"), Tok::Num(n as f32)))
}
fn col_end(self, n: i16) -> Self {
- self.css("grid-column-end", n.to_string())
+ self.decl(Decl::one(prop!("grid-column-end"), Tok::Num(n as f32)))
}
fn row_span(self, n: u16) -> Self {
self.css("grid-row", format!("span {n}"))
}
fn row_span_full(self) -> Self {
- self.css("grid-row", "1 / -1")
+ self.decl(Decl { prop: prop!("grid-row"), value: fixed_value!("1 / -1"), important: false })
}
fn row_start(self, n: i16) -> Self {
- self.css("grid-row-start", n.to_string())
+ self.decl(Decl::one(prop!("grid-row-start"), Tok::Num(n as f32)))
}
fn row_end(self, n: i16) -> Self {
- self.css("grid-row-end", n.to_string())
+ self.decl(Decl::one(prop!("grid-row-end"), Tok::Num(n as f32)))
}
// -- colors -------------------------------------------------------------------------------
fn bg(self, color: impl Into<Rgba>) -> Self {
- self.css_tokens("background-color", color_tokens(color.into()))
+ self.decl(Decl::one(prop!("background-color"), Tok::Color(color.into())))
}
fn text_color(self, color: impl Into<Rgba>) -> Self {
- self.css_tokens("color", color_tokens(color.into()))
+ self.decl(Decl::one(prop!("color"), Tok::Color(color.into())))
}
fn border_color(self, color: impl Into<Rgba>) -> Self {
- self.css_tokens("border-color", color_tokens(color.into()))
+ self.decl(Decl::one(prop!("border-color"), Tok::Color(color.into())))
}
fn outline_color(self, color: impl Into<Rgba>) -> Self {
- self.css_tokens("outline-color", color_tokens(color.into()))
+ self.decl(Decl::one(prop!("outline-color"), Tok::Color(color.into())))
}
fn accent_color(self, color: impl Into<Rgba>) -> Self {
- self.css_tokens("accent-color", color_tokens(color.into()))
+ self.decl(Decl::one(prop!("accent-color"), Tok::Color(color.into())))
}
fn opacity(self, value: f32) -> Self {
- self.css("opacity", value.to_string())
+ self.decl(Decl::one(prop!("opacity"), Tok::Num(value)))
}
// -- borders ----------------------------------------------------------------------------
@@ -385,16 +379,18 @@ pub trait Styled: Sized {
/// Single line, clipped with an ellipsis.
fn truncate(self) -> Self {
- self.css("overflow", "hidden").css("white-space", "nowrap").css("text-overflow", "ellipsis")
+ self.decl(Decl::one(prop!("overflow"), Tok::Ident("hidden".into())))
+ .decl(Decl::one(prop!("white-space"), Tok::Ident("nowrap".into())))
+ .decl(Decl::one(prop!("text-overflow"), Tok::Ident("ellipsis".into())))
}
fn text_size(self, size: impl Into<Length>) -> Self {
- self.css_tokens("font-size", len_tokens(size.into()))
+ self.decl(Decl::one(prop!("font-size"), Tok::length(size.into())))
}
fn line_height(self, h: impl Into<Length>) -> Self {
- self.css_tokens("line-height", len_tokens(h.into()))
+ self.decl(Decl::one(prop!("line-height"), Tok::length(h.into())))
}
fn font_weight(self, w: FontWeight) -> Self {
- self.css("font-weight", w.0.to_string())
+ self.decl(Decl::one(prop!("font-weight"), Tok::Num(w.0 as f32)))
}
fn font_family(self, family: impl AsRef<str>) -> Self {
self.css("font-family", family)
@@ -413,6 +409,6 @@ pub trait Styled: Sized {
}
fn z_index(self, z: i32) -> Self {
- self.css("z-index", z.to_string())
+ self.decl(Decl::one(prop!("z-index"), Tok::Num(z as f32)))
}
}
diff --git a/bindings/rust/blenderui/src/text.rs b/bindings/rust/blenderui/src/text.rs
index 704c6b3..baf87d1 100644
--- a/bindings/rust/blenderui/src/text.rs
+++ b/bindings/rust/blenderui/src/text.rs
@@ -1,9 +1,6 @@
//! Text measuring and wrapping with the kit's font engine (the same one that
//! draws, so layout and paint agree).
-use std::cell::RefCell;
-use std::collections::HashMap;
-
use crate::style::Computed;
use blenderui_sys as sys;
@@ -14,72 +11,72 @@ pub(crate) fn flags(c: &Computed) -> i32 {
type Widths = crate::style::FnvMap<Box<str>, f32>;
-thread_local! {
- /// (size bits, flags) -> text -> width; looked up by `&str`, no allocation.
- static CACHE: RefCell<HashMap<(u32, i32), Widths>> = RefCell::new(HashMap::new());
+/// Text widths by (size, flags) then text: looked up by `&str`, no
+/// allocation on a hit. Owned by the window, kept across frames.
+#[derive(Default)]
+pub(crate) struct TextCache {
+ fonts: crate::style::FnvMap<(u32, i32), Widths>,
}
-/// Advance width of `s` at `size` px.
-pub(crate) fn width(s: &str, size: f32, flags: i32) -> f32 {
- if s.is_empty() {
- return 0.0;
- }
- let font = (size.to_bits(), flags);
- if let Some(w) = CACHE.with(|c| c.borrow().get(&font).and_then(|m| m.get(s)).copied()) {
- return w;
- }
- let mut w = 0.0f32;
- // SAFETY: pointers are valid for the call; "" selects the UI font.
- let ok = unsafe {
- sys::BUI_text_measure(c"".as_ptr(), flags, 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
- }
- CACHE.with(|c| {
- let mut c = c.borrow_mut();
- let m = c.entry(font).or_default();
+impl TextCache {
+ /// Advance width of `s` at `size` px.
+ pub(crate) fn width(&mut self, s: &str, size: f32, flags: i32) -> f32 {
+ if s.is_empty() {
+ return 0.0;
+ }
+ let m = self.fonts.entry((size.to_bits(), flags)).or_default();
+ if let Some(&w) = m.get(s) {
+ return w;
+ }
+ let mut w = 0.0f32;
+ // SAFETY: pointers are valid for the call; "" selects the UI font.
+ let ok = unsafe {
+ sys::BUI_text_measure(c"".as_ptr(), flags, 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
+ }
if m.len() > 20_000 {
m.clear();
}
m.insert(s.into(), w);
- });
- w
-}
+ w
+ }
-/// Greedy word wrap of `s` into lines no wider than `max` (explicit newlines kept).
-pub(crate) fn wrap(s: &str, size: f32, flags: i32, max: f32) -> Vec<String> {
- let mut out = Vec::new();
- for para in s.split('\n') {
- let mut line = String::new();
- for word in para.split(' ').filter(|w| !w.is_empty()) {
- let candidate = if line.is_empty() { word.to_owned() } else { format!("{line} {word}") };
- if !line.is_empty() && width(&candidate, size, flags) > max {
- out.push(std::mem::replace(&mut line, word.to_owned()));
- } else {
- line = candidate;
+ /// Greedy word wrap of `s` into lines no wider than `max` (explicit newlines kept).
+ pub(crate) fn wrap(&mut self, s: &str, size: f32, flags: i32, max: f32) -> Vec<String> {
+ let mut out = Vec::new();
+ for para in s.split('\n') {
+ let mut line = String::new();
+ for word in para.split(' ').filter(|w| !w.is_empty()) {
+ let candidate = if line.is_empty() { word.to_owned() } else { format!("{line} {word}") };
+ if !line.is_empty() && self.width(&candidate, size, flags) > max {
+ out.push(std::mem::replace(&mut line, word.to_owned()));
+ } else {
+ line = candidate;
+ }
}
+ out.push(line);
}
- out.push(line);
+ out
}
- out
-}
-/// `s` cut to fit `max` with a trailing ellipsis (`text-overflow: ellipsis`).
-pub(crate) fn ellipsize(s: &str, size: f32, flags: i32, max: f32) -> String {
- if width(s, size, flags) <= max {
- return s.to_owned();
- }
- let chars: Vec<char> = s.chars().collect();
- let (mut lo, mut hi) = (0, chars.len());
- while lo < hi {
- let mid = (lo + hi).div_ceil(2);
- let t: String = chars[..mid].iter().collect::<String>() + "\u{2026}";
- if width(&t, size, flags) <= max {
- lo = mid;
- } else {
- hi = mid - 1;
+ /// `s` cut to fit `max` with a trailing ellipsis (`text-overflow: ellipsis`).
+ pub(crate) fn ellipsize(&mut self, s: &str, size: f32, flags: i32, max: f32) -> String {
+ if self.width(s, size, flags) <= max {
+ return s.to_owned();
+ }
+ let chars: Vec<char> = s.chars().collect();
+ let (mut lo, mut hi) = (0, chars.len());
+ while lo < hi {
+ let mid = (lo + hi).div_ceil(2);
+ let t: String = chars[..mid].iter().collect::<String>() + "\u{2026}";
+ if self.width(&t, size, flags) <= max {
+ lo = mid;
+ } else {
+ hi = mid - 1;
+ }
}
+ chars[..lo].iter().collect::<String>() + "\u{2026}"
}
- chars[..lo].iter().collect::<String>() + "\u{2026}"
}
diff --git a/bindings/rust/blenderui/src/widgets.rs b/bindings/rust/blenderui/src/widgets.rs
index a387d18..89a94a1 100644
--- a/bindings/rust/blenderui/src/widgets.rs
+++ b/bindings/rust/blenderui/src/widgets.rs
@@ -9,7 +9,8 @@ use crate::color::{parse_color, Rgba};
use crate::element::{AnyElement, Div};
use crate::events::ChangeEvent;
use crate::geometry::Bounds;
-use crate::layout::UiState;
+use crate::element::SharedString;
+use crate::layout::{Key, UiState};
use blenderui_sys as sys;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -88,8 +89,8 @@ fn text_of(children: &[AnyElement]) -> Option<String> {
}
impl WidgetSpec {
- fn new(kind: WKind, d: &Div) -> WidgetSpec {
- let num = |k: &str| d.get_attr(k).and_then(|v| v.trim().parse::<f64>().ok());
+ fn new(kind: WKind, attrs: &Attrs) -> WidgetSpec {
+ let num = |k: &str| attr(attrs, k).and_then(|v| v.trim().parse::<f64>().ok());
WidgetSpec {
kind,
label: String::new(),
@@ -100,31 +101,32 @@ impl WidgetSpec {
step: num("step").unwrap_or(1.0),
items: Vec::new(),
color: None,
- placeholder: d.get_attr("placeholder").unwrap_or("").to_owned(),
- disabled: d.get_attr("disabled").is_some(),
- name: d.get_attr("name").map(str::to_owned),
+ placeholder: attr(attrs, "placeholder").unwrap_or("").to_owned(),
+ disabled: attr(attrs, "disabled").is_some(),
+ name: attr(attrs, "name").map(str::to_owned),
}
}
/// The widget for a form element, or None to lay it out as a box
/// (a `<button>` holding elements, `<option>` outside a select ...).
- pub(crate) fn from_element(d: &Div, key: &str, state: &UiState) -> Option<WidgetSpec> {
- let num = |k: &str| d.get_attr(k).and_then(|v| v.trim().parse::<f64>().ok());
+ /// `attrs`: the element's attributes (already moved out of `d`).
+ pub(crate) fn from_element(d: &Div, attrs: &Attrs, key: Key, state: &UiState) -> Option<WidgetSpec> {
+ let num = |k: &str| attr(attrs, k).and_then(|v| v.trim().parse::<f64>().ok());
let checked = || {
- state.checked.get(key).copied().unwrap_or(d.get_attr("checked").is_some())
+ state.checked.get(&key).copied().unwrap_or(attr(attrs, "checked").is_some())
};
let mut s;
match d.tag {
"button" => {
- s = WidgetSpec::new(WKind::Button, d);
+ s = WidgetSpec::new(WKind::Button, attrs);
s.label = text_of(&d.children)?;
}
"input" => {
- let ty = d.get_attr("type").unwrap_or("text").to_ascii_lowercase();
- let value = d.get_attr("value").map(str::to_owned);
+ let ty = attr(attrs, "type").unwrap_or("text").to_ascii_lowercase();
+ let value = attr(attrs, "value").map(str::to_owned);
match ty.as_str() {
"button" | "submit" | "reset" => {
- s = WidgetSpec::new(WKind::Button, d);
+ s = WidgetSpec::new(WKind::Button, attrs);
s.label = value.unwrap_or_else(|| match ty.as_str() {
"submit" => "Submit".into(),
"reset" => "Reset".into(),
@@ -132,23 +134,23 @@ impl WidgetSpec {
});
}
"file" => {
- s = WidgetSpec::new(WKind::Button, d);
+ s = WidgetSpec::new(WKind::Button, attrs);
s.label = "Browse\u{2026}".into();
}
"checkbox" => {
- s = WidgetSpec::new(WKind::Checkbox, d);
+ s = WidgetSpec::new(WKind::Checkbox, attrs);
s.value = Some(checked() as i32 as f64);
}
"radio" => {
- s = WidgetSpec::new(WKind::Radio, d);
+ s = WidgetSpec::new(WKind::Radio, attrs);
s.value = Some(checked() as i32 as f64);
}
"number" => {
- s = WidgetSpec::new(WKind::Number, d);
+ s = WidgetSpec::new(WKind::Number, attrs);
s.value = num("value");
}
"range" => {
- s = WidgetSpec::new(WKind::Slider, d);
+ s = WidgetSpec::new(WKind::Slider, attrs);
if s.min.is_infinite() {
s.min = 0.0;
}
@@ -158,22 +160,22 @@ impl WidgetSpec {
s.value = Some(num("value").unwrap_or((s.min + s.max) / 2.0));
}
"color" => {
- s = WidgetSpec::new(WKind::Color, d);
+ s = WidgetSpec::new(WKind::Color, attrs);
s.color = Some(value.as_deref().and_then(parse_color)
.unwrap_or(crate::color::black()));
}
"image" | "hidden" => return None,
_ => {
// text, password, email, url, search, tel, date, time ...
- s = WidgetSpec::new(WKind::Text { mask: ty == "password" }, d);
+ s = WidgetSpec::new(WKind::Text { mask: ty == "password" }, attrs);
s.text = value;
}
}
}
"select" => {
- s = WidgetSpec::new(WKind::Select, d);
+ s = WidgetSpec::new(WKind::Select, attrs);
let mut selected = None;
- let want = d.get_attr("value");
+ let want = attr(attrs, "value");
fn options<'a>(c: &'a [AnyElement], out: &mut Vec<&'a Div>) {
for e in c {
if let AnyElement::Element(d) = e {
@@ -198,15 +200,15 @@ impl WidgetSpec {
s.value = Some(selected.unwrap_or(0) as f64);
}
"textarea" => {
- s = WidgetSpec::new(WKind::TextArea, d);
- s.text = Some(d.get_attr("value").map(str::to_owned)
+ s = WidgetSpec::new(WKind::TextArea, attrs);
+ s.text = Some(attr(attrs, "value").map(str::to_owned)
.unwrap_or_else(|| d.children.iter().filter_map(|c| match c {
AnyElement::Text(t) => Some(t.as_ref()),
_ => None,
}).collect()));
}
"progress" | "meter" => {
- s = WidgetSpec::new(WKind::Progress, d);
+ s = WidgetSpec::new(WKind::Progress, attrs);
let min = if d.tag == "meter" { num("min").unwrap_or(0.0) } else { 0.0 };
let max = num("max").unwrap_or(1.0);
let v = num("value").unwrap_or(0.0);
@@ -219,6 +221,12 @@ impl WidgetSpec {
}
}
+type Attrs = [(SharedString, SharedString)];
+
+fn attr<'a>(attrs: &'a Attrs, name: &str) -> Option<&'a str> {
+ attrs.iter().rev().find(|(n, _)| n == name).map(|(_, v)| v.as_ref())
+}
+
fn cstr(s: &str) -> CString {
CString::new(s.replace('\0', "")).unwrap_or_default()
}
@@ -231,7 +239,7 @@ pub(crate) struct WidgetNode {
/// The kit widgets of one window, keyed by element key.
pub(crate) struct Widgets {
- pub nodes: HashMap<String, WidgetNode>,
+ pub nodes: HashMap<Key, WidgetNode>,
/// Set while Rust writes values, so the kit's change echoes are ignored.
pub syncing: bool,
}
@@ -243,15 +251,15 @@ impl Widgets {
/// Ensure the kit node for `key` exists and matches `spec`; returns its
/// natural size in logical pixels.
- pub(crate) fn ensure(&mut self, parent: *mut sys::BKNode, key: &str, spec: &WidgetSpec, scale: f32)
+ pub(crate) fn ensure(&mut self, parent: *mut sys::BKNode, key: Key, spec: &WidgetSpec, scale: f32)
-> (f32, f32) {
- if self.nodes.get(key).is_some_and(|w| w.spec.kind != spec.kind) {
- let w = self.nodes.remove(key).unwrap();
+ if self.nodes.get(&key).is_some_and(|w| w.spec.kind != spec.kind) {
+ let w = self.nodes.remove(&key).unwrap();
// SAFETY: the node is ours and attached to `parent`.
unsafe { sys::BK_node_free(w.node) };
}
self.syncing = true;
- let entry = self.nodes.entry(key.to_owned()).or_insert_with(|| {
+ let entry = self.nodes.entry(key).or_insert_with(|| {
// SAFETY: plain constructor calls on a fresh node.
let node = unsafe { sys::BK_node_new(spec.kind.class().as_ptr()) };
unsafe {
@@ -276,7 +284,7 @@ impl Widgets {
}
/// Place every widget at its laid-out bounds; free those not rendered.
- pub(crate) fn place(&mut self, at: &HashMap<String, (Bounds<f32>, Option<Bounds<f32>>, bool)>,
+ pub(crate) fn place(&mut self, at: &HashMap<Key, (Bounds<f32>, Option<Bounds<f32>>, bool)>,
scale: f32) {
self.nodes.retain(|key, w| {
if !w.seen || !at.contains_key(key) {
@@ -301,13 +309,13 @@ impl Widgets {
});
}
- pub(crate) fn key_of(&self, node: *mut sys::BKNode) -> Option<String> {
- self.nodes.iter().find(|(_, w)| w.node == node).map(|(k, _)| k.clone())
+ pub(crate) fn key_of(&self, node: *mut sys::BKNode) -> Option<Key> {
+ self.nodes.iter().find(|(_, w)| w.node == node).map(|(k, _)| *k)
}
/// The control's current value, as an HTML `change` event sees it.
- pub(crate) fn read(&self, key: &str) -> ChangeEvent {
- let Some(w) = self.nodes.get(key) else { return ChangeEvent::default() };
+ pub(crate) fn read(&self, key: Key) -> ChangeEvent {
+ let Some(w) = self.nodes.get(&key) else { return ChangeEvent::default() };
let n = w.node;
// SAFETY: live node; returned strings are copied immediately.
unsafe {
@@ -338,16 +346,16 @@ impl Widgets {
}
/// Radio groups: turning one on turns the others with its name off.
- pub(crate) fn radio_group(&self, key: &str) -> Vec<String> {
- let Some(name) = self.nodes.get(key).and_then(|w| w.spec.name.clone()) else { return vec![] };
+ pub(crate) fn radio_group(&self, key: Key) -> Vec<Key> {
+ let Some(name) = self.nodes.get(&key).and_then(|w| w.spec.name.clone()) else { return vec![] };
self.nodes.iter()
- .filter(|(k, w)| *k != key && w.spec.kind == WKind::Radio && w.spec.name.as_ref() == Some(&name))
- .map(|(k, _)| k.clone())
+ .filter(|(k, w)| **k != key && w.spec.kind == WKind::Radio && w.spec.name.as_ref() == Some(&name))
+ .map(|(k, _)| *k)
.collect()
}
- pub(crate) fn set_value(&mut self, key: &str, v: f64) {
- if let Some(w) = self.nodes.get(key) {
+ pub(crate) fn set_value(&mut self, key: Key, v: f64) {
+ if let Some(w) = self.nodes.get(&key) {
self.syncing = true;
unsafe { sys::BK_set_num(w.node, c"value".as_ptr(), v) };
self.syncing = false;
diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rs
index 5e89d18..d0d8298 100644
--- a/bindings/rust/blenderui/src/window.rs
+++ b/bindings/rust/blenderui/src/window.rs
@@ -7,17 +7,17 @@
//! ```
use std::any::{Any, TypeId};
-use std::cell::{Ref, RefCell};
+use std::cell::Cell;
use std::collections::{HashMap, VecDeque};
use std::ffi::{c_char, c_double, c_int, c_void, CStr, CString};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
-use std::rc::Rc;
use crate::element::{AnyElement, IntoElement, Listener, Listeners, SharedString};
use crate::events::*;
use crate::geometry::{point, px, size, Bounds, Pixels, Size};
-use crate::layout::{layout, Content, Frame, UiState};
+use crate::layout::{id_key, layout, Content, Frame, Key, LayoutCaches, UiState};
+use crate::prof::{self, span, Phase};
use crate::paint::{paint_frame, Painter};
use crate::widgets::{WKind, Widgets};
use blenderui_sys as sys;
@@ -25,60 +25,84 @@ use blenderui_sys as sys;
// ==========================================================================
// Entities
-/// Shared state owned by the app (gpui's `Entity<T>`).
+/// State owned by the app (gpui's `Entity<T>`): a `Copy` handle (slot index
+/// and generation) into the app's entity slots. No reference counting.
pub struct Entity<T> {
- inner: Rc<RefCell<Option<T>>>,
+ id: u32,
+ generation: u32,
+ _t: PhantomData<fn() -> T>,
}
impl<T> Clone for Entity<T> {
fn clone(&self) -> Self {
- Entity { inner: self.inner.clone() }
+ *self
}
}
+impl<T> Copy for Entity<T> {}
+
+/// One entity's storage. The value is moved out while it is being updated.
+struct Slot {
+ generation: u32,
+ value: Option<Box<dyn Any>>,
+}
impl<T: 'static> Entity<T> {
/// Read the value.
- pub fn read<'a>(&'a self, _cx: &'a App) -> Ref<'a, T> {
- Ref::map(self.inner.borrow(), |v| v.as_ref().expect("entity is being built"))
+ pub fn read<'a>(&self, cx: &'a App) -> &'a T {
+ let slot = &cx.entities[self.id as usize];
+ assert!(slot.generation == self.generation, "entity was released");
+ slot.value.as_ref().expect("entity is being built or updated")
+ .downcast_ref::<T>().expect("entity type")
}
- /// Mutate the value with a [`Context`] for it.
+ /// Mutate the value with a [`Context`] for it. The value is taken out of
+ /// its slot meanwhile, so `cx` stays fully usable (except for updating
+ /// this same entity again, which panics).
pub fn update<R>(&self, cx: &mut App, f: impl FnOnce(&mut T, &mut Context<T>) -> R) -> R {
- let mut slot = self.inner.borrow_mut();
- let value = slot.as_mut().expect("entity is being built");
- let mut ctx = Context { app: cx, entity: self.clone() };
- f(value, &mut ctx)
+ let slot = &mut cx.entities[self.id as usize];
+ assert!(slot.generation == self.generation, "entity was released");
+ let mut value = slot.value.take().expect("entity is being built or already being updated");
+ let r = {
+ let v = value.downcast_mut::<T>().expect("entity type");
+ let mut ctx = Context { app: cx, entity: *self };
+ f(v, &mut ctx)
+ };
+ cx.entities[self.id as usize].value = Some(value);
+ r
}
/// Same entity?
pub fn entity_id(&self) -> usize {
- Rc::as_ptr(&self.inner) as *const () as usize
+ self.id as usize
}
pub fn downgrade(&self) -> WeakEntity<T> {
- WeakEntity { inner: Rc::downgrade(&self.inner) }
+ WeakEntity { entity: *self }
}
}
-/// A weak handle (gpui's `WeakEntity<T>`).
+/// A handle that may outlive its entity (gpui's `WeakEntity<T>`).
pub struct WeakEntity<T> {
- inner: std::rc::Weak<RefCell<Option<T>>>,
+ entity: Entity<T>,
}
impl<T> Clone for WeakEntity<T> {
fn clone(&self) -> Self {
- WeakEntity { inner: self.inner.clone() }
+ *self
}
}
+impl<T> Copy for WeakEntity<T> {}
impl<T: 'static> WeakEntity<T> {
- pub fn upgrade(&self) -> Option<Entity<T>> {
- self.inner.upgrade().map(|inner| Entity { inner })
+ /// The entity, if it hasn't been released.
+ pub fn upgrade_in(&self, cx: &App) -> Option<Entity<T>> {
+ let slot = cx.entities.get(self.entity.id as usize)?;
+ (slot.generation == self.entity.generation).then_some(self.entity)
}
/// Update if still alive.
pub fn update<R>(&self, cx: &mut App, f: impl FnOnce(&mut T, &mut Context<T>) -> R) -> Option<R> {
- self.upgrade().map(|e| e.update(cx, f))
+ self.upgrade_in(cx).map(|e| e.update(cx, f))
}
}
@@ -103,7 +127,7 @@ impl<T> DerefMut for Context<'_, T> {
impl<T: 'static> Context<'_, T> {
/// This entity.
pub fn entity(&self) -> Entity<T> {
- self.entity.clone()
+ self.entity
}
pub fn weak_entity(&self) -> WeakEntity<T> {
@@ -122,9 +146,7 @@ impl<T: 'static> Context<'_, T> {
) -> impl Fn(&E, &mut Window, &mut App) + 'static {
let weak = self.entity.downgrade();
move |e: &E, window: &mut Window, cx: &mut App| {
- if let Some(entity) = weak.upgrade() {
- entity.update(cx, |this, cx| f(this, e, window, cx));
- }
+ weak.update(cx, |this, cx| f(this, e, window, cx));
}
}
}
@@ -149,14 +171,14 @@ pub struct WindowHandle<V> {
impl<V> Clone for WindowHandle<V> {
fn clone(&self) -> Self {
- WindowHandle { id: self.id, entity: self.entity.clone() }
+ WindowHandle { id: self.id, entity: self.entity }
}
}
impl<V: 'static> WindowHandle<V> {
/// The root view of the window.
pub fn root(&self) -> Entity<V> {
- self.entity.clone()
+ self.entity
}
/// Update the root view with its window.
@@ -227,20 +249,39 @@ impl Application {
app.shutdown();
return;
}
- APP.with(|a| *a.borrow_mut() = Some(app));
- // SAFETY: plain message loop; callbacks re-enter through APP.
+ // the app stays on this stack frame; kit callbacks reach it through APP
+ APP.with(|a| a.set(&mut app as *mut App));
+ // SAFETY: plain message loop; `app` isn't touched here until it returns.
unsafe { sys::BK_window_run() };
- if let Some(mut app) = APP.with(|a| a.borrow_mut().take()) {
- app.shutdown();
- }
+ APP.with(|a| a.set(std::ptr::null_mut()));
+ app.shutdown();
}
}
thread_local! {
- /// The running app while the native loop runs (callbacks borrow it).
- static APP: RefCell<Option<App>> = const { RefCell::new(None) };
- /// Kit events that arrived while the app was busy.
- static QUEUE: RefCell<VecDeque<RawEvent>> = const { RefCell::new(VecDeque::new()) };
+ /// The app while the native loop runs (it lives on `Application::run`'s stack).
+ static APP: Cell<*mut App> = const { Cell::new(std::ptr::null_mut()) };
+ /// Set while a callback holds the app (a re-entrant callback must not).
+ static BUSY: Cell<bool> = const { Cell::new(false) };
+ /// Kit events, handled in order once the app is free.
+ static QUEUE: Cell<VecDeque<RawEvent>> = const { Cell::new(VecDeque::new()) };
+}
+
+fn queue_push(ev: RawEvent) {
+ QUEUE.with(|q| {
+ let mut v = q.take();
+ v.push_back(ev);
+ q.set(v);
+ });
+}
+
+fn queue_pop() -> Option<RawEvent> {
+ QUEUE.with(|q| {
+ let mut v = q.take();
+ let ev = v.pop_front();
+ q.set(v);
+ ev
+ })
}
struct RawEvent {
@@ -255,6 +296,7 @@ struct RawEvent {
/// The application state (gpui's `App`).
pub struct App {
windows: Vec<Option<Box<Window>>>,
+ entities: Vec<Slot>,
headless: bool,
globals: HashMap<TypeId, Box<dyn Any>>,
propagate: bool,
@@ -262,18 +304,28 @@ pub struct App {
impl App {
fn create(headless: bool) -> App {
- App { windows: Vec::new(), headless, globals: HashMap::new(), propagate: true }
+ App { windows: Vec::new(), entities: Vec::new(), headless, globals: HashMap::new(), propagate: true }
}
/// Create an entity (gpui's `cx.new`).
pub fn new<T: 'static>(&mut self, build: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
- let entity = Entity { inner: Rc::new(RefCell::new(None)) };
- let mut ctx = Context { app: self, entity: entity.clone() };
- let v = build(&mut ctx);
- *entity.inner.borrow_mut() = Some(v);
+ let id = self.entities.len() as u32;
+ self.entities.push(Slot { generation: 0, value: None });
+ let entity = Entity { id, generation: 0, _t: PhantomData };
+ let v = build(&mut Context { app: self, entity });
+ self.entities[id as usize].value = Some(Box::new(v));
entity
}
+ /// Drop an entity's value. Its handles become dead: `WeakEntity::update`
+ /// skips them, `Entity::read` / `update` panic.
+ pub fn release<T: 'static>(&mut self, entity: Entity<T>) {
+ if let Some(slot) = self.entities.get_mut(entity.id as usize).filter(|s| s.generation == entity.generation) {
+ slot.value = None;
+ slot.generation += 1;
+ }
+ }
+
/// Open a window whose root view is built by `build`.
pub fn open_window<V: Render>(
&mut self,
@@ -303,8 +355,8 @@ impl App {
}
}
let entity = build(&mut w, self);
- let view = entity.clone();
- w.view = Some(Rc::new(move |window: &mut Window, cx: &mut App| {
+ let view = entity;
+ w.view = Some(Box::new(move |window: &mut Window, cx: &mut App| {
view.update(cx, |v, cx| v.render(window, cx).into_any_element())
}));
w.dirty = true;
@@ -364,7 +416,7 @@ impl App {
/// Handle queued kit events, then re-render what changed.
fn drain(&mut self) {
- while let Some(ev) = QUEUE.with(|q| q.borrow_mut().pop_front()) {
+ while let Some(ev) = queue_pop() {
self.with_window(ev.window, |w, app| w.dispatch(ev, app));
}
}
@@ -416,7 +468,7 @@ impl App {
if w.raster.is_null() {
w.raster = sys::BUI_raster_create(pw, ph);
}
- let _s = crate::prof::span("kit render");
+ let _s = span(Phase::Widgets);
sys::BK_render(w.ctx, w.raster, pw, ph, 1);
let p = sys::BUI_raster_pixels(w.raster);
std::slice::from_raw_parts(p, (pw * ph) as usize).to_vec()
@@ -430,7 +482,7 @@ impl App {
self.flush();
let w = self.window(window)?;
let f = w.frame.as_ref()?;
- f.by_key().get(&format!("#{id}")).map(|&i| f.nodes[i].bounds)
+ f.by_key().get(&id_key(id)).map(|&i| f.nodes[i].bounds)
}
fn input(&mut self, window: WindowId, f: impl FnOnce(*mut sys::BKContext, f32)) {
@@ -490,7 +542,7 @@ unsafe extern "C" fn on_emit(data: *mut c_void, node: *mut sys::BKNode, kind: c_
// SAFETY: raw events carry a C string in `ref`.
unsafe { CStr::from_ptr(ref_ as *const c_char) }.to_string_lossy().into_owned()
};
- QUEUE.with(|q| q.borrow_mut().push_back(RawEvent { window: data as usize, node, kind, text, a, b }));
+ queue_push(RawEvent { window: data as usize, node, kind, text, a, b });
with_running_app(|app| app.flush());
}
@@ -515,10 +567,10 @@ unsafe extern "C" fn on_timer(data: *mut c_void, _win: *mut sys::BKWindow, _id:
unsafe extern "C" fn on_frame(data: *mut c_void, _win: *mut sys::BKWindow) {
// BUI_PROFILE: wall time between frames, i.e. rebuild + kit render + present
thread_local! { static LAST: std::cell::Cell<Option<std::time::Instant>> = const { std::cell::Cell::new(None) }; }
- if crate::prof::on() {
+ if prof::on() {
let now = std::time::Instant::now();
if let Some(t) = LAST.with(|l| l.replace(Some(now))) {
- crate::prof::add("frame interval", (now - t).as_secs_f64() * 1000.0);
+ prof::add(Phase::FrameInterval, (now - t).as_secs_f64() * 1000.0);
}
}
let id = data as usize;
@@ -543,12 +595,18 @@ unsafe extern "C" fn on_close(data: *mut c_void, _win: *mut sys::BKWindow) -> c_
1
}
+/// Run `f` with the app, unless there is none (before the loop, headless)
+/// or a callback further up the stack already holds it.
fn with_running_app(f: impl FnOnce(&mut App)) -> bool {
- let Some(mut app) = APP.with(|a| a.try_borrow_mut().ok().and_then(|mut a| a.take())) else {
+ let app = APP.with(Cell::get);
+ if app.is_null() || BUSY.with(Cell::get) {
return false;
- };
- f(&mut app);
- APP.with(|a| *a.borrow_mut() = Some(app));
+ }
+ BUSY.with(|b| b.set(true));
+ // SAFETY: `app` points at the live App on `Application::run`'s stack,
+ // which isn't touched while the loop runs; BUSY keeps this `&mut` unique.
+ f(unsafe { &mut *app });
+ BUSY.with(|b| b.set(false));
true
}
@@ -557,7 +615,7 @@ unsafe extern "C" fn noop(_: *mut c_void) {}
// ==========================================================================
// Windows
-type ViewFn = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
+type ViewFn = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>;
/// A window (gpui's `Window`): its kit context, layout and interaction state.
pub struct Window {
@@ -572,6 +630,11 @@ pub struct Window {
scale: f32,
view: Option<ViewFn>,
frame: Option<Frame>,
+ /// Styles, text widths, images, the author sheet and the taffy tree:
+ /// kept across frames.
+ caches: LayoutCaches,
+ /// The display list, reused every frame.
+ painter: Painter,
state: UiState,
widgets: Widgets,
dirty: bool,
@@ -582,7 +645,7 @@ pub struct Window {
title: String,
cursor: i32,
pointer: (f32, f32),
- pressed: Vec<String>,
+ pressed: Vec<Key>,
press_button: MouseButton,
}
@@ -624,6 +687,8 @@ impl Window {
scale: 1.0,
view: None,
frame: None,
+ caches: LayoutCaches::default(),
+ painter: Painter::new(),
state: UiState::default(),
widgets: Widgets::new(),
dirty: true,
@@ -729,27 +794,30 @@ impl Window {
/// The `.id()` of the focused element, if any.
pub fn focused_id(&self) -> Option<&str> {
- self.state.focused.as_deref().and_then(|k| k.strip_prefix('#'))
+ self.state.focused_id.as_deref()
}
/// Focus the element with `.id(id)` (keyboard events go to it).
pub fn focus_id(&mut self, id: &str) {
- self.state.focused = Some(format!("#{id}"));
+ let key = id_key(id);
+ self.state.focused = Some(key);
+ self.state.focus_path = [key].into_iter().collect();
+ self.state.focused_id = Some(id.to_owned());
self.dirty = true;
}
/// Is the element with `.id(id)` hovered?
pub fn is_hovered(&self, id: &str) -> bool {
- self.state.hovered.contains(&format!("#{id}"))
+ self.state.hovered.contains(&id_key(id))
}
/// Scroll offset of a scroll container with `.id(id)`.
pub fn scroll_offset(&self, id: &str) -> (f32, f32) {
- self.state.scroll.get(&format!("#{id}")).copied().unwrap_or((0.0, 0.0))
+ self.state.scroll.get(&id_key(id)).copied().unwrap_or((0.0, 0.0))
}
pub fn set_scroll_offset(&mut self, id: &str, x: f32, y: f32) {
- self.state.scroll.insert(format!("#{id}"), (x, y));
+ self.state.scroll.insert(id_key(id), (x, y));
self.dirty = true;
}
@@ -760,35 +828,44 @@ impl Window {
// -- render -----------------------------------------------------------------------------
fn rebuild(&mut self, app: &mut App) {
- let Some(view) = self.view.clone() else { return };
+ // the view is moved out while it renders (it gets `&mut Window`)
+ let Some(view) = self.view.take() else { return };
self.dirty = false;
let root = {
- let _s = crate::prof::span("render");
+ let _s = span(Phase::Render);
view(self, app)
};
+ if self.view.is_none() {
+ self.view = Some(view);
+ }
let vp = self.viewport();
let (canvas, scale) = (self.canvas, self.scale);
let widgets = &mut self.widgets;
- let frame = layout(root, vp, &self.state, &mut |key, spec| widgets.ensure(canvas, key, spec, scale));
- let mut p = Painter::new();
+ 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));
+ let p = &mut self.painter;
+ p.reset();
{
- let _s = crate::prof::span("paint");
- paint_frame(&frame, &mut p, vp);
+ let _s = span(Phase::Paint);
+ paint_frame(&frame, &self.caches.styles, &mut self.caches.text, p, vp);
}
{
- let _s = crate::prof::span("flush");
+ let _s = span(Phase::Flush);
p.flush(canvas, scale);
}
- let _rest = crate::prof::span("widgets+hover");
- let mut at = HashMap::new();
+ let _rest = span(Phase::Widgets);
+ let mut at = HashMap::new(); // empty (no allocation) without form widgets
for n in &frame.nodes {
if matches!(n.content, Content::Widget(_)) {
- at.insert(n.key.clone(), (n.bounds, n.clip, n.visible));
+ at.insert(n.key, (n.bounds, n.clip, n.visible));
}
}
self.widgets.place(&at, scale);
// an opaque <html> background covers the window: the kit can skip its clear
- let opaque = frame.nodes.first().is_some_and(|h| h.style.background.a >= 1.0 && h.style.opacity >= 1.0);
+ let styles = &self.caches.styles;
+ let opaque = frame.nodes.first()
+ .is_some_and(|h| styles[h.style].background.a >= 1.0 && styles[h.style].opacity >= 1.0);
if opaque != self.opaque {
self.opaque = opaque;
unsafe { sys::BK_set_num(self.root, c"opaque".as_ptr(), opaque as i32 as f64) };
@@ -799,51 +876,50 @@ impl Window {
self.frame = Some(frame);
self.update_hover(app, false);
drop(_rest);
- crate::prof::frame_done();
+ prof::frame_done();
}
// -- events ------------------------------------------------------------------------------
/// Element keys from the root to the deepest element under the pointer.
- fn path_at(&self, x: f32, y: f32) -> Vec<String> {
- let Some(f) = &self.frame else { return Vec::new() };
- f.hit_path(x, y).into_iter().map(|i| f.nodes[i].key.clone()).collect()
- }
-
- /// Listeners of `pick` from `key` up to the root (bubbling order).
- fn bubble<E: 'static>(&self, key: &str, pick: impl Fn(&Listeners) -> Vec<Listener<E>>)
- -> Vec<Listener<E>> {
+ fn path_at(&self, x: f32, y: f32) -> Vec<Key> {
let Some(f) = &self.frame else { return Vec::new() };
- let mut out = Vec::new();
- let mut cur = f.by_key().get(key).copied();
- while let Some(i) = cur {
- if let Some(el) = &f.nodes[i].el {
- out.extend(pick(&el.listeners));
- }
- cur = f.nodes[i].parent;
- }
- out
+ f.hit_path(x, y, &self.caches.styles).into_iter().map(|i| f.nodes[i].key).collect()
}
- fn fire<E: 'static>(&mut self, app: &mut App, listeners: Vec<Listener<E>>, e: &E) {
+ /// Call the listeners `pick` selects, from element `key` up to the root.
+ /// The frame is moved out of the window meanwhile, so listeners can take
+ /// `&mut Window` while the frame lends them out: no copies, no `Rc`.
+ fn emit<E: 'static>(&mut self, app: &mut App, key: Key, e: &E,
+ pick: impl Fn(&Listeners) -> Vec<&Listener<E>>) {
+ let Some(frame) = self.frame.take() else { return };
app.propagate = true;
- for l in listeners {
- l(e, self, app);
- if !app.propagate {
- break;
+ let mut cur = frame.by_key().get(&key).copied();
+ 'up: while let Some(i) = cur {
+ if let Some(ls) = frame.el(i).and_then(|e| e.listeners.as_deref()) {
+ for l in pick(ls) {
+ l(e, self, app);
+ if !app.propagate {
+ break 'up;
+ }
+ }
}
+ cur = frame.nodes[i].parent;
}
app.propagate = true;
+ if self.frame.is_none() {
+ self.frame = Some(frame);
+ }
}
fn update_hover(&mut self, app: &mut App, fire: bool) {
let path = self.path_at(self.pointer.0, self.pointer.1);
- let now: std::collections::HashSet<String> = path.iter().cloned().collect();
+ let now: std::collections::HashSet<Key> = path.iter().copied().collect();
if now == self.state.hovered {
return;
}
- let entered: Vec<String> = now.difference(&self.state.hovered).cloned().collect();
- let left: Vec<String> = self.state.hovered.difference(&now).cloned().collect();
+ let entered: Vec<Key> = now.difference(&self.state.hovered).copied().collect();
+ let left: Vec<Key> = self.state.hovered.difference(&now).copied().collect();
let restyle = self.frame.as_ref().is_some_and(|f| {
entered.iter().chain(&left).any(|k| f.by_key().get(k).is_some())
});
@@ -851,18 +927,26 @@ impl Window {
// cursor of the deepest element that sets one
if let Some(f) = &self.frame {
let cursor = path.iter().rev()
- .find_map(|k| f.by_key().get(k).and_then(|&i| f.nodes[i].style.cursor)).unwrap_or(0);
+ .find_map(|k| f.by_key().get(k).and_then(|&i| self.caches.styles[f.nodes[i].style].cursor)).unwrap_or(0);
if cursor != self.cursor {
self.cursor = cursor;
unsafe { sys::BK_set_num(self.canvas, c"cursor".as_ptr(), cursor as f64) };
}
}
if fire {
+ // hover listeners don't bubble: each element hears its own enter / leave
for (keys, on) in [(left, false), (entered, true)] {
for k in keys {
- let ls = self.frame.as_ref().and_then(|f| f.by_key().get(&k).map(|&i| f.nodes[i].clone_hover()))
- .unwrap_or_default();
- self.fire(app, ls, &on);
+ let Some(frame) = self.frame.take() else { return };
+ let el = frame.by_key().get(&k).and_then(|&i| frame.el(i));
+ if let Some(ls) = el.and_then(|e| e.listeners.as_deref()) {
+ for l in &ls.hover {
+ l(&on, self, app);
+ }
+ }
+ if self.frame.is_none() {
+ self.frame = Some(frame);
+ }
}
}
}
@@ -882,6 +966,16 @@ impl Window {
(Modifiers::from_kit(mods), button)
}
+ /// Focus the element `key` (path: its ancestors, for `:focus-within`).
+ fn set_focus(&mut self, path: &[Key]) {
+ self.state.focused = path.last().copied();
+ self.state.focus_path = path.iter().copied().collect();
+ self.state.focused_id = self.frame.as_ref().and_then(|f| {
+ let i = *f.by_key().get(path.last()?)?;
+ f.el(i)?.id.as_ref().map(|s| s.to_string())
+ });
+ }
+
fn dispatch(&mut self, ev: RawEvent, app: &mut App) {
if ev.node != self.canvas {
self.widget_event(ev, app);
@@ -903,8 +997,7 @@ impl Window {
let pressed = (!self.pressed.is_empty()).then_some(self.press_button);
let e = MouseMoveEvent { position: point(px(x), px(y)), pressed_button: pressed, modifiers };
if let Some(deepest) = self.state_deepest() {
- let ls = self.bubble(&deepest, |l| l.mouse_move.clone());
- self.fire(app, ls, &e);
+ self.emit(app, deepest, &e, |l| l.mouse_move.iter().collect());
}
}
sys::BK_EV_LEAVE => {
@@ -916,39 +1009,36 @@ impl Window {
let (modifiers, button) = self.pointer_event(&ev.text);
let path = self.path_at(x, y);
self.press_button = button;
- self.state.active = path.iter().cloned().collect();
- self.state.focused = path.last().cloned();
+ self.state.active = path.iter().copied().collect();
+ self.set_focus(&path);
self.pressed = path.clone();
self.dirty = true;
let e = MouseDownEvent { button, position: point(px(x), px(y)), modifiers,
click_count: if ev.kind == sys::BK_EV_DOUBLE { 2 } else { 1 } };
- if let Some(deepest) = path.last() {
- let ls = self.bubble(deepest, |l| l.mouse_down.iter()
- .filter(|(b, _)| b.is_none_or(|b| b == button)).map(|(_, f)| f.clone()).collect());
- self.fire(app, ls, &e);
+ if let Some(&deepest) = path.last() {
+ self.emit(app, deepest, &e, |l| l.mouse_down.iter()
+ .filter(|(b, _)| b.is_none_or(|b| b == button)).map(|(_, f)| f).collect());
}
}
sys::BK_EV_RELEASE => {
let (modifiers, button) = self.pointer_event(&ev.text);
let path = self.path_at(x, y);
let up = MouseUpEvent { button, position: point(px(x), px(y)), modifiers };
- if let Some(deepest) = path.last() {
- let ls = self.bubble(deepest, |l| l.mouse_up.iter()
- .filter(|(b, _)| b.is_none_or(|b| b == button)).map(|(_, f)| f.clone()).collect());
- self.fire(app, ls, &up);
+ if let Some(&deepest) = path.last() {
+ self.emit(app, deepest, &up, |l| l.mouse_up.iter()
+ .filter(|(b, _)| b.is_none_or(|b| b == button)).map(|(_, f)| f).collect());
}
// click: the deepest element under both press and release
let common = self.pressed.iter().zip(&path).take_while(|(a, b)| a == b)
- .map(|(a, _)| a.clone()).last();
+ .map(|(a, _)| *a).last();
self.pressed.clear();
self.state.active.clear();
self.dirty = true;
if let (Some(target), MouseButton::Left) = (common, button) {
- self.toggle_details(&target);
+ self.toggle_details(target);
let down = MouseDownEvent { button, position: point(px(x), px(y)), modifiers, click_count: 1 };
let e = ClickEvent { down, up };
- let ls = self.bubble(&target, |l| l.click.clone());
- self.fire(app, ls, &e);
+ self.emit(app, target, &e, |l| l.click.iter().collect());
}
}
sys::BK_EV_WHEEL => {
@@ -956,9 +1046,8 @@ impl Window {
let (px_, py_) = self.pointer;
let e = ScrollWheelEvent { position: point(px(px_), px(py_)), delta: ev.a as f32, modifiers };
let path = self.path_at(px_, py_);
- if let Some(deepest) = path.last() {
- let ls = self.bubble(deepest, |l| l.scroll.clone());
- self.fire(app, ls, &e);
+ if let Some(&deepest) = path.last() {
+ self.emit(app, deepest, &e, |l| l.scroll.iter().collect());
}
self.scroll_by(&path, -(ev.a as f32) * 40.0, modifiers.shift);
}
@@ -968,47 +1057,44 @@ impl Window {
let key = parts.next().unwrap_or("").to_owned();
let ks = Keystroke { key, key_char: (!ch.is_empty()).then_some(ch),
modifiers: Modifiers::from_kit(ev.a as i32) };
- let target = self.state.focused.clone().or_else(|| self.state_deepest())
- .unwrap_or_else(|| "html".into());
+ let target = self.state.focused.or_else(|| self.state_deepest())
+ .unwrap_or(crate::layout::ROOT_KEY);
if ev.kind == sys::BK_EV_KEY {
- let ls = self.bubble(&target, |l| l.key_down.clone());
- self.fire(app, ls, &KeyDownEvent { keystroke: ks });
+ self.emit(app, target, &KeyDownEvent { keystroke: ks }, |l| l.key_down.iter().collect());
} else {
- let ls = self.bubble(&target, |l| l.key_up.clone());
- self.fire(app, ls, &KeyUpEvent { keystroke: ks });
+ self.emit(app, target, &KeyUpEvent { keystroke: ks }, |l| l.key_up.iter().collect());
}
}
_ => {}
}
}
- fn state_deepest(&self) -> Option<String> {
- let path = self.path_at(self.pointer.0, self.pointer.1);
- path.last().cloned()
+ fn state_deepest(&self) -> Option<Key> {
+ self.path_at(self.pointer.0, self.pointer.1).last().copied()
}
/// `<summary>` clicks open and close their `<details>`.
- fn toggle_details(&mut self, target: &str) {
+ fn toggle_details(&mut self, target: Key) {
let Some(f) = &self.frame else { return };
- let mut cur = f.by_key().get(target).copied();
+ let mut cur = f.by_key().get(&target).copied();
while let Some(i) = cur {
- let n = &f.nodes[i];
- if n.el.as_ref().is_some_and(|e| e.tag == "summary") {
- if let Some(p) = n.parent.filter(|&p| f.nodes[p].el.as_ref().is_some_and(|e| e.tag == "details")) {
- let key = f.nodes[p].key.clone();
+ if f.el(i).is_some_and(|e| e.tag == "summary") {
+ let details = f.nodes[i].parent.filter(|&p| f.el(p).is_some_and(|e| e.tag == "details"));
+ if let Some(p) = details {
+ let key = f.nodes[p].key;
let open = self.state.details_open.get(&key).copied()
- .unwrap_or(f.nodes[p].attr("open").is_some());
+ .unwrap_or(f.attr(p, "open").is_some());
self.state.details_open.insert(key, !open);
self.dirty = true;
}
return;
}
- cur = n.parent;
+ cur = f.nodes[i].parent;
}
}
/// Scroll the innermost scroll container along `path` that can move.
- fn scroll_by(&mut self, path: &[String], dy: f32, horizontal: bool) {
+ fn scroll_by(&mut self, path: &[Key], dy: f32, horizontal: bool) {
let Some(f) = &self.frame else { return };
for key in path.iter().rev() {
let Some(&i) = f.by_key().get(key) else { continue };
@@ -1021,7 +1107,7 @@ impl Window {
(sx, (sy + dy).clamp(0.0, ry))
};
if (nx, ny) != (sx, sy) {
- self.state.scroll.insert(key.clone(), (nx, ny));
+ self.state.scroll.insert(*key, (nx, ny));
self.dirty = true;
return;
}
@@ -1035,25 +1121,23 @@ impl Window {
let Some(key) = self.widgets.key_of(ev.node) else { return };
match ev.kind {
sys::BK_EV_CHANGE => {
- let e = self.widgets.read(&key);
+ let e = self.widgets.read(key);
let kind = self.widgets.nodes.get(&key).map(|w| w.spec.kind);
match kind {
Some(WKind::Checkbox) => {
- self.state.checked.insert(key.clone(), e.checked);
+ self.state.checked.insert(key, e.checked);
}
Some(WKind::Radio) if e.checked => {
- self.state.checked.insert(key.clone(), true);
- for other in self.widgets.radio_group(&key) {
- self.state.checked.insert(other.clone(), false);
- self.widgets.set_value(&other, 0.0);
+ self.state.checked.insert(key, true);
+ for other in self.widgets.radio_group(key) {
+ self.state.checked.insert(other, false);
+ self.widgets.set_value(other, 0.0);
}
}
_ => {}
}
- let ls = self.bubble(&key, |l| l.input.clone());
- self.fire(app, ls, &e);
- let ls = self.bubble(&key, |l| l.change.clone());
- self.fire(app, ls, &e);
+ self.emit(app, key, &e, |l| l.input.iter().collect());
+ self.emit(app, key, &e, |l| l.change.iter().collect());
self.dirty = true;
}
sys::BK_EV_CLICK => {
@@ -1062,8 +1146,7 @@ impl Window {
modifiers: Modifiers::default(), click_count: 1 };
let up = MouseUpEvent { button: MouseButton::Left, position: point(px(x), px(y)),
modifiers: Modifiers::default() };
- let ls = self.bubble(&key, |l| l.click.clone());
- self.fire(app, ls, &ClickEvent { down, up });
+ self.emit(app, key, &ClickEvent { down, up }, |l| l.click.iter().collect());
self.dirty = true;
}
_ => {}
@@ -1071,12 +1154,6 @@ impl Window {
}
}
-impl crate::layout::BoxNode {
- fn clone_hover(&self) -> Vec<Listener<bool>> {
- self.el.as_ref().map(|e| e.listeners.hover.clone()).unwrap_or_default()
- }
-}
-
/// Marker so `Window` is not `Send` (it holds raw kit pointers).
#[allow(dead_code)]
struct NotSend(PhantomData<*const ()>);
diff --git a/bindings/rust/blenderui/tests/headless.rs b/bindings/rust/blenderui/tests/headless.rs
index 4d571e5..bd6ac10 100644
--- a/bindings/rust/blenderui/tests/headless.rs
+++ b/bindings/rust/blenderui/tests/headless.rs
@@ -213,3 +213,91 @@ fn canvas_painter() {
assert_ne!(at(100.0, 80.0), 0x303030, "filled");
});
}
+
+#[test]
+fn css_macro_matches_runtime_css() {
+ use blenderui::css::Prop;
+ let compiled = css!("display: flex; padding: 4px 8px; color: #e6a23c !important; --x: 1");
+ assert_eq!(compiled.len(), 4);
+ assert_eq!(compiled[0].prop, Prop::named("display"));
+ assert_eq!(compiled[2].prop, Prop::named("color"));
+ assert!(compiled[2].important);
+ assert_eq!(compiled[3].prop, Prop::CUSTOM);
+ let parsed = blenderui::css::parse_declarations("display: flex; padding: 4px 8px; color: #e6a23c !important; --x: 1");
+ for (a, b) in compiled.iter().zip(&parsed) {
+ assert_eq!(a, b); // same tokens, whether parsed at compile time or run time
+ }
+}
+
+struct SheetHover;
+
+impl Render for SheetHover {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ body().m_0()
+ .child(style().child(".b { background: #ff0000 } .b:hover { background: #00ff00 } .b:hover + .b { background: #0000ff }"))
+ .child(div().class("b").id("one").w(px(40.0)).h(px(20.0)))
+ .child(div().class("b").id("two").w(px(40.0)).h(px(20.0)))
+ }
+}
+
+#[test]
+fn stylesheet_hover_restyles_across_frames() {
+ Application::headless().run(|cx| {
+ let win = open(cx, 100.0, 60.0, SheetHover);
+ let at = |cx: &mut App, x: f32, y: f32| {
+ let img = cx.draw(win.id);
+ let s = img.0 as f32 / 100.0;
+ pixel(&img, (x * s) as usize, (y * s) as usize)
+ };
+ assert_eq!(at(cx, 10.0, 10.0), 0xff0000);
+ assert_eq!(at(cx, 10.0, 30.0), 0xff0000);
+ cx.simulate_mouse_move(win.id, 10.0, 10.0); // hover the first box
+ assert_eq!(at(cx, 10.0, 10.0), 0x00ff00);
+ assert_eq!(at(cx, 10.0, 30.0), 0x0000ff, "sibling selector sees the hover");
+ cx.simulate_mouse_move(win.id, 90.0, 55.0); // leave
+ assert_eq!(at(cx, 10.0, 10.0), 0xff0000);
+ assert_eq!(at(cx, 10.0, 30.0), 0xff0000);
+ });
+}
+
+/// A view whose layout changes from state to state.
+struct Morph {
+ step: usize,
+}
+
+impl Render for Morph {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ let s = self.step;
+ let labels: Vec<String> = match s % 5 {
+ 0 => vec!["a".into(), "bbbbbbbb".into(), "c".into()],
+ 1 => vec!["a".into(), "b".into(), "c".into()],
+ 2 => vec!["a".into(), "c".into()],
+ 3 => vec!["c".into(), "a".into(), "b b b b b b b b b b b b b".into(), "d".into()],
+ _ => vec![format!("{s}"); 6],
+ };
+ body().m_0()
+ .child(div().flex().gap(px(4.0)).p(px(4.0)).bg(rgb(0x202020))
+ .children(labels.into_iter().enumerate().map(|(k, t)| {
+ div().id(format!("item{k}")).px(px(6.0)).py(px(2.0)).bg(rgb(0x4772b3 + k as u32 * 0x101010))
+ .rounded(px(3.0)).child(t)
+ })))
+ .child(div().w(px(if s % 2 == 0 { 120.0 } else { 220.0 })).h(px(20.0)).bg(rgb(0xe6a23c)))
+ .child(p().w(px(150.0)).child(if s % 3 == 0 { "short" } else { "a much longer paragraph that wraps over several lines" }))
+ }
+}
+
+#[test]
+fn incremental_frames_match_fresh_renders() {
+ Application::headless().run(|cx| {
+ let live = open(cx, 400.0, 200.0, Morph { step: 0 });
+ cx.draw(live.id);
+ for step in 1..12 {
+ live.root().update(cx, |m, _| m.step = step);
+ cx.notify_all();
+ let incremental = cx.draw(live.id);
+ let fresh = open(cx, 400.0, 200.0, Morph { step });
+ let reference = cx.draw(fresh.id);
+ assert!(incremental.2 == reference.2, "step {step}: incremental frame differs from a fresh render");
+ }
+ });
+}
diff --git a/bindings/rust/blenderui/tests/parity.rs b/bindings/rust/blenderui/tests/parity.rs
index bd758ee..9e5af26 100644
--- a/bindings/rust/blenderui/tests/parity.rs
+++ b/bindings/rust/blenderui/tests/parity.rs
@@ -68,3 +68,10 @@ fn report() {
assert!(css21 * 100 / CSS21_VISUAL.len() >= 80, "CSS 2.1 coverage fell");
assert!(grid + 1 >= GRID.len(), "grid coverage fell");
}
+
+#[test]
+fn ua_stylesheet_parse_cost() {
+ let t = std::time::Instant::now();
+ let sheet = blenderui::css::Stylesheet::parse(blenderui::html::UA_CSS);
+ println!("UA stylesheet: {} rules parsed in {:.3} ms", sheet.rules.len(), t.elapsed().as_secs_f64() * 1e3);
+}
diff --git a/docs/rust.md b/docs/rust.md
index a3de112..c3a6395 100644
--- a/docs/rust.md
+++ b/docs/rust.md
@@ -57,7 +57,7 @@ It follows gpui closely:
| `Application::new().run(\|cx\| ...)` | the same; `Application::headless()` renders off-screen |
| `cx.open_window(options, \|window, cx\| cx.new(\|cx\| View))` | the same; returns `WindowHandle<View>` |
| `impl Render for View` | the same: `fn render(&mut self, window, cx) -> impl IntoElement` |
-| `Entity<T>`, `WeakEntity<T>`, `cx.new` | the same: `read`, `update`, `downgrade`, `upgrade` |
+| `Entity<T>`, `WeakEntity<T>`, `cx.new` | `Copy` handles into the app's entity slots: `read` (returns `&T`), `update`, `downgrade`; `cx.release(e)` drops a value |
| `Context<T>`: `notify`, `listener`, `entity` | the same; it derefs to `App` |
| `WindowOptions { window_bounds, titlebar, .. }`, `WindowBounds::Windowed(..)` | the same, plus `is_resizable`, `window_min_size` |
| `cx.set_global`, `cx.global` | the same |
@@ -141,11 +141,14 @@ Three ways, one cascade:
div().flex().items_center().gap_2().px_3().py_1().rounded_md().bg(rgb(0x3a3a3a))
.text_color(white()).shadow_md().hover(|s| s.bg(rgb(0x4772b3)))
-// 2. any CSS property
-div().css("grid-template-columns", "repeat(3, 1fr)")
- .style("border-left: 3px solid #4772b3; padding: 4px 8px")
+// 2. CSS blocks, checked at compile time (a misspelled property doesn't compile)
+div().style(css!("border-left: 3px solid #4772b3; padding: 4px 8px"))
-// 3. stylesheets, anywhere in the tree
+// 3. CSS built at run time
+div().css("grid-template-columns", format!("repeat({n}, 1fr)"))
+ .style(format!("width: {w}px"))
+
+// 4. stylesheets, anywhere in the tree
style().child(".card:hover > h4 { color: #e6a23c } @media (max-width: 600px) { nav { display: none } }")
```
@@ -322,14 +325,16 @@ how to re-run it.
| | blenderui | gpui-fast | gpui |
|---|---|---|---|
-| 100 / 1000 animated cells | 60 / 60 fps (display cap; 500 / 97 uncapped) | 60 / 60 fps | 60 / 60 fps |
-| 3000 animated cells | **32.6 fps** | 29.7 fps | 22.8 fps |
-| CPU per frame at 3000 cells | 39.7 ms (all threads) | **18.4 ms** + GPU | 44.1 ms + GPU |
-| RAM (working set) | **20-36 MB** | 34-65 MB + 19-24 MB GPU | 33-78 MB + 16-21 MB GPU |
-| First frame after launch | **~6 ms** | ~205 ms | ~220 ms |
-
-blenderui leads on frame rate in the heavy scene, memory and startup.
-gpui-fast does the least CPU work per frame. blenderui rasterises on the CPU
+| 100 / 1000 animated cells | 60 / 60 fps (display cap; 529 / 157 uncapped) | 60 / 60 fps | 60 / 60 fps |
+| 3000 animated cells | **57.5 fps** | 50.5 fps | 18.9 fps |
+| CPU per frame, 1000 / 3000 cells | 13.7 / 27.3 ms (all threads) | **6.7 / 20.1 ms** + GPU | 14.7 / 53.1 ms + GPU |
+| RAM (working set) | **18-31 MB** | 33-64 MB + 19-24 MB GPU | 31-76 MB + 16-21 MB GPU |
+| First frame after launch | **~6 ms** | ~250 ms | ~260 ms |
+| Idle CPU | **0 %** | 0-0.1 % | 0.7-1.4 % |
+
+blenderui leads on memory and startup, and in this session on the 3000-cell
+frame rate. gpui-fast does the least CPU work per frame; its heavy-scene frame
+rate varies between sessions on this laptop (29.7-59.8 fps). blenderui rasterises on the CPU
in parallel bands (`BUI_RASTER_THREADS=1` forces one thread). `BUI_PROFILE=1`
prints its per-phase frame times.
@@ -371,8 +376,29 @@ prints its per-phase frame times.
- `blenderui-sys` is the raw FFI over `kit/include/BUI_kit.h`; its build script
builds the C kit with CMake and links it statically.
-- Every style source (methods, `.css`, `.style`, sheets, the user-agent sheet,
- state refinements) becomes CSS declarations applied by one table of property
- handlers, so a property has exactly one implementation.
-- Each render rebuilds the display list and reconciles widget nodes by key,
- re-rendering after events (on the next turn of the native message loop).
+- Every style source (methods, `css!`, `.css`, `.style`, sheets, the
+ user-agent sheet, state refinements) becomes CSS declarations applied by
+ one table of property handlers, so a property has exactly one
+ implementation.
+- **Compile time**: the property table is a `const`. Style methods and
+ `css!` resolve property names to indices when the program compiles (a
+ typo is a compile error), typed methods (`.w(px(40.0))`, `.bg(rgb(..))`)
+ build their value token directly, and fixed values (`.flex()`,
+ `.shadow_md()`, `css!` values) are tokenized once per program.
+- **No `Rc` / `RefCell`**: a frame is a set of flat arenas (boxes, element
+ data, taffy nodes) linked by index, owned by the window and reused every
+ frame. Computed styles live in a per-window store, shared by every element
+ with the same inputs. Listeners are owned `Box`es; while one runs, the
+ frame is moved out of the window so it can take `&mut Window`. Entities
+ are `Copy` handles into an app-owned slot map; the app itself lives on
+ `Application::run`'s stack. Small per-element lists (matched rules,
+ declarations) stay on the stack. The only shared ownership left is
+ `Arc<Image>` for image pixels.
+- **Reuse across frames**: `render()` builds a fresh element tree each frame,
+ but the work behind it is reused. Matched selectors are memoized by an
+ element fingerprint (what selectors can see: tag, id, attributes, position,
+ state, ancestors, previous siblings). Computed styles are shared by input.
+ The taffy tree persists and is reconciled by key, so only changed subtrees
+ are laid out again. Widget nodes are reconciled by key too.
+- Rendering happens on the next turn of the native message loop after
+ events.
diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.h
index 9bdecc4..1749a2a 100644
--- a/kit/include/BUI_kit.h
+++ b/kit/include/BUI_kit.h
@@ -217,7 +217,12 @@ typedef struct BKCanvasItem {
float clip[4];
} 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); /* append, ids not checked */
+void BK_canvas_add_item(BKNode *canvas, const BKCanvasItem *item);
+/* Immediate-mode hosts that rebuild the whole list each frame: overwrite the
+ * item at `index` (index == count appends), reusing its buffers, then call
+ * BK_canvas_truncate with the new count (drops the rest, redraws once). */
+void BK_canvas_put_item(BKNode *canvas, int index, const BKCanvasItem *item);
+void BK_canvas_truncate(BKNode *canvas, int count); /* append, ids not checked */
void BK_canvas_delete(BKNode *canvas, int id); /* id < 0: all */
void BK_canvas_raise(BKNode *canvas, int id, int to_top);
int BK_canvas_count(BKNode *canvas);
diff --git a/kit/intern/kit_frame.c b/kit/intern/kit_frame.c
index 35a65eb..12ac769 100644
--- a/kit/intern/kit_frame.c
+++ b/kit/intern/kit_frame.c
@@ -10,6 +10,7 @@
*
* SPDX-License-Identifier: GPL-2.0-or-later */
+#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
@@ -745,13 +746,74 @@ typedef struct CItem {
float *coords;
char *text;
BKImage *img;
+ int coords_cap; /* floats allocated in coords */
+ int text_cap; /* bytes allocated in text */
} CItem;
typedef struct CanvasData {
CItem *items;
int n, cap;
+ /* id -> position, open addressing; rebuilt lazily after reorders/deletes */
+ int *idx_key, *idx_pos;
+ int idx_cap, idx_count;
+ bool idx_valid;
} CanvasData;
+#define IDX_EMPTY INT_MIN
+
+static unsigned idx_hash(int id, int cap)
+{
+ return ((unsigned)id * 2654435761u) & (unsigned)(cap - 1);
+}
+
+static void idx_put(CanvasData *d, int id, int pos)
+{
+ unsigned h = idx_hash(id, d->idx_cap);
+ while (d->idx_key[h] != IDX_EMPTY) {
+ if (d->idx_key[h] == id) {
+ return; /* duplicate id: the first one wins, like the linear search */
+ }
+ h = (h + 1) & (unsigned)(d->idx_cap - 1);
+ }
+ d->idx_key[h] = id;
+ d->idx_pos[h] = pos;
+ d->idx_count++;
+}
+
+static void idx_rebuild(CanvasData *d)
+{
+ int cap = 64;
+ while (cap < d->n * 2 + 2) {
+ cap *= 2;
+ }
+ if (cap != d->idx_cap) {
+ free(d->idx_key);
+ free(d->idx_pos);
+ d->idx_key = (int *)malloc(sizeof(int) * (size_t)cap);
+ d->idx_pos = (int *)malloc(sizeof(int) * (size_t)cap);
+ d->idx_cap = cap;
+ }
+ for (int k = 0; k < cap; k++) {
+ d->idx_key[k] = IDX_EMPTY;
+ }
+ d->idx_count = 0;
+ for (int i = 0; i < d->n; i++) {
+ idx_put(d, d->items[i].it.id, i);
+ }
+ d->idx_valid = true;
+}
+
+/* A new item at `pos` (keeps the index valid when there's room). */
+static void idx_added(CanvasData *d, int id, int pos)
+{
+ if (d->idx_valid && (d->idx_count + 1) * 2 < d->idx_cap) {
+ idx_put(d, id, pos);
+ }
+ else {
+ d->idx_valid = false;
+ }
+}
+
#define CANVAS(n) ((CanvasData *)(n)->ext)
static void canvas_init(BKNode *n)
@@ -773,11 +835,32 @@ static void canvas_free(BKNode *n)
citem_free(&d->items[i]);
}
free(d->items);
+ free(d->idx_key);
+ free(d->idx_pos);
free(d);
}
+/* Position of item `id` (-1 if none): O(1) through the index. */
static int canvas_find(CanvasData *d, int id)
{
+ if (!d->idx_valid) {
+ idx_rebuild(d);
+ }
+ unsigned h = idx_hash(id, d->idx_cap);
+ while (d->idx_key[h] != IDX_EMPTY) {
+ if (d->idx_key[h] == id) {
+ const int pos = d->idx_pos[h];
+ if (pos < d->n && d->items[pos].it.id == id) {
+ return pos;
+ }
+ break; /* stale: rebuild below */
+ }
+ h = (h + 1) & (unsigned)(d->idx_cap - 1);
+ }
+ if (d->idx_valid && d->idx_key[h] == IDX_EMPTY) {
+ return -1;
+ }
+ idx_rebuild(d);
for (int i = 0; i < d->n; i++) {
if (d->items[i].it.id == id) {
return i;
@@ -786,6 +869,99 @@ static int canvas_find(CanvasData *d, int id)
return -1;
}
+/* Copy `item` into slot `c`, reusing its coordinate and text buffers. */
+static void citem_assign(CItem *c, const BKCanvasItem *item)
+{
+ const int nc = BK_MAX(1, item->ncoords);
+ if (nc > c->coords_cap) {
+ c->coords = (float *)realloc(c->coords, sizeof(float) * (size_t)nc);
+ c->coords_cap = nc;
+ }
+ memcpy(c->coords, item->coords, sizeof(float) * (size_t)item->ncoords);
+ const int tl = item->text ? (int)strlen(item->text) + 1 : 0;
+ if (tl > c->text_cap) {
+ c->text = (char *)realloc(c->text, (size_t)tl);
+ c->text_cap = tl;
+ }
+ if (tl) {
+ memcpy(c->text, item->text, (size_t)tl);
+ }
+ bk_image_free(c->img);
+ c->img = item->rgba ? image_from_rgba(item->rgba, item->iw, item->ih) : NULL;
+ c->it = *item;
+ c->it.coords = c->coords;
+ c->it.text = tl ? c->text : NULL;
+ c->it.rgba = NULL;
+}
+
+/* The canvas-space box an item can paint into, with margins for outline
+ * width, anti-aliasing and glyph overhang. False when unknown. */
+static bool citem_bbox(const CItem *ci, float b[4])
+{
+ const BKCanvasItem *it = &ci->it;
+ const float *p = ci->coords;
+ if (it->ncoords < 2 || !p) {
+ return false;
+ }
+ float x0 = p[0], x1 = p[0], y0 = p[1], y1 = p[1];
+ for (int k = 2; k + 1 < it->ncoords; k += 2) {
+ x0 = BK_MIN(x0, p[k]);
+ x1 = BK_MAX(x1, p[k]);
+ y0 = BK_MIN(y0, p[k + 1]);
+ y1 = BK_MAX(y1, p[k + 1]);
+ }
+ float m = (it->width > 0 ? it->width : 1.0f) + 3.0f;
+ if (it->type == BK_ITEM_TEXT) {
+ if (!ci->text) {
+ return false;
+ }
+ 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);
+ 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);
+ x0 = x - size;
+ x1 = x + tw + size;
+ y0 = base - size * 1.5f;
+ y1 = base + size * 0.75f;
+ m = 2.0f;
+ }
+ else if (it->type == BK_ITEM_IMAGE) {
+ if (!ci->img) {
+ return false;
+ }
+ x0 = p[0] - anchor_off(it->anchor, ci->img->w, BK_ANCHOR_W, BK_ANCHOR_E);
+ y0 = p[1] - anchor_off(it->anchor, ci->img->h, BK_ANCHOR_N, BK_ANCHOR_S);
+ x1 = x0 + ci->img->w;
+ y1 = y0 + ci->img->h;
+ m = 2.0f;
+ }
+ b[0] = x0 - m;
+ b[1] = y0 - m;
+ b[2] = x1 + m;
+ b[3] = y1 + m;
+ return true;
+}
+
+/* Redraw only where item `ci` paints (the whole canvas when that's unknown). */
+static void canvas_damage(BKNode *n, const CItem *ci)
+{
+ BKContext *ctx = bk_ctx(n);
+ float b[4];
+ if (!ctx || n->w <= 0 || n->h <= 0 || !citem_bbox(ci, b)) {
+ bk_invalidate(n);
+ return;
+ }
+ const float ox = (float)(n->x - n->scroll_x), oy = (float)(n->y - n->scroll);
+ const int x0 = BK_MAX(n->x, (int)floorf(ox + b[0])), y0 = BK_MAX(n->y, (int)floorf(oy + b[1]));
+ const int x1 = BK_MIN(n->x + n->w, (int)ceilf(ox + b[2]));
+ const int y1 = BK_MIN(n->y + n->h, (int)ceilf(oy + b[3]));
+ if (x1 > x0 && y1 > y0) {
+ bk_ctx_dirty_rect(ctx, bk_rect(x0, y0, x1 - x0, y1 - y0));
+ }
+}
+
static void canvas_store(BKNode *n, const BKCanvasItem *item, bool replace)
{
if (n->cls != &bk_cls_canvas) {
@@ -800,20 +976,13 @@ static void canvas_store(BKNode *n, const BKCanvasItem *item, bool replace)
}
i = d->n++;
memset(&d->items[i], 0, sizeof(CItem));
+ idx_added(d, item->id, i);
}
else {
- citem_free(&d->items[i]);
+ canvas_damage(n, &d->items[i]); /* where it was */
}
- CItem *c = &d->items[i];
- c->it = *item;
- c->coords = (float *)malloc(sizeof(float) * (size_t)BK_MAX(1, item->ncoords));
- memcpy(c->coords, item->coords, sizeof(float) * (size_t)item->ncoords);
- c->it.coords = c->coords;
- c->text = item->text ? bk_strdup(item->text) : NULL;
- c->it.text = c->text;
- c->img = image_from_rgba(item->rgba, item->iw, item->ih);
- c->it.rgba = NULL;
- bk_invalidate(n);
+ citem_assign(&d->items[i], item);
+ canvas_damage(n, &d->items[i]); /* where it is */
}
void BK_canvas_set_item(BKNode *n, const BKCanvasItem *item)
@@ -827,17 +996,58 @@ void BK_canvas_add_item(BKNode *n, const BKCanvasItem *item)
canvas_store(n, item, false);
}
+void BK_canvas_put_item(BKNode *n, int index, const BKCanvasItem *item)
+{
+ if (n->cls != &bk_cls_canvas) {
+ return;
+ }
+ CanvasData *d = CANVAS(n);
+ index = BK_CLAMP(index, 0, d->n);
+ if (index == d->n) {
+ if (d->n == d->cap) {
+ d->cap = d->cap ? d->cap * 2 : 16;
+ d->items = (CItem *)realloc(d->items, sizeof(CItem) * (size_t)d->cap);
+ }
+ memset(&d->items[d->n++], 0, sizeof(CItem));
+ }
+ citem_assign(&d->items[index], item);
+ d->idx_valid = false; /* ids may have changed */
+}
+
+void BK_canvas_truncate(BKNode *n, int count)
+{
+ if (n->cls != &bk_cls_canvas) {
+ return;
+ }
+ CanvasData *d = CANVAS(n);
+ for (int i = BK_MAX(0, count); i < d->n; i++) {
+ citem_free(&d->items[i]);
+ }
+ d->n = BK_CLAMP(count, 0, d->n);
+ d->idx_valid = false;
+ bk_invalidate(n);
+}
+
void BK_canvas_delete(BKNode *n, int id)
{
CanvasData *d = CANVAS(n);
- for (int i = d->n - 1; i >= 0; i--) {
- if (id < 0 || d->items[i].it.id == id) {
+ if (id < 0) {
+ for (int i = 0; i < d->n; i++) {
citem_free(&d->items[i]);
- memmove(d->items + i, d->items + i + 1, sizeof(CItem) * (size_t)(d->n - i - 1));
- d->n--;
}
+ d->n = 0;
+ d->idx_valid = false;
+ bk_invalidate(n);
+ return;
+ }
+ int i;
+ while ((i = canvas_find(d, id)) >= 0) { /* through the index: no list scan */
+ canvas_damage(n, &d->items[i]);
+ citem_free(&d->items[i]);
+ memmove(d->items + i, d->items + i + 1, sizeof(CItem) * (size_t)(d->n - i - 1));
+ d->n--;
+ d->idx_valid = false;
}
- bk_invalidate(n);
}
void BK_canvas_raise(BKNode *n, int id, int to_top)
@@ -856,7 +1066,8 @@ void BK_canvas_raise(BKNode *n, int id, int to_top)
memmove(d->items + 1, d->items, sizeof(CItem) * (size_t)(d->n - 1));
d->items[0] = tmp;
}
- bk_invalidate(n);
+ d->idx_valid = false;
+ canvas_damage(n, to_top ? &d->items[d->n - 1] : &d->items[0]);
}
int BK_canvas_count(BKNode *n)
@@ -870,15 +1081,16 @@ static void canvas_measure(BKNode *n, int *rw, int *rh)
*rh = 5 * u();
}
-static void draw_polyline(const float *pts, int npts, float ox, float oy, const float c[4],
- float width, bool closed)
+static void draw_polyline(BuiRaster *r, const float *pts, int npts, float ox, float oy,
+ const float c[4], float width, bool closed)
{
for (int k = 0; k + 1 < npts; k++) {
- bk_line(ox + pts[2 * k], oy + pts[2 * k + 1], ox + pts[2 * k + 2], oy + pts[2 * k + 3], c,
- width);
+ BUI_raster_line(r, ox + pts[2 * k], oy + pts[2 * k + 1], ox + pts[2 * k + 2],
+ oy + pts[2 * k + 3], width, c);
}
if (closed && npts > 2) {
- bk_line(ox + pts[2 * npts - 2], oy + pts[2 * npts - 1], ox + pts[0], oy + pts[1], c, width);
+ BUI_raster_line(r, ox + pts[2 * npts - 2], oy + pts[2 * npts - 1], ox + pts[0], oy + pts[1],
+ width, c);
}
}
@@ -951,7 +1163,7 @@ static void canvas_item_draw(BuiRaster *r, const CItem *ci, float ox, float oy,
}
case BK_ITEM_LINE: {
const float *c = it->fill[3] > 0 ? it->fill : it->outline;
- draw_polyline(p, it->ncoords / 2, ox, oy, c, lw, false);
+ draw_polyline(r, p, it->ncoords / 2, ox, oy, c, lw, false);
break;
}
case BK_ITEM_POLYGON: {
@@ -966,7 +1178,7 @@ static void canvas_item_draw(BuiRaster *r, const CItem *ci, float ox, float oy,
free(pts);
}
if (outline) {
- draw_polyline(p, np, ox, oy, it->outline, lw, true);
+ draw_polyline(r, p, np, ox, oy, it->outline, lw, true);
}
break;
}
@@ -991,7 +1203,7 @@ static void canvas_item_draw(BuiRaster *r, const CItem *ci, float ox, float oy,
}
if (outline) {
for (int k = 1; k <= seg; k++) {
- bk_line(pts[k][0], pts[k][1], pts[k + 1][0], pts[k + 1][1], it->outline, lw);
+ BUI_raster_line(r, pts[k][0], pts[k][1], pts[k + 1][0], pts[k + 1][1], lw, it->outline);
}
}
break;
@@ -1042,18 +1254,60 @@ static void canvas_item_draw(BuiRaster *r, const CItem *ci, float ox, float oy,
* polygons use the kit's global drawing state and keep a canvas serial. */
#define PAR_MIN_ITEMS 64
+/* Every extra thread costs CPU (wake-ups, bands overlapping items), so an
+ * animation uses the fewest threads that still meet the frame deadline, and
+ * all of them only when it can't be met. */
+#define PAR_SLACK 0.7 /* aim for 70 % of the refresh interval */
-static bool item_parallel_safe(const BKCanvasItem *it)
+double bk_frame_ms = 0.0, bk_frame_budget_ms = 0.0;
+static double g_raster_ms = 0.0; /* the canvas's last draw time */
+static int g_raster_threads = 1; /* ... and how many threads drew it */
+
+/* Measured wall-time speedup of n threads (8 threads ~3.5x). */
+static double par_speedup(int n)
{
- switch (it->type) {
- case BK_ITEM_LINE:
- case BK_ITEM_ARC:
- return false;
- case BK_ITEM_POLYGON:
- return !(it->outline[3] > 0);
- default:
- return true;
+ return n / (1.0 + 0.18 * (n - 1));
+}
+
+static double now_ms(void)
+{
+#ifdef _WIN32
+ static LARGE_INTEGER freq;
+ LARGE_INTEGER t;
+ if (!freq.QuadPart) {
+ QueryPerformanceFrequency(&freq);
+ }
+ QueryPerformanceCounter(&t);
+ return (double)t.QuadPart * 1000.0 / (double)freq.QuadPart;
+#else
+ return 0.0;
+#endif
+}
+
+/* Threads for this draw: during a vsync'd animation, the fewest that keep the
+ * frame within budget; otherwise (first frames, input, uncapped) all of them. */
+static int threads_wanted(int max_threads)
+{
+ if (bk_frame_ms <= 0.0 || bk_frame_budget_ms <= 0.0 || g_raster_ms <= 0.0) {
+ return max_threads;
}
+ const double serial = g_raster_ms * par_speedup(g_raster_threads);
+ const double room = bk_frame_budget_ms * PAR_SLACK - (bk_frame_ms - g_raster_ms);
+ if (room <= 0.0) {
+ return max_threads; /* the frame is late anyway: draw as fast as possible */
+ }
+ for (int n = 1; n < max_threads; n++) {
+ if (serial / par_speedup(n) <= room) {
+ return n;
+ }
+ }
+ return max_threads;
+}
+
+static bool item_parallel_safe(const BKCanvasItem *it)
+{
+ (void)it; /* every item type draws into the band's own raster view */
+ return true;
}
/* Rows an item can touch, and its prepared text; false if text was not ready. */
@@ -1100,6 +1354,8 @@ typedef struct BandJob {
int clip[4]; /* the canvas clip, x0 y0 x1 y1 */
float ox, oy;
int nbands, band_h;
+ const int *start; /* band b draws items idx[start[b] .. start[b + 1]) */
+ const int *idx;
volatile long next;
} BandJob;
@@ -1113,11 +1369,8 @@ static void band_draw(const BandJob *j, int b)
if (!view) {
return;
}
- for (int i = 0; i < j->d->n; i++) {
- const ItemPrep *pp = &j->prep[i];
- if (pp->y1 < (float)y0 || pp->y0 >= (float)y1) {
- continue;
- }
+ for (int s = j->start[b]; s < j->start[b + 1]; s++) {
+ const int i = j->idx[s];
const CItem *ci = &j->d->items[i];
const BKCanvasItem *it = &ci->it;
int cx0 = j->clip[0], cy0 = y0, cx1 = j->clip[2], cy1 = y1;
@@ -1131,7 +1384,7 @@ static void band_draw(const BandJob *j, int b)
}
}
BUI_raster_view(j->base, view, cx0, cy0, cx1, cy1);
- canvas_item_draw(view, ci, j->ox, j->oy, it->type == BK_ITEM_TEXT ? pp : NULL);
+ canvas_item_draw(view, ci, j->ox, j->oy, it->type == BK_ITEM_TEXT ? &j->prep[i] : NULL);
}
free(view);
}
@@ -1169,9 +1422,8 @@ static VOID CALLBACK band_worker(PTP_CALLBACK_INSTANCE inst, PVOID ctx, PTP_WORK
#endif
/* Draw `d` in bands on several threads; false when it has to be drawn serially. */
-static bool canvas_draw_parallel(const CanvasData *d, float ox, float oy)
+static bool canvas_draw_parallel(const CanvasData *d, float ox, float oy, int threads)
{
- const int threads = par_threads();
if (threads < 2 || d->n < PAR_MIN_ITEMS) {
return false;
}
@@ -1216,12 +1468,66 @@ static bool canvas_draw_parallel(const CanvasData *d, float ox, float oy)
j->oy = oy;
j->nbands = threads * 3; /* more bands than threads: balances uneven rows */
j->band_h = BK_MAX(1, (j->clip[3] - j->clip[1] + j->nbands - 1) / j->nbands);
+ /* bucket items by band once (in list order), so each band reads only its
+ * own items instead of scanning the whole list */
+ const int nb = j->nbands;
+ int *start = (int *)calloc((size_t)nb + 1, sizeof(int));
+ int *range = (int *)malloc(sizeof(int) * 2 * (size_t)d->n);
+ if (!start || !range) {
+ free(start);
+ free(range);
+ free(prep);
+ return false;
+ }
+ long total = 0;
+ for (int i = 0; i < d->n; i++) {
+ const ItemPrep *pp = &prep[i];
+ int b0 = (int)floorf((pp->y0 - (float)j->clip[1]) / (float)j->band_h);
+ int b1 = (int)floorf((pp->y1 - (float)j->clip[1]) / (float)j->band_h);
+ b0 = BK_MAX(b0, 0);
+ b1 = BK_MIN(b1, nb - 1);
+ if (d->items[i].it.hidden || b1 < b0) {
+ b0 = 1;
+ b1 = 0; /* nothing to draw */
+ }
+ range[2 * i] = b0;
+ range[2 * i + 1] = b1;
+ for (int b = b0; b <= b1; b++) {
+ start[b + 1]++;
+ }
+ total += b1 >= b0 ? b1 - b0 + 1 : 0;
+ }
+ for (int b = 0; b < nb; b++) {
+ start[b + 1] += start[b];
+ }
+ int *idx = (int *)malloc(sizeof(int) * (size_t)BK_MAX(1, total));
+ int *fill = (int *)malloc(sizeof(int) * (size_t)nb);
+ if (!idx || !fill) {
+ free(start);
+ free(range);
+ free(idx);
+ free(fill);
+ free(prep);
+ return false;
+ }
+ memcpy(fill, start, sizeof(int) * (size_t)nb);
+ for (int i = 0; i < d->n; i++) {
+ for (int b = range[2 * i]; b <= range[2 * i + 1]; b++) {
+ idx[fill[b]++] = i;
+ }
+ }
+ free(fill);
+ free(range);
+ j->start = start;
+ j->idx = idx;
j->next = 0;
for (int t = 1; t < threads; t++) {
SubmitThreadpoolWork(work);
}
band_worker(NULL, j, NULL);
WaitForThreadpoolWorkCallbacks(work, FALSE);
+ free(start);
+ free(idx);
free(prep);
return true;
#else
@@ -1239,14 +1545,27 @@ static void canvas_draw(BKNode *n)
CanvasData *d = CANVAS(n);
bk_clip_push(n->x, n->y, n->w, n->h);
const float ox = (float)(n->x - n->scroll_x), oy = (float)(n->y - n->scroll);
+ const double t0 = now_ms();
+ const int *clip = bk_draw.clip;
+ const long region = (long)BK_MAX(0, clip[2] - clip[0]) * BK_MAX(0, clip[3] - clip[1]);
+ const bool small = region * 4 < (long)n->w * n->h; /* a damage rectangle, not the canvas */
+ const int threads = (d->n >= PAR_MIN_ITEMS && !small) ? threads_wanted(par_threads()) : 1;
if (bk_draw.clip[2] > bk_draw.clip[0] && bk_draw.clip[3] > bk_draw.clip[1] &&
- canvas_draw_parallel(d, ox, oy))
+ canvas_draw_parallel(d, ox, oy, threads))
{
+ g_raster_ms = now_ms() - t0;
+ g_raster_threads = threads;
bk_clip_pop();
return;
}
for (int i = 0; i < d->n; i++) {
const BKCanvasItem *it = &d->items[i].it;
+ float b[4];
+ if (small && citem_bbox(&d->items[i], b) &&
+ (ox + b[2] < clip[0] || ox + b[0] >= clip[2] || oy + b[3] < clip[1] || oy + b[1] >= clip[3]))
+ {
+ continue; /* entirely outside the region being redrawn */
+ }
if (it->clip_on) { /* overflow: hidden / scroll containers */
bk_clip_push((int)floorf(ox + it->clip[0]), (int)floorf(oy + it->clip[1]),
(int)ceilf(it->clip[2]), (int)ceilf(it->clip[3]));
@@ -1257,6 +1576,10 @@ static void canvas_draw(BKNode *n)
canvas_item_draw(bk_draw.r, &d->items[i], ox, oy, NULL);
}
}
+ if (d->n >= PAR_MIN_ITEMS) {
+ g_raster_ms = now_ms() - t0;
+ g_raster_threads = 1;
+ }
bk_clip_pop();
}
diff --git a/kit/intern/kit_intern.h b/kit/intern/kit_intern.h
index 304849b..b8bd542 100644
--- a/kit/intern/kit_intern.h
+++ b/kit/intern/kit_intern.h
@@ -78,6 +78,11 @@ typedef struct BKDraw {
extern BKDraw bk_draw; /* active frame */
+/* Animation pacing, set by the window host: the last animation frame's
+ * duration and the display's refresh interval, in ms (0 = not animating or
+ * no vsync). Lets the canvas draw on one thread when the frame has slack. */
+extern double bk_frame_ms, bk_frame_budget_ms;
+
void bk_clip_push(int x, int y, int w, int h);
void bk_clip_pop(void);
void bk_clip_reset(int w, int h);
diff --git a/kit/intern/kit_window.c b/kit/intern/kit_window.c
index 45d177b..f777542 100644
--- a/kit/intern/kit_window.c
+++ b/kit/intern/kit_window.c
@@ -237,6 +237,20 @@ static void vsync(void)
}
}
+/* The primary display's refresh interval in ms. */
+static double refresh_ms(void)
+{
+ static double ms = 0.0;
+ if (ms <= 0.0) {
+ DEVMODEW dm;
+ memset(&dm, 0, sizeof(dm));
+ dm.dmSize = sizeof(dm);
+ const int hz = EnumDisplaySettingsW(NULL, ENUM_CURRENT_SETTINGS, &dm) ? (int)dm.dmDisplayFrequency : 0;
+ ms = 1000.0 / (hz > 1 ? hz : 60);
+ }
+ return ms;
+}
+
/* Milliseconds since the current animation frame began. */
static double frame_ms(const BKWindow *win)
{
@@ -360,11 +374,16 @@ static LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
win->render_pending = 0;
do_render(win);
if (win->want_frame) { /* the host asked for the next frame */
- if (win->frame_vsync && frame_ms(win) < 15.0) {
+ bk_frame_ms = frame_ms(win);
+ bk_frame_budget_ms = win->frame_vsync ? refresh_ms() : 0.0;
+ if (win->frame_vsync && bk_frame_ms < refresh_ms() - 1.5) {
vsync(); /* early: wait for the next refresh; late: start right away */
}
host_request(win);
}
+ else {
+ bk_frame_ms = 0.0; /* the animation ended */
+ }
return 0;
case WM_PAINT: {
PAINTSTRUCT ps;