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: standalone app

Preetham Pemmasaniece028cae1f3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ef1fc4d..3b3feec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,7 @@ All notable changes to **blenderui** (BUI). The format follows
## [Unreleased]
-### Added (JavaScript)
+### Added (JavaScript: `@blender-ui/native` 0.2.0, `@blender-ui/react` 0.1.0)
- **`@blender-ui/native`** (`bindings/node`, napi-rs crate `blenderui-node`): BUI from JavaScript in native windows, GPUIX style, on **Node.js and Bun**.
- A DOM-like API: `createElement`, `setAttribute`, `appendChild`, `insertBefore`, `addEventListener` (events bubble; `stopPropagation` works), `requestAnimationFrame`, `getBoundingClientRect`, `screenshot`.
- BUI runs on its own UI thread, so JavaScript is never blocked and an idle UI uses no CPU.
@@ -25,6 +25,13 @@ All notable changes to **blenderui** (BUI). The format follows
- **Conformance suite:** runs each hook beside React's original (development and production builds, StrictMode). It fails when React adds a hook that isn't covered, which caught React 19.2's `useEffectEvent`.
- **JSX runtime** (`"jsxImportSource": "@blender-ui/react"`): render tracking for components, and types that let host props take signals.
- **Host components:** HTML host components, `className` / `style` objects / events, and one native batch per commit. `<Suspense>`, `<Activity>`, actions and `<ViewTransition>` (without animation) work.
+- **Standalone executables** (`bui build`, in `@blender-ui/native`):
+ - **Default:** `bui-runtime` (new crate `blenderui-qjs`), BUI with an embedded QuickJS engine (4.9 MB). It runs both packages unchanged, with JavaScript on the UI thread. An app is the runtime with its bundle appended: about 5 MB, first frame in about 70 ms at 19 MB of RAM, and no console window on Windows.
+ - **`--bun`:** compiles a Bun executable with the addon embedded.
+ - **`bui run`:** runs an app on the QuickJS runtime without building.
+- **`blenderui-jsview`** (new crate): the op decoder, mirrored tree, event listeners and window operations, shared by the napi addon and the QuickJS runtime.
+- **Style objects holding signals** (`style={{ color: colorSignal }}`) are bound: only that node's style updates.
+- **Startup benchmark** (`bench/startup.js`): first frame, launch to exit, RAM and size, for Node, Bun, the Bun executable and the QuickJS executable.
- **Benchmarks** for JavaScript (`bindings/node/bench/cells.js`, Node or Bun) measure CPU with the process cycle counter, as the Rust benchmark does.
- **Rust:**
- `UiSender` / `App::ui_sender()`: run closures on the UI thread from any thread.
diff --git a/README.md b/README.md
index fa2c0b7..2960023 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
# BUI
-**Blender's user interface, as a library you can use from Python, Rust and C.**
+**Blender's user interface, as a library you can use from Python, Rust, JS/React and C.**
Scrubbable number fields, drag-toggles, pie menus, the color wheel and Ctrl+Z on every edit:
the real Blender widgets, driven by the tkinter or Qt code you already know, by HTML + CSS + Tailwind in Rust, or by plain C.
@@ -40,13 +40,13 @@ code.
You can drive it five ways, and all of them share the same C runtime:
-| You write | You get | Status |
-|---|---|---|
-| **tkinter** code, even existing programs, unchanged | Blender-styled apps; every tkinter and ttk API | ✅ Complete |
-| **Qt-style** Python (`QWidget`, layouts, `clicked.connect`) | The common subset of Qt widgets | 🟡 Partial |
-| **Blender components** in Python (`Panel`, `NumberSlider`, `PieMenu` ...) | 45 native Blender widgets and editors | ✅ Complete |
-| **Rust**: HTML + CSS + Tailwind, JSX (`rsx!`), hooks, or gpui syntax | A web-like framework rendered with Blender widgets | ✅ Working |
-| **JavaScript / React** on Node.js or Bun: a DOM-like API or JSX | The same engine in native windows, over napi-rs; React's hooks backed by signals ([guide](docs/javascript.md)) | 🟡 New (Windows) |
+| You write | You get | Status |
+| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ---------------- |
+| **tkinter** code, even existing programs, unchanged | Blender-styled apps; every tkinter and ttk API | ✅ Complete |
+| **Qt-style** Python (`QWidget`, layouts, `clicked.connect`) | The common subset of Qt widgets | 🟡 Partial |
+| **Blender components** in Python (`Panel`, `NumberSlider`, `PieMenu` ...) | 45 native Blender widgets and editors | ✅ Complete |
+| **Rust**: HTML + CSS + Tailwind, JSX (`rsx!`), hooks, or gpui syntax | A web-like framework rendered with Blender widgets | ✅ Working |
+| **JavaScript / React** on Node.js or Bun: a DOM-like API or JSX | The same engine in native windows, over napi-rs; React's hooks backed by signals ([guide](docs/javascript.md)) | ✅ Working |
## Quick start
@@ -94,30 +94,52 @@ App("Object", (420, 520),
### JavaScript and React
+[![@blender-ui/react](https://img.shields.io/npm/v/@blender-ui/react?label=%40blender-ui%2Freact)](https://www.npmjs.com/package/@blender-ui/react)
+[![@blender-ui/native](https://img.shields.io/npm/v/@blender-ui/native?label=%40blender-ui%2Fnative)](https://www.npmjs.com/package/@blender-ui/native)
+
```sh
npm install @blender-ui/react react # or: bun add @blender-ui/react react
```
```jsx
/** @jsxImportSource @blender-ui/react */
-import { render, useState } from '@blender-ui/react'
+import { render, useState } from "@blender-ui/react"
-function Counter () {
- const [count, setCount] = useState(0) // React's hook, backed by a signal
+function Counter() {
+ const [count, setCount] = useState(0) // React's hook, holding a signal
return (
<main className="p-6 flex flex-col gap-3">
<span>Clicks: {count}</span>
- <button onClick={() => setCount(c => c + 1)}>Add one</button>
+ <button onClick={() => setCount((c) => c + 1)}>Add one</button>
</main>
)
}
-render(<Counter />, { title: 'Counter', width: 360, height: 200, gpu: true })
+render(<Counter />, { title: "Counter", width: 360, height: 200, gpu: true })
+```
+
+```sh
+bun app.jsx # run it (Bun reads JSX directly)
+npx bui build app.jsx # or ship it: app.exe, one 5 MB file
```
-A click updates the one text node; `Counter` doesn't re-render. Without
-React, `@blender-ui/native` gives you a DOM-like API with signals. Both run on
-Node.js and Bun, Windows x64 for now ([guide](docs/javascript.md)).
+- **React 19.3, natively.** Host components are HTML elements, styled with
+ CSS and Tailwind classes, with events, Suspense, transitions and actions.
+ BUI draws them, on the CPU or the GPU; there's no browser and no webview.
+- **React's hooks, by React's names.** `useState`, `useMemo`, `useEffect` ...
+ hold signals. Pass one into JSX (`{count}`) and a change updates that one
+ node without re-rendering the component. Read it while rendering
+ (`count.value`) and the component re-renders, as with React.
+- **One small executable.** `bui build` bundles the app onto `bui-runtime`,
+ which is BUI with an embedded QuickJS engine. The result starts in under
+ 70 ms and needs nothing installed. `--bun` builds a Bun executable instead,
+ with Node's APIs.
+- **No React?** [`@blender-ui/native`](https://www.npmjs.com/package/@blender-ui/native)
+ is a DOM-like API (`createElement`, `appendChild`, `addEventListener`) with
+ the same signals.
+
+Node.js 18+ or Bun, Windows x64 for now. Guide:
+[docs/javascript.md](docs/javascript.md).
### Rust
@@ -183,6 +205,7 @@ Build from source with CMake (see [Building from source](#building-from-source))
<tr><td width="50%" valign="top">
### 🎛️ Blender's widgets and interactions
+
- Number fields you **drag with a hidden, continuous cursor**: Shift for precision, Ctrl to snap.
- Ctrl+Wheel steps values, Ctrl+C / Ctrl+V copy values, Backspace resets.
- **Drag across checkboxes** to set them all.
@@ -194,6 +217,7 @@ Build from source with CMake (see [Building from source](#building-from-source))
</td><td width="50%" valign="top">
### 🐍 Python, three ways
+
- **tkinter**: all 7,846 public names of tkinter and ttk. Nine real programs behave identically on the standard library and on BUI.
- **Qt syntax**: widgets, layouts, signals, `QPainter`, menus and timers.
- **Components**: 45 Blender widgets, editors and templates.
@@ -203,6 +227,7 @@ Build from source with CMake (see [Building from source](#building-from-source))
<tr><td valign="top">
### 🦀 Rust: the web platform, natively
+
- **All 113 HTML elements**; form controls are real Blender widgets.
- **Modern CSS**: flexbox, grid with named areas, `calc()` and every math function, `var()`, `oklch()` and `color-mix()`, `:has()`, nesting, `@layer`, `@media` ranges, `::before`/`::after`.
- **Tailwind CSS v4**: `class="md:hover:bg-sky-500/50"` or bare attributes (`<div p-4 bg-[#4772b3]>`), with **"did you mean" compile errors**.
@@ -212,11 +237,31 @@ Build from source with CMake (see [Building from source](#building-from-source))
</td><td valign="top">
### ⚡ Fast by design
+
- **Damage rendering**: an idle UI costs 0% CPU, and a hover redraws only the widget it touches.
- **Opt-in GPU renderer** (Direct3D 11), modeled on Blender's instanced widget drawing. It draws the same pixels as the CPU raster.
- In the benchmark, **2–4× less CPU per frame than gpui-fast**, with **less RAM** and a **~5 ms first frame**.
- **Blender's text**: Inter (Blender's UI font) is embedded, so text looks the same on every platform. On the GPU, glyphs are drawn from their outlines with [Slug](https://github.com/EricLengyel/Slug), falling back to a per-glyph atlas like Blender's.
+</td></tr>
+<tr><td valign="top">
+
+### ⚛️ JavaScript and React
+
+- **React 19.3** renders to BUI: HTML host components, CSS and Tailwind, events, Suspense, transitions, actions.
+- **React's hooks, by React's names**, holding signals: a change updates one node without re-rendering. A conformance suite checks each against React's own.
+- **`@blender-ui/native`**: a DOM-like API with signals, for apps without React.
+- **Node.js and Bun**, through a napi-rs addon, with headless mode for tests.
+
+</td><td valign="top">
+
+### 📦 Small standalone apps
+
+- **`bui build app.jsx`** produces one executable of about **5 MB**: BUI with an embedded QuickJS engine.
+- **First frame in ~70 ms**, at **19 MB** of RAM, with nothing to install. There's no browser and no webview.
+- **`--bun`** builds a Bun executable instead, with Node's APIs and a JIT.
+- Builds take under a second: the app's bundle is appended to a prebuilt runtime.
+
</td></tr>
</table>
@@ -261,38 +306,38 @@ error: rsx!: `bg-sky-50O` is not a Tailwind utility; did you mean `bg-sky-500` o
### ✅ Done
-| Area | What works |
-|---|---|
-| C runtime (`kit/`) | Nodes, Tk-style geometry managers, input, Blender widget drawing, damage rendering, undo, animation, text area, canvas, scroll views |
-| Windows | A native Win32 window in C: DPI-aware, vsync-paced animation, clipboard, cursors, window-manager features |
-| tkinter syntax | **Complete**: every public tkinter and ttk name (7,846 of 7,846) |
-| Components | 45 Blender components, including the color ramp and curve editors |
-| Rust | HTML (113/113 elements), Flexbox 12/12, Grid 23/23, CSS 2.1 82/90, math functions, `var()`, CSS Color 4/5, Selectors 4, `@layer`/`@media`/`@supports`/`@scope`/`@container`/`@font-face`/`@property`, background images, `object-fit`, Tailwind v4, `rsx!`, `#[component]` with optional props and `key`, hooks, headless testing |
-| Rendering | Software raster (parallel, damage-tracked), GPU renderer (Direct3D 11), portable text engine |
-| JavaScript / React | `@blender-ui/native`: a DOM-like API over napi-rs, with its own UI thread, only changes crossing the boundary, vsync-paced `requestAnimationFrame` and signals. `@blender-ui/react`: a React 19.3 renderer whose hooks (`useState`, `useMemo`, `useEffect` ...) hold signals that update nodes without re-renders. Both on Node.js and Bun, with headless testing ([guide](docs/javascript.md)) |
-| Packaging | [`blenderui` on PyPI](https://pypi.org/project/blenderui/), with a CI workflow for wheels on all platforms |
+| Area | What works |
+| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| C runtime (`kit/`) | Nodes, Tk-style geometry managers, input, Blender widget drawing, damage rendering, undo, animation, text area, canvas, scroll views |
+| Windows | A native Win32 window in C: DPI-aware, vsync-paced animation, clipboard, cursors, window-manager features |
+| tkinter syntax | **Complete**: every public tkinter and ttk name (7,846 of 7,846) |
+| Components | 45 Blender components, including the color ramp and curve editors |
+| Rust | HTML (113/113 elements), Flexbox 12/12, Grid 23/23, CSS 2.1 82/90, math functions, `var()`, CSS Color 4/5, Selectors 4, `@layer`/`@media`/`@supports`/`@scope`/`@container`/`@font-face`/`@property`, background images, `object-fit`, Tailwind v4, `rsx!`, `#[component]` with optional props and `key`, hooks, headless testing |
+| Rendering | Software raster (parallel, damage-tracked), GPU renderer (Direct3D 11), portable text engine |
+| JavaScript / React | `@blender-ui/native`: a DOM-like API over napi-rs, with its own UI thread, only changes crossing the boundary, vsync-paced `requestAnimationFrame` and signals. `@blender-ui/react`: a React 19.3 renderer whose hooks (`useState`, `useMemo`, `useEffect` ...) hold signals that update nodes without re-renders. Both on Node.js and Bun, with headless testing. `bui build` makes standalone executables: about 5 MB with the embedded QuickJS runtime, or Bun's with `--bun` ([guide](docs/javascript.md)) |
+| Packaging | [`blenderui` on PyPI](https://pypi.org/project/blenderui/), with a CI workflow for wheels on all platforms; [`@blender-ui/react`](https://www.npmjs.com/package/@blender-ui/react) and [`@blender-ui/native`](https://www.npmjs.com/package/@blender-ui/native) on npm |
### 🟡 Partial or in progress
-| Area | What's missing |
-|---|---|
-| Qt syntax (~25%) | Model/view classes, docks, toolbars, splitters, Qt stylesheets ([details](docs/qt.md#coverage)) |
+| Area | What's missing |
+| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| Qt syntax (~25%) | Model/view classes, docks, toolbars, splitters, Qt stylesheets ([details](docs/qt.md#coverage)) |
| CSS (207 of 745 W3C properties render, 177 more parse) | Rendering effects: `rotate`/`skew` transforms, `filter`/`backdrop-filter`, blend modes, `clip-path`, masks, `border-image`, non-solid borders. Also animations and transitions. Most of the remaining W3C list is drafts, speech, print and SVG ([breakdown](docs/rust.md#coverage)) |
-| Text | No text wrapping around floats; no right-to-left shaping |
-| Rust components | No async resources (`use_resource`); no generic components |
-| JavaScript / React | Prebuilt for Windows x64 only (elsewhere: build from source, headless); events reach JavaScript after BUI handled them (no native `preventDefault`), and `event.target` is the deepest *listening* element |
-| Linux / macOS | They work through a fallback window (the stdlib Tk window shows BUI's frame), but they're less tested. No native window host and no GPU renderer yet |
-| crates.io | The crates are ready to publish but not published yet; use the git dependency for now |
+| Text | No text wrapping around floats; no right-to-left shaping |
+| Rust components | No async resources (`use_resource`); no generic components |
+| JavaScript / React on Linux / macOS | Prebuilt for Windows x64 only (elsewhere: build from source, headless); events reach JavaScript after BUI handled them (no native `preventDefault`), and `event.target` is the deepest _listening_ element |
+| Linux / macOS | They work through a fallback window (the stdlib Tk window shows BUI's frame), but they're less tested. No native window host and no GPU renderer yet |
+| crates.io | The crates are ready to publish but not published yet; use the git dependency for now |
### 🗺️ Planned
-| Target | Plan |
-|---|---|
-| **WebAssembly** | The kit in the browser: the raster blits to `<canvas>`, DOM events feed the kit; `@blender-ui/react` and the DOM-like API on top, unchanged |
-| **egui** | BUI panels inside egui, plus a Blender-styled theme |
-| **Native Linux / macOS windows** | Wayland / X11 and Cocoa hosts in C, like the Win32 one |
-| **More GPU backends** | Vulkan / Metal / WebGPU drawing the same instance stream as Direct3D 11 |
-| **More languages** | C#, Go, Zig, Swift, Kotlin and Lua over the same C header; Dear ImGui; Godot, Unity and Bevy; Flutter |
+| Target | Plan |
+| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
+| **WebAssembly** | The kit in the browser: the raster blits to `<canvas>`, DOM events feed the kit; `@blender-ui/react` and the DOM-like API on top, unchanged |
+| **egui** | BUI panels inside egui, plus a Blender-styled theme |
+| **Native Linux / macOS windows** | Wayland / X11 and Cocoa hosts in C, like the Win32 one |
+| **More GPU backends** | Vulkan / Metal / WebGPU drawing the same instance stream as Direct3D 11 |
+| **More languages** | C#, Go, Zig, Swift, Kotlin and Lua over the same C header; Dear ImGui; Godot, Unity and Bevy; Flutter |
## How it works
@@ -323,39 +368,40 @@ More: [ARCHITECTURE.md](ARCHITECTURE.md).
Python and C, on the full component demo (520×900):
-| Frame | Time |
-|---|---|
-| Complete frame (everything redrawn) | ~0.7 ms |
+| Frame | Time |
+| ----------------------------------------- | -------- |
+| Complete frame (everything redrawn) | ~0.7 ms |
| Hover or number-scrub frame (damage only) | ~0.05 ms |
-| Native window: input event → on screen | ~0.06 ms |
+| Native window: input event → on screen | ~0.06 ms |
Rust, against Zed's [gpui](https://crates.io/crates/gpui) and the faster fork
[gpui-fast](https://github.com/longbridge/gpui-fast). The scene is 3000
animated cells, the machine a Ryzen 7 5800U laptop, and all apps ran in the
same session:
-| | blenderui (GPU) | blenderui (CPU) | gpui-fast | gpui |
-|---|---:|---:|---:|---:|
-| FPS | **59.9** | 57.6 | 31.5 | 19.9 |
-| CPU per frame | **11.6 ms** | 22.0 ms | 31.9 ms + GPU | 50.5 ms + GPU |
-| RAM | 40 MB | **30 MB** | 65 MB | 77 MB |
-| First frame | **~5 ms** | **~5 ms** | ~200 ms | ~220 ms |
-| Idle CPU | **0 %** | 0–0.9 % | 0–0.4 % | 0.9–1.4 % |
+| | blenderui (GPU) | blenderui (CPU) | gpui-fast | gpui |
+| ------------- | --------------: | --------------: | ------------: | ------------: |
+| FPS | **59.9** | 57.6 | 31.5 | 19.9 |
+| CPU per frame | **11.6 ms** | 22.0 ms | 31.9 ms + GPU | 50.5 ms + GPU |
+| RAM | 40 MB | **30 MB** | 65 MB | 77 MB |
+| First frame | **~5 ms** | **~5 ms** | ~200 ms | ~220 ms |
+| Idle CPU | **0 %** | 0–0.9 % | 0–0.4 % | 0.9–1.4 % |
<details>
<summary>Full results, the GPU renderer, and the method</summary>
-| | blenderui (GPU) | blenderui (CPU) | gpui-fast | gpui |
-|---|---:|---:|---:|---:|
-| FPS, 1000 animated cells | **60** | **60** | 49.2 | 36.4 |
-| CPU per frame, 1000 / 100 cells | **4.7 / 1.2 ms** | 10.2 / 4.6 ms | 20.5 / 2.7 ms + GPU | 27.7 / 4.7 ms + GPU |
-| Uncapped FPS, 100 / 1000 / 3000 cells | **1491 / 309 / 94** | 649 / 202 / 76 | - | - |
-| RAM, 1000 / 100 cells | 35 / 28 MB | **24 / 21 MB** | 45 / 47 MB | 47 / 40 MB |
-| GPU memory | 19–22 MB | **none** | 19–24 MB | 16–21 MB |
+| | blenderui (GPU) | blenderui (CPU) | gpui-fast | gpui |
+| ------------------------------------- | ------------------: | --------------: | ------------------: | ------------------: |
+| FPS, 1000 animated cells | **60** | **60** | 49.2 | 36.4 |
+| CPU per frame, 1000 / 100 cells | **4.7 / 1.2 ms** | 10.2 / 4.6 ms | 20.5 / 2.7 ms + GPU | 27.7 / 4.7 ms + GPU |
+| Uncapped FPS, 100 / 1000 / 3000 cells | **1491 / 309 / 94** | 649 / 202 / 76 | - | - |
+| RAM, 1000 / 100 cells | 35 / 28 MB | **24 / 21 MB** | 45 / 47 MB | 47 / 40 MB |
+| GPU memory | 19–22 MB | **none** | 19–24 MB | 16–21 MB |
The GPU renderer is off by default. Turn it on with
`Application::new().gpu(true)`, `tk.Tk(gpu=True)`, `bui.set_gpu(True)` or
`BUI_GPU=1`:
+
- Every primitive is one instance of a single shader, so a frame is a few
`DrawInstanced` calls.
- Text and images are cached in atlases.
@@ -370,50 +416,89 @@ gpui-fast's heavy-scene frame rate varies between sessions on this laptop
[bindings/rust/bench/README.md](bindings/rust/bench/README.md).
</details>
-JavaScript, on the same scene in `one` mode: one cell changes per frame, the
-GPU renderer, medians of 3 runs. CPU is the whole process, counted the same
-way as for Rust. Plain JS uses `@blender-ui/native`; React uses
-`@blender-ui/react` in its production build.
-
-| 3,000 cells | FPS | CPU per frame | RAM |
-|---|---:|---:|---:|
-| Rust | 59.6 | **12.0 ms** | **43 MB** |
-| Bun 1.4: plain JS / React with signals / React with state | 58.8 / 58.4 / 55.8 | 13.1 / 13.3 / 20.8 ms | 80 / 85 / 118 MB |
-| Node 22: plain JS / React with signals / React with state | 55.8 / 56.7 / 54.8 | 14.4 / 14.0 / 18.9 ms | 88 / 93 / 121 MB |
-
-At 1,000 cells every configuration holds 60 FPS, at 4.8 ms per frame (Rust)
-to 7.5 ms (React re-rendering). Method and more:
+### JavaScript and React: startup and animation
+
+**Startup.** These launch a small React app (the counter above) that quits
+once its first frame is on screen. Each figure is the median of 12 launches
+after a warm-up launch (`node bench/startup.js`).
+
+| | First frame | Launch to exit | RAM at first frame | What you ship |
+| --------------------------------------- | ----------: | -------------: | -----------------: | --------------: |
+| **QuickJS executable** (`bui build`) | **68 ms** | **104 ms** | **19 MB** | **4.9 MB** |
+| Bun executable (`bui build --bun`) | 79 ms | 147 ms | 35 MB | 114 MB |
+| Bun (`bun app.js`) | 80 ms | 152 ms | 35 MB | Bun + your app |
+| Node.js (`node app.js`) | 108 ms | 187 ms | 45 MB | Node + your app |
+| Rust (for reference: the benchmark app) | 5 ms | ~92 ms | | 3.5 MB |
+
+First frame is measured from the runtime's start. Launch to exit is wall time
+measured from outside, including process creation and teardown.
+
+**Animation.** The same scene as the Rust table above, in `one` mode: one cell
+changes per frame, GPU renderer, medians of 3 runs. CPU is the whole process,
+counted with the cycle counter as for Rust.
+
+- **Plain JS** uses `@blender-ui/native`.
+- **React with signals** passes the changing values as signals, so the grid
+ renders once.
+- **React with state** re-renders the grid every frame.
+- **React's production build** is used throughout.
+
+| 3,000 cells | FPS | CPU per frame | RAM |
+| --------------------------------------------------------- | -----------------: | --------------------: | ------------------: |
+| Rust | 59.6 | **12.0 ms** | **43 MB** |
+| QuickJS: plain JS / React with signals / React with state | 59.1 / 58.7 / 19.7 | 16.3 / 14.9 / 51.0 ms | **56 / 61 / 67 MB** |
+| Bun 1.4: plain JS / React with signals / React with state | 58.8 / 58.4 / 55.8 | 13.1 / 13.3 / 20.8 ms | 80 / 85 / 118 MB |
+| Node 22: plain JS / React with signals / React with state | 55.8 / 56.7 / 54.8 | 14.4 / 14.0 / 18.9 ms | 88 / 93 / 121 MB |
+
+| 1,000 cells | FPS | CPU per frame | RAM |
+| --------------------------------------------------------- | -------------: | ------------------: | ------------------: |
+| Rust | 60 | **4.8 ms** | **32 MB** |
+| QuickJS: plain JS / React with signals / React with state | 60 / 60 / 56.8 | 6.0 / 5.6 / 17.8 ms | **38 / 40 / 43 MB** |
+| Bun: plain JS / React with signals / React with state | 60 / 60 / 60 | 5.2 / 5.2 / 7.5 ms | 58 / 63 / 81 MB |
+| Node: plain JS / React with signals / React with state | 60 / 60 / 60 | 5.6 / 5.6 / 6.9 ms | 68 / 71 / 97 MB |
+
+What this means:
+
+- **JavaScript costs little over Rust:** 0.4–2.4 ms per frame, for sending
+ changes to BUI's UI thread.
+- **Signals make React as cheap as the plain API:** the component doesn't
+ re-render.
+- **QuickJS** starts fastest and uses the least memory, from a 5 MB file. It
+ has no JIT, so re-rendering a 3,000-element list every frame drops it to
+ 20 FPS. Keep big lists on signals, or build with `--bun`.
+
+Method, the memory breakdown and how to rerun:
[docs/javascript.md](docs/javascript.md#performance).
-
## Documentation
-| Guide | What's inside |
-|---|---|
-| [Getting started](docs/getting-started.md) | Building, environment variables, window hosts, GPU rendering, troubleshooting |
-| [tkinter](docs/tkinter.md) | Running tkinter apps on BUI, behavior notes, limitations |
-| [Qt syntax](docs/qt.md) | Classes, signals, layouts, painting, coverage |
-| [Components](docs/components.md) | The `bui.components` reference |
-| [Rust](docs/rust.md) | `rsx!`, hooks, HTML, CSS and Tailwind coverage, events, headless tests |
+| Guide | What's inside |
+| ------------------------------------------ | ------------------------------------------------------------------------------------------ |
+| [Getting started](docs/getting-started.md) | Building, environment variables, window hosts, GPU rendering, troubleshooting |
+| [tkinter](docs/tkinter.md) | Running tkinter apps on BUI, behavior notes, limitations |
+| [Qt syntax](docs/qt.md) | Classes, signals, layouts, painting, coverage |
+| [Components](docs/components.md) | The `bui.components` reference |
+| [Rust](docs/rust.md) | `rsx!`, hooks, HTML, CSS and Tailwind coverage, events, headless tests |
| [JavaScript and React](docs/javascript.md) | `@blender-ui/native`, `@blender-ui/react`, how changes cross to the UI thread, performance |
-| [C API](docs/c-api.md) | The C kit (`BUI_kit.h`) |
-| [Integration](INTEGRATION.md) | Embedding BUI drawing in C, C++, Qt or PySide hosts |
-| [Architecture](ARCHITECTURE.md) | Modules and what was taken from Blender |
-| [Publishing](docs/publishing.md) | Releasing to PyPI and crates.io |
-| [Changelog](CHANGELOG.md) | What changed |
+| [C API](docs/c-api.md) | The C kit (`BUI_kit.h`) |
+| [Integration](INTEGRATION.md) | Embedding BUI drawing in C, C++, Qt or PySide hosts |
+| [Architecture](ARCHITECTURE.md) | Modules and what was taken from Blender |
+| [Publishing](docs/publishing.md) | Releasing to PyPI and crates.io |
+| [Changelog](CHANGELOG.md) | What changed |
<details>
<summary><b>Examples</b></summary>
-| File | Shows |
-|---|---|
-| [`examples/tk_unchanged_app.py`](examples/tk_unchanged_app.py) | A plain tkinter app: menus, notebook, form, table, text, canvas |
-| [`examples/components_demo.py`](examples/components_demo.py) | Every Blender component in a properties-editor layout |
-| [`examples/qt_syntax_demo.py`](examples/qt_syntax_demo.py) | Qt syntax: layouts, form widgets, signals |
-| [`examples/tk_syntax_demo.py`](examples/tk_syntax_demo.py) | tkinter syntax laid out like a Blender properties editor |
-| [`examples/kit_hello.c`](examples/kit_hello.c) | The C kit: a slider and a button in a native window |
-| [`hello.rs`](bindings/rust/blenderui/examples/hello.rs) | Rust: a component, hooks and Tailwind attributes |
-| [`showcase.rs`](bindings/rust/blenderui/examples/showcase.rs) | Rust: HTML, a stylesheet, flex/grid, tables, Blender form widgets |
+| File | Shows |
+| -------------------------------------------------------------- | ----------------------------------------------------------------- |
+| [`examples/tk_unchanged_app.py`](examples/tk_unchanged_app.py) | A plain tkinter app: menus, notebook, form, table, text, canvas |
+| [`examples/components_demo.py`](examples/components_demo.py) | Every Blender component in a properties-editor layout |
+| [`examples/qt_syntax_demo.py`](examples/qt_syntax_demo.py) | Qt syntax: layouts, form widgets, signals |
+| [`examples/tk_syntax_demo.py`](examples/tk_syntax_demo.py) | tkinter syntax laid out like a Blender properties editor |
+| [`examples/kit_hello.c`](examples/kit_hello.c) | The C kit: a slider and a button in a native window |
+| [`hello.rs`](bindings/rust/blenderui/examples/hello.rs) | Rust: a component, hooks and Tailwind attributes |
+| [`showcase.rs`](bindings/rust/blenderui/examples/showcase.rs) | Rust: HTML, a stylesheet, flex/grid, tables, Blender form widgets |
+
</details>
## Building from source
@@ -435,17 +520,18 @@ cd bindings/rust && cargo test # Rust: CSS, Tailwind, rsx!, hooks,
<details>
<summary>Repository layout</summary>
-| Path | Contents |
-|---|---|
-| `kit/` | The C runtime: nodes, input, widget drawing (the `interface_widgets.cc` port), menus, geometry managers, canvas, the Win32 host. API: `kit/include/BUI_kit.h` |
-| `gpu/` | Software raster, Direct3D 11 renderer (`gpu_d3d11.c`, `shaders/`, Slug text), text engine (stb_truetype + embedded Inter, or GDI) |
-| `core/`, `types/` | Blender's `blenlib` subset and data types |
-| `ui/`, `compat/` | Blender's original interface sources and the seams replacing Blender's application APIs |
-| `api/` | Stable C ABI for render-sink hosts |
-| `bindings/python/` | The `buipy` extension and the `bui` / `blenderui` packages |
-| `bindings/rust/` | `blenderui`, `blenderui-sys`, `blenderui-macros`, `blenderui-tailwind`, and the benchmark |
-| `backends/qt/` | C++ Qt/QPainter render-sink backend |
-| `examples/`, `tools/` | Demos, the icon generator, the docs screenshot generator |
+| Path | Contents |
+| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `kit/` | The C runtime: nodes, input, widget drawing (the `interface_widgets.cc` port), menus, geometry managers, canvas, the Win32 host. API: `kit/include/BUI_kit.h` |
+| `gpu/` | Software raster, Direct3D 11 renderer (`gpu_d3d11.c`, `shaders/`, Slug text), text engine (stb_truetype + embedded Inter, or GDI) |
+| `core/`, `types/` | Blender's `blenlib` subset and data types |
+| `ui/`, `compat/` | Blender's original interface sources and the seams replacing Blender's application APIs |
+| `api/` | Stable C ABI for render-sink hosts |
+| `bindings/python/` | The `buipy` extension and the `bui` / `blenderui` packages |
+| `bindings/rust/` | `blenderui`, `blenderui-sys`, `blenderui-macros`, `blenderui-tailwind`, and the benchmark |
+| `backends/qt/` | C++ Qt/QPainter render-sink backend |
+| `examples/`, `tools/` | Demos, the icon generator, the docs screenshot generator |
+
</details>
## FAQ
@@ -466,10 +552,24 @@ differences.
<details>
<summary><b>Is it a web browser in Rust?</b></summary>
-No. There's no DOM, no JavaScript and no network. The Rust crate gives you
-HTML elements and CSS as a <i>UI language</i>: they are laid out with
+No. There's no browser engine and no network. BUI takes HTML elements and CSS
+as a <i>UI language</i>: they are laid out with
<a href="https://github.com/DioxusLabs/taffy">taffy</a> and drawn with Blender's
-widgets, in a native window.
+widgets, in a native window. JavaScript is optional: the Rust crate needs
+none, and the JavaScript packages drive the same engine.
+</details>
+
+<details>
+<summary><b>How is it different from Electron, Electrobun or GPUIX?</b></summary>
+<ul>
+<li><b>Electron</b> ships Chromium with every app: on the order of 100 MB or more.</li>
+<li><b>Electrobun</b> runs on Bun and renders in the system's webview. It's
+small to download, but the UI is still a browser page.</li>
+<li><b>GPUIX</b>, like BUI, renders React natively: React drives Zed's GPUI.</li>
+</ul>
+BUI also renders natively, with Blender's widgets, a much larger part of CSS,
+Tailwind, and hooks backed by signals. <code>bui build</code> makes a 5 MB
+executable that reaches its first frame in about 70 ms.
</details>
<details>
diff --git a/bindings/node/.gitignore b/bindings/node/.gitignore
index e41c098..6fe5c3a 100644
--- a/bindings/node/.gitignore
+++ b/bindings/node/.gitignore
@@ -1,3 +1,4 @@
*.node
node_modules/
LICENSE
+bui-runtime.*
diff --git a/bindings/node/README.md b/bindings/node/README.md
index 4e25cf4..988931c 100644
--- a/bindings/node/README.md
+++ b/bindings/node/README.md
@@ -1,13 +1,19 @@
# @blender-ui/native
-Blender's UI toolkit from JavaScript: native windows drawn on the CPU or with
-Direct3D 11, HTML elements, CSS and Tailwind classes, and signals. It runs on
-Node.js and Bun through a native addon (napi-rs), with no browser and no
-Electron. For React, see
-[`@blender-ui/react`](https://www.npmjs.com/package/@blender-ui/react).
+[![npm](https://img.shields.io/npm/v/@blender-ui/native)](https://www.npmjs.com/package/@blender-ui/native)
+[![license](https://img.shields.io/npm/l/@blender-ui/native)](https://github.com/ppmpreetham/BUI/blob/main/LICENSE)
+
+[BUI](https://github.com/ppmpreetham/BUI), Blender's UI toolkit, from
+JavaScript. It gives you native windows drawn on the CPU or with Direct3D 11,
+HTML elements, CSS and Tailwind classes, and signals. It runs on Node.js and
+Bun through a napi-rs addon, and `bui build` turns an app into a single
+executable of about 5 MB. There's no browser and no webview.
+
+For React, use [`@blender-ui/react`](https://www.npmjs.com/package/@blender-ui/react),
+which is built on this package.
```sh
-npm install @blender-ui/native
+npm install @blender-ui/native # or: bun add @blender-ui/native
```
```js
@@ -30,40 +36,91 @@ win.body.appendChild(button)
## API
- **A DOM-like tree:** `createElement`, `createTextNode`, `appendChild`,
- `insertBefore`, `removeChild`, `setAttribute`, `className` (with Tailwind
- classes), `style` (a string or an object), `textContent`.
+ `insertBefore`, `removeChild`, `setAttribute`, `className` (Tailwind
+ classes included), `style` (a string or an object), `textContent`.
+ - Moving nodes and the error cases behave as in the DOM.
+ - `destroy()` frees a removed subtree natively.
- **Events:** `addEventListener` for `click`, `mousedown`, `mouseup`,
`mousemove`, `mouseenter`, `mouseleave`, `wheel`, `keydown`, `keyup`, `input`
- and `change`. They bubble through the tree, and `stopPropagation()` works.
- They arrive after BUI has handled them, so `preventDefault()` only marks the
- event.
+ and `change`.
+ - They bubble through the tree, and `stopPropagation()` works.
+ - They arrive after BUI has handled them, so `preventDefault()` only marks
+ the event.
- **Frames and measurement:** `win.requestAnimationFrame(cb)` is paced by the
display. `el.getBoundingClientRect()` and `win.screenshot()` return
promises.
- **Signals:** `signal`, `memo`, `effect`, `batch`, `untrack`,
- `startTransition`. Pass a signal to `setAttribute`, `style`, `textContent`
- or `createTextNode`, and its changes update that node alone. The signals are
- also available without the addon: `require('@blender-ui/native/signals')`.
+ `startTransition`.
+ - Pass a signal to `setAttribute`, `style` (or inside a style object),
+ `textContent` or `createTextNode`, and its changes update that node
+ alone.
+ - Memos and effects track what they read, are glitch-free, and need no
+ dependency arrays.
+ - Without the addon: `require('@blender-ui/native/signals')`.
- **Tests:** `new App({ headless: true })` renders off-screen, and
`win.click(x, y)` simulates input.
+## Standalone apps
+
+```sh
+npx bui build app.js # app.exe: BUI + embedded QuickJS, ~5 MB
+npx bui build app.js --bun # app.exe: Bun, with Node's APIs and a JIT, ~115 MB
+npx bui run app.js # run on the QuickJS runtime, no build
+```
+
+Options:
+
+- `-o <file>`: the output file.
+- `--console`: keep a console window for logs (Windows builds open none).
+- `--dev`: React's development build.
+
+Bundling uses [Bun](https://bun.sh), so it must be installed.
+
+**How the default build works.** It appends your bundled app to `bui-runtime`,
+BUI with the QuickJS engine embedded. That takes under a second and compiles
+nothing.
+
+- **It's fast to start:** the result reaches its first frame in about 70 ms
+ and uses 19 MB of RAM there.
+- **It's limited:** no Node modules (`fs` and the like) and no JIT. Keep
+ frequent updates on signals, or use `--bun`.
+
## How it's fast
- **Its own UI thread:** BUI renders on a thread of its own, so it never
- blocks Node and an idle window uses no CPU.
-- **Only changes cross:** each tick, a window sends one batch of operations
- (an `Int32Array` and a string table) to the UI thread.
+ blocks JavaScript, and an idle window uses no CPU.
+- **Only changes cross:** each tick, a window sends one batch of operations,
+ an `Int32Array` and a string table.
- **Styles parsed once:** a `style` value is parsed when it's set, not every
frame.
+## Benchmarks
+
+Ryzen 7 5800U laptop, Windows 11, GPU renderer. Method:
+[guide](https://github.com/ppmpreetham/BUI/blob/main/docs/javascript.md#performance).
+
+| Startup (small app, quits at first frame) | First frame | Launch to exit | RAM | Size |
+|---|---:|---:|---:|---:|
+| **`bui build`** (QuickJS) | **68 ms** | **104 ms** | **19 MB** | **4.9 MB** |
+| `bui build --bun` | 79 ms | 147 ms | 35 MB | 114 MB |
+| `bun app.js` | 80 ms | 152 ms | 35 MB | |
+| `node app.js` | 108 ms | 187 ms | 45 MB | |
+
+| 3,000 cells, one changing per frame | FPS | CPU per frame | RAM |
+|---|---:|---:|---:|
+| Bun | 58.8 | 13.1 ms | 80 MB |
+| Node.js | 55.8 | 14.4 ms | 88 MB |
+| QuickJS (`bui build`) | 59.1 | 16.3 ms | 56 MB |
+| *Rust, for reference* | 59.6 | 12.0 ms | 43 MB |
+
## Requirements
-- **Prebuilt for Windows x64.** On other platforms, build from a clone of the
+- **Prebuilt for Windows x64.** Elsewhere, build from a clone of the
[repository](https://github.com/ppmpreetham/BUI) with `npm run build` in
- `bindings/node`. That needs Rust, CMake and a C compiler; native windows
- there are not supported yet, so use `headless: true`.
+ `bindings/node`. You need Rust, CMake and a C compiler, and native windows
+ aren't supported there yet, so use `headless: true`.
- **Runtimes:** Node.js 18 or newer, or Bun.
-Guide, benchmarks and internals:
-[docs/javascript.md](https://github.com/ppmpreetham/BUI/blob/main/docs/javascript.md).
-License: GPL-2.0-or-later.
+Guide: [docs/javascript.md](https://github.com/ppmpreetham/BUI/blob/main/docs/javascript.md) ·
+Source: [github.com/ppmpreetham/BUI](https://github.com/ppmpreetham/BUI) ·
+License: GPL-2.0-or-later
diff --git a/bindings/node/bench/cells.js b/bindings/node/bench/cells.js
index f4490f0..f08e485 100644
--- a/bindings/node/bench/cells.js
+++ b/bindings/node/bench/cells.js
@@ -2,13 +2,16 @@
// grid of N cells; every frame (16 ms) cell 0 changes colour and label.
// node bench/cells.js [cells=3000] [--react [--signals]] [--gpu] [--seconds=5]
// --signals: cell 0's style and label are BUI signals; the grid renders once.
-// --dev: React's development build. Runs on Node or Bun (`bun bench/cells.js`).
+// --dev: React's development build. Runs on Node, Bun (`bun bench/cells.js`) or
+// the QuickJS runtime (`node cli.js run bench/cells.js -- 3000 --gpu`).
// Prints frames per second, CPU per frame (the whole process: JavaScript,
// BUI's UI thread, the runtime) and resident memory.
'use strict'
const args = process.argv.slice(2)
// React's production build, as an app ships (--dev: the development build)
-if (!args.includes('--dev')) process.env.NODE_ENV = 'production'
+// (through a variable: bundlers replace `process.env.NODE_ENV` reads)
+const env = process.env
+if (!args.includes('--dev')) env.NODE_ENV = 'production'
const cells = Number(args.find(a => /^\d+$/.test(a)) ?? 3000)
const useReact = args.includes('--react')
const useSignals = args.includes('--signals')
@@ -39,7 +42,7 @@ let tick
let app
let win
if (useReact) {
- const React = require(require.resolve('react', { paths: [require('node:path').join(__dirname, '../../react')] }))
+ const React = require('react')
const { render } = require('../../react')
const h = React.createElement
let setT
@@ -129,7 +132,7 @@ setTimeout(() => {
clearInterval(sampler)
console.log(JSON.stringify({
app: useReact ? (useSignals ? 'blenderui-react-signals' : 'blenderui-react') : 'blenderui-js',
- runtime: typeof Bun !== 'undefined' ? `bun ${Bun.version}` : `node ${process.versions.node}`,
+ runtime: globalThis.__BUI_NATIVE__ ? 'quickjs (bui-runtime)' : typeof Bun !== 'undefined' ? `bun ${Bun.version}` : `node ${process.versions.node}`,
gpu,
cells,
fps: +(updates / wall * 1000).toFixed(1),
diff --git a/bindings/node/bench/first-frame.js b/bindings/node/bench/first-frame.js
new file mode 100644
index 0000000..9fb00fc
--- /dev/null
+++ b/bindings/node/bench/first-frame.js
@@ -0,0 +1,20 @@
+// A small React app that quits once its first frame is on screen, printing
+// how long that took (ms since the runtime started) and the resident memory
+// then. Used by bench/startup.js.
+'use strict'
+const { render, createElement: h, useState } = require('@blender-ui/react')
+
+function App () {
+ const [count, setCount] = useState(0)
+ return h('main', { className: 'p-6 flex flex-col gap-3 bg-[#2b2b2b] text-[#e6e6e6]' },
+ h('h1', { className: 'text-xl font-bold' }, 'Hello'),
+ h('div', { className: 'flex items-center gap-3' },
+ h('span', null, 'Clicks: ', count),
+ h('button', { onClick: () => setCount(c => c + 1) }, 'Add one')))
+}
+
+const { app, window } = render(h(App), { title: 'first frame', width: 360, height: 200, gpu: true })
+window.requestAnimationFrame(() => {
+ console.log(`first-frame ${performance.now().toFixed(1)} rss ${(process.memoryUsage.rss() / 1048576).toFixed(1)}`)
+ app.quit()
+})
diff --git a/bindings/node/bench/startup.js b/bindings/node/bench/startup.js
new file mode 100644
index 0000000..2ae6517
--- /dev/null
+++ b/bindings/node/bench/startup.js
@@ -0,0 +1,57 @@
+// Launch to first frame, for every way to run an app: the same React app
+// (bench/first-frame.js) on Node, on Bun, as a Bun executable and as a
+// QuickJS executable (`bui build`). Prints a JSON line per runtime: median
+// and best of N launches, wall time from launch to exit, the app's own
+// first-frame time and memory then, and the file size.
+// node bench/startup.js [runs=12]
+'use strict'
+const fs = require('node:fs')
+const os = require('node:os')
+const path = require('node:path')
+const { spawnSync } = require('node:child_process')
+
+const runs = Number(process.argv[2] ?? 12)
+const app = path.join(__dirname, 'first-frame.js')
+const cli = path.join(__dirname, '..', 'cli.js')
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bui-startup-'))
+const exe = process.platform === 'win32' ? '.exe' : ''
+const env = { ...process.env, NODE_ENV: 'production' }
+
+function build (args, out) {
+ const r = spawnSync(process.execPath, [cli, 'build', app, '-o', out, '--console', ...args], { encoding: 'utf8' })
+ if (r.status !== 0) throw new Error(r.stderr)
+ return out
+}
+const bunExe = spawnSync('bun', ['-e', 'process.stdout.write(process.execPath)'],
+ { encoding: 'utf8', shell: process.platform === 'win32' }).stdout.trim()
+
+const variants = [
+ ['Node.js', process.execPath, [app], null],
+ ['Bun', bunExe, [app], null],
+ ['Bun executable (bui build --bun)', build(['--bun'], path.join(dir, `bun-app${exe}`)), [], 'self'],
+ ['QuickJS executable (bui build)', build([], path.join(dir, `qjs-app${exe}`)), [], 'self'],
+]
+
+const median = (a) => { const s = [...a].sort((x, y) => x - y); return s[Math.floor(s.length / 2)] }
+for (const [name, file, args, sized] of variants) {
+ const wall = [], first = [], rss = []
+ for (let i = 0; i < runs + 1; i++) {
+ const t = process.hrtime.bigint()
+ const r = spawnSync(file, args, { encoding: 'utf8', env })
+ const ms = Number(process.hrtime.bigint() - t) / 1e6
+ const m = /first-frame ([\d.]+) rss ([\d.]+)/.exec(r.stdout)
+ if (r.status !== 0 || !m) throw new Error(`${name}: ${r.stderr || r.stdout}`)
+ if (i === 0) continue // the first launch warms the disk cache (and virus scanners)
+ wall.push(ms)
+ first.push(Number(m[1]))
+ rss.push(Number(m[2]))
+ }
+ console.log(JSON.stringify({
+ runtime: name,
+ launch_to_exit_ms: { median: +median(wall).toFixed(0), best: +Math.min(...wall).toFixed(0) },
+ first_frame_ms: { median: +median(first).toFixed(0), best: +Math.min(...first).toFixed(0) },
+ rss_at_first_frame_mb: +median(rss).toFixed(1),
+ size_mb: sized ? +(fs.statSync(file).size / 1048576).toFixed(1) : null,
+ }))
+}
+fs.rmSync(dir, { recursive: true, force: true })
diff --git a/bindings/node/cli.js b/bindings/node/cli.js
new file mode 100644
index 0000000..6daeb21
--- /dev/null
+++ b/bindings/node/cli.js
@@ -0,0 +1,138 @@
+#!/usr/bin/env node
+// bui: build standalone apps from a JavaScript / JSX entry.
+//
+// bui build app.jsx [-o app.exe] a small executable: BUI + QuickJS (~5 MB)
+// bui build app.jsx --bun a Bun executable (full Node APIs, ~120 MB)
+// bui run app.jsx [args] run on the small runtime (no executable)
+//
+// Options:
+// -o, --out <file> output file (default: the entry's name, .exe on Windows)
+// --bun compile with `bun build --compile` instead of QuickJS
+// --console keep a console window (Windows; default: none, for apps)
+// --dev React's development build (default: production)
+//
+// Bundling uses Bun (https://bun.sh), which must be installed.
+// SPDX-License-Identifier: GPL-2.0-or-later
+'use strict'
+const fs = require('node:fs')
+const os = require('node:os')
+const path = require('node:path')
+const { spawnSync } = require('node:child_process')
+
+const MAGIC = Buffer.from('BUIAPP01')
+const TAG = `${process.platform}-${process.arch}`
+const EXE = process.platform === 'win32' ? '.exe' : ''
+
+function fail (msg) {
+ console.error(`bui: ${msg}`)
+ process.exit(1)
+}
+
+function parse (argv) {
+ const o = { cmd: argv[0], entry: null, out: null, bun: false, console: false, dev: false, rest: [] }
+ for (let i = 1; i < argv.length; i++) {
+ const a = argv[i]
+ if (o.cmd === 'run' && o.entry !== null) o.rest.push(a)
+ else if (a === '-o' || a === '--out') o.out = argv[++i]
+ else if (a === '--bun') o.bun = true
+ else if (a === '--console') o.console = true
+ else if (a === '--dev') o.dev = true
+ else if (a.startsWith('-')) fail(`unknown option ${a}`)
+ else o.entry = a
+ }
+ return o
+}
+
+/** The QuickJS runtime shipped in this package (or the workspace build). */
+function runtimePath () {
+ const shipped = path.join(__dirname, `bui-runtime.${TAG}${EXE}`)
+ if (fs.existsSync(shipped)) return shipped
+ const built = path.join(__dirname, '../rust/target/release', `bui-runtime${EXE}`)
+ if (fs.existsSync(built)) return built
+ fail(`no bui-runtime for ${TAG}: prebuilt for Windows x64; run \`npm run build\` in bindings/node to build it`)
+}
+
+/** Bun's executable: this process when running on Bun; otherwise asked once
+ * (npm installs it behind a shell shim on Windows), then run without a shell
+ * so arguments keep their quotes. */
+let bunPath = null
+function findBun () {
+ if (bunPath !== null) return bunPath
+ if (typeof Bun !== 'undefined') return (bunPath = process.execPath)
+ const r = spawnSync('bun', ['-e', 'process.stdout.write(process.execPath)'],
+ { encoding: 'utf8', shell: process.platform === 'win32' })
+ if (r.status !== 0 || !r.stdout) fail('bundling needs Bun: https://bun.sh')
+ return (bunPath = r.stdout.trim())
+}
+
+function bun (args, opts = {}) {
+ const r = spawnSync(findBun(), args, { stdio: opts.quiet ? 'pipe' : 'inherit', encoding: 'utf8' })
+ if (r.status !== 0) fail(`bun ${args[0]} failed${r.stderr ? `:
+${r.stderr}` : ''}`)
+ return r
+}
+
+/** One script for QuickJS: the app and its packages, React in production mode. */
+function bundle (entry, dev) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bui-'))
+ // an ES module importing the entry: Bun's IIFE output runs a CommonJS
+ // entry only when something imports it
+ const wrapper = path.join(dir, 'entry.mjs')
+ fs.writeFileSync(wrapper, `import ${JSON.stringify(path.resolve(entry).split(path.sep).join('/'))}\n`)
+ const out = path.join(dir, 'app.js')
+ bun(['build', wrapper, '--target=browser', '--format=iife', '--minify',
+ `--define=process.env.NODE_ENV="${dev ? 'development' : 'production'}"`,
+ '--external=node:*', '--external=*.node', `--outfile=${out}`], { quiet: true })
+ const js = fs.readFileSync(out)
+ fs.rmSync(dir, { recursive: true, force: true })
+ return js
+}
+
+/** Windows: mark the executable as a windowed app (no console window). */
+function setGuiSubsystem (buf) {
+ if (buf.readUInt16LE(0) !== 0x5a4d) return
+ const pe = buf.readUInt32LE(0x3c)
+ if (buf.readUInt32LE(pe) !== 0x4550) return
+ buf.writeUInt16LE(2, pe + 24 + 68) // IMAGE_SUBSYSTEM_WINDOWS_GUI
+}
+
+function build (o) {
+ const name = path.basename(o.entry).replace(/\.[^.]+$/, '')
+ const out = path.resolve(o.out ?? `${name}${EXE}`)
+ const t0 = Date.now()
+ if (o.bun) {
+ const args = ['build', '--compile', '--minify', o.entry, `--outfile=${out}`,
+ `--define=process.env.NODE_ENV="${o.dev ? 'development' : 'production'}"`]
+ if (process.platform === 'win32' && !o.console) args.push('--windows-hide-console')
+ bun(args)
+ } else {
+ const js = bundle(o.entry, o.dev)
+ const runtime = fs.readFileSync(runtimePath())
+ if (process.platform === 'win32' && !o.console) setGuiSubsystem(runtime)
+ const trailer = Buffer.alloc(16)
+ MAGIC.copy(trailer, 0)
+ trailer.writeBigUInt64LE(BigInt(js.length), 8)
+ fs.writeFileSync(out, Buffer.concat([runtime, js, trailer]))
+ if (process.platform !== 'win32') fs.chmodSync(out, 0o755)
+ }
+ const mb = (fs.statSync(out).size / 1048576).toFixed(1)
+ console.log(`bui: built ${path.relative(process.cwd(), out)} (${mb} MB, ${o.bun ? 'Bun' : 'QuickJS'}) in ${Date.now() - t0} ms`)
+}
+
+function run (o) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bui-run-'))
+ const file = path.join(dir, `${path.basename(o.entry).replace(/\.[^.]+$/, '')}.js`)
+ fs.writeFileSync(file, bundle(o.entry, o.dev))
+ const r = spawnSync(runtimePath(), [file, ...o.rest], { stdio: 'inherit' })
+ fs.rmSync(dir, { recursive: true, force: true })
+ process.exit(r.status ?? 1)
+}
+
+const o = parse(process.argv.slice(2))
+if (!['build', 'run'].includes(o.cmd) || !o.entry) {
+ console.log(fs.readFileSync(__filename, 'utf8').split('\n').slice(1, 14).map((l) => l.replace(/^\/\/ ?/, '')).join('\n'))
+ process.exit(o.cmd ? 1 : 0)
+}
+if (!fs.existsSync(o.entry)) fail(`no such file: ${o.entry}`)
+if (o.cmd === 'build') build(o)
+else run(o)
diff --git a/bindings/node/index.js b/bindings/node/index.js
index 2fe274d..52021e8 100644
--- a/bindings/node/index.js
+++ b/bindings/node/index.js
@@ -10,21 +10,26 @@
// SPDX-License-Identifier: GPL-2.0-or-later
'use strict'
-const path = require('node:path')
-
-const addon = process.env.BUI_NODE_ADDON ||
- path.join(__dirname, `blenderui.${process.platform}-${process.arch}.node`)
-let native
-try {
- native = require(addon)
-} catch (err) {
- throw new Error(`@blender-ui/native: no native addon for ${process.platform}-${process.arch} (${addon}). ` +
- 'Prebuilt binaries are for Windows x64; elsewhere, build it from a clone of ' +
- 'https://github.com/ppmpreetham/BUI with `npm run build` in bindings/node (needs Rust, CMake and a C compiler).',
- { cause: err })
+// The native layer: the QuickJS runtime's built-in one (bui-runtime, apps
+// made by `bui build`), or the napi addon (Node.js, Bun).
+const native = globalThis.__BUI_NATIVE__ ?? loadAddon()
+
+function loadAddon () {
+ const env = process.env.BUI_NODE_ADDON
+ try {
+ // a literal path where a prebuilt binary exists: `bun build --compile` (and
+ // other bundlers) can then embed the addon in the executable
+ if (!env && process.platform === 'win32' && process.arch === 'x64') return require('./blenderui.win32-x64.node')
+ return require(env || require('node:path').join(__dirname, `blenderui.${process.platform}-${process.arch}.node`))
+ } catch (err) {
+ throw new Error(`@blender-ui/native: no native addon for ${process.platform}-${process.arch}. ` +
+ 'Prebuilt binaries are for Windows x64; elsewhere, build it from a clone of ' +
+ 'https://github.com/ppmpreetham/BUI with `npm run build` in bindings/node (needs Rust, CMake and a C compiler).',
+ { cause: err })
+ }
}
const signals = require('./signals')
-const { isSignal, effect, unowned } = signals
+const { isSignal, effect, unowned, memo } = signals
// Keep in sync with bindings/rust/blenderui-node/src/lib.rs.
const OP = { CREATE: 0, TEXT: 1, SET_ATTR: 2, REMOVE_ATTR: 3, APPEND: 4, INSERT: 5, REMOVE: 6, SET_TEXT: 7, LISTEN: 8, FREE: 9 }
@@ -246,7 +251,13 @@ class Element extends Node {
set className (v) { this.setAttribute('class', v) }
get style () { return this._attrs.get('style') ?? '' }
/** A CSS declaration string, or an object (`{ backgroundColor: 'red', width: 40 }`). */
- set style (v) { this.setAttribute('style', typeof v === 'string' || isSignal(v) ? v : styleText(v)) }
+ set style (v) {
+ if (v == null) return this.removeAttribute('style')
+ if (typeof v === 'string' || isSignal(v)) return this.setAttribute('style', v)
+ // an object: plain values, or some signals (`{ color: colorSignal }`), then bound
+ for (const k in v) if (isSignal(v[k])) return this.setAttribute('style', memo(() => styleText(v)))
+ this.setAttribute('style', styleText(v))
+ }
get textContent () { return super.textContent }
set textContent (t) {
for (const c of [...this.childNodes]) { this.removeChild(c); c.destroy() }
@@ -310,7 +321,8 @@ const UNITLESS = new Set(['opacity', 'z-index', 'flex', 'flex-grow', 'flex-shrin
function styleText (o) {
let s = ''
for (const k in o) {
- const v = o[k]
+ const raw = o[k]
+ const v = isSignal(raw) ? raw.value : raw // read: a memo around this follows it
if (v == null || v === false || v === '') continue
const prop = k.startsWith('--') ? k : k.replace(/[A-Z]/g, m => '-' + m.toLowerCase())
s += `${prop}: ${typeof v === 'number' && v !== 0 && !UNITLESS.has(prop) ? v + 'px' : v}; `
diff --git a/bindings/node/package.json b/bindings/node/package.json
index 30ce3ab..654f851 100644
--- a/bindings/node/package.json
+++ b/bindings/node/package.json
@@ -1,9 +1,12 @@
{
"name": "@blender-ui/native",
- "version": "0.1.0",
+ "version": "0.2.0",
"description": "Blender's UI from JavaScript: native windows (CPU or Direct3D 11), HTML elements, CSS and Tailwind classes, signals. Node.js and Bun, through napi-rs.",
"main": "index.js",
"types": "index.d.ts",
+ "bin": {
+ "bui": "cli.js"
+ },
"exports": {
".": {
"types": "./index.d.ts",
@@ -16,7 +19,9 @@
"index.js",
"signals.js",
"index.d.ts",
+ "cli.js",
"blenderui.*.node",
+ "bui-runtime.*",
"README.md",
"LICENSE"
],
diff --git a/bindings/node/scripts/build.js b/bindings/node/scripts/build.js
index acee233..04b7f7f 100644
--- a/bindings/node/scripts/build.js
+++ b/bindings/node/scripts/build.js
@@ -1,5 +1,7 @@
-// Builds the native addon (bindings/rust/blenderui-node) and copies it here
-// as blenderui.<platform>-<arch>.node. `--debug` for a debug build.
+// Builds the native addon (bindings/rust/blenderui-node) and the QuickJS
+// runtime (bindings/rust/blenderui-qjs, `bui-runtime`) and copies them here
+// as blenderui.<platform>-<arch>.node and bui-runtime.<platform>-<arch>[.exe].
+// `--debug` for a debug build.
'use strict'
const { execFileSync } = require('node:child_process')
const fs = require('node:fs')
@@ -7,10 +9,14 @@ const path = require('node:path')
const debug = process.argv.includes('--debug')
const rust = path.resolve(__dirname, '../../rust')
-const args = ['build', '-p', 'blenderui-node', ...(debug ? [] : ['--release'])]
+const args = ['build', '-p', 'blenderui-node', '-p', 'blenderui-qjs', ...(debug ? [] : ['--release'])]
execFileSync('cargo', args, { cwd: rust, stdio: 'inherit' })
+const target = path.join(rust, 'target', debug ? 'debug' : 'release')
+const tag = `${process.platform}-${process.arch}`
+const exe = process.platform === 'win32' ? '.exe' : ''
const lib = { win32: 'blenderui_node.dll', darwin: 'libblenderui_node.dylib' }[process.platform] ?? 'libblenderui_node.so'
-const from = path.join(rust, 'target', debug ? 'debug' : 'release', lib)
-const to = path.join(__dirname, '..', `blenderui.${process.platform}-${process.arch}.node`)
-fs.copyFileSync(from, to)
-console.log(`wrote ${path.relative(process.cwd(), to)}`)
+for (const [from, to] of [[lib, `blenderui.${tag}.node`], [`bui-runtime${exe}`, `bui-runtime.${tag}${exe}`]]) {
+ const dest = path.join(__dirname, '..', to)
+ fs.copyFileSync(path.join(target, from), dest)
+ console.log(`wrote ${path.relative(process.cwd(), dest)}`)
+}
diff --git a/bindings/node/test/fixtures/react-app.jsx b/bindings/node/test/fixtures/react-app.jsx
new file mode 100644
index 0000000..d8713c2
--- /dev/null
+++ b/bindings/node/test/fixtures/react-app.jsx
@@ -0,0 +1,51 @@
+/** @jsxImportSource @blender-ui/react */
+// A headless React app that checks itself: rendering, a click, signals,
+// re-rendering on a read, and a screenshot. Prints one JSON line.
+import { render, useState } from '@blender-ui/react'
+
+let renders = 0
+function Counter () {
+ renders++
+ const [count, setCount] = useState(0)
+ const [color, setColor] = useState('#0000ff')
+ return (
+ <main style={{ margin: 0 }}>
+ <div id="btn" style={{ width: 80, height: 30, backgroundColor: color }}
+ onClick={() => { setCount(c => c + 1); setColor('#00ff00') }}>count {count}</div>
+ <Many count={count} />
+ </main>
+ )
+}
+
+// reads the signal while rendering: re-renders when it changes
+function Many ({ count }) {
+ return count.value > 1 ? <p id="many">many</p> : null
+}
+
+const { app, window } = render(<Counter />, { width: 200, height: 120, headless: true })
+window.body.style = 'margin: 0; background: #000'
+const tick = (ms = 40) => new Promise(r => setTimeout(r, ms))
+const find = (id) => [...window._nodes.values()].find(n => n.getAttribute?.('id') === id)
+const pixel = (s, x, y) => { const i = (y * s.width + x) * 4; return [s.data[i], s.data[i + 1], s.data[i + 2]] }
+
+;(async () => {
+ await tick()
+ const before = await window.screenshot()
+ window.click(10, 10)
+ await tick()
+ const once = find('btn').textContent
+ const rendersAfterOne = renders
+ window.click(10, 10)
+ await tick()
+ const after = await window.screenshot()
+ console.log(JSON.stringify({
+ runtime: globalThis.__BUI_NATIVE__ ? 'quickjs' : (typeof Bun !== 'undefined' ? 'bun' : 'node'),
+ before: pixel(before, 40, 15),
+ after: pixel(after, 40, 15),
+ once,
+ rendersAfterOne,
+ many: Boolean(find('many')),
+ renders,
+ }))
+ app.quit()
+})()
diff --git a/bindings/node/test/runtime.test.js b/bindings/node/test/runtime.test.js
new file mode 100644
index 0000000..e62699c
--- /dev/null
+++ b/bindings/node/test/runtime.test.js
@@ -0,0 +1,55 @@
+'use strict'
+// `bui build` / `bui run`: the same React app as a QuickJS executable, a Bun
+// executable, and on the QuickJS runtime directly.
+const test = require('node:test')
+const assert = require('node:assert')
+const fs = require('node:fs')
+const os = require('node:os')
+const path = require('node:path')
+const { spawnSync } = require('node:child_process')
+
+const cli = path.join(__dirname, '..', 'cli.js')
+const app = path.join(__dirname, 'fixtures', 'react-app.jsx')
+const hasBun = spawnSync('bun', ['--version'], { shell: true }).status === 0
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bui-test-'))
+test.after(() => fs.rmSync(dir, { recursive: true, force: true }))
+
+function check (stdout, runtime) {
+ const line = stdout.trim().split('\n').pop()
+ const r = JSON.parse(line)
+ assert.strictEqual(r.runtime, runtime)
+ assert.deepStrictEqual(r.before, [0, 0, 255], 'rendered')
+ assert.deepStrictEqual(r.after, [0, 255, 0], 'a signal prop updated after the click')
+ assert.strictEqual(r.once, 'count 1', 'a signal child updated')
+ assert.strictEqual(r.rendersAfterOne, 1, 'no re-render for signals passed on')
+ assert.strictEqual(r.many, true, 'a render that read the signal re-rendered')
+ return r
+}
+
+function exec (file, args = []) {
+ const r = spawnSync(file, args, { encoding: 'utf8', env: { ...process.env, BUI_HEADLESS: '1' }, timeout: 60000 })
+ assert.strictEqual(r.status, 0, `${file} failed: ${r.stderr}`)
+ return r.stdout
+}
+
+test('bui build: a QuickJS executable of a few MB runs the React app', { skip: !hasBun }, () => {
+ const out = path.join(dir, `react-app${process.platform === 'win32' ? '.exe' : ''}`)
+ const b = spawnSync(process.execPath, [cli, 'build', app, '-o', out, '--console'], { encoding: 'utf8' })
+ assert.strictEqual(b.status, 0, b.stderr)
+ const size = fs.statSync(out).size / 1048576
+ assert.ok(size < 8, `small: ${size.toFixed(1)} MB`)
+ check(exec(out), 'quickjs')
+})
+
+test('bui run: the same app on the QuickJS runtime, no executable', { skip: !hasBun }, () => {
+ const r = spawnSync(process.execPath, [cli, 'run', app], { encoding: 'utf8', env: { ...process.env, BUI_HEADLESS: '1' } })
+ assert.strictEqual(r.status, 0, r.stderr)
+ check(r.stdout, 'quickjs')
+})
+
+test('bui build --bun: a Bun executable runs it too', { skip: !hasBun }, () => {
+ const out = path.join(dir, `react-app-bun${process.platform === 'win32' ? '.exe' : ''}`)
+ const b = spawnSync(process.execPath, [cli, 'build', app, '-o', out, '--bun', '--console'], { encoding: 'utf8' })
+ assert.strictEqual(b.status, 0, b.stderr)
+ check(exec(out), 'bun')
+})
diff --git a/bindings/package-lock.json b/bindings/package-lock.json
index a43ea6d..cf1483d 100644
--- a/bindings/package-lock.json
+++ b/bindings/package-lock.json
@@ -12,7 +12,7 @@
},
"node": {
"name": "@blender-ui/native",
- "version": "0.1.0",
+ "version": "0.2.0",
"cpu": [
"x64"
],
@@ -20,6 +20,9 @@
"os": [
"win32"
],
+ "bin": {
+ "bui": "cli.js"
+ },
"engines": {
"node": ">=18"
}
@@ -67,7 +70,7 @@
"version": "0.1.0",
"license": "GPL-2.0-or-later",
"dependencies": {
- "@blender-ui/native": "^0.1.0",
+ "@blender-ui/native": "^0.2.0",
"react-reconciler": "0.34.0"
},
"devDependencies": {
diff --git a/bindings/react/README.md b/bindings/react/README.md
index 0881c0f..cfb1824 100644
--- a/bindings/react/README.md
+++ b/bindings/react/README.md
@@ -1,16 +1,25 @@
# @blender-ui/react
-A React 19 renderer for [BUI](https://github.com/ppmpreetham/BUI): JSX
-rendered with Blender's UI toolkit in native windows, with no browser and no
-Electron. It runs on Node.js and Bun. React's hooks are exported by their own
-names, with signals underneath, so a state change can update a single node
-without re-rendering its component.
+[![npm](https://img.shields.io/npm/v/@blender-ui/react)](https://www.npmjs.com/package/@blender-ui/react)
+[![license](https://img.shields.io/npm/l/@blender-ui/react)](https://github.com/ppmpreetham/BUI/blob/main/LICENSE)
+
+React 19 for the desktop, drawn by [BUI](https://github.com/ppmpreetham/BUI),
+Blender's UI toolkit. You write JSX with HTML elements, CSS and Tailwind
+classes, and BUI renders it in native windows on the CPU or the GPU. There's
+no browser, no webview and no Electron.
+
+- **React's hooks, by React's names, holding signals.** A change updates the
+ one node that shows it, without re-rendering the component.
+- **Node.js and Bun.**
+- **One small executable:** `bui build` makes an app of about 5 MB that
+ reaches its first frame in about 70 ms.
```sh
-npm install @blender-ui/react react
+npm install @blender-ui/react react # or: bun add @blender-ui/react react
```
```jsx
+/** @jsxImportSource @blender-ui/react */
import { render, useState } from '@blender-ui/react'
function Counter () {
@@ -26,24 +35,29 @@ function Counter () {
render(<Counter />, { title: 'Counter', width: 360, height: 200, gpu: true })
```
-Set `"jsxImportSource": "@blender-ui/react"` in your `tsconfig.json`, or in
-your bundler's JSX options. This does two things: components re-render when
-a signal they read while rendering changes, and in TypeScript, host-element
-props accept signals.
+```sh
+bun app.jsx # run it (Bun reads JSX as is)
+npx bui build app.jsx # ship it: app.exe, one ~5 MB file
+```
+
+Put `"jsxImportSource": "@blender-ui/react"` in your `tsconfig.json`, or in
+your bundler's JSX options; the `/** @jsxImportSource */` comment works per
+file. Without JSX, use this package's `createElement`.
## Hooks
The hooks have React's names, arguments and timing, but the state they hold
is a **signal**:
-- **Passed as a prop or child** (`<span>{count}</span>`,
- `style={styleMemo}`): a change updates that node. The component doesn't
- re-render.
+- **Passed into JSX** (`<span>{count}</span>`, `style={styleMemo}`,
+ `style={{ color: colorSignal }}`): a change updates that node. The
+ component doesn't re-render.
- **Read while rendering** (`count.value`; in plain JavaScript also
`count + 1` or `count > 5`): the component re-renders when it changes, as
- with React. TypeScript needs `.value` for arithmetic.
-- **Conditions and `===` need `.value`.** A signal is an object, so it's always
- truthy: write `{isPending.value && <Spinner />}` and `count.value === 0`.
+ with React.
+- **Conditions and `===` need `.value`.** A signal is an object, so it's
+ always truthy: write `{isPending.value && <Spinner />}` and
+ `count.value === 0`. TypeScript also needs `.value` for arithmetic.
| Hook | Returns |
|---|---|
@@ -52,7 +66,7 @@ is a **signal**:
| `useMemo(fn, deps?)` | a memo, recomputed when the signals it reads change |
| `useRef(v)` | `{ current }`, observable by effects and memos |
| `useCallback(fn, deps?)` / `useEffectEvent(fn)` | a function whose calls are batched |
-| `useEffect` / `useLayoutEffect` / `useInsertionEffect` | React's timing and deps, plus a re-run when signals the effect read change |
+| `useEffect` / `useLayoutEffect` / `useInsertionEffect` | React's timing and deps, plus a re-run when the signals the effect read change |
| `useSyncExternalStore(subscribe, get)` | a signal following the store |
| `useTransition()` | `[isPending, startTransition]`; signal updates run after urgent ones |
| `useDeferredValue(value, initial?)` | a signal that follows `value` at low priority |
@@ -67,35 +81,85 @@ Also exported:
- **Plain signals:** `signal`, `computed`, `effect`, `batch`, `untrack`,
`startTransition`.
-Want React's plain-value hooks instead? Import them from `react`; they work
-here too.
+React's plain-value hooks still work: import them from `react`.
-Every hook is built from React's public hooks. A test suite runs each one
-beside React's original, in development and production builds and under
-StrictMode. The suite fails when a new React release adds a hook this package
-doesn't cover yet.
+Every hook is built from React's public hooks. A conformance suite runs each
+one beside React's original, in development and production builds and under
+StrictMode. It fails when a React release adds a hook this package doesn't
+cover yet.
## The renderer
- **Host components are HTML elements.** `className` takes Tailwind classes,
- `style` takes strings, objects or signals. `onClick`, `onChange` and the
- other mouse and keyboard handlers work. Events bubble, and
+ `style` takes strings, objects or signals, and the mouse, keyboard and form
+ events work (`onClick`, `onChange` ...). Events bubble, and
`stopPropagation` works.
- **One native batch per commit:** only what changed crosses to BUI's UI
thread.
-- **React 19.3 features:** `<Suspense>`, `<Activity>`, transitions, actions,
- and `<ViewTransition>` (it commits, without animating).
+- **React 19.3:** `<Suspense>`, `<Activity>`, transitions, actions and
+ `<ViewTransition>`, which commits without animating.
- **API:** `render(element, options)` opens a window. `createRoot(window)`
- renders into a window you opened with
- [`@blender-ui/native`](https://www.npmjs.com/package/@blender-ui/native).
- `act(fn)` is for tests.
+ renders into one you opened with
+ [`@blender-ui/native`](https://www.npmjs.com/package/@blender-ui/native),
+ and `act(fn)` is for tests.
+ - Window options: `title`, `width`, `height`, `resizable`, `gpu`,
+ `headless`.
+
+## Standalone apps
+
+`bui` comes with this package, through `@blender-ui/native`:
+
+```sh
+npx bui build app.jsx # app.exe: BUI + embedded QuickJS, ~5 MB
+npx bui build app.jsx --bun # app.exe: Bun, with Node's APIs and a JIT, ~115 MB
+npx bui run app.jsx # run on the QuickJS runtime, no build
+```
+
+Options:
+
+- `-o <file>`: the output file.
+- `--console`: keep a console window for logs.
+- `--dev`: React's development build.
+
+Bundling uses [Bun](https://bun.sh), so it must be installed.
+
+The default build runs your app on QuickJS, a small JavaScript engine embedded
+in BUI. It has no Node modules (`fs` and the like) and no JIT, so keep large
+lists updating through signals, or use `--bun`.
+
+## Benchmarks
+
+Ryzen 7 5800U laptop, Windows 11, GPU renderer, React's production build.
+The full method is in the [guide](https://github.com/ppmpreetham/BUI/blob/main/docs/javascript.md#performance).
+
+**Startup:** a small React app that quits at its first frame; medians of 12
+launches.
+
+| | First frame | Launch to exit | RAM | Size |
+|---|---:|---:|---:|---:|
+| **`bui build`** (QuickJS) | **68 ms** | **104 ms** | **19 MB** | **4.9 MB** |
+| `bui build --bun` | 79 ms | 147 ms | 35 MB | 114 MB |
+| `bun app.js` | 80 ms | 152 ms | 35 MB | |
+| `node app.js` | 108 ms | 187 ms | 45 MB | |
+
+**Animation:** 3,000 cells, one changing per frame.
+
+- **With signals:** the changing values are signals, so the grid renders once.
+- **With state:** the grid re-renders every frame.
+
+| 3,000 cells | FPS | CPU per frame | RAM |
+|---|---:|---:|---:|
+| Bun: with signals / with state | 58.4 / 55.8 | 13.3 / 20.8 ms | 85 / 118 MB |
+| Node: with signals / with state | 56.7 / 54.8 | 14.0 / 18.9 ms | 93 / 121 MB |
+| QuickJS: with signals / with state | 58.7 / 19.7 | 14.9 / 51.0 ms | 61 / 67 MB |
+| *Rust, for reference* | 59.6 | 12.0 ms | 43 MB |
## Requirements
-- Windows x64 for native windows; `headless: true` renders off-screen.
-- Node.js 18 or newer, or Bun.
-- React 19.3.
+- **Windows x64** for native windows; `headless: true` renders off-screen.
+- **Node.js 18** or newer, or Bun.
+- **React 19.3.**
-Guide, benchmarks and internals:
-[docs/javascript.md](https://github.com/ppmpreetham/BUI/blob/main/docs/javascript.md).
-License: GPL-2.0-or-later.
+Guide: [docs/javascript.md](https://github.com/ppmpreetham/BUI/blob/main/docs/javascript.md) ·
+Source: [github.com/ppmpreetham/BUI](https://github.com/ppmpreetham/BUI) ·
+License: GPL-2.0-or-later
diff --git a/bindings/react/package.json b/bindings/react/package.json
index 86c0245..2a67527 100644
--- a/bindings/react/package.json
+++ b/bindings/react/package.json
@@ -40,7 +40,7 @@
"node": ">=18"
},
"dependencies": {
- "@blender-ui/native": "^0.1.0",
+ "@blender-ui/native": "^0.2.0",
"react-reconciler": "0.34.0"
},
"peerDependencies": {
diff --git a/bindings/rust/Cargo.lock b/bindings/rust/Cargo.lock
index 86307c8..df24ccb 100644
--- a/bindings/rust/Cargo.lock
+++ b/bindings/rust/Cargo.lock
@@ -17,6 +17,12 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "allocator-api2"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -42,6 +48,13 @@ dependencies = [
"taffy",
]
+[[package]]
+name = "blenderui-jsview"
+version = "0.1.0"
+dependencies = [
+ "blenderui",
+]
+
[[package]]
name = "blenderui-macros"
version = "0.1.0"
@@ -54,11 +67,21 @@ name = "blenderui-node"
version = "0.1.0"
dependencies = [
"blenderui",
+ "blenderui-jsview",
"napi",
"napi-build",
"napi-derive",
]
+[[package]]
+name = "blenderui-qjs"
+version = "0.1.0"
+dependencies = [
+ "blenderui",
+ "blenderui-jsview",
+ "rquickjs",
+]
+
[[package]]
name = "blenderui-sys"
version = "0.1.0"
@@ -123,6 +146,12 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "equivalent"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
+
[[package]]
name = "fdeflate"
version = "0.3.7"
@@ -149,6 +178,23 @@ dependencies = [
"zlib-rs",
]
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash",
+]
+
[[package]]
name = "libloading"
version = "0.8.9"
@@ -314,6 +360,44 @@ version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+[[package]]
+name = "relative-path"
+version = "2.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38540a682c6e9bca04a8bca9e5ec5a6ba168dfbb04c9998fe517a9befb92eb68"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "rquickjs"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0a22bf72f515cc4189dd7c63d016f6de92a11eee98ddf7dd64794198f6eb34e"
+dependencies = [
+ "rquickjs-core",
+]
+
+[[package]]
+name = "rquickjs-core"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6657979a24d543e5fc66f32cef2f47ca82ce8eb55cec5f7d59a12b7b570bbf24"
+dependencies = [
+ "hashbrown",
+ "relative-path",
+ "rquickjs-sys",
+]
+
+[[package]]
+name = "rquickjs-sys"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cee271d0eeba64f0915b846cb7ae02e16faf3dfdffdca91731101d9d30fe3423"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "semver"
version = "1.0.28"
diff --git a/bindings/rust/Cargo.toml b/bindings/rust/Cargo.toml
index ccd79cf..0187ff7 100644
--- a/bindings/rust/Cargo.toml
+++ b/bindings/rust/Cargo.toml
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
-members = ["blenderui-sys", "blenderui-tailwind", "blenderui-macros", "blenderui", "blenderui-node"]
+members = ["blenderui-sys", "blenderui-tailwind", "blenderui-macros", "blenderui", "blenderui-jsview", "blenderui-node", "blenderui-qjs"]
exclude = ["bench"]
[workspace.package]
diff --git a/bindings/rust/blenderui-jsview/Cargo.toml b/bindings/rust/blenderui-jsview/Cargo.toml
new file mode 100644
index 0000000..1489544
--- /dev/null
+++ b/bindings/rust/blenderui-jsview/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "blenderui-jsview"
+description = "The JavaScript view of a blenderui window, shared by the Node.js addon and the QuickJS runtime"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+repository.workspace = true
+rust-version.workspace = true
+publish = false
+
+[dependencies]
+blenderui = { path = "../blenderui" }
diff --git a/bindings/rust/blenderui-jsview/src/lib.rs b/bindings/rust/blenderui-jsview/src/lib.rs
new file mode 100644
index 0000000..f62a2e3
--- /dev/null
+++ b/bindings/rust/blenderui-jsview/src/lib.rs
@@ -0,0 +1,574 @@
+//! The JavaScript view of a BUI window, shared by the JavaScript runtimes
+//! (`blenderui-node`: Node.js / Bun through napi-rs; `blenderui-qjs`: the
+//! embedded QuickJS runtime).
+//!
+//! JavaScript keeps a retained tree and sends what changed as ops (an `i32`
+//! array plus a string table); [`JsView`] applies them to its mirror of the
+//! tree and renders it. Events go back through a [`Sink`]. The functions at
+//! the end run the window operations both runtimes expose (open, commit,
+//! frame, close, screenshot, bounds, click) on the UI thread.
+//!
+//! SPDX-License-Identifier: GPL-2.0-or-later
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use blenderui::prelude::*;
+
+/// An event from a window (`kind`: click, mousedown, mouseup, mousemove,
+/// mouseenter, mouseleave, wheel, keydown, keyup, change, input, frame,
+/// close).
+#[derive(Clone, Debug, Default)]
+pub struct Event {
+ pub kind: String,
+ pub window: u32,
+ /// The node whose listener fired.
+ pub target: u32,
+ pub x: f64,
+ pub y: f64,
+ /// 0 left, 1 middle, 2 right (DOM numbering).
+ pub button: u32,
+ pub click_count: u32,
+ pub delta: f64,
+ pub key: Option<String>,
+ pub key_char: Option<String>,
+ pub value: Option<String>,
+ pub checked: bool,
+ pub number: f64,
+ pub shift: bool,
+ pub ctrl: bool,
+ pub alt: bool,
+}
+
+/// Where a window's events go (called on the UI thread).
+pub type Sink = Arc<dyn Fn(Event)>;
+
+/// A window as JavaScript opens it.
+#[derive(Clone, Debug, Default)]
+pub struct WindowConfig {
+ pub title: Option<String>,
+ pub width: Option<f64>,
+ pub height: Option<f64>,
+ pub resizable: Option<bool>,
+ pub gpu: Option<bool>,
+}
+
+/// A layout box, logical pixels.
+#[derive(Clone, Copy, Debug)]
+pub struct Rect {
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
+
+/// Ops (`commit`): opcode, then its arguments; `s` = index into the strings.
+pub mod op {
+ pub const CREATE: i32 = 0; // id, s(tag)
+ pub const TEXT: i32 = 1; // id, s(text)
+ pub const SET_ATTR: i32 = 2; // id, s(name), s(value)
+ pub const REMOVE_ATTR: i32 = 3; // id, s(name)
+ pub const APPEND: i32 = 4; // parent, child
+ pub const INSERT: i32 = 5; // parent, child, before
+ pub const REMOVE: i32 = 6; // parent, child
+ pub const SET_TEXT: i32 = 7; // id, s(text)
+ pub const LISTEN: i32 = 8; // id, event bits (replaces)
+ pub const FREE: i32 = 9; // id
+}
+
+/// Event bits (`LISTEN`), matching `bindings/node/index.js`.
+pub mod ev {
+ pub const CLICK: u32 = 1;
+ pub const MOUSE_DOWN: u32 = 2;
+ pub const MOUSE_UP: u32 = 4;
+ pub const MOUSE_MOVE: u32 = 8;
+ pub const HOVER: u32 = 16;
+ pub const WHEEL: u32 = 32;
+ pub const KEY_DOWN: u32 = 64;
+ pub const KEY_UP: u32 = 128;
+ pub const CHANGE: u32 = 256;
+ pub const INPUT: u32 = 512;
+}
+
+// ==========================================================================
+// The retained tree (UI thread)
+
+struct JsNode {
+ tag: &'static str,
+ key: SharedString,
+ text: Option<SharedString>,
+ attrs: Vec<(SharedString, SharedString)>,
+ /// The `style` attribute, parsed once when set (renders reuse it).
+ style: Option<Box<[blenderui::css::Decl]>>,
+ children: Vec<u32>,
+ events: u32,
+}
+
+/// `style="..."` parsed into declarations whose values are shared.
+fn parse_style(css: &str) -> Box<[blenderui::css::Decl]> {
+ blenderui::css::parse_declarations(css).into_iter().map(|d| blenderui::css::Decl {
+ value: blenderui::css::Value::Shared(std::sync::Arc::from(&*d.value)),
+ ..d
+ }).collect()
+}
+
+/// Hashes a node id as itself: ids are unique, increasing integers.
+#[derive(Default, Clone, Copy)]
+struct IdHasher(u64);
+
+impl std::hash::Hasher for IdHasher {
+ fn finish(&self) -> u64 {
+ self.0
+ }
+ fn write(&mut self, bytes: &[u8]) {
+ for &b in bytes {
+ self.0 = (self.0 << 8) | u64::from(b);
+ }
+ }
+ fn write_u32(&mut self, n: u32) {
+ self.0 = u64::from(n);
+ }
+}
+
+type NodeMap = HashMap<u32, JsNode, std::hash::BuildHasherDefault<IdHasher>>;
+
+/// One window's tree; node ids are per window, never reused (root = 0).
+struct JsView {
+ window: u32,
+ nodes: NodeMap,
+ sink: Sink,
+ /// JS asked for an animation frame: tell it when this one renders.
+ raf: bool,
+ /// The next vsync frame is already scheduled (changes just wait for it).
+ frame_scheduled: bool,
+}
+
+/// Tag names as the `&'static str` elements need: HTML tags from the
+/// table, others interned once.
+fn intern_tag(tag: &str, custom: &mut HashMap<String, &'static str>) -> &'static str {
+ if let Some((t, _)) = blenderui::html::TAGS.iter().find(|(t, _)| *t == tag) {
+ return t;
+ }
+ *custom.entry(tag.to_string()).or_insert_with(|| Box::leak(tag.to_string().into_boxed_str()))
+}
+
+impl JsView {
+ fn node(&mut self, id: i32) -> Option<&mut JsNode> {
+ self.nodes.get_mut(&u32::try_from(id).ok()?)
+ }
+
+ fn put(&mut self, id: i32, n: JsNode) {
+ if let Ok(i) = u32::try_from(id) {
+ self.nodes.insert(i, n);
+ }
+ }
+
+ fn apply(&mut self, ops: &[i32], strings: &[String], tags: &mut HashMap<String, &'static str>) {
+ let s = |k: i32| strings.get(k as usize).map(String::as_str).unwrap_or("");
+ let mut i = 0;
+ while i < ops.len() {
+ let a = |k: usize| ops.get(i + k).copied().unwrap_or(-1);
+ match ops[i] {
+ op::CREATE => {
+ let tag = intern_tag(s(a(2)), tags);
+ self.put(a(1), JsNode { tag, key: format!("n{}", a(1)).into(), text: None, attrs: Vec::new(),
+ style: None, children: Vec::new(), events: 0 });
+ i += 3;
+ }
+ op::TEXT => {
+ let text = s(a(2)).to_string();
+ self.put(a(1), JsNode { tag: "", key: SharedString::Borrowed(""), text: Some(text.into()),
+ attrs: Vec::new(), style: None, children: Vec::new(), events: 0 });
+ i += 3;
+ }
+ op::SET_ATTR => {
+ let (name, value) = (s(a(2)).to_string(), s(a(3)).to_string());
+ if let Some(n) = self.node(a(1)) {
+ if name == "style" {
+ n.style = Some(parse_style(&value));
+ }
+ match n.attrs.iter_mut().find(|(k, _)| *k == name) {
+ Some((_, v)) => *v = value.into(),
+ None => n.attrs.push((name.into(), value.into())),
+ }
+ }
+ i += 4;
+ }
+ op::REMOVE_ATTR => {
+ let name = s(a(2));
+ if let Some(n) = self.node(a(1)) {
+ if name == "style" {
+ n.style = None;
+ }
+ n.attrs.retain(|(k, _)| k != name);
+ }
+ i += 3;
+ }
+ op::APPEND => {
+ let child = a(2) as u32;
+ if let Some(n) = self.node(a(1)) {
+ n.children.retain(|&c| c != child);
+ n.children.push(child);
+ }
+ i += 3;
+ }
+ op::INSERT => {
+ let (child, before) = (a(2) as u32, a(3) as u32);
+ if let Some(n) = self.node(a(1)) {
+ n.children.retain(|&c| c != child);
+ let at = n.children.iter().position(|&c| c == before).unwrap_or(n.children.len());
+ n.children.insert(at, child);
+ }
+ i += 4;
+ }
+ op::REMOVE => {
+ let child = a(2) as u32;
+ if let Some(n) = self.node(a(1)) {
+ n.children.retain(|&c| c != child);
+ }
+ i += 3;
+ }
+ op::SET_TEXT => {
+ let text = s(a(2)).to_string();
+ if let Some(n) = self.node(a(1)) {
+ n.text = Some(text.into());
+ }
+ i += 3;
+ }
+ op::LISTEN => {
+ let bits = a(2) as u32;
+ if let Some(n) = self.node(a(1)) {
+ n.events = bits;
+ }
+ i += 3;
+ }
+ op::FREE => {
+ if let Ok(k) = u32::try_from(a(1)) {
+ self.nodes.remove(&k);
+ }
+ i += 2;
+ }
+ _ => break, // malformed: stop rather than misread
+ }
+ }
+ }
+
+ fn build(&self, id: u32) -> AnyElement {
+ let Some(n) = self.nodes.get(&id) else {
+ return String::new().into_any_element();
+ };
+ if let Some(t) = &n.text {
+ return t.clone().into_any_element();
+ }
+ let mut d = Div::new(n.tag).key(n.key.clone());
+ for (k, v) in &n.attrs {
+ d = match &**k {
+ "class" | "className" => d.class(v.clone()),
+ "style" => d, // parsed: below
+ "id" => d.id(v.clone()),
+ _ => d.attr(k.clone(), v.clone()),
+ };
+ }
+ if let Some(s) = &n.style {
+ d = d.style(&s[..]);
+ }
+ if n.events != 0 {
+ d = self.listeners(d, id, n.events);
+ }
+ for &c in &n.children {
+ d = d.child(self.build(c));
+ }
+ d.into_any_element()
+ }
+
+ fn listeners(&self, mut d: Div, id: u32, bits: u32) -> Div {
+ let base = Event { window: self.window, target: id, ..Default::default() };
+ let send = {
+ let t = self.sink.clone();
+ move |e: Event| t(e)
+ };
+ fn mods(e: &mut Event, m: &Modifiers) {
+ (e.shift, e.ctrl, e.alt) = (m.shift, m.control, m.alt);
+ }
+ fn button(b: &MouseButton) -> u32 {
+ match b {
+ MouseButton::Left => 0,
+ MouseButton::Middle => 1,
+ MouseButton::Right => 2,
+ }
+ }
+ // The deepest listening node gets the event, and native propagation
+ // stops there: JavaScript bubbles it through its own tree, so
+ // stopPropagation() works. Hover (mouseenter / mouseleave) doesn't bubble.
+ macro_rules! on {
+ ($bit:expr, $method:ident $(($arg:expr))?, |$e:ident, $ev:ident| $body:block) => {
+ on!(@ true, $bit, $method $(($arg))?, |$e, $ev| $body)
+ };
+ (@ $stop:expr, $bit:expr, $method:ident $(($arg:expr))?, |$e:ident, $ev:ident| $body:block) => {
+ if bits & $bit != 0 {
+ let (send, base) = (send.clone(), base.clone());
+ d = d.$method($($arg,)? move |$ev, _, app| {
+ let mut $e = base.clone();
+ $body
+ send($e);
+ if $stop {
+ app.stop_propagation();
+ }
+ });
+ }
+ };
+ }
+ on!(ev::CLICK, on_click, |e, c| {
+ e.kind = "click".into();
+ (e.x, e.y) = (c.up.position.x.0 as f64, c.up.position.y.0 as f64);
+ e.button = button(&c.up.button);
+ e.click_count = c.down.click_count as u32;
+ mods(&mut e, &c.up.modifiers);
+ });
+ on!(ev::MOUSE_DOWN, on_any_mouse_down, |e, m| {
+ e.kind = "mousedown".into();
+ (e.x, e.y) = (m.position.x.0 as f64, m.position.y.0 as f64);
+ e.button = button(&m.button);
+ e.click_count = m.click_count as u32;
+ mods(&mut e, &m.modifiers);
+ });
+ for b in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] {
+ on!(ev::MOUSE_UP, on_mouse_up(b.clone()), |e, m| {
+ e.kind = "mouseup".into();
+ (e.x, e.y) = (m.position.x.0 as f64, m.position.y.0 as f64);
+ e.button = button(&m.button);
+ mods(&mut e, &m.modifiers);
+ });
+ }
+ on!(ev::MOUSE_MOVE, on_mouse_move, |e, m| {
+ e.kind = "mousemove".into();
+ (e.x, e.y) = (m.position.x.0 as f64, m.position.y.0 as f64);
+ mods(&mut e, &m.modifiers);
+ });
+ on!(@ false, ev::HOVER, on_hover, |e, h| {
+ e.kind = if *h { "mouseenter" } else { "mouseleave" }.into();
+ });
+ on!(ev::WHEEL, on_scroll_wheel, |e, w| {
+ e.kind = "wheel".into();
+ (e.x, e.y) = (w.position.x.0 as f64, w.position.y.0 as f64);
+ e.delta = w.delta as f64;
+ mods(&mut e, &w.modifiers);
+ });
+ on!(ev::KEY_DOWN, on_key_down, |e, k| {
+ e.kind = "keydown".into();
+ e.key = Some(k.keystroke.key.clone());
+ e.key_char = k.keystroke.key_char.clone();
+ mods(&mut e, &k.keystroke.modifiers);
+ });
+ on!(ev::KEY_UP, on_key_up, |e, k| {
+ e.kind = "keyup".into();
+ e.key = Some(k.keystroke.key.clone());
+ e.key_char = k.keystroke.key_char.clone();
+ mods(&mut e, &k.keystroke.modifiers);
+ });
+ on!(ev::CHANGE, on_change, |e, c| {
+ e.kind = "change".into();
+ (e.value, e.checked, e.number) = (Some(c.value.clone()), c.checked, c.number);
+ });
+ on!(ev::INPUT, on_input, |e, c| {
+ e.kind = "input".into();
+ (e.value, e.checked, e.number) = (Some(c.value.clone()), c.checked, c.number);
+ });
+ d
+ }
+}
+
+impl Render for JsView {
+ fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ self.frame_scheduled = false;
+ if self.raf {
+ // requestAnimationFrame: JS runs its callbacks while this frame
+ // presents, and the next vsync frame is scheduled now (as a
+ // browser does), so their changes make it into that frame
+ self.raf = false;
+ self.frame_scheduled = true;
+ window.request_animation_frame();
+ (self.sink)(Event { kind: "frame".into(), window: self.window, ..Default::default() });
+ }
+ self.build(0)
+ }
+}
+
+/// UI-thread state: JS window ids -> windows.
+#[derive(Default)]
+pub struct UiState {
+ windows: HashMap<u32, WindowHandle<JsView>>,
+ by_native: HashMap<usize, u32>,
+ tags: HashMap<String, &'static str>,
+}
+
+impl JsView {
+ /// A view of window `window` (JavaScript's id) with an empty `<body>` as node 0.
+ pub fn new(window: u32, sink: Sink) -> JsView {
+ let mut v = JsView { window, nodes: NodeMap::default(), sink, raf: false, frame_scheduled: false };
+ v.put(0, JsNode { tag: "body", key: "n0".into(), text: None, attrs: Vec::new(),
+ style: None, children: Vec::new(), events: 0 });
+ v
+ }
+}
+
+// ==========================================================================
+// Window operations (UI thread)
+
+/// Set up the UI-thread state; `sink` also gets `close` events.
+pub fn init(cx: &mut App, sink: Sink) {
+ cx.set_global(UiState::default());
+ cx.set_global(CloseSink(sink));
+ cx.on_window_closed(|id, cx| {
+ let Some(w) = cx.global::<UiState>().by_native.get(&id.0).copied() else { return };
+ let st = cx.global_mut::<UiState>();
+ st.windows.remove(&w);
+ st.by_native.remove(&id.0);
+ let sink = cx.global::<CloseSink>().0.clone();
+ sink(Event { kind: "close".into(), window: w, ..Default::default() });
+ });
+}
+
+struct CloseSink(Sink);
+
+/// Open window `id` (chosen by JavaScript); its events go to `sink`.
+pub fn open_window(cx: &mut App, id: u32, config: WindowConfig, sink: Sink) {
+ let opts = blenderui::WindowOptions {
+ window_bounds: Some(WindowBounds::Windowed(Bounds {
+ origin: point(px(0.0), px(0.0)),
+ size: size(px(config.width.unwrap_or(800.0) as f32), px(config.height.unwrap_or(600.0) as f32)),
+ })),
+ titlebar: config.title.map(|t| TitlebarOptions { title: Some(t.into()) }),
+ is_resizable: config.resizable,
+ gpu: config.gpu,
+ ..Default::default()
+ };
+ let handle = cx.open_window(opts, |_, cx| cx.new(|_| JsView::new(id, sink)));
+ if let Ok(handle) = handle {
+ let st = cx.global_mut::<UiState>();
+ st.by_native.insert(handle.id.0, id);
+ st.windows.insert(id, handle);
+ }
+}
+
+/// Apply a batch of ops to window `window` and re-render it: right away, or
+/// (`animated`, during requestAnimationFrame) on the next vsync.
+pub fn commit(cx: &mut App, window: u32, ops: &[i32], strings: &[String], animated: bool) {
+ let Some(handle) = cx.global::<UiState>().windows.get(&window).cloned() else { return };
+ let mut tags = std::mem::take(&mut cx.global_mut::<UiState>().tags);
+ handle.update(cx, |v, w, _| {
+ v.apply(ops, strings, &mut tags);
+ if !animated {
+ w.refresh(); // this window only
+ } else if !v.frame_scheduled {
+ v.frame_scheduled = true;
+ w.request_animation_frame();
+ }
+ });
+ cx.global_mut::<UiState>().tags = tags;
+}
+
+/// Send a `frame` event when window `window` next renders (vsync).
+pub fn request_frame(cx: &mut App, window: u32) {
+ if let Some(handle) = cx.global::<UiState>().windows.get(&window).cloned() {
+ handle.update(cx, |v, w, _| {
+ v.raf = true;
+ if !v.frame_scheduled {
+ v.frame_scheduled = true;
+ w.request_animation_frame();
+ }
+ });
+ }
+}
+
+pub fn close_window(cx: &mut App, window: u32) {
+ let st = cx.global_mut::<UiState>();
+ if let Some(h) = st.windows.remove(&window) {
+ st.by_native.remove(&h.id.0);
+ cx.close_window(h.id);
+ }
+}
+
+/// How many windows are open.
+pub fn window_count(cx: &App) -> usize {
+ cx.try_global::<UiState>().map_or(0, |s| s.windows.len())
+}
+
+/// Close every window.
+pub fn close_all(cx: &mut App) {
+ let ids: Vec<WindowId> = cx.global::<UiState>().windows.values().map(|h| h.id).collect();
+ for id in ids {
+ cx.close_window(id);
+ }
+ let st = cx.global_mut::<UiState>();
+ st.windows.clear();
+ st.by_native.clear();
+}
+
+/// Render window `window`: `(width, height, RGBA bytes)` in device pixels.
+pub fn screenshot(cx: &mut App, window: u32) -> Option<(u32, u32, Vec<u8>)> {
+ let handle = cx.global::<UiState>().windows.get(&window).cloned()?;
+ let (w, h, px) = cx.draw(handle.id);
+ let mut rgba = Vec::with_capacity(px.len() * 4);
+ for p in px {
+ rgba.extend_from_slice(&[(p >> 16) as u8, (p >> 8) as u8, p as u8, 255]);
+ }
+ Some((w as u32, h as u32, rgba))
+}
+
+/// Bounds of node `node` of window `window`, after rendering it.
+pub fn bounds(cx: &mut App, window: u32, node: u32) -> Option<Rect> {
+ let h = cx.global::<UiState>().windows.get(&window).cloned()?;
+ cx.draw(h.id);
+ cx.element_bounds(h.id, &format!("n{node}")).map(|b| Rect {
+ x: b.origin.x as f64,
+ y: b.origin.y as f64,
+ width: b.size.width as f64,
+ height: b.size.height as f64,
+ })
+}
+
+/// Click at (x, y) in window `window` (tests; logical pixels).
+pub fn simulate_click(cx: &mut App, window: u32, x: f64, y: f64) {
+ if let Some(h) = cx.global::<UiState>().windows.get(&window).cloned() {
+ cx.simulate_click(h.id, x as f32, y as f32);
+ }
+}
+
+// ==========================================================================
+// Measuring (benchmarks): the same counters as bench/common/measure.rs.
+
+#[cfg(windows)]
+#[link(name = "kernel32")]
+unsafe extern "system" {
+ fn GetCurrentProcess() -> isize;
+ fn QueryProcessCycleTime(p: isize, cycles: *mut u64) -> i32;
+}
+
+/// CPU cycles used by every thread of this process (Windows; otherwise None).
+pub fn process_cpu_cycles() -> Option<f64> {
+ #[cfg(windows)]
+ {
+ let mut c = 0u64;
+ // SAFETY: the current-process pseudo handle and a valid out pointer.
+ unsafe { QueryProcessCycleTime(GetCurrentProcess(), &mut c) };
+ Some(c as f64)
+ }
+ #[cfg(not(windows))]
+ {
+ None
+ }
+}
+
+/// The time-stamp counter (x86-64; otherwise None).
+pub fn timestamp_counter() -> Option<f64> {
+ #[cfg(target_arch = "x86_64")]
+ {
+ // SAFETY: rdtsc has no preconditions on x86-64.
+ Some(unsafe { core::arch::x86_64::_rdtsc() } as f64)
+ }
+ #[cfg(not(target_arch = "x86_64"))]
+ {
+ None
+ }
+}
diff --git a/bindings/rust/blenderui-node/Cargo.toml b/bindings/rust/blenderui-node/Cargo.toml
index a681bcc..f4545eb 100644
--- a/bindings/rust/blenderui-node/Cargo.toml
+++ b/bindings/rust/blenderui-node/Cargo.toml
@@ -13,6 +13,7 @@ crate-type = ["cdylib"]
[dependencies]
blenderui = { path = "../blenderui" }
+blenderui-jsview = { path = "../blenderui-jsview" }
napi = { version = "2.16", default-features = false, features = ["napi6"] }
napi-derive = "2.16"
diff --git a/bindings/rust/blenderui-node/src/lib.rs b/bindings/rust/blenderui-node/src/lib.rs
index 7235934..a600a1a 100644
--- a/bindings/rust/blenderui-node/src/lib.rs
+++ b/bindings/rust/blenderui-node/src/lib.rs
@@ -1,21 +1,21 @@
-//! Node.js bindings (napi-rs): BUI driven from JavaScript, GPUIX style.
+//! Node.js / Bun bindings (napi-rs): BUI driven from JavaScript, GPUIX style.
//!
-//! BUI runs on its own UI thread: Node's thread is never blocked, and an
-//! idle UI costs no CPU. JavaScript keeps a retained element tree and sends
-//! only what changed: per window and per tick, one `Int32Array` of ops plus
-//! a string table (no tree serialization, no per-node calls). The UI thread
-//! applies the ops to its mirror of the tree and re-renders; events come back
-//! through a thread-safe function.
+//! BUI runs on its own UI thread: the JavaScript thread is never blocked,
+//! and an idle UI costs no CPU. JavaScript keeps a retained element tree and
+//! sends only what changed: per window and per tick, one `Int32Array` of ops
+//! plus a string table. The UI thread applies them to its mirror of the tree
+//! (`blenderui-jsview`, shared with the QuickJS runtime) and re-renders;
+//! events come back through a thread-safe function.
//!
//! The JavaScript side lives in `bindings/node` (`@blender-ui/native`, with
//! `@blender-ui/react` on top).
//!
//! SPDX-License-Identifier: GPL-2.0-or-later
-use std::collections::HashMap;
-use std::sync::mpsc;
+use std::sync::{Arc, mpsc};
use blenderui::prelude::*;
+use blenderui_jsview as view;
use napi::bindgen_prelude::*;
use napi::threadsafe_function::{
ErrorStrategy, ThreadSafeCallContext, ThreadsafeFunction, ThreadsafeFunctionCallMode,
@@ -29,7 +29,7 @@ type Tsfn = ThreadsafeFunction<BuiEvent, ErrorStrategy::Fatal>;
// Values crossing the boundary
/// An event from a window (`kind`: click, mousedown, mouseup, mousemove,
-/// mouseenter, mouseleave, wheel, keydown, keyup, change, input, close).
+/// mouseenter, mouseleave, wheel, keydown, keyup, change, input, frame, close).
#[napi(object)]
#[derive(Clone, Default)]
pub struct BuiEvent {
@@ -53,6 +53,16 @@ pub struct BuiEvent {
pub alt: bool,
}
+impl From<view::Event> for BuiEvent {
+ fn from(e: view::Event) -> BuiEvent {
+ BuiEvent {
+ kind: e.kind, window: e.window, target: e.target, x: e.x, y: e.y, button: e.button,
+ click_count: e.click_count, delta: e.delta, key: e.key, key_char: e.key_char, value: e.value,
+ checked: e.checked, number: e.number, shift: e.shift, ctrl: e.ctrl, alt: e.alt,
+ }
+ }
+}
+
#[napi(object)]
pub struct AppOptions {
/// Draw on the GPU (Direct3D 11).
@@ -64,6 +74,7 @@ pub struct AppOptions {
}
#[napi(object)]
+#[derive(Clone)]
pub struct WindowConfig {
pub title: Option<String>,
pub width: Option<f64>,
@@ -80,348 +91,16 @@ pub struct Rect {
pub height: f64,
}
-/// Ops (`commit`): opcode, then its arguments; `s` = index into the strings.
-mod op {
- pub const CREATE: i32 = 0; // id, s(tag)
- pub const TEXT: i32 = 1; // id, s(text)
- pub const SET_ATTR: i32 = 2; // id, s(name), s(value)
- pub const REMOVE_ATTR: i32 = 3; // id, s(name)
- pub const APPEND: i32 = 4; // parent, child
- pub const INSERT: i32 = 5; // parent, child, before
- pub const REMOVE: i32 = 6; // parent, child
- pub const SET_TEXT: i32 = 7; // id, s(text)
- pub const LISTEN: i32 = 8; // id, event bits (replaces)
- pub const FREE: i32 = 9; // id
-}
-
-/// Event bits (`LISTEN`), matching `bindings/node/index.js`.
-mod ev {
- pub const CLICK: u32 = 1;
- pub const MOUSE_DOWN: u32 = 2;
- pub const MOUSE_UP: u32 = 4;
- pub const MOUSE_MOVE: u32 = 8;
- pub const HOVER: u32 = 16;
- pub const WHEEL: u32 = 32;
- pub const KEY_DOWN: u32 = 64;
- pub const KEY_UP: u32 = 128;
- pub const CHANGE: u32 = 256;
- pub const INPUT: u32 = 512;
+#[napi(object)]
+pub struct Screenshot {
+ pub width: u32,
+ pub height: u32,
+ /// RGBA, row-major.
+ pub data: Buffer,
}
// ==========================================================================
-// The retained tree (UI thread)
-
-struct JsNode {
- tag: &'static str,
- key: SharedString,
- text: Option<SharedString>,
- attrs: Vec<(SharedString, SharedString)>,
- /// The `style` attribute, parsed once when set (renders reuse it).
- style: Option<Box<[blenderui::css::Decl]>>,
- children: Vec<u32>,
- events: u32,
-}
-
-/// `style="..."` parsed into declarations whose values are shared.
-fn parse_style(css: &str) -> Box<[blenderui::css::Decl]> {
- blenderui::css::parse_declarations(css).into_iter().map(|d| blenderui::css::Decl {
- value: blenderui::css::Value::Shared(std::sync::Arc::from(&*d.value)),
- ..d
- }).collect()
-}
-
-/// Hashes a node id as itself: ids are unique, increasing integers.
-#[derive(Default, Clone, Copy)]
-struct IdHasher(u64);
-
-impl std::hash::Hasher for IdHasher {
- fn finish(&self) -> u64 {
- self.0
- }
- fn write(&mut self, bytes: &[u8]) {
- for &b in bytes {
- self.0 = (self.0 << 8) | u64::from(b);
- }
- }
- fn write_u32(&mut self, n: u32) {
- self.0 = u64::from(n);
- }
-}
-
-type NodeMap = HashMap<u32, JsNode, std::hash::BuildHasherDefault<IdHasher>>;
-
-/// One window's tree; node ids are per window, never reused (root = 0).
-struct JsView {
- window: u32,
- nodes: NodeMap,
- tsfn: Tsfn,
- /// JS asked for an animation frame: tell it when this one renders.
- raf: bool,
- /// The next vsync frame is already scheduled (changes just wait for it).
- frame_scheduled: bool,
-}
-
-/// Tag names as the `&'static str` elements need: HTML tags from the
-/// table, others interned once.
-fn intern_tag(tag: &str, custom: &mut HashMap<String, &'static str>) -> &'static str {
- if let Some((t, _)) = blenderui::html::TAGS.iter().find(|(t, _)| *t == tag) {
- return t;
- }
- *custom.entry(tag.to_string()).or_insert_with(|| Box::leak(tag.to_string().into_boxed_str()))
-}
-
-impl JsView {
- fn node(&mut self, id: i32) -> Option<&mut JsNode> {
- self.nodes.get_mut(&u32::try_from(id).ok()?)
- }
-
- fn put(&mut self, id: i32, n: JsNode) {
- if let Ok(i) = u32::try_from(id) {
- self.nodes.insert(i, n);
- }
- }
-
- fn apply(&mut self, ops: &[i32], strings: &[String], tags: &mut HashMap<String, &'static str>) {
- let s = |k: i32| strings.get(k as usize).map(String::as_str).unwrap_or("");
- let mut i = 0;
- while i < ops.len() {
- let a = |k: usize| ops.get(i + k).copied().unwrap_or(-1);
- match ops[i] {
- op::CREATE => {
- let tag = intern_tag(s(a(2)), tags);
- self.put(a(1), JsNode { tag, key: format!("n{}", a(1)).into(), text: None, attrs: Vec::new(),
- style: None, children: Vec::new(), events: 0 });
- i += 3;
- }
- op::TEXT => {
- let text = s(a(2)).to_string();
- self.put(a(1), JsNode { tag: "", key: SharedString::Borrowed(""), text: Some(text.into()),
- attrs: Vec::new(), style: None, children: Vec::new(), events: 0 });
- i += 3;
- }
- op::SET_ATTR => {
- let (name, value) = (s(a(2)).to_string(), s(a(3)).to_string());
- if let Some(n) = self.node(a(1)) {
- if name == "style" {
- n.style = Some(parse_style(&value));
- }
- match n.attrs.iter_mut().find(|(k, _)| *k == name) {
- Some((_, v)) => *v = value.into(),
- None => n.attrs.push((name.into(), value.into())),
- }
- }
- i += 4;
- }
- op::REMOVE_ATTR => {
- let name = s(a(2));
- if let Some(n) = self.node(a(1)) {
- if name == "style" {
- n.style = None;
- }
- n.attrs.retain(|(k, _)| k != name);
- }
- i += 3;
- }
- op::APPEND => {
- let child = a(2) as u32;
- if let Some(n) = self.node(a(1)) {
- n.children.retain(|&c| c != child);
- n.children.push(child);
- }
- i += 3;
- }
- op::INSERT => {
- let (child, before) = (a(2) as u32, a(3) as u32);
- if let Some(n) = self.node(a(1)) {
- n.children.retain(|&c| c != child);
- let at = n.children.iter().position(|&c| c == before).unwrap_or(n.children.len());
- n.children.insert(at, child);
- }
- i += 4;
- }
- op::REMOVE => {
- let child = a(2) as u32;
- if let Some(n) = self.node(a(1)) {
- n.children.retain(|&c| c != child);
- }
- i += 3;
- }
- op::SET_TEXT => {
- let text = s(a(2)).to_string();
- if let Some(n) = self.node(a(1)) {
- n.text = Some(text.into());
- }
- i += 3;
- }
- op::LISTEN => {
- let bits = a(2) as u32;
- if let Some(n) = self.node(a(1)) {
- n.events = bits;
- }
- i += 3;
- }
- op::FREE => {
- if let Ok(k) = u32::try_from(a(1)) {
- self.nodes.remove(&k);
- }
- i += 2;
- }
- _ => break, // malformed: stop rather than misread
- }
- }
- }
-
- fn build(&self, id: u32) -> AnyElement {
- let Some(n) = self.nodes.get(&id) else {
- return String::new().into_any_element();
- };
- if let Some(t) = &n.text {
- return t.clone().into_any_element();
- }
- let mut d = Div::new(n.tag).key(n.key.clone());
- for (k, v) in &n.attrs {
- d = match &**k {
- "class" | "className" => d.class(v.clone()),
- "style" => d, // parsed: below
- "id" => d.id(v.clone()),
- _ => d.attr(k.clone(), v.clone()),
- };
- }
- if let Some(s) = &n.style {
- d = d.style(&s[..]);
- }
- if n.events != 0 {
- d = self.listeners(d, id, n.events);
- }
- for &c in &n.children {
- d = d.child(self.build(c));
- }
- d.into_any_element()
- }
-
- fn listeners(&self, mut d: Div, id: u32, bits: u32) -> Div {
- let base = BuiEvent { window: self.window, target: id, ..Default::default() };
- let send = {
- let t = self.tsfn.clone();
- move |e: BuiEvent| {
- t.call(e, ThreadsafeFunctionCallMode::NonBlocking);
- }
- };
- fn mods(e: &mut BuiEvent, m: &Modifiers) {
- (e.shift, e.ctrl, e.alt) = (m.shift, m.control, m.alt);
- }
- fn button(b: &MouseButton) -> u32 {
- match b {
- MouseButton::Left => 0,
- MouseButton::Middle => 1,
- MouseButton::Right => 2,
- }
- }
- // The deepest listening node gets the event, and native propagation
- // stops there: JavaScript bubbles it through its own tree, so
- // stopPropagation() works. Hover (mouseenter / mouseleave) doesn't bubble.
- macro_rules! on {
- ($bit:expr, $method:ident $(($arg:expr))?, |$e:ident, $ev:ident| $body:block) => {
- on!(@ true, $bit, $method $(($arg))?, |$e, $ev| $body)
- };
- (@ $stop:expr, $bit:expr, $method:ident $(($arg:expr))?, |$e:ident, $ev:ident| $body:block) => {
- if bits & $bit != 0 {
- let (send, base) = (send.clone(), base.clone());
- d = d.$method($($arg,)? move |$ev, _, app| {
- let mut $e = base.clone();
- $body
- send($e);
- if $stop {
- app.stop_propagation();
- }
- });
- }
- };
- }
- on!(ev::CLICK, on_click, |e, c| {
- e.kind = "click".into();
- (e.x, e.y) = (c.up.position.x.0 as f64, c.up.position.y.0 as f64);
- e.button = button(&c.up.button);
- e.click_count = c.down.click_count as u32;
- mods(&mut e, &c.up.modifiers);
- });
- on!(ev::MOUSE_DOWN, on_any_mouse_down, |e, m| {
- e.kind = "mousedown".into();
- (e.x, e.y) = (m.position.x.0 as f64, m.position.y.0 as f64);
- e.button = button(&m.button);
- e.click_count = m.click_count as u32;
- mods(&mut e, &m.modifiers);
- });
- for b in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] {
- on!(ev::MOUSE_UP, on_mouse_up(b.clone()), |e, m| {
- e.kind = "mouseup".into();
- (e.x, e.y) = (m.position.x.0 as f64, m.position.y.0 as f64);
- e.button = button(&m.button);
- mods(&mut e, &m.modifiers);
- });
- }
- on!(ev::MOUSE_MOVE, on_mouse_move, |e, m| {
- e.kind = "mousemove".into();
- (e.x, e.y) = (m.position.x.0 as f64, m.position.y.0 as f64);
- mods(&mut e, &m.modifiers);
- });
- on!(@ false, ev::HOVER, on_hover, |e, h| {
- e.kind = if *h { "mouseenter" } else { "mouseleave" }.into();
- });
- on!(ev::WHEEL, on_scroll_wheel, |e, w| {
- e.kind = "wheel".into();
- (e.x, e.y) = (w.position.x.0 as f64, w.position.y.0 as f64);
- e.delta = w.delta as f64;
- mods(&mut e, &w.modifiers);
- });
- on!(ev::KEY_DOWN, on_key_down, |e, k| {
- e.kind = "keydown".into();
- e.key = Some(k.keystroke.key.clone());
- e.key_char = k.keystroke.key_char.clone();
- mods(&mut e, &k.keystroke.modifiers);
- });
- on!(ev::KEY_UP, on_key_up, |e, k| {
- e.kind = "keyup".into();
- e.key = Some(k.keystroke.key.clone());
- e.key_char = k.keystroke.key_char.clone();
- mods(&mut e, &k.keystroke.modifiers);
- });
- on!(ev::CHANGE, on_change, |e, c| {
- e.kind = "change".into();
- (e.value, e.checked, e.number) = (Some(c.value.clone()), c.checked, c.number);
- });
- on!(ev::INPUT, on_input, |e, c| {
- e.kind = "input".into();
- (e.value, e.checked, e.number) = (Some(c.value.clone()), c.checked, c.number);
- });
- d
- }
-}
-
-impl Render for JsView {
- fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
- self.frame_scheduled = false;
- if self.raf {
- // requestAnimationFrame: JS runs its callbacks while this frame
- // presents, and the next vsync frame is scheduled now (as a
- // browser does), so their changes make it into that frame
- self.raf = false;
- self.frame_scheduled = true;
- window.request_animation_frame();
- self.tsfn.call(BuiEvent { kind: "frame".into(), window: self.window, ..Default::default() },
- ThreadsafeFunctionCallMode::NonBlocking);
- }
- self.build(0)
- }
-}
-
-/// UI-thread state: JS window ids -> windows.
-#[derive(Default)]
-struct UiState {
- windows: HashMap<u32, WindowHandle<JsView>>,
- by_native: HashMap<usize, u32>,
- tags: HashMap<String, &'static str>,
-}
+// The UI thread
type Job = Box<dyn FnOnce(&mut App) + Send>;
@@ -442,6 +121,17 @@ impl Link {
}
}
+/// The headless loop ends after the job that set this.
+struct Quit;
+
+/// Events to JavaScript, from the UI thread.
+fn sink(tsfn: &Tsfn) -> view::Sink {
+ let t = tsfn.clone();
+ Arc::new(move |e: view::Event| {
+ t.call(BuiEvent::from(e), ThreadsafeFunctionCallMode::NonBlocking);
+ })
+}
+
// ==========================================================================
// The JavaScript class
@@ -474,20 +164,10 @@ impl NativeApp {
if let Some(s) = slug {
a = a.slug(s);
}
- let close = tsfn.clone();
+ let events = tsfn.clone();
a.run(move |cx| {
- cx.set_global(UiState::default());
- cx.set_global(close.clone());
- cx.on_window_closed(move |id, cx| {
- let js = cx.global::<UiState>().by_native.get(&id.0).copied();
- if let Some(w) = js {
- close.call(BuiEvent { kind: "close".into(), window: w, ..Default::default() },
- ThreadsafeFunctionCallMode::NonBlocking);
- let st = cx.global_mut::<UiState>();
- st.windows.remove(&w);
- st.by_native.remove(&id.0);
- }
- });
+ cx.set_global(events.clone());
+ view::init(cx, sink(&events));
if headless {
let (tx, rx) = mpsc::channel::<Job>();
let _ = ltx.send(Link::Headless(tx));
@@ -503,7 +183,7 @@ impl NativeApp {
let _ = ltx.send(Link::Native(cx.ui_sender()));
}
});
- // the loop ended: let Node exit
+ // the loop ended: let the runtime exit
drop(tsfn);
}).map_err(|e| Error::from_reason(format!("starting the UI thread: {e}")))?;
let link = lrx.recv().map_err(|_| Error::from_reason("the UI thread failed to start"))?;
@@ -519,35 +199,12 @@ impl NativeApp {
/// Open window `id` (chosen by JS) with an empty `<body>` as node 0.
#[napi]
pub fn open_window(&self, id: u32, config: Option<WindowConfig>) {
- let (title, w, h, resizable, gpu) = match config {
- Some(c) => (c.title, c.width.unwrap_or(800.0), c.height.unwrap_or(600.0), c.resizable, c.gpu),
- None => (None, 800.0, 600.0, None, None),
- };
+ let c = config.map(|c| view::WindowConfig {
+ title: c.title, width: c.width, height: c.height, resizable: c.resizable, gpu: c.gpu,
+ }).unwrap_or_default();
self.link.send(move |cx| {
- let tsfn = cx.global::<Tsfn>().clone();
- let opts = blenderui::WindowOptions {
- window_bounds: Some(WindowBounds::Windowed(Bounds {
- origin: point(px(0.0), px(0.0)),
- size: size(px(w as f32), px(h as f32)),
- })),
- titlebar: title.map(|t| TitlebarOptions { title: Some(t.into()) }),
- is_resizable: resizable,
- gpu,
- ..Default::default()
- };
- let handle = cx.open_window(opts, |_, cx| {
- cx.new(|_| {
- let mut v = JsView { window: id, nodes: NodeMap::default(), tsfn, raf: false, frame_scheduled: false };
- v.put(0, JsNode { tag: "body", key: "n0".into(), text: None, attrs: Vec::new(),
- style: None, children: Vec::new(), events: 0 });
- v
- })
- });
- if let Ok(handle) = handle {
- let st = cx.global_mut::<UiState>();
- st.by_native.insert(handle.id.0, id);
- st.windows.insert(id, handle);
- }
+ let s = sink(cx.global::<Tsfn>());
+ view::open_window(cx, id, c, s);
});
}
@@ -557,50 +214,21 @@ impl NativeApp {
pub fn commit(&self, window: u32, ops: Int32Array, strings: Vec<String>, animated: Option<bool>) {
let ops: Vec<i32> = ops.to_vec();
let animated = animated.unwrap_or(false);
- self.link.send(move |cx| {
- let Some(handle) = cx.global::<UiState>().windows.get(&window).cloned() else { return };
- let mut tags = std::mem::take(&mut cx.global_mut::<UiState>().tags);
- handle.update(cx, |v, w, _| {
- v.apply(&ops, &strings, &mut tags);
- if !animated {
- w.refresh(); // this window only
- } else if !v.frame_scheduled {
- v.frame_scheduled = true;
- w.request_animation_frame();
- }
- });
- cx.global_mut::<UiState>().tags = tags;
- });
+ self.link.send(move |cx| view::commit(cx, window, &ops, &strings, animated));
}
/// Ask for a `frame` event when window `window` next renders (vsync).
#[napi]
pub fn request_frame(&self, window: u32) {
- self.link.send(move |cx| {
- if let Some(handle) = cx.global::<UiState>().windows.get(&window).cloned() {
- handle.update(cx, |v, w, _| {
- v.raf = true;
- if !v.frame_scheduled {
- v.frame_scheduled = true;
- w.request_animation_frame();
- }
- });
- }
- });
+ self.link.send(move |cx| view::request_frame(cx, window));
}
#[napi]
pub fn close_window(&self, window: u32) {
- self.link.send(move |cx| {
- let st = cx.global_mut::<UiState>();
- if let Some(h) = st.windows.remove(&window) {
- st.by_native.remove(&h.id.0);
- cx.close_window(h.id);
- }
- });
+ self.link.send(move |cx| view::close_window(cx, window));
}
- /// Draw on the GPU from now on (new windows) / GPU text mode.
+ /// GPU text: Slug (glyph outlines) or the glyph atlas.
#[napi]
pub fn set_slug(&self, on: bool) {
self.link.send(move |cx| {
@@ -613,11 +241,7 @@ impl NativeApp {
#[napi]
pub fn quit(&self) {
self.link.send(|cx| {
- let ids: Vec<WindowId> = cx.global::<UiState>().windows.values().map(|h| h.id).collect();
- for id in ids {
- cx.close_window(id);
- }
- cx.global_mut::<UiState>().windows.clear();
+ view::close_all(cx);
cx.set_global(Quit);
cx.quit();
});
@@ -628,17 +252,11 @@ impl NativeApp {
#[napi(ts_return_type = "Promise<{ width: number, height: number, data: Buffer }>")]
pub fn screenshot(&self, env: Env, window: u32) -> Result<JsObject> {
let (deferred, promise) = env.create_deferred()?;
- self.link.send(move |cx| {
- let Some(handle) = cx.global::<UiState>().windows.get(&window).cloned() else {
- deferred.reject(Error::from_reason("no such window"));
- return;
- };
- let (w, h, px) = cx.draw(handle.id);
- let mut rgba = Vec::with_capacity(px.len() * 4);
- for p in px {
- rgba.extend_from_slice(&[(p >> 16) as u8, (p >> 8) as u8, p as u8, 255]);
+ self.link.send(move |cx| match view::screenshot(cx, window) {
+ Some((width, height, rgba)) => {
+ deferred.resolve(move |_| Ok(Screenshot { width, height, data: rgba.into() }));
}
- deferred.resolve(move |_| Ok(Screenshot { width: w as u32, height: h as u32, data: rgba.into() }));
+ None => deferred.reject(Error::from_reason("no such window")),
});
Ok(promise)
}
@@ -648,14 +266,8 @@ impl NativeApp {
pub fn bounds(&self, env: Env, window: u32, node: u32) -> Result<JsObject> {
let (deferred, promise) = env.create_deferred()?;
self.link.send(move |cx| {
- let handle = cx.global::<UiState>().windows.get(&window).cloned();
- let r = handle.and_then(|h| {
- cx.draw(h.id);
- cx.element_bounds(h.id, &format!("n{node}"))
- });
- deferred.resolve(move |_| Ok(r.map(|b| Rect { x: b.origin.x as f64, y: b.origin.y as f64,
- width: b.size.width as f64,
- height: b.size.height as f64 })));
+ let r = view::bounds(cx, window, node);
+ deferred.resolve(move |_| Ok(r.map(|b| Rect { x: b.x, y: b.y, width: b.width, height: b.height })));
});
Ok(promise)
}
@@ -663,63 +275,23 @@ impl NativeApp {
/// Click at (x, y) in window `window` (tests; logical pixels).
#[napi]
pub fn simulate_click(&self, window: u32, x: f64, y: f64) {
- self.link.send(move |cx| {
- if let Some(h) = cx.global::<UiState>().windows.get(&window).cloned() {
- cx.simulate_click(h.id, x as f32, y as f32);
- }
- });
+ self.link.send(move |cx| view::simulate_click(cx, window, x, y));
}
}
-/// The headless loop ends after the job that set this.
-struct Quit;
-
-#[napi(object)]
-pub struct Screenshot {
- pub width: u32,
- pub height: u32,
- /// RGBA, row-major.
- pub data: Buffer,
-}
-
// ==========================================================================
// Measuring (benchmarks): the same counters as bench/common/measure.rs.
-#[cfg(windows)]
-#[link(name = "kernel32")]
-unsafe extern "system" {
- fn GetCurrentProcess() -> isize;
- fn QueryProcessCycleTime(p: isize, cycles: *mut u64) -> i32;
-}
-
/// CPU cycles used by every thread of this process (Windows; otherwise null).
/// Unlike tick-based CPU time, exact for threads that wake on each vsync.
#[napi]
pub fn process_cpu_cycles() -> Option<f64> {
- #[cfg(windows)]
- {
- let mut c = 0u64;
- // SAFETY: the current-process pseudo handle and a valid out pointer.
- unsafe { QueryProcessCycleTime(GetCurrentProcess(), &mut c) };
- Some(c as f64)
- }
- #[cfg(not(windows))]
- {
- None
- }
+ view::process_cpu_cycles()
}
/// The time-stamp counter (x86-64; otherwise null): divide cycle counts by
/// its rate, measured against the wall clock, to get CPU time.
#[napi]
pub fn timestamp_counter() -> Option<f64> {
- #[cfg(target_arch = "x86_64")]
- {
- // SAFETY: rdtsc has no preconditions on x86-64.
- Some(unsafe { core::arch::x86_64::_rdtsc() } as f64)
- }
- #[cfg(not(target_arch = "x86_64"))]
- {
- None
- }
+ view::timestamp_counter()
}
diff --git a/bindings/rust/blenderui-qjs/Cargo.toml b/bindings/rust/blenderui-qjs/Cargo.toml
new file mode 100644
index 0000000..8a3092c
--- /dev/null
+++ b/bindings/rust/blenderui-qjs/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "blenderui-qjs"
+description = "bui-runtime: blenderui with an embedded QuickJS engine, for small standalone JavaScript apps"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+repository.workspace = true
+rust-version.workspace = true
+publish = false
+
+[[bin]]
+name = "bui-runtime"
+path = "src/main.rs"
+
+[dependencies]
+blenderui = { path = "../blenderui" }
+blenderui-jsview = { path = "../blenderui-jsview" }
+rquickjs = { version = "0.14", features = ["classes", "properties", "array-buffer"] }
diff --git a/bindings/rust/blenderui-qjs/src/main.rs b/bindings/rust/blenderui-qjs/src/main.rs
new file mode 100644
index 0000000..cd494da
--- /dev/null
+++ b/bindings/rust/blenderui-qjs/src/main.rs
@@ -0,0 +1,576 @@
+//! `bui-runtime`: blenderui with an embedded QuickJS engine.
+//!
+//! A standalone app is this executable with a JavaScript bundle appended
+//! (see `bui build` in bindings/node): no Node.js, no Bun, no browser. The
+//! JavaScript packages (`@blender-ui/native`, `@blender-ui/react`) run on it
+//! unchanged: `prelude.js` gives them the addon's API (`__BUI_NATIVE__`),
+//! timers, `console` and `process`.
+//!
+//! JavaScript runs on the UI thread, as in a browser. A "pump" runs it: it
+//! delivers window events and request results, runs due timers and promise
+//! jobs, then applies what JavaScript asked for (open a window, commit ops,
+//! request a frame ...) through `blenderui-jsview`, shared with the Node.js
+//! addon. Events and timers schedule the next pump; nothing runs when idle.
+//!
+//! bui-runtime app.js [args] run a script (development)
+//! app.exe [args] an app built by `bui build`
+//! BUI_HEADLESS=1 / --headless off-screen windows (tests)
+//!
+//! SPDX-License-Identifier: GPL-2.0-or-later
+
+use std::cell::Cell;
+use std::sync::{Arc, mpsc};
+use std::time::{Duration, Instant};
+
+use blenderui::prelude::*;
+use blenderui_jsview as view;
+use rquickjs::{Context, Ctx, Function, Object, Runtime, TypedArray, Value};
+
+/// The end of an app executable: `MAGIC`, then the bundle's length (u64 LE).
+const MAGIC: &[u8; 8] = b"BUIAPP01";
+const PRELUDE: &str = include_str!("prelude.js");
+
+// ==========================================================================
+// State shared between the host functions and the pump (UI thread only).
+// Each cell's value is moved out while used: no RefCell.
+
+/// What JavaScript asked for, applied by the pump with `&mut App`.
+enum Command {
+ Open(u32, view::WindowConfig),
+ Commit(u32, Vec<i32>, Vec<String>, bool),
+ Frame(u32),
+ Close(u32),
+ Slug(bool),
+ Quit,
+ Screenshot(u32, u32),
+ Bounds(u32, u32, u32),
+ Click(u32, f64, f64),
+}
+
+/// A finished request (screenshot, bounds) for its promise.
+enum Answer {
+ Screenshot(u32, u32, Vec<u8>),
+ Bounds(Option<view::Rect>),
+ Error(String),
+}
+
+struct Js {
+ runtime: Runtime,
+ context: Context,
+}
+
+thread_local! {
+ static JS: Cell<Option<Js>> = const { Cell::new(None) };
+ static COMMANDS: Cell<Vec<Command>> = const { Cell::new(Vec::new()) };
+ static EVENTS: Cell<Vec<view::Event>> = const { Cell::new(Vec::new()) };
+ static ANSWERS: Cell<Vec<(u32, Answer)>> = const { Cell::new(Vec::new()) };
+ static WAKE: Cell<Option<Wake>> = const { Cell::new(None) };
+ static QUIT: Cell<bool> = const { Cell::new(false) };
+ static SCHEDULED: Cell<bool> = const { Cell::new(false) };
+ static HEADLESS: Cell<bool> = const { Cell::new(false) };
+}
+
+fn push<T>(cell: &'static std::thread::LocalKey<Cell<Vec<T>>>, item: T) {
+ cell.with(|c| {
+ let mut v = c.take();
+ v.push(item);
+ c.set(v);
+ });
+}
+
+fn take<T>(cell: &'static std::thread::LocalKey<Cell<Vec<T>>>) -> Vec<T> {
+ cell.with(|c| c.take())
+}
+
+fn command(c: Command) {
+ push(&COMMANDS, c);
+}
+
+// ==========================================================================
+// Waking the pump
+
+/// How the next pump gets scheduled: through the native loop (and a timer
+/// thread for deadlines), or, headless, by the loop in `main` itself.
+#[derive(Clone)]
+struct Wake {
+ ui: Option<UiSender>,
+ timer: Option<mpsc::Sender<Option<Instant>>>,
+}
+
+/// Run a pump soon (native: once, however many events ask for it).
+fn wake() {
+ let w = WAKE.with(|c| {
+ let w = c.take();
+ c.set(w.clone());
+ w
+ });
+ if let Some(ui) = w.and_then(|w| w.ui) {
+ if !SCHEDULED.with(|s| s.replace(true)) {
+ ui.send(|cx| { pump(cx); });
+ }
+ }
+}
+
+/// A thread that sends a pump to the UI thread at the next timer deadline.
+fn timer_thread(ui: UiSender) -> mpsc::Sender<Option<Instant>> {
+ let (tx, rx) = mpsc::channel::<Option<Instant>>();
+ std::thread::Builder::new().name("bui-timers".into()).spawn(move || {
+ let mut next: Option<Instant> = None;
+ loop {
+ let got = match next {
+ Some(t) => {
+ let now = Instant::now();
+ if t <= now {
+ next = None;
+ ui.send(|cx| { pump(cx); });
+ continue;
+ }
+ rx.recv_timeout(t - now)
+ }
+ None => rx.recv().map_err(|_| mpsc::RecvTimeoutError::Disconnected),
+ };
+ match got {
+ Ok(t) => next = t,
+ Err(mpsc::RecvTimeoutError::Timeout) => {}
+ Err(mpsc::RecvTimeoutError::Disconnected) => break,
+ }
+ }
+ }).expect("starting the timer thread");
+ tx
+}
+
+/// Window events, from the UI thread.
+fn sink() -> view::Sink {
+ Arc::new(|e: view::Event| {
+ push(&EVENTS, e);
+ wake();
+ })
+}
+
+// ==========================================================================
+// The pump
+
+static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
+
+fn now_ms() -> f64 {
+ START.get_or_init(Instant::now).elapsed().as_secs_f64() * 1000.0
+}
+
+/// Run JavaScript until it settles, apply what it asked for; returns the
+/// next timer deadline (ms on the `now_ms` clock).
+fn pump(cx: &mut App) -> Option<f64> {
+ SCHEDULED.with(|s| s.set(false));
+ let Some(js) = JS.with(|c| c.take()) else { return None };
+ let mut next = None;
+ // a bounded number of rounds, so the native loop keeps running (input,
+ // painting) even if JavaScript keeps itself busy
+ for _ in 0..64 {
+ let events = take(&EVENTS);
+ let answers = take(&ANSWERS);
+ js.context.with(|ctx| {
+ let g = ctx.globals();
+ if !events.is_empty() {
+ if let Ok(dispatch) = g.get::<_, Function>("__bui_dispatch") {
+ for e in events {
+ if let Ok(o) = event_object(&ctx, e) {
+ report(&ctx, dispatch.call::<_, ()>((o,)));
+ }
+ }
+ }
+ }
+ if !answers.is_empty() {
+ if let Ok(resolve) = g.get::<_, Function>("__bui_resolve") {
+ for (id, a) in answers {
+ let r = answer_value(&ctx, a).and_then(|(ok, v)| resolve.call::<_, ()>((id, ok, v)));
+ report(&ctx, r);
+ }
+ }
+ }
+ if let Ok(tick) = g.get::<_, Function>("__bui_tick") {
+ let t: rquickjs::Result<f64> = tick.call(());
+ next = match t {
+ Ok(t) if t >= 0.0 => Some(t),
+ Ok(_) => None,
+ Err(e) => {
+ report::<()>(&ctx, Err(e));
+ None
+ }
+ };
+ }
+ });
+ run_jobs(&js);
+ let commands = take(&COMMANDS);
+ let busy = !commands.is_empty();
+ for c in commands {
+ apply(cx, c);
+ }
+ if HEADLESS.with(|h| h.get()) {
+ cx.run_pending(); // render: frames, events
+ }
+ let more = busy
+ || EVENTS.with(|c| { let v = c.take(); let n = !v.is_empty(); c.set(v); n })
+ || ANSWERS.with(|c| { let v = c.take(); let n = !v.is_empty(); c.set(v); n })
+ || next.is_some_and(|t| t <= now_ms());
+ if !more || QUIT.with(|q| q.get()) {
+ break;
+ }
+ }
+ let busy = js.context.with(|ctx| {
+ ctx.globals().get::<_, Function>("__bui_busy").and_then(|f| f.call::<_, bool>(())).unwrap_or(false)
+ });
+ JS.with(|c| c.set(Some(js)));
+ // nothing left to wait for: no window, no timer, no request in flight
+ if view::window_count(cx) == 0 && next.is_none() && !busy && !QUIT.with(|q| q.get()) {
+ command(Command::Quit);
+ for c in take(&COMMANDS) {
+ apply(cx, c);
+ }
+ }
+ // the next timer
+ let w = WAKE.with(|c| {
+ let w = c.take();
+ c.set(w.clone());
+ w
+ });
+ if let Some(timer) = w.and_then(|w| w.timer) {
+ let at = next.map(|t| START.get_or_init(Instant::now).checked_add(Duration::from_secs_f64(t / 1000.0)));
+ let _ = timer.send(at.flatten());
+ }
+ next
+}
+
+fn run_jobs(js: &Js) {
+ loop {
+ match js.runtime.execute_pending_job() {
+ Ok(true) => {}
+ Ok(false) => break,
+ Err(e) => {
+ e.0.with(|ctx| {
+ let v = ctx.catch();
+ eprintln!("{}", describe(&v));
+ });
+ }
+ }
+ }
+}
+
+fn apply(cx: &mut App, c: Command) {
+ match c {
+ Command::Open(id, config) => view::open_window(cx, id, config, sink()),
+ Command::Commit(w, ops, strings, animated) => view::commit(cx, w, &ops, &strings, animated),
+ Command::Frame(w) => view::request_frame(cx, w),
+ Command::Close(w) => view::close_window(cx, w),
+ Command::Slug(on) => {
+ blenderui::set_slug(on);
+ cx.notify_all();
+ }
+ Command::Quit => {
+ if !QUIT.with(|q| q.replace(true)) {
+ view::close_all(cx);
+ if !HEADLESS.with(|h| h.get()) {
+ // done: exit now, as Node and Bun do. Tearing the app down
+ // (GPU device, windows) can take seconds and nothing needs it.
+ exit(0);
+ }
+ cx.quit();
+ }
+ }
+ Command::Screenshot(w, id) => {
+ let a = match view::screenshot(cx, w) {
+ Some((width, height, data)) => Answer::Screenshot(width, height, data),
+ None => Answer::Error("no such window".into()),
+ };
+ push(&ANSWERS, (id, a));
+ }
+ Command::Bounds(w, node, id) => push(&ANSWERS, (id, Answer::Bounds(view::bounds(cx, w, node)))),
+ Command::Click(w, x, y) => view::simulate_click(cx, w, x, y),
+ }
+}
+
+fn event_object<'js>(ctx: &Ctx<'js>, e: view::Event) -> rquickjs::Result<Object<'js>> {
+ let o = Object::new(ctx.clone())?;
+ o.set("kind", e.kind)?;
+ o.set("window", e.window)?;
+ o.set("target", e.target)?;
+ o.set("x", e.x)?;
+ o.set("y", e.y)?;
+ o.set("button", e.button)?;
+ o.set("clickCount", e.click_count)?;
+ o.set("delta", e.delta)?;
+ o.set("key", e.key)?;
+ o.set("keyChar", e.key_char)?;
+ o.set("value", e.value)?;
+ o.set("checked", e.checked)?;
+ o.set("number", e.number)?;
+ o.set("shift", e.shift)?;
+ o.set("ctrl", e.ctrl)?;
+ o.set("alt", e.alt)?;
+ Ok(o)
+}
+
+fn answer_value<'js>(ctx: &Ctx<'js>, a: Answer) -> rquickjs::Result<(bool, Value<'js>)> {
+ Ok(match a {
+ Answer::Screenshot(w, h, data) => {
+ let o = Object::new(ctx.clone())?;
+ o.set("width", w)?;
+ o.set("height", h)?;
+ o.set("data", TypedArray::<u8>::new(ctx.clone(), data)?)?;
+ (true, o.into_value())
+ }
+ Answer::Bounds(Some(r)) => {
+ let o = Object::new(ctx.clone())?;
+ o.set("x", r.x)?;
+ o.set("y", r.y)?;
+ o.set("width", r.width)?;
+ o.set("height", r.height)?;
+ (true, o.into_value())
+ }
+ Answer::Bounds(None) => (true, Value::new_null(ctx.clone())),
+ Answer::Error(m) => (false, rquickjs::String::from_str(ctx.clone(), &m)?.into_value()),
+ })
+}
+
+/// Print an uncaught JavaScript error.
+fn report<T>(ctx: &Ctx<'_>, r: rquickjs::Result<T>) {
+ if let Err(e) = r {
+ if matches!(e, rquickjs::Error::Exception) {
+ eprintln!("{}", describe(&ctx.catch()));
+ } else {
+ eprintln!("bui-runtime: {e}");
+ }
+ }
+}
+
+fn describe(v: &Value<'_>) -> String {
+ if let Some(ex) = v.as_exception() {
+ let msg = ex.message().unwrap_or_default();
+ let stack = ex.stack().unwrap_or_default();
+ return format!("Uncaught {msg}\n{stack}");
+ }
+ match v.get::<String>() {
+ Ok(s) => format!("Uncaught {s}"),
+ Err(_) => "Uncaught exception".into(),
+ }
+}
+
+// ==========================================================================
+// Host functions (`host` in prelude.js)
+
+fn host_object<'js>(ctx: &Ctx<'js>, argv: Vec<String>) -> rquickjs::Result<Object<'js>> {
+ let h = Object::new(ctx.clone())?;
+ macro_rules! f {
+ ($name:literal, $f:expr) => {
+ h.set($name, Function::new(ctx.clone(), $f)?)?;
+ };
+ }
+ f!("print", |level: u32, msg: String| {
+ if level == 0 {
+ println!("{msg}");
+ } else {
+ eprintln!("{msg}");
+ }
+ });
+ f!("now", now_ms);
+ f!("headless", || HEADLESS.with(|h| h.get()));
+ f!("platform", || match std::env::consts::OS {
+ "windows" => "win32".to_string(),
+ "macos" => "darwin".to_string(),
+ os => os.to_string(),
+ });
+ f!("arch", || match std::env::consts::ARCH {
+ "x86_64" => "x64".to_string(),
+ "aarch64" => "arm64".to_string(),
+ a => a.to_string(),
+ });
+ let args = argv.clone();
+ f!("argv", move || args.clone());
+ f!("env", |ctx: Ctx<'js>| -> rquickjs::Result<Object<'js>> {
+ let o = Object::new(ctx)?;
+ for (k, v) in std::env::vars() {
+ o.set(k, v)?;
+ }
+ Ok(o)
+ });
+ f!("exit", |code: i32| -> () {
+ exit(code);
+ });
+ f!("rss", rss);
+ f!("cpuCycles", view::process_cpu_cycles);
+ f!("tsc", view::timestamp_counter);
+ f!("openWindow", |id: u32, title: Option<String>, width: f64, height: f64, resizable: Option<bool>, gpu: Option<bool>| {
+ command(Command::Open(id, view::WindowConfig { title, width: Some(width), height: Some(height), resizable, gpu }));
+ });
+ f!("commit", |w: u32, ops: TypedArray<'js, i32>, strings: Vec<String>, animated: bool| {
+ // SAFETY: copied right away, before JavaScript can detach or resize the buffer
+ let ops = unsafe { ops.as_slice() }.to_vec();
+ command(Command::Commit(w, ops, strings, animated));
+ });
+ f!("requestFrame", |w: u32| command(Command::Frame(w)));
+ f!("closeWindow", |w: u32| command(Command::Close(w)));
+ f!("setSlug", |on: bool| command(Command::Slug(on)));
+ f!("quit", || command(Command::Quit));
+ f!("screenshot", |w: u32, id: u32| command(Command::Screenshot(w, id)));
+ f!("bounds", |w: u32, node: u32, id: u32| command(Command::Bounds(w, node, id)));
+ f!("simulateClick", |w: u32, x: f64, y: f64| command(Command::Click(w, x, y)));
+ Ok(h)
+}
+
+/// Resident memory (the working set on Windows), bytes.
+fn rss() -> f64 {
+ #[cfg(windows)]
+ {
+ #[repr(C)]
+ #[derive(Default)]
+ struct MemCounters {
+ cb: u32,
+ page_faults: u32,
+ peak_working_set: usize,
+ working_set: usize,
+ quota_peak_paged: usize,
+ quota_paged: usize,
+ quota_peak_nonpaged: usize,
+ quota_nonpaged: usize,
+ pagefile: usize,
+ peak_pagefile: usize,
+ }
+ #[link(name = "kernel32")]
+ unsafe extern "system" {
+ fn GetCurrentProcess() -> isize;
+ fn K32GetProcessMemoryInfo(p: isize, m: *mut MemCounters, cb: u32) -> i32;
+ }
+ let mut m = MemCounters { cb: std::mem::size_of::<MemCounters>() as u32, ..Default::default() };
+ // SAFETY: the current-process pseudo handle and a sized out struct.
+ unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut m, m.cb) };
+ m.working_set as f64
+ }
+ #[cfg(not(windows))]
+ {
+ 0.0
+ }
+}
+
+// ==========================================================================
+// Startup
+
+/// The app's JavaScript: the bundle appended to this executable, or the
+/// script named on the command line. Returns (name, source, script args).
+fn load() -> Result<(String, Vec<u8>, Vec<String>), String> {
+ let mut args: Vec<String> = std::env::args().skip(1).filter(|a| a != "--headless").collect();
+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;
+ if let Ok(bytes) = std::fs::read(&exe) {
+ if bytes.len() > 16 && &bytes[bytes.len() - 16..bytes.len() - 8] == MAGIC {
+ let n = u64::from_le_bytes(bytes[bytes.len() - 8..].try_into().unwrap()) as usize;
+ if n <= bytes.len() - 16 {
+ let start = bytes.len() - 16 - n;
+ let name = exe.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
+ return Ok((name, bytes[start..bytes.len() - 16].to_vec(), args));
+ }
+ }
+ }
+ if args.is_empty() {
+ return Err("usage: bui-runtime <app.js> [args] (or build an app with `bui build`)".into());
+ }
+ let path = args.remove(0);
+ let src = std::fs::read(&path).map_err(|e| format!("{path}: {e}"))?;
+ Ok((path, src, args))
+}
+
+fn start(cx: &mut App, name: String, source: Vec<u8>, args: Vec<String>) {
+ let runtime = Runtime::new().expect("QuickJS runtime");
+ runtime.set_max_stack_size(48 << 20);
+ let context = Context::full(&runtime).expect("QuickJS context");
+ view::init(cx, sink());
+ let exe = std::env::current_exe().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default();
+ let mut argv = vec![exe, name.clone()];
+ argv.extend(args);
+ let ok = context.with(|ctx| {
+ let host = match host_object(&ctx, argv) {
+ Ok(h) => h,
+ Err(e) => {
+ report::<()>(&ctx, Err(e));
+ return false;
+ }
+ };
+ let prelude: rquickjs::Result<Function> = ctx.eval(PRELUDE);
+ let r = prelude.and_then(|p| p.call::<_, ()>((host,)));
+ if r.is_err() {
+ report(&ctx, r);
+ return false;
+ }
+ let mut opts = rquickjs::context::EvalOptions::default();
+ opts.filename = Some(name.clone());
+ opts.strict = false;
+ let r: rquickjs::Result<()> = ctx.eval_with_options(source, opts);
+ if r.is_err() {
+ report(&ctx, r);
+ return false;
+ }
+ true
+ });
+ JS.with(|c| c.set(Some(Js { runtime, context })));
+ if !ok {
+ std::process::exit(1);
+ }
+}
+
+fn main() {
+ let (name, source, args) = match load() {
+ Ok(x) => x,
+ Err(e) => {
+ eprintln!("{e}");
+ std::process::exit(2);
+ }
+ };
+ let headless = std::env::args().any(|a| a == "--headless")
+ || std::env::var("BUI_HEADLESS").is_ok_and(|v| v == "1")
+ || !blenderui::native_windows();
+ START.get_or_init(Instant::now);
+ // a large stack: JavaScript recursion runs on the C stack
+ let ui = std::thread::Builder::new().name("bui-main".into()).stack_size(64 << 20).spawn(move || {
+ HEADLESS.with(|h| h.set(headless));
+ if headless {
+ Application::headless().run(move |cx| {
+ WAKE.with(|c| c.set(Some(Wake { ui: None, timer: None })));
+ start(cx, name, source, args);
+ loop {
+ let next = pump(cx);
+ if QUIT.with(|q| q.get()) {
+ break;
+ }
+ let pending = EVENTS.with(|c| { let v = c.take(); let n = !v.is_empty(); c.set(v); n });
+ if pending {
+ continue;
+ }
+ match next {
+ Some(t) => {
+ let wait = t - now_ms();
+ if wait > 0.0 {
+ std::thread::sleep(Duration::from_secs_f64(wait / 1000.0));
+ }
+ }
+ // headless, only timers can bring new work: none, and no
+ // window left means done; windows alone keep it waiting
+ None if view::window_count(cx) == 0 => break,
+ None => std::thread::sleep(Duration::from_millis(5)),
+ }
+ }
+ });
+ } else {
+ Application::new().keep_alive(true).run(move |cx| {
+ let ui = cx.ui_sender();
+ WAKE.with(|c| c.set(Some(Wake { ui: Some(ui.clone()), timer: Some(timer_thread(ui)) })));
+ start(cx, name, source, args);
+ pump(cx);
+ });
+ }
+ }).expect("starting the UI thread");
+ let _ = ui.join();
+}
+
+/// End the process with `code`, flushing what JavaScript printed.
+fn exit(code: i32) -> ! {
+ use std::io::Write;
+ let _ = std::io::stdout().flush();
+ let _ = std::io::stderr().flush();
+ std::process::exit(code)
+}
diff --git a/bindings/rust/blenderui-qjs/src/prelude.js b/bindings/rust/blenderui-qjs/src/prelude.js
new file mode 100644
index 0000000..83be785
--- /dev/null
+++ b/bindings/rust/blenderui-qjs/src/prelude.js
@@ -0,0 +1,133 @@
+// The globals a BUI app expects (console, timers, performance, process) and
+// `__BUI_NATIVE__`: the same API as the Node.js addon (`NativeApp`), on the
+// QuickJS host. Runs before the app's bundle. `host` is the Rust side.
+// SPDX-License-Identifier: GPL-2.0-or-later
+(function (host) {
+ 'use strict'
+ const g = globalThis
+
+ // ---- console ---------------------------------------------------------------
+ function fmt (v, depth = 0) {
+ if (typeof v === 'string') return v
+ if (v instanceof Error) return v.stack ? `${v.name}: ${v.message}\n${v.stack}` : String(v)
+ if (typeof v === 'function') return `[Function ${v.name || 'anonymous'}]`
+ if (typeof v !== 'object' || v === null) return String(v)
+ if (depth > 2) return Array.isArray(v) ? '[Array]' : '[Object]'
+ try {
+ if (Array.isArray(v)) return `[ ${v.map((x) => fmt(x, depth + 1)).join(', ')} ]`
+ const parts = Object.keys(v).map((k) => `${k}: ${typeof v[k] === 'string' ? JSON.stringify(v[k]) : fmt(v[k], depth + 1)}`)
+ return `{ ${parts.join(', ')} }`
+ } catch (e) {
+ return String(v)
+ }
+ }
+ const log = (level) => (...args) => host.print(level, args.map((a) => fmt(a)).join(' '))
+ g.console = { log: log(0), info: log(0), debug: log(0), warn: log(1), error: log(2), trace: log(2) }
+
+ // ---- timers ----------------------------------------------------------------
+ const now = () => host.now()
+ const timers = new Map() // id -> { at, fn, args, every }
+ let nextTimer = 1
+ function addTimer (fn, ms, args, every) {
+ const id = nextTimer++
+ const delay = Math.max(0, Number(ms) || 0)
+ timers.set(id, { at: now() + delay, fn, args, every: every ? Math.max(1, delay) : 0 })
+ return id
+ }
+ const clear = (id) => { timers.delete(id) }
+ g.setTimeout = (fn, ms, ...args) => addTimer(fn, ms, args, false)
+ g.setInterval = (fn, ms, ...args) => addTimer(fn, ms, args, true)
+ g.setImmediate = (fn, ...args) => addTimer(fn, 0, args, false)
+ g.clearTimeout = g.clearInterval = g.clearImmediate = clear
+ g.queueMicrotask = (fn) => { Promise.resolve().then(fn) }
+ g.performance = { now, timeOrigin: Date.now() - now() }
+
+ /** Run the timers that are due; return the next deadline (ms) or -1. */
+ g.__bui_tick = () => {
+ const t = now()
+ const due = []
+ for (const [id, tm] of timers) if (tm.at <= t) due.push(id)
+ due.sort((a, b) => timers.get(a).at - timers.get(b).at || a - b)
+ for (const id of due) {
+ const tm = timers.get(id)
+ if (!tm) continue
+ if (tm.every) tm.at = t + tm.every
+ else timers.delete(id)
+ try {
+ tm.fn(...tm.args)
+ } catch (e) {
+ console.error(e)
+ }
+ }
+ let next = -1
+ for (const tm of timers.values()) if (next < 0 || tm.at < next) next = tm.at
+ return next
+ }
+
+ // ---- process ----------------------------------------------------------------
+ const rss = () => host.rss()
+ g.process = {
+ argv: host.argv(),
+ env: host.env(),
+ platform: host.platform(),
+ arch: host.arch(),
+ versions: { quickjs: 'quickjs-ng', bui: '0.1.0' },
+ exit: (code) => host.exit(code ?? 0),
+ nextTick: (fn, ...args) => g.queueMicrotask(() => fn(...args)),
+ cpuUsage: () => ({ user: 0, system: 0 }),
+ memoryUsage: Object.assign(() => ({ rss: rss(), heapUsed: 0, heapTotal: 0, external: 0, arrayBuffers: 0 }), { rss }),
+ on () { return g.process },
+ cwd: () => '.',
+ }
+
+ // ---- the native API (as the Node.js addon has it) ----------------------------
+ let onEvent = null
+ const requests = new Map()
+ let nextRequest = 1
+ function request (send) {
+ const id = nextRequest++
+ return new Promise((resolve, reject) => {
+ requests.set(id, { resolve, reject })
+ send(id)
+ })
+ }
+ g.__bui_resolve = (id, ok, value) => {
+ const r = requests.get(id)
+ if (!r) return
+ requests.delete(id)
+ if (ok) r.resolve(value)
+ else r.reject(new Error(value))
+ }
+ g.__bui_dispatch = (e) => { if (onEvent !== null) onEvent(e) }
+ g.__bui_busy = () => requests.size > 0
+
+ class NativeApp {
+ constructor (options, callback) {
+ this._options = options || {}
+ onEvent = callback
+ if (this._options.slug != null) host.setSlug(!!this._options.slug)
+ }
+
+ get headless () { return host.headless() }
+ openWindow (id, c) {
+ c = c || {}
+ host.openWindow(id, c.title ?? null, c.width ?? 800, c.height ?? 600, c.resizable ?? null,
+ c.gpu ?? this._options.gpu ?? null)
+ }
+
+ commit (window, ops, strings, animated) { host.commit(window, ops, strings, !!animated) }
+ requestFrame (window) { host.requestFrame(window) }
+ closeWindow (window) { host.closeWindow(window) }
+ setSlug (on) { host.setSlug(!!on) }
+ quit () { host.quit() }
+ screenshot (window) { return request((id) => host.screenshot(window, id)) }
+ bounds (window, node) { return request((id) => host.bounds(window, node, id)) }
+ simulateClick (window, x, y) { host.simulateClick(window, x, y) }
+ }
+
+ g.__BUI_NATIVE__ = {
+ NativeApp,
+ processCpuCycles: () => host.cpuCycles(),
+ timestampCounter: () => host.tsc(),
+ }
+})
diff --git a/docs/javascript.md b/docs/javascript.md
index 7ee9d6d..221470c 100644
--- a/docs/javascript.md
+++ b/docs/javascript.md
@@ -4,7 +4,9 @@ BUI runs from JavaScript through a native addon built with napi-rs, much as
[GPUIX](https://www.npmjs.com/package/@gpuix/react) drives GPUI. You get native
windows drawn on the CPU or with Direct3D 11, HTML elements, CSS and Tailwind
classes, and the same engine as the Rust crate. There's no browser and no
-Electron. It works on **Node.js** and **Bun**.
+Electron. It works on **Node.js** and **Bun**, and `bui build` turns an app
+into a **single executable of about 5 MB**: BUI with an embedded QuickJS
+engine ([Standalone apps](#standalone-apps)).
| Package | What it is |
|---|---|
@@ -215,6 +217,63 @@ The signals are push-pull and glitch-free:
- **Errors:** a memo that throws rethrows on read and recovers when its
sources change.
+## Standalone apps
+
+`bui build` turns an app into one executable. It ships with `@blender-ui/native`
+and needs [Bun](https://bun.sh) for bundling.
+
+```sh
+npx bui build app.jsx # app.exe: BUI + QuickJS, about 5 MB
+npx bui build app.jsx --bun # app.exe: a Bun executable, about 115 MB
+npx bui run app.jsx # run on the QuickJS runtime, no executable
+```
+
+Options:
+
+- `-o <file>`: the output file.
+- `--console`: keep a console window for logs. By default, Windows builds open
+ no console.
+- `--dev`: use React's development build.
+
+**The default build** is `bui-runtime`, BUI with an embedded
+[QuickJS](https://github.com/quickjs-ng/quickjs) engine (4.9 MB), with your
+app's bundle appended. Your code and both packages run unchanged:
+
+- **JavaScript runs on the UI thread**, as in a browser: no Node.js, no Bun,
+ no browser, no webview.
+- **What it provides:** `console`, timers, `queueMicrotask`, `performance` and
+ a `process` with `env`, `argv`, `exit` and `platform`.
+- **What it doesn't:** Node's modules (`fs`, `net` ...) aren't there. Apps that
+ need them use `--bun`.
+
+**With `--bun`** you get `bun build --compile`: the full Bun runtime with
+Node's APIs and a JIT, and `@blender-ui/native`'s addon embedded in the
+executable.
+
+| A small React app, Windows x64 | QuickJS (default) | `--bun` |
+|---|---:|---:|
+| Executable | **4.9 MB** | 114 MB |
+| First frame | **68 ms** | 79 ms |
+| Launch to exit | **104 ms** | 147 ms |
+| RAM at first frame | **19 MB** | 35 MB |
+| RAM, 3,000 animated cells | **56–67 MB** | 80–118 MB |
+| JavaScript speed | interpreter | JIT |
+
+QuickJS has no JIT, so heavy JavaScript runs several times slower than on Bun
+or Node. With BUI that matters less than it sounds:
+
+- **The renderer is native:** layout, painting and the GPU cost the same on
+ either runtime.
+- **Signals keep JavaScript light:** a change updates a node without
+ re-rendering components. Re-rendering a 3,000-element list every frame is
+ where QuickJS falls behind (see Performance), so use signals there, or
+ `--bun`.
+
+The executable is built by appending the bundle to `bui-runtime`: nothing is
+compiled per app, and a build takes well under a second. Prebuilt runtimes
+are for Windows x64. On other platforms, `npm run build` in `bindings/node`
+builds `bui-runtime` from source.
+
## How it works
- **A UI thread.** BUI runs its own message loop on a thread of its own, so
@@ -240,10 +299,36 @@ The signals are push-pull and glitch-free:
## Performance
+### Startup
+
+`node bench/startup.js` launches a small React app (`bench/first-frame.js`)
+that quits as soon as its first frame is on screen. It does that 12 times for
+each way to run an app, after one warm-up launch, and reports the medians.
+
+- **First frame** is measured inside the app, from the runtime's start.
+- **Launch to exit** is wall time measured from outside, including process
+ creation and teardown.
+
+| | First frame | Launch to exit | RAM at first frame | What you ship |
+|---|---:|---:|---:|---:|
+| **QuickJS executable** (`bui build`) | **68 ms** | **104 ms** | **19 MB** | **4.9 MB** |
+| Bun executable (`bui build --bun`) | 79 ms | 147 ms | 35 MB | 114 MB |
+| Bun (`bun app.js`) | 80 ms | 152 ms | 35 MB | Bun + the app |
+| Node.js (`node app.js`) | 108 ms | 187 ms | 45 MB | Node + the app |
+| Rust, for reference (the benchmark app) | 5 ms | ~92 ms | | 3.5 MB |
+
+Timings vary by about ±20% between sessions on this laptop; the ranking
+doesn't change. The first launch of a newly written executable can take
+seconds while antivirus software scans it, which is why the warm-up launch
+isn't counted.
+
+### Animation
+
The Rust benchmark's `one` mode: a 1000×800 window with a grid of N cells,
where one cell changes colour and label every frame, driven from
`requestAnimationFrame`. Command: `bench/cells.js N --gpu [--react
-[--signals]]`, run with `node` or `bun`.
+[--signals]]`, run with `node`, `bun` or `node cli.js run` (the QuickJS
+runtime).
- **"React, signals":** cell 0's style and label are signals, so the grid
renders once.
@@ -258,7 +343,8 @@ counted with the process cycle counter, as the Rust benchmark does
that wake on each vsync.
The table shows medians of 3 runs, GPU renderer, on a Ryzen 7 5800U laptop
-(Windows 11, 60 Hz) with Node.js 22.17 and Bun 1.4.4, all in one session.
+(Windows 11, 60 Hz) with Node.js 22.17 and Bun 1.4.4. Rust, Bun and Node ran
+in one session; QuickJS (`bui-runtime`) ran in a later one.
| 3,000 cells | FPS | CPU per frame | RAM (resident) |
|---|---:|---:|---:|
@@ -269,12 +355,16 @@ The table shows medians of 3 runs, GPU renderer, on a Ryzen 7 5800U laptop
| Node, plain JS | 55.8 | 14.4 ms | 88 MB |
| Node, React with signals | 56.7 | 14.0 ms | 93 MB |
| Node, React with state | 54.8 | 18.9 ms | 121 MB |
+| QuickJS, plain JS | 59.1 | 16.3 ms | **56 MB** |
+| QuickJS, React with signals | 58.7 | 14.9 ms | 61 MB |
+| QuickJS, React with state | 19.7 | 51.0 ms | 67 MB |
-| 1,000 cells (all at 60 FPS) | CPU per frame | RAM |
+| 1,000 cells (60 FPS, except as noted) | CPU per frame | RAM |
|---|---:|---:|
| Rust | **4.8 ms** | **32 MB** |
| Bun: plain JS / React with signals / React with state | 5.2 / 5.2 / 7.5 ms | 58 / 63 / 81 MB |
| Node: plain JS / React with signals / React with state | 5.6 / 5.6 / 6.9 ms | 68 / 71 / 97 MB |
+| QuickJS: plain JS / React with signals / React with state (56.8 FPS) | 6.0 / 5.6 / 17.8 ms | **38 / 40 / 43 MB** |
What these show:
@@ -283,6 +373,11 @@ What these show:
thread, and of its copy of the tree.
- **Memory:** most of the extra RAM is the runtime itself. Node alone is about
32 MB, and Bun's footprint is about 10 MB smaller.
+- **QuickJS:** the leanest in memory: 38–67 MB, about 20–40 MB below Bun and
+ Node. JavaScript shares the UI thread and has no JIT, so CPU per frame is a
+ little higher with plain JS and signals. Re-rendering 3,000 elements every
+ frame drops it to 20 FPS, so keep big lists on signals, or build with
+ `--bun`.
- **React with signals:** costs what the plain API does. At 3,000 cells it
uses about a quarter less CPU and memory than re-rendering, because the
component never re-renders.
@@ -317,16 +412,31 @@ MinGW, put its `bin` folder on `PATH`.
## Publishing
-Both packages are ready for `npm publish` from their folders, in this order:
+The packages are published under the [`@blender-ui`](https://www.npmjs.com/org/blender-ui)
+npm organization. `@blender-ui/react` depends on `@blender-ui/native`
+(`^0.2.0`), so publish the native package first, whenever it has changed.
-1. Bump the versions. `@blender-ui/react` depends on `@blender-ui/native` by
- version, so publish that first.
-2. Run `npm publish --access public` in `bindings/node`, then in
- `bindings/react`.
- - `prepublishOnly` builds the addon and runs the tests.
- - `prepack` copies the repository's `LICENSE` into the package.
+```sh
+npm login # an account in the blender-ui org
+cd bindings
+npm install # link the workspace
+cd node && npm publish --access public # @blender-ui/native (builds the addon and runtime, runs the tests)
+cd ../react && npm publish --access public # @blender-ui/react (runs the tests)
+```
-The native package ships `blenderui.win32-x64.node` and is limited to Windows
-x64 (`os` and `cpu` in `package.json`). Supporting more platforms means
-building the addon on each one, typically in CI, and publishing them as
-optional per-platform packages, the napi-rs convention.
+- **`prepublishOnly`** runs the tests before uploading. For the native
+ package it first builds the addon and `bui-runtime` (Rust, CMake and a C
+ compiler; with MinGW, put its `bin` folder on `PATH`).
+- **`prepack`** copies the repository's `LICENSE` into the package.
+- **Previewing:** `npm pack --dry-run` lists what a package will contain;
+ `npm pack` writes the `.tgz` you can install elsewhere to try it.
+- **Releasing again:** bump `version` in the package's `package.json` first, since
+ npm refuses to publish the same version twice. When the native package
+ changes in a way React needs, raise React's `@blender-ui/native` range to
+ match.
+
+The native package ships `blenderui.win32-x64.node` and
+`bui-runtime.win32-x64.exe`, and `os` / `cpu` in its `package.json` limit it
+to Windows x64. Supporting more platforms means building both on each
+platform, typically in CI, and publishing them as optional per-platform
+packages, the napi-rs convention.