Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI
feat: tailwind & readme
Preetham Pemmasani35c6a5f089b6
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlnew file mode 100644index 0000000..c9513e7--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -0,0 +1,31 @@+name: Bug report+description: Something doesn't work or looks wrong+labels: [bug]+body:+ - type: dropdown+ id: area+ attributes:+ label: Area+ options: [tkinter syntax, Qt syntax, Components, Rust (blenderui), C kit, Rendering / GPU, Packaging, Other]+ validations: { required: true }+ - type: textarea+ id: what+ attributes:+ label: What happened, and what did you expect?+ description: Screenshots help a lot for drawing issues.+ validations: { required: true }+ - type: textarea+ id: repro+ attributes:+ label: Minimal code to reproduce+ render: python+ validations: { required: true }+ - type: input+ id: env+ attributes:+ label: Environment+ placeholder: "blenderui 0.1.0, Python 3.12, Windows 11 (or crate commit, Rust version)"+ validations: { required: true }+ - type: markdown+ attributes:+ value: "For tkinter apps: does the same code behave differently on the standard library tkinter? That's what we want to hear about."diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.ymlnew file mode 100644index 0000000..c0acaeb--- /dev/null+++ b/.github/ISSUE_TEMPLATE/config.yml@@ -0,0 +1,8 @@+blank_issues_enabled: false+contact_links:+ - name: Security vulnerability+ url: https://github.com/ppmpreetham/BUI/security/advisories/new+ about: Please report security problems privately.+ - name: Documentation+ url: https://github.com/ppmpreetham/BUI/tree/main/docs+ about: Guides for tkinter, Qt, components, Rust and the C API.diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlnew file mode 100644index 0000000..2eaaefd--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -0,0 +1,19 @@+name: Feature request+description: A missing API, CSS feature, widget or platform+labels: [enhancement]+body:+ - type: textarea+ id: what+ attributes:+ label: What would you like?+ description: "For missing tkinter/Qt APIs or CSS properties, name them exactly (e.g. `Treeview.tag_bind`, `backdrop-filter`)."+ validations: { required: true }+ - type: textarea+ id: why+ attributes:+ label: What would you use it for?+ - type: textarea+ id: example+ attributes:+ label: Example code+ render: rustdiff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdnew file mode 100644index 0000000..7a2ca8f--- /dev/null+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -0,0 +1,16 @@+## What does this change?++<!-- One or two sentences. Link the issue: "Fixes #123". -->++## How was it tested?++- [ ] `ctest --test-dir build` passes+- [ ] `cargo test` passes (if Rust changed)+- [ ] Added or updated a test for this change+- [ ] Benchmarks attached (for rendering or layout changes)++## Checklist++- [ ] `CHANGELOG.md` updated (Unreleased)+- [ ] Docs updated (`docs/`, README if user-facing)+- [ ] New files carry the `SPDX-License-Identifier: GPL-2.0-or-later` headerdiff --git a/.gitignore b/.gitignoreindex ff30b67..228114d 100644--- a/.gitignore+++ b/.gitignore@@ -10,3 +10,6 @@ dist/wheelhouse/*.egg-info/*.whl++# C sources vendored into the published Rust crate (scripts/vendor_c.py)+bindings/rust/blenderui-sys/csrc/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9de7804..2b64fa3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,20 @@ All notable changes to **blenderui** (BUI). The format follows## [Unreleased]### Added+- **Components and hooks** (Rust, compatible with zopra, React and Leptos):+ - `#[component]` turns a function into a component, with lowercase or uppercase names and `&str` props.+ - `use_state` returns `count()` / `set_count(..)` closures that need no `cx`.+ - Signals: `use_signal`, `Signal`/`RwSignal`, and `signal`/`create_signal` with read and write halves.+ - Auto-tracked `Memo` and `Effect`; `use_effect` / `use_effect!` and `use_memo` with explicit dependencies.+ - Context: `provide_context` / `use_context`.+ - State is tied to the call site, like React, and freed when its component stops rendering. Setters re-render their window. No `Rc` or `RefCell`.+- **`rsx!` / `view!` markup** (Rust): JSX syntax lowered to builder calls at compile time, in about 470 lines with no dependencies.+ - **Syntax:** any tag or custom element; text, `{expr}` and `{...spread}` children; `for`, `if` and `match` in markup; fragments; and struct components with children.+ - **Uniform lowering:** `{expr}` attributes call the builder method of the same name, so the whole API is reachable without per-attribute code.+ - **Events:** listener closures may omit the `(event, window, cx)` parameters.+ - **Attributify:** bare Tailwind utilities are attributes too: `<div p-4 bg-[#4772b3] hover:bg-sky-500/50>`. They compile to classes, while HTML boolean attributes stay attributes.+ - **Did-you-mean errors:** a misspelled utility, variant, root or value is a compile error with suggestions, in `rsx!` and `tw!` (`blenderui_tailwind::suggest`).+ - **Variant attributes:** every Tailwind variant works as an attribute prefix: `hover:class="..."`, `md:dark:hover:style="..."`, `group-hover:color="red"`, `active:bg={red()}`.- **Modern CSS in the Rust crate**:- **Layout:** [taffy](https://github.com/DioxusLabs/taffy) 0.6 → 0.15 behind a layout tree of our own. taffy's built-in tree resolves `calc()` to 0; ours evaluates it. That brings mixed-unit `calc()` everywhere (`calc(100% - 2rem)`, grid tracks, `fit-content(calc())`), floats and `clear`, `direction: rtl`, `grid-template-areas` with named lines and areas, the sizing keywords (`min-content`, `max-content`, `fit-content`, `stretch`), `display: flow-root`, real `position: static` / `fixed` with containing blocks, `contain`, `flex-wrap: balance`, and `safe` / `unsafe` alignment.- **Math:** `calc()`, `min()`, `max()`, `clamp()`, `round()` (all four strategies), `mod()`, `rem()`, `abs()`, `sign()`, trigonometry, `pow()`, `sqrt()`, `hypot()`, `log()`, `exp()`, the constants `e`/`pi`/`infinity`, and every length unit (`vmin`/`vmax`, `dvh`/`svh`/`lvh`, `ch`, `ex`, `lh`, `rlh`, `cap`, `cq*` ...) plus angles. Expressions are interned once.diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.mdnew file mode 100644index 0000000..de69624--- /dev/null+++ b/CODE_OF_CONDUCT.md@@ -0,0 +1,15 @@+# Code of Conduct++BUI follows the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/).++In short:+- Be respectful, welcoming and patient.+- Give and accept constructive feedback gracefully.+- Focus on what is best for the project and its users.+- No harassment, insults, or personal or political attacks.++Report unacceptable behavior privately to the maintainers by opening a+[private security advisory](https://github.com/ppmpreetham/BUI/security/advisories/new)+with "Code of Conduct" in the title, or by contacting a maintainer directly.+All reports are reviewed and kept confidential. Maintainers may remove+contributions or ban contributors who break these rules.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..cd267a2--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,52 @@+# Contributing to BUI++Thanks for helping! Bug reports, missing tkinter/Qt behavior, CSS features,+platform hosts, docs and examples are all welcome.++## Before you start++- **Bugs and features:** open an [issue](https://github.com/ppmpreetham/BUI/issues)+ first, so we can agree on the approach.+- **Security problems:** report them privately (see [SECURITY.md](SECURITY.md)).+- Be kind: this project follows the [Code of Conduct](CODE_OF_CONDUCT.md).++## Setting up++```sh+git clone https://github.com/ppmpreetham/BUI && cd BUI+cmake -S . -B build && cmake --build build+ctest --test-dir build --output-on-failure # C and Python suites+cd bindings/rust && cargo test # Rust crates+```++You need CMake ≥ 3.20, a C11 compiler (on Windows, MSYS2 MinGW is the tested+toolchain for the Python build) and Python 3.11+. More detail:+[docs/getting-started.md](docs/getting-started.md).++## Where things live++| You want to change | Look in |+|---|---|+| Widget drawing, input, layout, rendering | `kit/` (C), `gpu/` (raster, GPU, text) |+| tkinter / Qt behavior | `bindings/python/bui/tksyntax/`, `bindings/python/bui/qtsyntax.py` |+| Components | `bindings/python/bui/components/` |+| Rust: CSS, layout, hooks | `bindings/rust/blenderui/src/` |+| Rust: `rsx!`, `#[component]`, `tw!` | `bindings/rust/blenderui-macros/src/` |+| Tailwind utilities and variants | `bindings/rust/blenderui-tailwind/src/lib.rs` |++[ARCHITECTURE.md](ARCHITECTURE.md) explains the module boundaries.++## Pull requests++- Keep each PR focused on one change, and add a test for it:+ - C: `ctest`.+ - Python: `bindings/python/tests/`. For tkinter behavior, add to the side-by-side compat suite.+ - Rust: `bindings/rust/blenderui/tests/`.+- Don't let performance regress. The test suite enforces frame budgets. For+ rendering or layout changes, run the benchmark in `bindings/rust/bench/`+ and include before and after numbers.+- Keep the SPDX header (`GPL-2.0-or-later`) in new files. Contributions are+ accepted under that license.+- Update `CHANGELOG.md` (the Unreleased section) and the relevant guide in `docs/`.+- Code style: follow the surrounding code. C is formatted like Blender's+ sources, and Rust with `rustfmt` defaults (max width 120).diff --git a/README.md b/README.mdindex eb1c112..f791192 100644--- a/README.md+++ b/README.md@@ -1,154 +1,73 @@-# BUI (Blender UI)+<div align="center">-> [!NOTE]-> This repository is built entirely using LLMs. No human-written code.+# BUI-BUI is the user interface of [Blender](https://www.blender.org), extracted-into a standalone, fast, C-first UI library. You get Blender's look _and_-Blender's interactions, scrubbable number fields, drag-toggles, pie menus,-the color wheel, Ctrl+Z on any edit and you can drive it three ways:+**Blender's user interface, as a library you can use from Python, Rust and C.**-- **tkinter syntax**: run existing tkinter programs unchanged, now looking- like Blender.-- **Qt syntax**: write `QWidget` / `QVBoxLayout` / `clicked.connect` code- (a common subset today).-- **Blender components**: a native component library (`Panel`,- `NumberSlider`, `ColorSwatch`, `TreeView`, `PieMenu` ...).-- **Rust, gpui syntax**: the `blenderui` crate. `div().flex().gap_2().child(...)`,- `cx.listener`, `Render`, plus every HTML element and CSS (stylesheets,- selectors, flexbox, grid, tables), with form controls as Blender widgets.+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.-All of them share one C runtime (`kit/`). Python (or Rust) builds the widget-tree and runs your callbacks. Input, widget drawing and presenting stay in C.--```sh-pip install blenderui # on PyPI: https://pypi.org/project/blenderui/-```--<p align="center">- <img src="docs/images/components.png" width="340" alt="Blender components">- <img src="docs/images/tkinter_items.png" width="300" alt="A plain tkinter program on BUI">-</p>-<p align="center"><sub>Left: the component library (<code>examples/components_demo.py</code>).-Right: an unmodified tkinter program (<code>examples/tk_unchanged_app.py</code>) running on BUI.</sub></p>-------## Contents--- [Why BUI](#why-bui)-- [Status](#status)-- [Install and build](#install-and-build)-- [Quick start](#quick-start)- - [tkinter syntax](#tkinter-syntax)- - [Qt syntax](#qt-syntax)- - [Blender components](#blender-components)- - [Rust (gpui syntax, HTML and CSS)](#rust-gpui-syntax-html-and-css)-- [How it works](#how-it-works)-- [Performance](#performance) (including [blenderui vs gpui](#rust-blenderui-vs-gpui) and the [GPU renderer](#gpu-renderer))-- [Roadmap: more languages and platforms](#roadmap-more-languages-and-platforms)-- [Packaging](#packaging)-- [Documentation](#documentation)-- [Repository layout](#repository-layout)-- [Testing](#testing)-- [License](#license)-------## Why BUI--| | |-| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| **Blender's real UI code** | Widget drawing is a C port of Blender's `interface_widgets.cc` (`round_box_edges`, `widgetbase_draw`, `widget_state`, the shape tables). Color math, rects and text cursors are Blender's `blenlib`, linked. The HSV wheel uses Blender's own functions. |-| **Blender's interactions** | Drag number fields with a hidden, continuous cursor (Shift is precise, Ctrl snaps). Ctrl+Wheel steps values, Ctrl+C/V copies and pastes them, Backspace resets. Drag across checkboxes to set them all. Press-drag-release picks menu items, and typing in a menu searches it. Ctrl+Z / Ctrl+Shift+Z undoes UI edits. Tab moves between fields. Drag vertically over number fields to edit several at once. Panels collapse with an animation. |-| **Familiar APIs** | Use the tkinter or Qt code you already know, or the component library. |-| **Fast** | Rendering is damage-driven: an idle UI draws nothing, and a hover or scrub redraws only the widget it touches. A full window renders in under a millisecond (see [Performance](#performance)). |-| **Small dependencies** | C11 plus a CPython extension. No Qt or Tk widgets are used to draw anything. |--## Status--| Part | State | Details |-| ------------------------------------ | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| C kit (`kit/`) | ✅ Working | Nodes, Tk-style geometry managers, input, Blender widget drawing, damage rendering, undo, animation, text area, canvas, scroll views, multi-select |-| Native window (Windows) | ✅ Working | Win32 window in C: DPI-aware, vsync'd animation, clipboard, cursors, window-manager features |-| Other platforms | ⚠️ Fallback | The window is hosted by the stdlib `tkinter`, which draws the frame buffer; the UI is identical. Linux and macOS are not regularly tested. |-| **tkinter syntax** (`bui.tksyntax`) | ✅ **Complete API** | Every public name of every tkinter and ttk widget class exists (7846/7846). Nine real tkinter programs behave identically on the stdlib and on BUI. |-| **Qt syntax** (`bui.qtsyntax`) | 🟡 **Partial (~25%)** | The common subset works: widgets, layouts, signals, `QPainter`, menus, timers. Model/view, docks, toolbars, splitters and stylesheets are missing. [Details](docs/qt.md#coverage). |-| Component library (`bui.components`) | ✅ Working | 45 Blender components, including editors (color ramp, curves) and templates |-| C++ / Qt render-sink backends | ✅ Working | For embedding BUI drawing into your own renderer ([INTEGRATION.md](INTEGRATION.md)) |-| Packaging (`pip install blenderui`) | ✅ Published | [`blenderui` 0.1.0 on PyPI](https://pypi.org/project/blenderui/): a prebuilt wheel for Windows / CPython 3.12, and a source package that other platforms compile on install (needs CMake and a C compiler). Prebuilt wheels for all platforms come from CI on the next tagged release ([docs/publishing.md](docs/publishing.md)) |-| **Rust** (`blenderui` crate) | ✅ **Working** | gpui syntax (`Render`, `Context`, `Entity`, `cx.listener`, ~1,300 `Styled` methods) over **113/113 HTML elements** and CSS: **180 properties rendered** (+81 parsed without effect); against the 745-property W3C index, 24% rendered, 10% parsed only and 66% left (mostly drafts, speech, print and SVG; [details](docs/rust.md#coverage)), CSS 2.1 screen properties 80/90 rendered, Flexbox 12/12, Grid 23/23, plus `calc()` and every math function, `var()`, CSS Color 4/5 (`oklch`, `color-mix`), Selectors 4 (`:has()`), nesting, `@layer`, and **Tailwind CSS v4** classes (`tw!` checks them at compile time). Layout by [taffy](https://github.com/DioxusLabs/taffy). Native window on Windows, headless rendering everywhere. Animating 3000 elements: 59.9 fps on 11.6 ms CPU per frame with the opt-in GPU renderer (same session: gpui-fast 31.5 fps on 31.9 ms, gpui 19.9 fps on 50.5 ms), with less memory and a ~5 ms first frame ([benchmark](bindings/rust/bench/README.md)). [docs/rust.md](docs/rust.md) |-| **egui integration** | 🗺️ Planned | BUI panels drawn inside egui (raster → `egui::TextureHandle`, input forwarded) and a Blender-styled `egui::Visuals` theme. Builds on the Rust crate |-| **WebAssembly build** | 🗺️ Planned | The kit compiled with Emscripten: the raster blits to `<canvas>` (damage rectangles only), DOM events feed `BK_press` / `BK_key` |-| **React** (`@blenderui/react`) | 🗺️ Planned | A JSX reconciler over the WASM build (`<Panel>`, `<NumberSlider>` ...); `@blenderui/web` for plain JS/TS, N-API for Node |-| Other languages and hosts | 🗺️ Planned | C#, Go, Zig, Swift, Kotlin, Lua; Dear ImGui; Godot, Unity, Bevy; Flutter; native Linux/macOS windows; Vulkan/Metal/WebGPU renderers ([roadmap](#roadmap-more-languages-and-platforms)) |--## Install and build--### From PyPI+[](https://pypi.org/project/blenderui/)+[](https://pypi.org/project/blenderui/)+[](https://github.com/ppmpreetham/BUI/actions/workflows/wheels.yml)+[](#license)+-```sh-pip install blenderui-```+[Quick start](#quick-start) ·+[What it can do](#what-it-can-do) ·+[Status](#status-whats-done-and-whats-not) ·+[Docs](#documentation) ·+[Performance](#performance) ·+[Contributing](#contributing)-```python-import blenderui.tksyntax as tk # tkinter syntax-from blenderui.components import App # Blender components-from blenderui.qtsyntax import QWidget # Qt syntax-```+<img src="https://raw.githubusercontent.com/ppmpreetham/BUI/main/docs/images/components.png" width="330" alt="BUI's Blender components: panels, number sliders, vector fields, checkboxes and a color swatch">+<img src="https://raw.githubusercontent.com/ppmpreetham/BUI/main/docs/images/tkinter_items.png" width="300" alt="An unmodified tkinter program running on BUI">-`blenderui` and `bui` are the same package (`blenderui.X` *is* `bui.X`);-the examples below use `bui` because that's how the source tree is-organised. Use `blenderui` in published code: the `bui` name on PyPI-belongs to an unrelated project. A console script comes with it:-`blenderui-tk app.py` runs a tkinter app on BUI.+<sub>Left: the component library. Right: an unmodified tkinter program, now looking like Blender.</sub>-### From source+</div>-Requirements: **CMake ≥ 3.20**, a **C11/C++17 compiler** (GCC / MinGW or-Clang; MSVC is untested), and **Python 3.11+** with development headers.+> [!NOTE]+> This repository is built entirely using LLMs. No human-written code.-```sh-git clone <this repository> BUI-cd BUI-cmake -S . -B build-cmake --build build-ctest --test-dir build # C + Python test suites-```+## What is BUI?-The Python package lives in `bindings/python/bui`. Its compiled extension-(`buipy`) stays in the build tree, and `import bui` finds it there-automatically. Put `bindings/python` on `PYTHONPATH` and you are done:+BUI takes the user interface of [Blender](https://www.blender.org) (its widget+drawing, its interaction rules and its look) and turns it into a standalone+UI library with a small C core. Your code builds the widget tree and handles+callbacks. Layout, input, drawing and presenting all happen in fast native+code.-```sh-export PYTHONPATH=$PWD/bindings/python # Windows: set PYTHONPATH=%CD%\bindings\python-python examples/components_demo.py-```+You can drive it four ways, and all of them share the same C runtime:-More detail, including environment variables and troubleshooting:-[docs/getting-started.md](docs/getting-started.md).+| 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 |## Quick start-### tkinter syntax+### Python-Run any tkinter program on BUI **without changing it**:+```sh+pip install blenderui+```++Run any tkinter program on BUI **without changing a line**:```sh-python -m bui.tksyntax examples/tk_unchanged_app.py+blenderui-tk my_app.py # same as: python -m bui.tksyntax my_app.py```-Or opt in from code, before anything imports `tkinter`:+Or opt in from code:```python-import bui.tksyntax-bui.tksyntax.install() # `import tkinter` now returns BUI's tkinter--import tkinter as tk-from tkinter import ttk, messagebox+import blenderui.tksyntax as tk+from blenderui.tksyntax import ttk, messageboxroot = tk.Tk()-root.title("Hello")name = tk.StringVar(value="Cube")ttk.Entry(root, textvariable=name).pack(fill="x", padx=8, pady=8)ttk.Button(root, text="Greet",@@ -156,395 +75,388 @@ ttk.Button(root, text="Greet",root.mainloop()```-Or import it directly, under its own name:--```python-import bui.tksyntax as tk-from bui.tksyntax import ttk-```--<p align="center">- <img src="docs/images/tkinter_notes.png" width="260" alt="Text with tags">- <img src="docs/images/tkinter_canvas.png" width="260" alt="Canvas">- <img src="docs/images/tkinter_messagebox.png" width="260" alt="messagebox">-</p>--Everything is supported, including ttk, `messagebox`, `filedialog`,-`simpledialog`, `colorchooser`, `font` and `scrolledtext`. That covers-`pack`/`grid`/`place`, scrollbars, `Canvas` (tags, `create_window`,-scroll regions), `Text` (indices, tags, marks, search, undo), `Treeview`,-bindings, variables and traces, `after`, and window-manager calls.-Full guide: **[docs/tkinter.md](docs/tkinter.md)**.--> **GPU rendering:** add `gpu=True` to `Tk(...)` (or call `bui.set_gpu(True)`,-> or run with `BUI_GPU=1`) to draw on the GPU. See [GPU renderer](#gpu-renderer).--### Qt syntax--```python-from bui.qtsyntax import (QApplication, QWidget, QVBoxLayout, QFormLayout,- QLineEdit, QSlider, QPushButton, QLabel)--app = QApplication([])-window = QWidget()-window.setWindowTitle("Qt syntax on BUI")-layout = QVBoxLayout(window)--form = QFormLayout()-name = QLineEdit()-name.setPlaceholderText("type here…")-level = QSlider()-level.setRange(0, 100)-form.addRow("Name:", name)-form.addRow("Level:", level)-layout.addLayout(form)--status = QLabel("Press the button.")-button = QPushButton("Click me")-button.clicked.connect(lambda: status.setText("Hello " + (name.text() or "BUI")))-layout.addWidget(status)-layout.addWidget(button)--window.show()-app.exec()-```--<p align="center"><img src="docs/images/qt.png" width="460" alt="Qt syntax on BUI"></p>--Supported classes, signals, layouts and the known gaps:-**[docs/qt.md](docs/qt.md)**.--### Blender components+Or build with Blender's own components:```python-from bui.components import (App, Panel, NumberSlider, VectorField, EnumRow,- Checkbox, ColorSwatch, Button)+from blenderui.components import App, Panel, NumberSlider, VectorField, Checkbox, ColorSwatch, ButtonApp("Object", (420, 520),Panel("Transform",VectorField("Location", (0.0, 1.25, 0.0)),NumberSlider("Scale", 1.0, min=0, max=10, on_change=print)),Panel("Shading",- EnumRow("Mode", ["Solid", "Material", "Rendered"]),Checkbox("Shadows", True),ColorSwatch("Color", (0.8, 0.3, 0.1, 1.0))),Button("Apply", on_click=lambda: print("apply")),).run()```-Component reference and Blender interaction details:-**[docs/components.md](docs/components.md)**.--### Rust (gpui syntax, HTML and CSS)+### Rust```toml[dependencies]-blenderui = { git = "https://github.com/ppmpreetham/BUI" } # needs CMake and a C compiler+blenderui = { git = "https://github.com/ppmpreetham/BUI" } # crates.io release coming; needs CMake + a C compiler``````rustuse blenderui::prelude::*;-struct Counter { count: i32 }--impl Render for Counter {- fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {- div().flex().flex_col().gap_2().p_4()- .child(h1().child(format!("Count: {}", self.count)))- .child(p().child("Any ").child(b().child("HTML element")).child(", styled with ")- .child(code().child(".css()")).child(" or a <style> sheet."))- .child(button().child("Add one").on_click(cx.listener(|this, _, _, cx| {- this.count += 1;- cx.notify();- })))- .child(input().input_type("range").min(0.0).max(10.0)) // a Blender slider+#[component]+fn counter(label: &str) {+ let (count, set_count) = use_state(0);+ rsx! {+ <div flex items-center gap-3 p-4 rounded-xl bg-zinc-800>+ <span text-zinc-300>{label.to_string()} ": " {count().to_string()}</span>+ <div px-3 py-1 rounded-md bg-sky-700 hover:bg-sky-500 onClick={move || set_count(count() + 1)}>+ "Add one"+ </div>+ </div>+ }+}++struct Hello;++impl Render for Hello {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ rsx! {+ <body m-0 p-6 min-h-screen flex flex-col gap-4 bg-zinc-900 text-white>+ <h1 text-2xl font-bold>"Hello, BUI"</h1>+ <counter label="Clicks" />+ <input type="range" min={0.0} max={10.0} /> // a real Blender slider+ </body>+ }}}fn main() {- Application::new().run(|cx: &mut App| {- cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Counter { count: 0 }))- .unwrap();+ Application::new().run(|cx| {+ cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Hello)).unwrap();});}```-> **GPU rendering:** `Application::new().gpu(true)` (or `BUI_GPU=1`) draws every-> window with Direct3D 11: same pixels, about half the CPU of the default-> software raster, and less than gpui-fast. See [GPU renderer](#gpu-renderer).+<p align="center">+ <img src="https://raw.githubusercontent.com/ppmpreetham/BUI/main/docs/images/rust-hello.png" width="420" alt="The Rust hello example: a heading, a counter component and a Blender slider">+</p>++This example lives at [`bindings/rust/blenderui/examples/hello.rs`](bindings/rust/blenderui/examples/hello.rs)+(`cargo run --release --example hello`).++### C++```c+#include "BUI_kit.h" /* see examples/kit_hello.c and docs/c-api.md */+```++Build from source with CMake (see [Building from source](#building-from-source)).++## What it can do++<table>+<tr><td width="50%" valign="top">-<p align="center"><img src="docs/images/rust-showcase.png" width="560" alt="The Rust showcase example"></p>-<p align="center"><sub><code>bindings/rust/blenderui/examples/showcase.rs</code>: a stylesheet, grid cards with-gradients and shadows, Blender form widgets, a table, lists, <code><details></code> and <code><pre></code>.</sub></p>+### 🎛️ 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.+- Press-drag-release menus, **type to search** in menus, pie menus.+- **Ctrl+Z / Ctrl+Shift+Z** on every UI edit, Tab between fields.+- Multi-field vertical drags, animated collapsing panels.+- The HSV color wheel, color ramps, curves, trees, lists, text areas and canvases.-Elements, the CSS that is supported, events and testing headless:-**[docs/rust.md](docs/rust.md)**.+</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.+- One `pip install`, no Qt or Tk widgets drawing anything.++</td></tr>+<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**.+- **`rsx!` / `view!`** JSX, **`#[component]`**, and **hooks** in zopra, React or Leptos style (`use_state`, `signal`, `Memo`, `Effect`, context).+- **gpui-compatible syntax** too: `div().flex().gap_2()`, `Render`, `cx.listener`.++</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**.+- Text works everywhere: GDI on Windows, a bundled TrueType engine on Linux, macOS and wasm.++</td></tr>+</table>++<details>+<summary><b>More screenshots</b></summary>+<p align="center">+ <img src="https://raw.githubusercontent.com/ppmpreetham/BUI/main/docs/images/rust-showcase.png" width="560" alt="The Rust showcase: a stylesheet, grid cards, Blender form widgets, a table and lists">+ <br><sub><code>examples/showcase.rs</code>: HTML + CSS in Rust</sub><br><br>+ <img src="https://raw.githubusercontent.com/ppmpreetham/BUI/main/docs/images/qt.png" width="420" alt="Qt syntax on BUI">+ <br><sub>Qt syntax</sub><br><br>+ <img src="https://raw.githubusercontent.com/ppmpreetham/BUI/main/docs/images/tkinter_notes.png" width="260" alt="tkinter Text with tags">+ <img src="https://raw.githubusercontent.com/ppmpreetham/BUI/main/docs/images/tkinter_canvas.png" width="260" alt="tkinter Canvas">+ <img src="https://raw.githubusercontent.com/ppmpreetham/BUI/main/docs/images/tkinter_messagebox.png" width="260" alt="tkinter messagebox">+ <br><sub>tkinter programs: text with tags, canvas, dialogs</sub>+</p>+</details>++### A taste of the Rust side++```rust+rsx! {+ // Tailwind as attributes, any variant, arbitrary values; typos fail to compile+ <button px-3 py-1 rounded-md bg-zinc-800 hover:bg-sky-600 md:dark:hover:bg-sky-400+ active:style="transform: scale(0.97)" onClick={move || save()}>+ "Save"+ </button>++ // control flow right in the markup+ <ul>{for item in items { <li class="py-1">{item}</li> }}</ul>+ {if dirty { <p text-amber-400>"Unsaved changes"</p> }}++ // real CSS, evaluated by the engine+ <div style="width: calc(100% - 2 * var(--gap)); background: color-mix(in oklch, var(--brand) 60%, white)" />+}+```++```text+error: rsx!: `bg-sky-50O` is not a Tailwind utility; did you mean `bg-sky-500` or `bg-sky-50` or `bg-sky-100`?+```++## Status: what's done and what's not++### ✅ 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 80/90, math functions, `var()`, CSS Color 4/5, Selectors 4, `@layer`/`@media`/`@supports`/`@scope`, Tailwind v4, `rsx!`, `#[component]`, hooks, headless testing |+| Rendering | Software raster (parallel, damage-tracked), GPU renderer (Direct3D 11), portable text engine |+| Packaging | [`blenderui` on PyPI](https://pypi.org/project/blenderui/), with a CI workflow for wheels on all platforms |++### 🟡 Partial or in progress++| Area | What's missing |+|---|---|+| Qt syntax (~25%) | Model/view classes, docks, toolbars, splitters, Qt stylesheets ([details](docs/qt.md#coverage)) |+| CSS (176 of 745 W3C properties render) | Rendering effects: `rotate`/`skew` transforms, `filter`/`backdrop-filter`, blend modes, `clip-path`, masks, `border-image`, non-solid borders. Also animations and transitions, background images, applying `@container`, `@font-face`. Most of the remaining W3C list is drafts, speech, print and SVG ([breakdown](docs/rust.md#coverage)) |+| Text | No text wrapping around floats; no right-to-left shaping |+| Rust components | No optional props; no async resources (`use_resource`); no generic components |+| Linux / macOS | They work through a fallback window (the stdlib Tk window shows BUI's frame), but they're less tested. No native window host and no GPU renderer yet |+| crates.io | The crates are ready to publish but not published yet; use the git dependency for now |++### 🗺️ Planned++| Target | Plan |+|---|---|+| **WebAssembly** | The kit in the browser: the raster blits to `<canvas>`, DOM events feed the kit. This unlocks the React, JS/TS and Tauri targets |+| **React** (`@blenderui/react`) | A JSX reconciler over the WASM build |+| **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```- your code: tkinter syntax Qt syntax bui.components- │ │ │- └──────── Python: options, signals, variables, callbacks- │- C kit (kit/): node tree ─ geometry (pack/grid/place) ─ input & interaction- ─ Blender widget drawing ─ damage-driven raster rendering- │- window host: native Win32 window (Windows) │ stdlib Tk window (elsewhere)+ your code: tkinter syntax Qt syntax components Rust: rsx! / HTML / CSS / Tailwind / hooks+ │ │ │ │+ └──── Python: options, signals, callbacks └── style cascade + taffy layout+ │ │+ C kit (kit/): node tree · geometry · input & interaction · Blender widget drawing · undo · animation+ │+ renderer: damage-driven software raster (parallel) or GPU (Direct3D 11, instanced, opt-in)+ │+ window: native Win32 window · stdlib Tk window (elsewhere) · headless (tests, screenshots)```-- **One node tree.** Every widget wraps one kit node: `button`, `number`,- `slider`, `text`, `textarea`, `list`, `tree`, `canvas`, `scrollbar` and so- on. The C kit owns layout, hit testing, hover, focus, drag grabs, menus,- tooltips, undo and animation.-- **Tk's geometry managers in C.** `pack` and `grid` are ports of Tk's own- packer and gridder. Qt's box, grid and form layouts are mapped onto them.-- **Damage rendering.** A state change marks only its widget's rectangle.- A frame redraws just those regions into a frame buffer (anti-aliased SDF- shapes and a cached glyph-run text engine: GDI on Windows, stb_truetype- elsewhere), on the CPU or, opt-in, on the GPU. Only the changed tiles are- presented to the window.-- **Python stays thin.** Facades keep what tkinter and Qt keep in their own- scripting layers: option values, variables, traces, signals and bindings.+- **Blender's real UI code.** Widget drawing is a C port of Blender's+ `interface_widgets.cc` (`round_box_edges`, `widgetbase_draw`, the shape+ tables). Color math, rects and text cursors are Blender's `blenlib`.+- **One node tree.** Every widget is one kit node. The C kit owns layout, hit+ testing, hover, focus, drags, menus, tooltips, undo and animation.+- **Damage rendering.** A change marks only its widget's rectangle, and only+ changed tiles reach the screen.+- **Thin bindings.** Python and Rust keep only what the syntax layer needs.More: [ARCHITECTURE.md](ARCHITECTURE.md).## Performance-Measured on the full component demo (520×900) on a desktop CPU:+Python and C, on the full component demo (520×900):-| Frame | Time |-| ----------------------------------------------- | -------- |-| Complete frame (everything redrawn) | ~0.7 ms |-| Hover or number-scrub frame (damage only) | ~0.05 ms |-| Native window: input event → render → on screen | ~0.06 ms |-| Tk-hosted window, the same path | ~0.18 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 |-The test suite enforces a 120 Hz budget: full frames under 8.3 ms, and-interaction frames under 1 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:-### Rust: blenderui vs gpui+| | 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 % |-The same UI built with the `blenderui` crate and with-[gpui](https://crates.io/crates/gpui) 0.2.2 (Zed's GPU-rendered framework)-and its faster fork [gpui-fast](https://github.com/longbridge/gpui-fast): a-1000×800 window of N rounded, labelled cells that all change every frame.-Ryzen 7 5800U laptop on mains power, 60 Hz display, release builds, all apps-back to back in one session-([method and full data](bindings/rust/bench/README.md)). blenderui is shown-with its opt-in GPU renderer (`.gpu(true)` / `BUI_GPU=1`) and its default-software raster.+<details>+<summary>Full results, the GPU renderer, and the method</summary>-| | blenderui (GPU) | blenderui (CPU raster) | gpui-fast | gpui |+| | blenderui (GPU) | blenderui (CPU) | gpui-fast | gpui ||---|---:|---:|---:|---:|-| FPS, 3000 animated cells | **59.9** | 57.6 | 31.5 | 19.9 || FPS, 1000 animated cells | **60** | **60** | 49.2 | 36.4 |-| CPU per frame, 3000 cells | **11.6 ms** | 22.0 ms | 31.9 ms + GPU | 50.5 ms + GPU |-| CPU per frame, 1000 cells | **4.7 ms** | 10.2 ms | 20.5 ms + GPU | 27.7 ms + GPU |-| CPU per frame, 100 cells | **1.2 ms** | 4.6 ms | 2.7 ms + GPU | 4.7 ms + GPU |+| 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 (working set), 3000 / 1000 / 100 cells | 40 / 35 / 28 MB | **30 / 24 / 21 MB** | 65 / 45 / 47 MB | 77 / 47 / 40 MB |-| GPU memory | 19-22 MB | **none** | 19-24 MB | 16-21 MB |-| First frame after launch | **~5 ms** | **~5 ms** | ~200 ms | ~220 ms |-| Idle CPU | **0 %** | 0-0.9 % | 0-0.4 % | 0.9-1.4 % |--With the GPU renderer, blenderui beats gpui-fast on every row. It does the-least CPU work per frame at every scene size (2.2-4.4x less than gpui-fast),-holds 60 fps where both gpuis drop, and uses less RAM with the same GPU-memory. It still starts about 40x faster. The software raster remains the-default, because it needs no GPU memory or driver. gpui-fast's heavy-scene-frame rate varies between sessions on this laptop (30-60 fps at 3000 cells),-so compare within a session.--### GPU renderer--Off by default; turn it on per app or per window:--```rust-Application::new().gpu(true).run(|cx| { /* ... */ }); // every window-cx.open_window(WindowOptions { gpu: Some(true), ..Default::default() }, build); // one window-```+| 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.+- Frames render into a persistent target, so only damaged regions redraw.+- Presentation uses a flip-model swap chain with dirty rects.++Its shaders evaluate the software raster's formulas: the parity test finds+10 of 172,800 pixels that differ by more than 3/255.++gpui-fast's heavy-scene frame rate varies between sessions on this laptop+(30–60 fps), so compare within one session. Method, raw data and how to rerun:+[bindings/rust/bench/README.md](bindings/rust/bench/README.md).+</details>-```python-from bui import tksyntax as tk-root = tk.Tk(gpu=True) # or bui.set_gpu(True) for every window-```+## Documentation-Or set `BUI_GPU=1` for any BUI app (C, Python, Rust); `BUI_GPU=0` forces the-software raster. It is Direct3D 11 on Windows. On other platforms, or when-no device can be created, windows stay on the software raster. The design-follows Blender's instanced widget-base batches (`interface_widgets.cc`):-- Every primitive is one 128-byte instance of a single uber-shader- ([`gpu/shaders/bui_ui.hlsl`](gpu/shaders/bui_ui.hlsl)). The primitives are- rects, Blender widget bases with outline and emboss, circles, lines,- shadows, gradients, HSV wheels, images and text runs.-- A frame of thousands of widgets is a few `DrawInstanced` calls.-- Text runs and images are cached in atlases.-- Frames render into a persistent target, so damage tracking still limits- redraws to what changed. Presentation uses a flip-model swap chain with- dirty rects.-- The device is created on a worker thread, so startup never waits for the- driver.--The shaders evaluate the software raster's own coverage formulas, so both-renderers draw the same pixels: the `gpu_parity` test finds 10 of 172,800-pixels that differ by more than 3/255, all on hard triangle edges.--### tkinter canvas--[`bindings/python/bench/tk_canvas_bench.py`](bindings/python/bench/tk_canvas_bench.py) (2000 rectangles, ovals, lines, polygons, arcs and-labels on one tkinter-syntax `Canvas`, rendered headless):--| Per frame | before | now |-|---|---:|---:|-| Render, every item moved | 11.1 ms | **3.6 ms** (parallel raster for all item types) |-| Render, one item moved | 9.4 ms | **0.08 ms** (only the item's old and new boxes redraw) |-| Python, 2000 `Canvas.move` calls | 22.5 ms | **15.0 ms** (cached colors, O(1) item lookup) |--## Roadmap: more languages and platforms--BUI's core is plain C with a small, stable surface (`kit/include/BUI_kit.h`-for widgets, `api/bui_c_api.h` for render sinks). Its output is either a-frame buffer (`BuiRaster`, ARGB pixels plus damage rectangles) or a stream-of draw primitives. That makes every target below the same job: bind the C-API, feed in input events, and present the pixels or primitives. None of-them needs Python.--| Target | Plan | Status |-|---|---|---|-| **Python**: tkinter, Qt, components | `bui.tksyntax`, `bui.qtsyntax`, `bui.components` | ✅ Done (Qt partial) |-| **C / C++** | `BUI_kit.h`, render sinks, Qt/QPainter backend | ✅ Done |-| **Rust** | `blenderui-sys` (FFI over `BUI_kit.h`, builds the kit with CMake) and `blenderui`: gpui syntax, all HTML elements, CSS, taffy layout ([docs/rust.md](docs/rust.md)) | ✅ Done (native window on Windows; Linux/macOS render headless until their window hosts land) |-| **egui** | Two ways in: draw a BUI panel inside egui (raster to an `egui::TextureHandle`, with input forwarded), and a Blender-styled `egui::Visuals` theme | 🗺️ Planned |-| **WebAssembly** | Compile the kit with rust. The raster blits to a `<canvas>` (`putImageData` of the damage rectangles only), and DOM pointer and keyboard events go to `BK_press` / `BK_key` | 🗺️ Planned |-| **React** | `@blenderui/react` on top of the WASM build: a reconciler that maps JSX to kit nodes (`<Panel>`, `<NumberSlider>` ...) | 🗺️ Planned |-| **JavaScript / TypeScript** | `@blenderui/web` (the plain WASM API), and Node through N-API | 🗺️ Planned |-| **Tauri / Electron** | The WASM build in the webview, or the native kit through the host language | 🗺️ Planned |-| **C# / .NET** | P/Invoke over `BUI_kit.h` (WinForms / WPF / Avalonia hosts) | 🗺️ Planned |-| **Go**, **Zig**, **Swift**, **Kotlin/JVM**, **Lua** | cgo / `@cImport` / Swift C interop / Panama FFI / LuaJIT FFI over the same header | 🗺️ Planned |-| **Dear ImGui** | A backend that shows BUI panels in an ImGui window, plus a Blender-styled ImGui theme | 🗺️ Planned |-| **Game engines**: Godot, Unity, Bevy | Editor-style tool panels: GDExtension, a native Unity plugin, a Bevy plugin through the Rust crate | 🗺️ Planned |-| **Flutter** | `dart:ffi` bindings, with the frame buffer shown as a `Texture` | 🗺️ Planned |-| **Native windows on Linux / macOS** | Wayland / X11 and Cocoa hosts in C, like the Win32 one (today the stdlib Tk window hosts them) | 🗺️ Planned |-| **GPU renderers** | Direct3D 11 done (opt-in, see [GPU renderer](#gpu-renderer)); Vulkan / Metal / WebGPU backends for the same instance stream | 🟡 D3D11 done |+| 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 |+| [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>Intended API sketches (planned, not implemented yet)</summary>+<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 |+</details>-egui:+## Building from source-```rust-egui::Window::new("Properties").show(ctx, |ui| {- blenderui_egui::panel(ui, &mut state.bui_panel); // a BUI subtree inside egui-});-```+You need **CMake ≥ 3.20**, a **C11 compiler** (GCC/MinGW or Clang; MSVC+works for the Rust build) and **Python 3.11+** with headers.-React (WebAssembly):+```sh+git clone https://github.com/ppmpreetham/BUI && cd BUI+cmake -S . -B build && cmake --build build+ctest --test-dir build # C and Python test suites-```jsx-import { render } from "@blenderui/react";+export PYTHONPATH=$PWD/bindings/python # Windows: set PYTHONPATH=%CD%\bindings\python+python examples/components_demo.py-export default function Properties() {- const [size, setSize] = useState(1);- return (- render(<App />, {title: "Bla bla", width: 1920, height: 1080})- );-}+cd bindings/rust && cargo test # Rust: CSS, Tailwind, rsx!, hooks, headless windows```+<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/`), text (GDI / stb_truetype) |+| `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>-Work order: the Rust crate is done (it also unlocks egui and Bevy); next is-the WebAssembly build (it unlocks React, JS/TS, Tauri and Electron), then-native Linux / macOS windows.+## FAQ-## Packaging+<details>+<summary><b>Do I need Blender installed?</b></summary>+No. BUI contains the parts of Blender's UI code it needs and builds on its own.+</details>-The project is packaged as **`blenderui`** for PyPI: `pyproject.toml` with-scikit-build-core, which drives the CMake build. One wheel contains the-`buipy` extension plus the `bui` and `blenderui` packages.+<details>+<summary><b>Is it really my unchanged tkinter app?</b></summary>+Yes. <code>blenderui-tk app.py</code> makes <code>import tkinter</code> return BUI's+implementation, which covers every public tkinter and ttk name. Nine real+programs are tested to behave identically on the standard library and on BUI.+See <a href="docs/tkinter.md#limitations">the limitations</a> for the few+differences.+</details>-```sh-python -m pip install build-python -m build # dist/blenderui-<version>.tar.gz and a wheel-```+<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+<a href="https://github.com/DioxusLabs/taffy">taffy</a> and drawn with Blender's+widgets, in a native window.+</details>-- **Version:** a single source, `bindings/python/bui/_version.py`, read by- CMake and by the packaging.-- **CI:** `.github/workflows/wheels.yml` runs `cibuildwheel` for CPython- 3.11–3.14 on Windows (MinGW), Linux (manylinux) and macOS (arm64 and- x86_64), plus an sdist and the full ctest run. Pushing a `v*` tag- publishes to PyPI with trusted publishing (no tokens stored).-- **Verified locally:** a wheel built on Windows installs into a clean- virtualenv and passes the component, syntax, render, tkinter-compat and- input suites.-- **Release steps and one-time PyPI setup:** [docs/publishing.md](docs/publishing.md).- Changes are recorded in [CHANGELOG.md](CHANGELOG.md).+<details>+<summary><b>Do the macros cost performance?</b></summary>+<code>rsx!</code>, <code>#[component]</code>, <code>css!</code> and <code>tw!</code>+expand at compile time into the same builder calls you would write by hand.+Tailwind classes are compiled to CSS once, on first use. Hooks are a few+nanoseconds per read or write.+</details>-## Documentation+<details>+<summary><b>Why GPL?</b></summary>+BUI is derived from Blender's source code, which is GPL-2.0-or-later, so BUI is too.+</details>-| Guide | What's inside |-| -------------------------------------------------- | ---------------------------------------------------------------------------------------- |-| [docs/getting-started.md](docs/getting-started.md) | Building, `PYTHONPATH`, environment variables, choosing the window host, troubleshooting |-| [docs/tkinter.md](docs/tkinter.md) | Running tkinter apps on BUI, module map, behaviour notes, the Blender look, limitations |-| [docs/qt.md](docs/qt.md) | Qt-syntax guide: classes, signals, layouts, painting, timers, coverage and gaps |-| [docs/components.md](docs/components.md) | `bui.components` reference: layout, values, views, menus, color, editors, `App` |-| [docs/c-api.md](docs/c-api.md) | The C kit (`BUI_kit.h`): nodes, properties, events, windows |-| [docs/rust.md](docs/rust.md) | The Rust crate: gpui syntax, HTML elements, CSS coverage, events, headless testing |-| [docs/publishing.md](docs/publishing.md) | Packaging as `blenderui`, building wheels, CI, releasing to PyPI |-| [CHANGELOG.md](CHANGELOG.md) | Release notes |-| [SYNTAX_COVERAGE.md](SYNTAX_COVERAGE.md) | Member-by-member coverage tables for both syntax layers |-| [INTEGRATION.md](INTEGRATION.md) | Embedding BUI drawing in C, C++, Qt or PySide hosts through render sinks |-| [ARCHITECTURE.md](ARCHITECTURE.md) | Modules, dependency rules, what was taken from Blender and how |--Examples (`examples/`):--| File | Shows |-| ------------------------------ | --------------------------------------------------------------- |-| `tk_unchanged_app.py` | A plain tkinter app: menus, notebook, form, table, text, canvas |-| `tk_syntax_demo.py` | tkinter syntax laid out like a Blender properties editor |-| `qt_syntax_demo.py` | Qt syntax: layouts, form widgets, signals |-| `components_demo.py` | Every Blender component, in a properties-editor layout |-| `kit_hello.c` | The C kit from C: a slider and a button in a native window |-| `bindings/rust/blenderui/examples/showcase.rs` | Rust: HTML, a stylesheet, flex/grid, tables, Blender form widgets |-| `python_demo.py`, `svg_demo.c` | Low-level drawing into an SVG render sink |--## Repository layout--| Path | Contents |-| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `kit/` | **The C runtime**: `kit_core.c` (nodes, input, rendering, undo, views), `kit_draw.c` (theme and the `interface_widgets.cc` port), `kit_widgets.c`, `kit_views.c` (lists, trees), `kit_menus.c`, `kit_color.c`, `kit_frame.c` (geometry managers, canvas), `kit_textarea.c`, `kit_window.c` (Win32 host). Public API: `kit/include/BUI_kit.h` |-| `gpu/` | Drawing: software raster (`gpu_raster.c`), D3D11 GPU renderer (`gpu_d3d11.c`, `shaders/`), text (GDI / stb_truetype), render-sink dispatch |-| `core/`, `types/` | Blender's `blenlib` subset (C11) 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 (`bui_c_api.h`) |-| `bindings/python/` | `buipy` extension (`src/`) and the `bui` package: `tksyntax/`, `qtsyntax.py`, `components/`, `host.py` |-| `backends/qt/` | C++ Qt/QPainter render-sink backend |-| `bindings/rust/` | Cargo workspace: `blenderui-sys` (FFI, builds the kit with CMake) and `blenderui` (gpui syntax, HTML, CSS, taffy layout) |-| `bindings/python/blenderui/` | The `blenderui` import alias (the PyPI name) |-| `pyproject.toml`, `.github/workflows/` | PyPI packaging (scikit-build-core) and the wheel and release CI |-| `examples/`, `tools/` | Demos, the icon generator, the docs screenshot generator |--## Testing+## Contributing-```sh-ctest --test-dir build --output-on-failure-```+Contributions are welcome: bug reports, missing tkinter/Qt behavior, CSS+features, platform hosts and docs. Read [CONTRIBUTING.md](CONTRIBUTING.md) first,+and please follow the [Code of Conduct](CODE_OF_CONDUCT.md). Report security+issues privately, as [SECURITY.md](SECURITY.md) describes.-| Suite | Covers |-| -------------------------------- | ---------------------------------------------------------------------------------- |-| `core` | blenlib subset |-| `buipy`, `buipy_render` | Raster primitives, damage tracking, the native window against the frame buffer |-| `buipy_components` | Every component, Blender interactions, undo, multi-drag, animation, 120 Hz budgets |-| `buipy_syntax`, `buipy_advanced` | Qt and tkinter facades: layouts, painting, menus, dialogs, images |-| `buipy_tk_compat` | Nine tkinter programs run on stdlib tkinter **and** BUI; results must match |-| `buipy_tk_input` | tkinter widgets driven by real pointer and keyboard input through the kit |+## Acknowledgments-Rust (`cd bindings/rust && cargo test`): CSS parsing and selectors, the HTML and CSS-coverage report (`cargo test --test parity -- --nocapture`), and headless windows-checking layout positions, painted pixels, clicks, `:hover` and Blender widgets.+- [Blender](https://www.blender.org): the UI this project is built from.+- [taffy](https://github.com/DioxusLabs/taffy): flexbox, grid and block layout for the Rust crate.+- [Tailwind CSS](https://tailwindcss.com): the v4 theme (MIT) behind the Tailwind support.+- [stb_truetype](https://github.com/nothings/stb): the portable text engine (public domain).+- [gpui](https://github.com/zed-industries/zed), [zopra](https://github.com/ppmpreetham/zopra) and [Leptos](https://leptos.dev): the APIs the Rust syntax follows.## License-Derived from Blender sources: **GPL-2.0-or-later** (see `LICENSE` and the SPDX-headers kept in every file).+BUI is derived from Blender sources and is licensed **GPL-2.0-or-later**. The+SPDX header is kept in every file. Third-party parts keep their own licenses:+stb_truetype is public domain, and the Tailwind theme values are MIT.diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 0000000..d511eeb--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,16 @@+# Security Policy++## Supported versions++Security fixes go into the latest release on PyPI (`blenderui`) and into the+`main` branch.++## Reporting a vulnerability++Please **don't open a public issue** for security problems. Report them+privately through+[GitHub's private vulnerability reporting](https://github.com/ppmpreetham/BUI/security/advisories/new).+Include steps to reproduce, the affected version and platform, and the impact.++You'll get an acknowledgment within a week. Once a fix is released, you'll+be credited in the changelog, unless you'd rather stay anonymous.diff --git a/bindings/rust/Cargo.toml b/bindings/rust/Cargo.tomlindex 6b45684..e37f2de 100644--- a/bindings/rust/Cargo.toml+++ b/bindings/rust/Cargo.toml@@ -8,4 +8,4 @@ version = "0.1.0"edition = "2024"license = "GPL-2.0-or-later"repository = "https://github.com/ppmpreetham/BUI"-rust-version = "1.85"+rust-version = "1.88"diff --git a/bindings/rust/blenderui-macros/Cargo.toml b/bindings/rust/blenderui-macros/Cargo.tomlindex 5ae9092..3519219 100644--- a/bindings/rust/blenderui-macros/Cargo.toml+++ b/bindings/rust/blenderui-macros/Cargo.toml@@ -1,11 +1,13 @@[package]name = "blenderui-macros"-description = "Compile-time CSS for blenderui: the css! macro"+description = "Compile-time macros for blenderui: rsx!/view!, #[component], css! and tw!"version.workspace = trueedition.workspace = truelicense.workspace = truerepository.workspace = truerust-version.workspace = true+keywords = ["gui", "jsx", "rsx", "tailwind", "css"]+categories = ["gui"][lib]proc-macro = truediff --git a/bindings/rust/blenderui-macros/src/component.rs b/bindings/rust/blenderui-macros/src/component.rsnew file mode 100644index 0000000..8870242--- /dev/null+++ b/bindings/rust/blenderui-macros/src/component.rs@@ -0,0 +1,122 @@+//! `#[component]`: a function becomes a component (zopra / Leptos style).+//!+//! ```ignore+//! #[component]+//! fn profile(username: &str, likes: u32) {+//! let (n, set_n) = use_state(likes);+//! rsx! { <span onClick={move || set_n(n() + 1)}>{username} " " {n()}</span> }+//! }+//! // used as <profile username="Alice" likes={3} />+//! ```+//!+//! Expands to a props struct named like the function, with an `IntoElement`+//! impl that runs the body in a component scope (hooks, context). `&str`+//! props are stored as `String`; the body still sees `&str`.++use proc_macro::{Delimiter, Group, TokenStream, TokenTree};++pub fn component(input: TokenStream) -> TokenStream {+ match expand(input) {+ Ok(ts) => ts,+ Err(e) => format!("::core::compile_error!({e:?});").parse().unwrap(),+ }+}++fn ts(s: &str) -> TokenStream {+ s.parse().expect("#[component]: scaffold")+}++fn expand(input: TokenStream) -> Result<TokenStream, String> {+ let toks: Vec<TokenTree> = input.into_iter().collect();+ let fn_at = toks.iter().position(|t| matches!(t, TokenTree::Ident(i) if i.to_string() == "fn"))+ .ok_or("#[component] goes on a function")?;+ let vis: TokenStream = toks[..fn_at].iter()+ .filter(|t| !matches!(t, TokenTree::Punct(p) if p.as_char() == '#'))+ .filter(|t| !matches!(t, TokenTree::Group(g) if g.delimiter() == Delimiter::Bracket))+ .cloned().collect();+ let name = match toks.get(fn_at + 1) {+ Some(TokenTree::Ident(i)) => i.to_string(),+ _ => return Err("#[component]: expected a function name".into()),+ };+ let params = match toks.get(fn_at + 2) {+ Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Parenthesis => g.stream(),+ _ => return Err("#[component]: generic components are not supported; use concrete prop types".into()),+ };+ let body = match toks.last() {+ Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Brace => g.clone(),+ _ => return Err("#[component]: expected a body".into()),+ };+ // props: `name: Type` split at top-level commas (angle brackets count)+ let mut props: Vec<(String, TokenStream)> = Vec::new();+ let mut cur: Vec<TokenTree> = Vec::new();+ let mut depth = 0i32;+ let ptoks: Vec<TokenTree> = params.into_iter().collect();+ for (k, t) in ptoks.iter().enumerate() {+ match t {+ TokenTree::Punct(p) if p.as_char() == '<' => depth += 1,+ TokenTree::Punct(p) if p.as_char() == '>'+ && !matches!(k.checked_sub(1).and_then(|j| ptoks.get(j)), Some(TokenTree::Punct(q)) if q.as_char() == '-') => {+ depth -= 1+ }+ TokenTree::Punct(p) if p.as_char() == ',' && depth == 0 => {+ props.push(prop(&cur)?);+ cur.clear();+ continue;+ }+ _ => {}+ }+ cur.push(t.clone());+ }+ if !cur.is_empty() {+ props.push(prop(&cur)?);+ }+ let mut fields = TokenStream::new();+ let mut names = Vec::new();+ let mut shadows = TokenStream::new();+ for (n, ty) in &props {+ let s = ty.to_string().replace(' ', "");+ let field_ty = if s == "&str" || s == "&'staticstr" {+ shadows.extend(ts(&format!("let {n}: &str = &{n};")));+ ts("::std::string::String")+ } else if s.starts_with('&') {+ return Err(format!("#[component]: prop `{n}` borrows (`{s}`); use an owned type"));+ } else {+ ty.clone()+ };+ fields.extend(ts(&format!("pub {n}:")));+ fields.extend(field_ty);+ fields.extend(ts(","));+ names.push(n.clone());+ }+ let mut out = ts("#[allow(non_camel_case_types)]");+ out.extend(vis);+ out.extend(ts(&format!("struct {name}")));+ out.extend([TokenTree::Group(Group::new(Delimiter::Brace, fields))]);+ // impl IntoElement+ let mut inner = ts(&format!("let {name} {{ {} }} = self;", names.join(", ")));+ inner.extend(shadows);+ inner.extend(ts("::blenderui::hooks::component"));+ let mut closure = ts("|| ::blenderui::element::IntoElement::into_any_element");+ closure.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, body_expr(body)))]);+ inner.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, closure))]);+ let mut method = ts("fn into_any_element(self) -> ::blenderui::element::AnyElement");+ method.extend([TokenTree::Group(Group::new(Delimiter::Brace, inner))]);+ out.extend(ts(&format!("impl ::blenderui::element::IntoElement for {name}")));+ out.extend([TokenTree::Group(Group::new(Delimiter::Brace, method))]);+ Ok(out)+}++/// The body as an expression: a block, whose last expression may also be+/// bare markup (zopra lets a component end in `<div>..</div>`).+fn body_expr(body: Group) -> TokenStream {+ TokenStream::from(TokenTree::Group(body))+}++fn prop(toks: &[TokenTree]) -> Result<(String, TokenStream), String> {+ let colon = toks.iter().position(|t| matches!(t, TokenTree::Punct(p) if p.as_char() == ':'))+ .ok_or("#[component]: props are `name: Type`")?;+ let name = toks[..colon].iter()+ .filter(|t| !matches!(t, TokenTree::Ident(i) if i.to_string() == "mut"))+ .map(|t| t.to_string()).collect::<String>();+ Ok((name, toks[colon + 1..].iter().cloned().collect()))+}diff --git a/bindings/rust/blenderui-macros/src/lib.rs b/bindings/rust/blenderui-macros/src/lib.rsindex a6bf6e2..aa41ad6 100644--- a/bindings/rust/blenderui-macros/src/lib.rs+++ b/bindings/rust/blenderui-macros/src/lib.rs@@ -11,6 +11,23 @@use proc_macro::{TokenStream, TokenTree};+mod component;+mod rsx;++/// A function component (zopra / Leptos style): `#[component] fn card(title: &str) { rsx!{..} }`,+/// used as `<card title="x"/>`. See `component.rs`.+#[proc_macro_attribute]+pub fn component(_attr: TokenStream, item: TokenStream) -> TokenStream {+ component::component(item)+}++/// JSX-style markup: `rsx! { <div class="p-4" onClick={|| ..}>"hi" {name}</div> }`.+/// See `rsx.rs` for the (uniform) lowering to builder calls.+#[proc_macro]+pub fn rsx(input: TokenStream) -> TokenStream {+ rsx::rsx(input)+}+#[proc_macro]pub fn css(input: TokenStream) -> TokenStream {match expand(input) {@@ -33,9 +50,10 @@ pub fn tw(input: TokenStream) -> TokenStream {let Some(text) = unquote(&lit) else {return "::core::compile_error!(\"tw! takes one string literal\")".parse().unwrap();};- let unknown: Vec<&str> = text.split_whitespace().filter(|c| blenderui_tailwind::compile(c).is_none()).collect();+ let unknown: Vec<String> = text.split_whitespace().filter(|c| blenderui_tailwind::compile(c).is_none())+ .map(blenderui_tailwind::unknown_message).collect();if !unknown.is_empty() {- let msg = format!("tw!: not Tailwind utilities: {}", unknown.join(", "));+ let msg = format!("tw!: {}", unknown.join("; "));return format!("::core::compile_error!({msg:?})").parse().unwrap();}format!("{text:?}").parse().unwrap()diff --git a/bindings/rust/blenderui-macros/src/rsx.rs b/bindings/rust/blenderui-macros/src/rsx.rsnew file mode 100644index 0000000..1c2365a--- /dev/null+++ b/bindings/rust/blenderui-macros/src/rsx.rs@@ -0,0 +1,716 @@+//! `rsx!`: JSX-style markup lowered to blenderui's builder calls.+//!+//! The lowering is uniform, so nothing is special-cased per element or+//! attribute; the compiler checks the result against the real API:+//!+//! | markup | becomes |+//! |--------------------------------|-------------------------------------------|+//! | `<div ...>` | `html::div()` (any tag; `<my-el>` -> `Div::new("my-el")`) |+//! | `<Card a={x}>..</Card>` | `Card { a: x, children: vec![..] }` (components) |+//! | `name="lit"` / bare `name` | `.attr("name", "lit")` (`class`, `style`, `id`: their methods) |+//! | `name={expr}` | `.name(expr)`: any builder method (`checked`, `w`, `hover` ...) |+//! | `onClick={|| ..}` | `.on_click(|_, _, _| ..)` (missing listener params added) |+//! | `"text"`, `{expr}`, `{...it}` | `.child(..)`, `.children(it)` |+//! | `{for x in it { <li/> }}` | `.children(it.into_iter().map(..))` |+//! | `{if c { <a/> } else { .. }}` | `.children(if c { Some(..) } else { .. })` |+//! | `{match v { p => <a/>, .. }}` | `.child(match v { p => .., .. })` |+//! | `<>..</>` | `display: contents` wrapper |++use proc_macro::{Delimiter, Group, Spacing, TokenStream, TokenTree};++type R<T> = Result<T, String>;++pub fn rsx(input: TokenStream) -> TokenStream {+ let toks: Vec<TokenTree> = input.into_iter().collect();+ match markup(&toks) {+ Ok(ts) => ts,+ Err(e) => format!("::core::compile_error!({e:?})").parse().unwrap(),+ }+}++fn ts(s: &str) -> TokenStream {+ s.parse().expect("rsx!: scaffold")+}++fn is(t: Option<&TokenTree>, c: char) -> bool {+ matches!(t, Some(TokenTree::Punct(p)) if p.as_char() == c)+}++/// One or more nodes; several become a fragment.+fn markup(toks: &[TokenTree]) -> R<TokenStream> {+ let mut p = P { t: toks, i: 0 };+ let mut nodes = Vec::new();+ while p.i < p.t.len() {+ nodes.push(p.node()?);+ }+ Ok(match nodes.len() {+ 1 => match nodes.pop() {+ Some(Child::One(e)) => e,+ Some(other) => fragment(vec![other]),+ None => unreachable!(),+ },+ _ => fragment(nodes),+ })+}++fn fragment(nodes: Vec<Child>) -> TokenStream {+ let mut out = ts("::blenderui::html::div().style(\"display: contents\")");+ for n in nodes {+ out.extend(n.call());+ }+ out+}++/// A child, as the call that adds it.+enum Child {+ One(TokenStream),+ Many(TokenStream),+}++impl Child {+ fn call(self) -> TokenStream {+ let (m, e) = match self {+ Child::One(e) => ("child", e),+ Child::Many(e) => ("children", e),+ };+ let mut out = ts(&format!(".{m}"));+ out.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, e))]);+ out+ }+}++struct P<'a> {+ t: &'a [TokenTree],+ i: usize,+}++impl P<'_> {+ fn peek(&self) -> Option<&TokenTree> {+ self.t.get(self.i)+ }++ fn node(&mut self) -> R<Child> {+ match self.peek() {+ Some(TokenTree::Punct(p)) if p.as_char() == '<' => self.element().map(Child::One),+ Some(TokenTree::Literal(l)) => {+ let l = l.clone();+ self.i += 1;+ Ok(Child::One(TokenStream::from(TokenTree::Literal(l))))+ }+ Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Brace => {+ let g = g.clone();+ self.i += 1;+ braced(&g)+ }+ Some(TokenTree::Ident(_)) => {+ // bare text: words up to the next tag or brace, joined by spaces+ let mut words = Vec::new();+ while let Some(t @ (TokenTree::Ident(_) | TokenTree::Punct(_) | TokenTree::Literal(_))) = self.peek() {+ if is(Some(t), '<') {+ break;+ }+ words.push(t.to_string());+ self.i += 1;+ }+ Ok(Child::One(ts(&format!("{:?}", join_words(&words)))))+ }+ Some(t) => Err(format!("rsx!: unexpected `{t}`")),+ None => Err("rsx!: unexpected end".into()),+ }+ }++ /// `name` or `name-with-dashes` (tags and attributes).+ fn name(&mut self) -> R<String> {+ // pieces joined by `-` / `:` (and `@` / `*` starting a piece): `data-x`,+ // `md:hover:class`, `2xl:class`, `@md:class`, `*:class`, `data-[state=open]:class`+ let mut s = String::new();+ let mut want_piece = true;+ let mut last_end: Option<(usize, usize)> = None;+ loop {+ let t = self.peek().cloned();+ // pieces of one name touch in the source: `h-1 -mt-2` is two names+ if let (Some(end), Some(t)) = (last_end, &t) {+ let start = t.span().start();+ if (start.line(), start.column()) != end {+ break;+ }+ }+ if let Some(t) = &t {+ let e = t.span().end();+ last_end = Some((e.line(), e.column()));+ }+ match t {+ Some(TokenTree::Ident(i)) if want_piece => s.push_str(&i.to_string()),+ Some(TokenTree::Literal(l)) if want_piece && !l.to_string().starts_with('"') => s.push_str(&l.to_string()),+ Some(TokenTree::Group(g)) if want_piece && g.delimiter() == Delimiter::Bracket => {+ s.push('[');+ s.push_str(&g.stream().to_string().replace(' ', ""));+ s.push(']');+ }+ // `-mt-2`, `!p-4`: a sign before the first piece+ Some(TokenTree::Punct(p)) if matches!(p.as_char(), '-' | '!') && s.is_empty() => {+ s.push(p.as_char());+ self.i += 1;+ continue;+ }+ // `w-1/2`, `bg-sky-500/50`, `text-sm/6` (not the `/` of `/>`)+ Some(TokenTree::Punct(p)) if p.as_char() == '/' && !want_piece && !s.is_empty()+ && !is(self.t.get(self.i + 1), '>') => {+ s.push('/');+ self.i += 1;+ want_piece = true;+ continue;+ }+ // `p-4!`: important+ Some(TokenTree::Punct(p)) if p.as_char() == '!' && !want_piece && !s.is_empty() => {+ s.push('!');+ self.i += 1;+ break;+ }+ Some(TokenTree::Punct(p)) if matches!(p.as_char(), '@' | '*') && want_piece => {+ s.push(p.as_char());+ self.i += 1;+ continue; // still expecting the rest of the piece (or a separator after `*`)+ }+ Some(TokenTree::Punct(p)) if matches!(p.as_char(), '-' | ':') && !s.is_empty() && !want_piece => {+ s.push(p.as_char());+ self.i += 1;+ want_piece = true;+ continue;+ }+ Some(TokenTree::Punct(p)) if p.as_char() == ':' && s.ends_with('*') => {+ s.push(':');+ self.i += 1;+ continue;+ }+ _ => break,+ }+ self.i += 1;+ want_piece = false;+ }+ if s.is_empty() || s.ends_with(['-', ':', '/']) {+ return Err(format!("rsx!: expected a name, found `{}`",+ self.peek().map(|t| t.to_string()).unwrap_or_default()));+ }+ Ok(s.trim_start_matches("r#").to_string())+ }++ fn element(&mut self) -> R<TokenStream> {+ self.i += 1; // <+ if is(self.peek(), '>') {+ // fragment <>...</>+ self.i += 1;+ let kids = self.children_until("")?;+ return Ok(fragment(kids));+ }+ let tag = self.name()?;+ let component = tag.chars().next().is_some_and(|c| c.is_ascii_uppercase())+ || !tag.contains('-') && !tag.contains(':') && !HTML_TAGS.contains(&tag.as_str());+ let mut base = if component {+ TokenStream::new()+ } else if tag.contains('-') || tag.contains(':') {+ ts(&format!("::blenderui::element::Div::new({tag:?})"))+ } else {+ ts(&format!("::blenderui::html::{tag}()"))+ };+ let mut fields = TokenStream::new(); // component props+ let mut classes: Vec<String> = Vec::new(); // bare utility attributes+ loop {+ match self.peek() {+ Some(TokenTree::Punct(p)) if p.as_char() == '/' => {+ self.i += 1;+ if !is(self.peek(), '>') {+ return Err(format!("rsx!: expected `>` after `/` in <{tag}>"));+ }+ self.i += 1;+ if !classes.is_empty() {+ base.extend(ts(&format!(".class({:?})", classes.join(" "))));+ }+ return Ok(if component { component_expr(&tag, fields, Vec::new()) } else { base });+ }+ Some(TokenTree::Punct(p)) if p.as_char() == '>' => {+ self.i += 1;+ break;+ }+ Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Brace && !component => {+ // `{...spread}` attributes: a builder closure `{|el| el.w(px(3.))}`+ let g = g.clone();+ self.i += 1;+ let mut call = TokenStream::from(TokenTree::Group(Group::new(Delimiter::Parenthesis, g.stream())));+ call.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, std::mem::take(&mut base)))]);+ base = call;+ }+ _ => {+ let name = self.name()?;+ let value = if is(self.peek(), '=') {+ self.i += 1;+ match self.peek() {+ Some(t @ (TokenTree::Literal(_) | TokenTree::Group(_))) => {+ let t = t.clone();+ self.i += 1;+ Some(t)+ }+ _ => return Err(format!("rsx!: `{name}=` needs \"text\" or {{expr}}")),+ }+ } else {+ None+ };+ if value.is_none() && !component {+ match bare(&name)? {+ Some(class) => {+ classes.push(class);+ continue;+ }+ None => {}+ }+ }+ if component {+ fields.extend(ts(&format!("{}:", name.replace('-', "_"))));+ fields.extend(match value {+ Some(TokenTree::Group(g)) => g.stream(),+ Some(t) => {+ let mut s = TokenStream::from(t);+ s.extend(ts(".into()"));+ s+ }+ None => ts("true"),+ });+ fields.extend(ts(","));+ } else {+ base.extend(attribute(&name, value)?);+ }+ }+ }+ }+ if !classes.is_empty() {+ base.extend(ts(&format!(".class({:?})", classes.join(" "))));+ }+ let kids = self.children_until(&tag)?;+ if component {+ return Ok(component_expr(&tag, fields, kids));+ }+ for k in kids {+ base.extend(k.call());+ }+ Ok(base)+ }++ /// Children up to `</tag>` (or `</>` for fragments).+ fn children_until(&mut self, tag: &str) -> R<Vec<Child>> {+ let mut kids = Vec::new();+ loop {+ if is(self.peek(), '<') && is(self.t.get(self.i + 1), '/') {+ self.i += 2;+ if !tag.is_empty() {+ let close = self.name()?;+ if close != tag {+ return Err(format!("rsx!: <{tag}> closed by </{close}>"));+ }+ }+ if !is(self.peek(), '>') {+ return Err(format!("rsx!: expected `>` in </{tag}>"));+ }+ self.i += 1;+ return Ok(kids);+ }+ if self.peek().is_none() {+ return Err(format!("rsx!: <{tag}> is never closed"));+ }+ kids.push(self.node()?);+ }+ }+}++fn join_words(words: &[String]) -> String {+ let mut s = String::new();+ for w in words {+ let glue = !s.is_empty() && !matches!(w.as_str(), "," | "." | "!" | "?" | ";" | ":" | "'" | ")")+ && !s.ends_with(['(', '\'']);+ if glue {+ s.push(' ');+ }+ s.push_str(w);+ }+ s+}++/// `<Card a={x}>kids</Card>` -> `Card { a: x, children: vec![..] }`+fn component_expr(tag: &str, mut fields: TokenStream, kids: Vec<Child>) -> TokenStream {+ if !kids.is_empty() {+ // { let mut v = Vec::new(); v.push(..); v.extend(..); v }+ let mut body = ts("let mut __v: ::std::vec::Vec<::blenderui::element::AnyElement> = ::std::vec::Vec::new();");+ for k in kids {+ match k {+ Child::One(e) => {+ body.extend(ts("__v.push"));+ body.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, any(e)))]);+ }+ Child::Many(e) => {+ let mut it = ts("::core::iter::IntoIterator::into_iter");+ it.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, e))]);+ it.extend(ts(".map(::blenderui::element::IntoElement::into_any_element)"));+ body.extend(ts("__v.extend"));+ body.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, it))]);+ }+ }+ body.extend(ts(";"));+ }+ body.extend(ts("__v"));+ fields.extend(ts("children:"));+ fields.extend([TokenTree::Group(Group::new(Delimiter::Brace, body))]);+ fields.extend(ts(","));+ }+ let mut out = ts(tag);+ out.extend([TokenTree::Group(Group::new(Delimiter::Brace, fields))]);+ out+}++/// `hover:class="..."`, `md:dark:style="..."`, `hover:color="red"`,+/// `active:bg={red()}`: an attribute under Tailwind variants. Classes get the+/// prefix, CSS becomes arbitrary properties (`hover:[color:red]`), so every+/// Tailwind variant works through the same engine; typed `{expr}` values+/// use the native `.hover()` / `.active()` / `.focus()` refinements.+fn variant_attribute(name: &str, value: Option<TokenTree>) -> R<TokenStream> {+ let (variants, base) = name.rsplit_once(':').ok_or("rsx!: variant")?;+ let prefix = format!("{variants}:");+ let class_call = |s: String| ts(&format!(".class({s:?})"));+ // a CSS declaration list -> `v:[prop:value]` classes+ let decls_to_classes = |css: &str| -> String {+ css.split(';').filter_map(|d| {+ let (p, v) = d.split_once(':')?;+ let v = v.trim().replace('_', "\\_").replace(' ', "_");+ Some(format!("{prefix}[{}:{}]", p.trim(), v))+ }).collect::<Vec<_>>().join(" ")+ };+ let unquote = |l: &proc_macro::Literal| -> R<String> {+ let s = l.to_string();+ s.strip_prefix('"').and_then(|s| s.strip_suffix('"')).map(|s| s.replace("\\\"", "\""))+ .ok_or_else(|| format!("rsx!: `{name}` needs a string"))+ };+ Ok(match (base, value) {+ ("class", Some(TokenTree::Literal(l))) => {+ let v = unquote(&l)?;+ class_call(v.split_whitespace().map(|c| format!("{prefix}{c}")).collect::<Vec<_>>().join(" "))+ }+ ("style", Some(TokenTree::Literal(l))) => class_call(decls_to_classes(&unquote(&l)?)),+ // run time: prefix the classes / convert the CSS of an expression+ ("class" | "style", Some(TokenTree::Group(g))) => {+ let conv = if base == "class" {+ format!("__c.split_whitespace().map(|c| ::std::format!(\"{prefix}{{c}}\")).collect::<::std::vec::Vec<_>>().join(\" \")")+ } else {+ format!("__c.split(';').filter_map(|d| {{ let (p, v) = d.split_once(':')?; \+ ::core::option::Option::Some(::std::format!(\"{prefix}[{{}}:{{}}]\", p.trim(), \+ v.trim().replace('_', \"\\\\_\").replace(' ', \"_\"))) }}) \+ .collect::<::std::vec::Vec<_>>().join(\" \")")+ };+ let mut arg = ts("&");+ arg.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, g.stream()))]);+ let mut body = ts("let __c: ::std::string::String = ::std::string::ToString::to_string");+ body.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, arg))]);+ body.extend(ts(&format!("; {conv}")));+ let mut out = ts(".class");+ out.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis,+ TokenStream::from(TokenTree::Group(Group::new(Delimiter::Brace, body)))))]);+ out+ }+ // hover:color="red": a CSS property under the variants+ (prop, Some(TokenTree::Literal(l))) => class_call(decls_to_classes(&format!("{prop}: {}", unquote(&l)?))),+ // active:bg={red()}: a typed style method in the state's refinement+ (method, Some(TokenTree::Group(g))) if matches!(variants, "hover" | "active" | "focus") => {+ let mut inner = ts(&format!("|__s| __s.{}", method_name(method)));+ inner.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, g.stream()))]);+ let mut out = ts(&format!(".{variants}"));+ out.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, inner))]);+ out+ }+ (_, Some(TokenTree::Group(_))) => {+ return Err(format!("rsx!: `{name}={{..}}`: typed values work under hover / active / focus; \+ use `{variants}:class` or `{variants}:style` for other variants"));+ }+ _ => return Err(format!("rsx!: `{name}` needs a value")),+ })+}++/// Tags with an element function; any other lowercase tag is a component+/// (`<profile ..>` -> `profile { .. }`, as in zopra).+const HTML_TAGS: &[&str] = &[+ "html", "body", "article", "section", "nav", "aside", "h1", "h2", "h3", "h4", "h5", "h6", "hgroup",+ "header", "footer", "address", "p", "hr", "pre", "blockquote", "ol", "ul", "menu", "li", "dl", "dt", "dd",+ "figure", "figcaption", "main", "search", "div", "a", "em", "strong", "small", "s", "cite", "q", "dfn",+ "abbr", "ruby", "rt", "rp", "data", "time", "code", "var", "samp", "kbd", "sub", "sup", "i", "b", "u",+ "mark", "bdi", "bdo", "span", "ins", "del", "picture", "table", "caption", "colgroup", "col", "tbody",+ "thead", "tfoot", "tr", "td", "th", "form", "label", "fieldset", "legend", "details", "summary", "dialog",+ "noscript", "slot", "output", "map", "selectedcontent", "svg", "math", "button", "input", "select",+ "option", "optgroup", "textarea", "progress", "meter", "datalist", "img", "iframe", "embed", "object",+ "video", "audio", "head", "title", "base", "link", "meta", "style", "script", "template", "source",+ "track", "area", "br", "wbr",+];++/// HTML boolean attributes: bare, they stay attributes even where a+/// Tailwind utility has the same name (`hidden`).+const BOOLEAN_ATTRS: &[&str] = &[+ "allowfullscreen", "async", "autofocus", "autoplay", "checked", "controls", "default", "defer", "disabled",+ "formnovalidate", "hidden", "inert", "ismap", "itemscope", "loop", "multiple", "muted", "nomodule",+ "novalidate", "open", "playsinline", "readonly", "required", "reversed", "selected", "popover", "draggable",+ "contenteditable", "spellcheck", "translate",+];++/// A bare attribute (`<div p-4 hover:bg-sky-500>`): Some(class) when it is+/// a Tailwind utility, None for a plain boolean attribute, an error with+/// suggestions when it looks like a misspelled utility.+fn bare(name: &str) -> R<Option<String>> {+ if BOOLEAN_ATTRS.contains(&name) || name.starts_with("data-") && !name.contains(':')+ || name.starts_with("aria-") && !name.contains(':')+ {+ return Ok(None);+ }+ if blenderui_tailwind::compile(name).is_some() {+ return Ok(Some(name.to_string()));+ }+ let looks_like_utility = name.contains(':') || name.contains('[') || name.contains('/')+ || !blenderui_tailwind::suggest(name).is_empty() && name.contains('-');+ if looks_like_utility {+ return Err(format!("rsx!: {}", blenderui_tailwind::unknown_message(name)));+ }+ Ok(None)+}++/// One attribute on an HTML element.+fn attribute(name: &str, value: Option<TokenTree>) -> R<TokenStream> {+ let ns = name.split(':').next().unwrap_or("");+ if name.contains(':') && !matches!(ns, "xlink" | "xml" | "xmlns") {+ return variant_attribute(name, value);+ }+ let lit = |s: &str| ts(&format!("{s:?}"));+ Ok(match value {+ // literals: the method for class / style / id, an attribute otherwise+ Some(TokenTree::Literal(l)) => {+ let m = match name {+ "class" | "className" => "class",+ "style" => "style",+ "id" | "key" => "id",+ _ => {+ let mut out = ts(".attr");+ let mut args = lit(name);+ args.extend(ts(","));+ args.extend([TokenTree::Literal(l)]);+ out.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, args))]);+ return Ok(out);+ }+ };+ let mut out = ts(&format!(".{m}"));+ out.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, TokenStream::from(TokenTree::Literal(l))))]);+ out+ }+ // expressions: the builder method of that name (snake_cased)+ Some(TokenTree::Group(g)) => {+ let method = method_name(name);+ if name.contains('-') || name.contains(':') || name == "for" || name == "htmlFor" {+ let name = if name == "htmlFor" { "for" } else { name };+ let mut args = lit(name);+ args.extend(ts(","));+ args.extend(g.stream());+ let mut out = ts(".attr");+ out.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, args))]);+ return Ok(out);+ }+ let arg = if method.starts_with("on_") { listener(g.stream()) } else { g.stream() };+ let mut out = ts(&format!(".{method}"));+ out.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, arg))]);+ out+ }+ None => {+ let mut args = lit(name);+ args.extend(ts(", \"\""));+ let mut out = ts(".attr");+ out.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, args))]);+ out+ }+ Some(t) => return Err(format!("rsx!: bad value `{t}` for `{name}`")),+ })+}++/// `onClick` -> `on_click`, `type` -> `input_type`, `className` -> `class`.+fn method_name(name: &str) -> String {+ match name {+ "type" => return "input_type".into(),+ "className" => return "class".into(),+ "key" => return "id".into(),+ _ => {}+ }+ let mut s = String::new();+ for (k, c) in name.chars().enumerate() {+ if c.is_ascii_uppercase() {+ if k > 0 {+ s.push('_');+ }+ s.push(c.to_ascii_lowercase());+ } else {+ s.push(c);+ }+ }+ if s.starts_with("on") && !s.starts_with("on_") && s.len() > 2 {+ s.insert(2, '_');+ }+ s+}++/// A listener closure with fewer than the three `(event, window, cx)`+/// parameters gets `_` for the missing ones: `|| ..`, `|e| ..` work.+fn listener(stream: TokenStream) -> TokenStream {+ let toks: Vec<TokenTree> = stream.into_iter().collect();+ let start = usize::from(matches!(toks.first(), Some(TokenTree::Ident(i)) if i.to_string() == "move"));+ let pipe = |k: usize| matches!(toks.get(k), Some(TokenTree::Punct(p)) if p.as_char() == '|');+ if !pipe(start) {+ return toks.into_iter().collect(); // a path or other expression: as is+ }+ // `||` is one Punct pair (joint) with nothing between+ let (params, body_at): (Vec<TokenTree>, usize) = if matches!(toks.get(start), Some(TokenTree::Punct(p)) if p.spacing() == Spacing::Joint)+ && pipe(start + 1)+ {+ (Vec::new(), start + 2)+ } else {+ let close = (start + 1..toks.len()).find(|&k| pipe(k)).unwrap_or(toks.len());+ (toks[start + 1..close].to_vec(), close + 1)+ };+ let given = if params.is_empty() {+ 0+ } else {+ params.iter().filter(|t| matches!(t, TokenTree::Punct(p) if p.as_char() == ',')).count() + 1+ };+ let mut out: TokenStream = toks[..start].iter().cloned().collect();+ out.extend(ts("|"));+ out.extend(params);+ for k in given..3 {+ out.extend(ts(if k == 0 { "_" } else { ", _" }));+ }+ out.extend(ts("|"));+ out.extend(toks[body_at.min(toks.len())..].iter().cloned());+ out+}++/// `{...}` children: control flow, spreads, or an expression.+fn braced(g: &Group) -> R<Child> {+ let toks: Vec<TokenTree> = g.stream().into_iter().collect();+ let kw = |k: usize, s: &str| matches!(toks.get(k), Some(TokenTree::Ident(i)) if i.to_string() == s);+ if is(toks.first(), '.') && is(toks.get(1), '.') && is(toks.get(2), '.') {+ return Ok(Child::Many(toks[3..].iter().cloned().collect()));+ }+ if kw(0, "for") {+ // for PAT in ITER { BODY }+ let in_at = (1..toks.len()).find(|&k| kw(k, "in")).ok_or("rsx!: `for` without `in`")?;+ let body = match toks.last() {+ Some(TokenTree::Group(b)) if b.delimiter() == Delimiter::Brace => b.clone(),+ _ => return Err("rsx!: `for` needs a { body }".into()),+ };+ let pat: TokenStream = toks[1..in_at].iter().cloned().collect();+ let iter: TokenStream = toks[in_at + 1..toks.len() - 1].iter().cloned().collect();+ let mut out = ts("::core::iter::IntoIterator::into_iter");+ out.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, iter))]);+ let mut closure = ts("move |");+ closure.extend(pat);+ closure.extend(ts("|"));+ closure.extend([TokenTree::Group(Group::new(Delimiter::Brace, any(body_expr(&body)?)))]);+ out.extend(ts(".map"));+ out.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, closure))]);+ return Ok(Child::Many(out));+ }+ if kw(0, "if") {+ return Ok(Child::Many(if_chain(&toks)?));+ }+ if kw(0, "match") {+ let arms = match toks.last() {+ Some(TokenTree::Group(b)) if b.delimiter() == Delimiter::Brace => b.clone(),+ _ => return Err("rsx!: `match` needs { arms }".into()),+ };+ let mut out: TokenStream = toks[..toks.len() - 1].iter().cloned().collect();+ out.extend([TokenTree::Group(Group::new(Delimiter::Brace, match_arms(&arms)?))]);+ return Ok(Child::One(out));+ }+ Ok(Child::One(g.stream()))+}++/// A body: markup when it starts with `<` (or is text), Rust otherwise.+fn body_expr(b: &Group) -> R<TokenStream> {+ let toks: Vec<TokenTree> = b.stream().into_iter().collect();+ if is(toks.first(), '<') {+ markup(&toks)+ } else {+ Ok(b.stream())+ }+}++fn any(e: TokenStream) -> TokenStream {+ let mut c = ts("::blenderui::element::IntoElement::into_any_element");+ c.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, e))]);+ c+}++/// `if c { A } else if d { B } else { C }` -> the same chain of `Some(..)` / `None`.+fn if_chain(toks: &[TokenTree]) -> R<TokenStream> {+ let mut out = TokenStream::new();+ let mut k = 0;+ let mut has_else = false;+ while k < toks.len() {+ match &toks[k] {+ TokenTree::Group(b) if b.delimiter() == Delimiter::Brace+ && toks.get(k + 1).is_none_or(|t| matches!(t, TokenTree::Ident(i) if i.to_string() == "else")) => {+ let mut some = ts("::core::option::Option::Some");+ some.extend([TokenTree::Group(Group::new(Delimiter::Parenthesis, any(body_expr(b)?)))]);+ out.extend([TokenTree::Group(Group::new(Delimiter::Brace, some))]);+ if matches!(toks.get(k - 1), Some(TokenTree::Ident(i)) if i.to_string() == "else") {+ has_else = true;+ }+ }+ t => out.extend([t.clone()]),+ }+ k += 1;+ }+ if !has_else {+ out.extend(ts("else { ::core::option::Option::None }"));+ }+ Ok(out)+}++/// `p => <a/>, q => { <b/> }` -> each arm's value as an AnyElement.+fn match_arms(arms: &Group) -> R<TokenStream> {+ let toks: Vec<TokenTree> = arms.stream().into_iter().collect();+ let mut out = TokenStream::new();+ let mut k = 0;+ while k < toks.len() {+ // pattern up to `=>`+ let start = k;+ while k + 1 < toks.len() && !(is(toks.get(k), '=') && is(toks.get(k + 1), '>')) {+ k += 1;+ }+ if k + 1 >= toks.len() {+ return Err("rsx!: match arm without `=>`".into());+ }+ out.extend(toks[start..k + 2].iter().cloned());+ k += 2;+ // value up to the top-level `,` (markup elements are matched by tag)+ let vstart = k;+ let value: TokenStream = if let Some(TokenTree::Group(b)) = toks.get(k).filter(|_| {+ matches!(toks.get(k), Some(TokenTree::Group(b)) if b.delimiter() == Delimiter::Brace)+ }) {+ k += 1;+ body_expr(b)?+ } else if is(toks.get(k), '<') {+ let mut p = P { t: &toks, i: k };+ let e = p.element()?;+ k = p.i;+ e+ } else {+ while k < toks.len() && !is(toks.get(k), ',') {+ k += 1;+ }+ toks[vstart..k].iter().cloned().collect()+ };+ out.extend(any(value));+ out.extend(ts(","));+ if is(toks.get(k), ',') {+ k += 1;+ }+ }+ Ok(out)+}diff --git a/bindings/rust/blenderui-sys/Cargo.toml b/bindings/rust/blenderui-sys/Cargo.tomlindex 0553fa4..c7f84de 100644--- a/bindings/rust/blenderui-sys/Cargo.toml+++ b/bindings/rust/blenderui-sys/Cargo.toml@@ -8,6 +8,10 @@ repository.workspace = truerust-version.workspace = truelinks = "bui_kit"build = "build.rs"+keywords = ["gui", "ui", "blender", "ffi"]+categories = ["gui", "external-ffi-bindings"]+# csrc/ is git-ignored (vendored by scripts/vendor_c.py), so list it explicitly+include = ["src/**", "build.rs", "Cargo.toml", "csrc/**"][features]# The portable stb_truetype text engine on Windows too (always on elsewhere).diff --git a/bindings/rust/blenderui-sys/build.rs b/bindings/rust/blenderui-sys/build.rsindex e0f74e1..b9ec36e 100644--- a/bindings/rust/blenderui-sys/build.rs+++ b/bindings/rust/blenderui-sys/build.rs@@ -1,13 +1,17 @@//! Builds the C kit (kit + gpu + core) with the project's own CMake files and-//! links it statically. Set `BUI_SOURCE_DIR` to build from another checkout.+//! links it statically. Set `BUI_SOURCE_DIR` to build from another checkout;+//! published crates carry the sources in `csrc/`.use std::path::PathBuf;fn main() {let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());- let root = std::env::var("BUI_SOURCE_DIR")- .map(PathBuf::from)- .unwrap_or_else(|_| manifest.join("../../.."));+ // BUI_SOURCE_DIR, else the repository around this crate, else the sources+ // vendored into the published crate (`csrc/`, see scripts/vendor_c.py)+ let root = std::env::var("BUI_SOURCE_DIR").map(PathBuf::from).unwrap_or_else(|_| {+ let repo = manifest.join("../../..");+ if repo.join("kit/include/BUI_kit.h").exists() { repo } else { manifest.join("csrc") }+ });let root = root.canonicalize().expect("BUI source tree not found (set BUI_SOURCE_DIR)");// Windows canonical paths are \\?\C:\...; compilers' /FI and -include can't take them.let root = PathBuf::from(root.to_string_lossy().trim_start_matches(r"\\?\").to_string());diff --git a/bindings/rust/blenderui-tailwind/Cargo.toml b/bindings/rust/blenderui-tailwind/Cargo.tomlindex 1dc17cb..d34205e 100644--- a/bindings/rust/blenderui-tailwind/Cargo.toml+++ b/bindings/rust/blenderui-tailwind/Cargo.toml@@ -6,3 +6,5 @@ edition.workspace = truelicense.workspace = truerepository.workspace = truerust-version.workspace = true+keywords = ["tailwind", "css", "gui", "blenderui"]+categories = ["gui", "web-programming"]diff --git a/bindings/rust/blenderui-tailwind/src/lib.rs b/bindings/rust/blenderui-tailwind/src/lib.rsindex edbffa5..1f4a236 100644--- a/bindings/rust/blenderui-tailwind/src/lib.rs+++ b/bindings/rust/blenderui-tailwind/src/lib.rs@@ -951,7 +951,8 @@ fn utility_decls(u: &str) -> Option<Out> {Out { decls: s.iter().map(|x| (format!("scroll-padding{x}"), val.clone())).collect(), child: None, keyframes: None }}"will-change" if !neg => one("will-change", free(v)?.1)?,- "touch" if !neg => one("touch-action", v.replace("pan-", "pan-"))?,+ "touch" if !neg && matches!(v, "pan-x" | "pan-left" | "pan-right" | "pan-y" | "pan-up" | "pan-down"+ | "pinch-zoom") => one("touch-action", v.into())?,"border-spacing" | "border-spacing-x" | "border-spacing-y" if !neg => one("border-spacing", spacing(v)?)?,"break-before" | "break-after" | "break-inside" if !neg => one(root, v.into())?,"mask" if !neg => one("mask-image", free(v)?.1)?,@@ -961,34 +962,36 @@ fn utility_decls(u: &str) -> Option<Out> {Some(out)}+const ROOTS: &[&str] = &[+ "backdrop-hue-rotate", "backdrop-brightness", "backdrop-contrast", "backdrop-grayscale", "backdrop-saturate",+ "backdrop-opacity", "backdrop-invert", "backdrop-sepia", "backdrop-blur", "perspective-origin",+ "underline-offset", "outline-offset", "border-spacing-x", "border-spacing-y", "border-spacing", "inset-shadow",+ "drop-shadow", "text-shadow", "justify-items", "justify-self", "place-content", "place-items", "place-self",+ "ring-offset", "inset-ring", "will-change", "line-clamp", "list-image", "hue-rotate", "break-before",+ "break-after", "break-inside", "min-inline", "max-inline", "min-block", "max-block", "translate-x",+ "translate-y", "translate-z", "grid-cols", "grid-rows", "col-start", "row-start", "auto-cols", "auto-rows",+ "brightness", "grayscale", "translate", "perspective", "col-span", "row-span", "col-end", "row-end",+ "rounded-ss", "rounded-se", "rounded-ee", "rounded-es", "rounded-tl", "rounded-tr", "rounded-br",+ "rounded-bl", "rounded-s", "rounded-e", "rounded-t", "rounded-r", "rounded-b", "rounded-l", "rounded",+ "border-x", "border-y", "border-s", "border-e", "border-t", "border-r", "border-b", "border-l",+ "border-bs", "border-be", "divide-x", "divide-y", "scroll-mx", "scroll-my", "scroll-ms", "scroll-me",+ "scroll-mt", "scroll-mr", "scroll-mb", "scroll-ml", "scroll-px", "scroll-py", "scroll-ps", "scroll-pe",+ "scroll-pt", "scroll-pr", "scroll-pb", "scroll-pl", "scroll-m", "scroll-p", "rotate-x", "rotate-y",+ "rotate-z", "scale-x", "scale-y", "scale-z", "skew-x", "skew-y", "space-x", "space-y", "bg-blend",+ "mix-blend", "contrast", "saturate", "duration", "tracking", "leading", "opacity", "content", "columns",+ "inset-x", "inset-y", "transform", "transition", "animate", "decoration", "outline", "origin", "invert",+ "sepia", "divide", "border", "shadow", "rotate", "scale", "skew", "basis", "order", "accent", "caret",+ "cursor", "stroke", "aspect", "object", "indent", "gap-x", "gap-y", "min-w", "max-w", "min-h", "max-h",+ "inline", "block", "inset", "start", "items", "justify", "self", "align", "delay", "ease", "blur", "ring",+ "fill", "font", "text", "list", "mask", "touch", "size", "flex", "grow", "shrink", "from", "via", "top",+ "right", "bottom", "left", "end", "col", "row", "gap", "pbs", "pbe", "mbs", "mbe", "bg", "to", "z",+ "px", "py", "ps", "pe", "pt", "pr", "pb", "pl", "mx", "my", "ms", "me", "mt", "mr", "mb", "ml", "p", "m",+ "w", "h",+ ];+/// Split `p-4` into (`p`, `4`) using the longest known root.fn split_root(u: &str) -> Option<(&str, &str)> {- const ROOTS: &[&str] = &[- "backdrop-hue-rotate", "backdrop-brightness", "backdrop-contrast", "backdrop-grayscale", "backdrop-saturate",- "backdrop-opacity", "backdrop-invert", "backdrop-sepia", "backdrop-blur", "perspective-origin",- "underline-offset", "outline-offset", "border-spacing-x", "border-spacing-y", "border-spacing", "inset-shadow",- "drop-shadow", "text-shadow", "justify-items", "justify-self", "place-content", "place-items", "place-self",- "ring-offset", "inset-ring", "will-change", "line-clamp", "list-image", "hue-rotate", "break-before",- "break-after", "break-inside", "min-inline", "max-inline", "min-block", "max-block", "translate-x",- "translate-y", "translate-z", "grid-cols", "grid-rows", "col-start", "row-start", "auto-cols", "auto-rows",- "brightness", "grayscale", "translate", "perspective", "col-span", "row-span", "col-end", "row-end",- "rounded-ss", "rounded-se", "rounded-ee", "rounded-es", "rounded-tl", "rounded-tr", "rounded-br",- "rounded-bl", "rounded-s", "rounded-e", "rounded-t", "rounded-r", "rounded-b", "rounded-l", "rounded",- "border-x", "border-y", "border-s", "border-e", "border-t", "border-r", "border-b", "border-l",- "border-bs", "border-be", "divide-x", "divide-y", "scroll-mx", "scroll-my", "scroll-ms", "scroll-me",- "scroll-mt", "scroll-mr", "scroll-mb", "scroll-ml", "scroll-px", "scroll-py", "scroll-ps", "scroll-pe",- "scroll-pt", "scroll-pr", "scroll-pb", "scroll-pl", "scroll-m", "scroll-p", "rotate-x", "rotate-y",- "rotate-z", "scale-x", "scale-y", "scale-z", "skew-x", "skew-y", "space-x", "space-y", "bg-blend",- "mix-blend", "contrast", "saturate", "duration", "tracking", "leading", "opacity", "content", "columns",- "inset-x", "inset-y", "transform", "transition", "animate", "decoration", "outline", "origin", "invert",- "sepia", "divide", "border", "shadow", "rotate", "scale", "skew", "basis", "order", "accent", "caret",- "cursor", "stroke", "aspect", "object", "indent", "gap-x", "gap-y", "min-w", "max-w", "min-h", "max-h",- "inline", "block", "inset", "start", "items", "justify", "self", "align", "delay", "ease", "blur", "ring",- "fill", "font", "text", "list", "mask", "touch", "size", "flex", "grow", "shrink", "from", "via", "top",- "right", "bottom", "left", "end", "col", "row", "gap", "pbs", "pbe", "mbs", "mbe", "bg", "to", "z",- "px", "py", "ps", "pe", "pt", "pr", "pb", "pl", "mx", "my", "ms", "me", "mt", "mr", "mb", "ml", "p", "m",- "w", "h",- ];+for r in ROOTS {if let Some(rest) = u.strip_prefix(r) {if let Some(v) = rest.strip_prefix('-') {@@ -1455,3 +1458,140 @@ mod tests {assert!(compile("p-1").unwrap().sort < compile("px-1").unwrap().sort);}}++// ==========================================================================+// Suggestions ("did you mean ...?")++/// Variant names for suggestions (functional ones by prefix).+const VARIANTS: &[&str] = &[+ "hover", "focus", "focus-visible", "focus-within", "active", "visited", "target", "first", "last", "only",+ "odd", "even", "first-of-type", "last-of-type", "only-of-type", "empty", "disabled", "enabled", "checked",+ "indeterminate", "default", "optional", "required", "valid", "invalid", "user-valid", "user-invalid",+ "in-range", "out-of-range", "placeholder-shown", "autofill", "read-only", "read-write", "open", "inert",+ "before", "after", "placeholder", "file", "marker", "selection", "first-line", "first-letter", "backdrop",+ "sm", "md", "lg", "xl", "2xl", "max-sm", "max-md", "max-lg", "max-xl", "max-2xl", "@sm", "@md", "@lg",+ "@xl", "@2xl", "dark", "motion-safe", "motion-reduce", "contrast-more", "contrast-less", "print",+ "portrait", "landscape", "forced-colors", "rtl", "ltr", "starting", "*", "**", "group-hover", "group-focus",+ "group-active", "peer-hover", "peer-focus", "peer-checked", "peer-invalid", "has-checked", "not-first",+ "pointer-fine", "pointer-coarse",+];++fn distance(a: &str, b: &str) -> usize {+ let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());+ let mut prev: Vec<usize> = (0..=b.len()).collect();+ for i in 1..=a.len() {+ let mut cur = vec![i; b.len() + 1];+ for j in 1..=b.len() {+ let cost = usize::from(a[i - 1] != b[j - 1]);+ cur[j] = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost);+ }+ prev = cur;+ }+ prev[b.len()]+}++/// Values worth trying after a root: theme keys and the common scales.+fn value_candidates() -> Vec<String> {+ let mut v: Vec<String> = THEME.iter().filter_map(|(k, _)| {+ ["color-", "text-", "radius-", "shadow-", "blur-", "font-weight-", "tracking-", "leading-",+ "breakpoint-", "container-", "drop-shadow-", "inset-shadow-", "text-shadow-", "perspective-"]+ .iter().find_map(|p| k.strip_prefix(p)).filter(|r| !r.contains("--")).map(String::from)+ }).collect();+ for n in ["0", "0.5", "1", "1.5", "2", "2.5", "3", "3.5", "4", "5", "6", "7", "8", "9", "10", "11", "12",+ "14", "16", "20", "24", "28", "32", "36", "40", "44", "48", "52", "56", "60", "64", "72", "80",+ "96", "px", "auto", "full", "screen", "min", "max", "fit", "none", "1/2", "1/3", "2/3", "1/4",+ "3/4", "sans", "serif", "mono", "left", "center", "right", "start", "end", "between", "around",+ "evenly", "stretch", "baseline", "row", "col", "wrap", "nowrap", "black", "white", "transparent",+ "current", "inherit", "50", "75", "90", "95", "100", "105", "110", "125", "150", "45", "90", "180"] {+ v.push(n.to_string());+ }+ v.sort();+ v.dedup();+ v+}++/// Valid classes close to `class` (best first, at most 3): misspelled+/// variants, roots, values or whole utilities.+pub fn suggest(class: &str) -> Vec<String> {+ let Some(parts) = split_variants(class) else { return Vec::new() };+ let (vars, util) = parts.split_at(parts.len() - 1);+ let util = util[0];+ // each variant: itself when valid, else its nearest names+ let mut var_options: Vec<Vec<String>> = Vec::new();+ for v in vars {+ if variant(v, ".x").is_some() {+ var_options.push(vec![v.to_string()]);+ } else {+ let mut near: Vec<&str> = VARIANTS.to_vec();+ near.sort_by_key(|n| distance(v, n));+ var_options.push(near.into_iter().take(2).map(String::from).collect());+ }+ }+ // the utility: itself when valid, else candidates+ let utils: Vec<String> = if utility_decls(util.trim_matches('!')).is_some() {+ vec![util.to_string()]+ } else {+ let (neg, body) = match util.strip_prefix('-') {+ Some(b) => ("-", b),+ None => ("", util),+ };+ let mut c: Vec<String> = STATIC.iter().map(|(n, _)| n.to_string()).collect();+ let values = value_candidates();+ let dashes: Vec<usize> = body.char_indices().filter(|(_, ch)| *ch == '-').map(|(k, _)| k).collect();+ for &k in &dashes {+ let (root, val) = (&body[..k], &body[k + 1..]);+ for r in ROOTS {+ c.push(format!("{neg}{r}-{val}")); // fix the root+ }+ for v in &values {+ c.push(format!("{neg}{root}-{v}")); // fix the value+ }+ }+ if dashes.is_empty() {+ for r in ROOTS {+ c.push(format!("{neg}{r}"));+ }+ }+ c.retain(|x| utility_decls(x).is_some());+ c.sort_by_key(|x| (distance(util, x), x.len().abs_diff(util.len())));+ c.dedup();+ c.into_iter().take(3).collect()+ };+ // combine (variants x utilities), keep what compiles, closest first+ let mut out: Vec<String> = vec![String::new()];+ for opts in var_options.iter().chain(std::iter::once(&utils)) {+ out = out.iter().flat_map(|p| opts.iter().map(move |o| if p.is_empty() { o.clone() } else { format!("{p}:{o}") }))+ .collect();+ }+ out.retain(|x| x != class && compile(x).is_some());+ out.sort_by_key(|x| (distance(class, x), x.len().abs_diff(class.len())));+ out.dedup();+ out.truncate(3);+ out+}++/// A compile-time error message for an unknown class.+pub fn unknown_message(class: &str) -> String {+ let s = suggest(class);+ if s.is_empty() {+ format!("`{class}` is not a Tailwind utility")+ } else {+ format!("`{class}` is not a Tailwind utility; did you mean {}?",+ s.iter().map(|x| format!("`{x}`")).collect::<Vec<_>>().join(" or "))+ }+}++#[cfg(test)]+mod suggest_tests {+ use super::*;++ #[test]+ fn did_you_mean() {+ assert_eq!(suggest("bg-sky-50O").first().map(String::as_str), Some("bg-sky-500"));+ assert_eq!(suggest("bgg-red-500").first().map(String::as_str), Some("bg-red-500"));+ assert_eq!(suggest("hovr:p-4").first().map(String::as_str), Some("hover:p-4"));+ assert_eq!(suggest("flx").first().map(String::as_str), Some("flex"));+ assert_eq!(suggest("itms-center").first().map(String::as_str), Some("items-center"));+ assert!(unknown_message("roundd-lg").contains("`rounded-lg`"));+ }+}diff --git a/bindings/rust/blenderui/examples/hello.rs b/bindings/rust/blenderui/examples/hello.rsnew file mode 100644index 0000000..4b6eb6d--- /dev/null+++ b/bindings/rust/blenderui/examples/hello.rs@@ -0,0 +1,57 @@+//! The README's hello world: a component with state, Tailwind utilities as+//! attributes, and a hover style. `cargo run --release --example hello`+//! (`--screenshot out.png` renders it headless instead).++use blenderui::prelude::*;++#[component]+fn counter(label: &str) {+ let (count, set_count) = use_state(0);+ rsx! {+ <div flex items-center gap-3 p-4 rounded-xl bg-zinc-800>+ <span text-zinc-300>{label.to_string()} ": " {count().to_string()}</span>+ <div px-3 py-1 rounded-md bg-sky-700 hover:bg-sky-500 cursor-pointer+ onClick={move || set_count(count() + 1)}>+ "Add one"+ </div>+ </div>+ }+}++struct Hello;++impl Render for Hello {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ rsx! {+ <body m-0 p-6 min-h-screen flex flex-col gap-4 bg-zinc-900 text-white>+ <h1 text-2xl font-bold>"Hello, BUI"</h1>+ <counter label="Clicks" />+ <input type="range" min={0.0} max={10.0} />+ </body>+ }+ }+}++fn main() {+ let shot = std::env::args().skip_while(|a| a != "--screenshot").nth(1);+ let app = if shot.is_some() { Application::headless() } else { Application::new() };+ app.run(move |cx| {+ let opts = WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds {+ origin: point(px(0.0), px(0.0)),+ size: size(px(420.0), px(260.0)),+ })),+ ..Default::default()+ };+ let win = cx.open_window(opts, |_, cx| cx.new(|_| Hello)).unwrap();+ if let Some(path) = &shot {+ let (w, h, px) = cx.draw(win.id);+ let rgba: Vec<u8> = px.iter().flat_map(|p| [(p >> 16) as u8, (p >> 8) as u8, *p as u8, 255]).collect();+ let file = std::fs::File::create(path).expect("create png");+ let mut enc = png::Encoder::new(std::io::BufWriter::new(file), w as u32, h as u32);+ enc.set_color(png::ColorType::Rgba);+ enc.set_depth(png::BitDepth::Eight);+ enc.write_header().expect("png").write_image_data(&rgba).expect("png");+ }+ });+}diff --git a/bindings/rust/blenderui/src/element.rs b/bindings/rust/blenderui/src/element.rsindex 826a688..22af336 100644--- a/bindings/rust/blenderui/src/element.rs+++ b/bindings/rust/blenderui/src/element.rs@@ -98,7 +98,8 @@ impl IntoElement for Cow<'static, str> {}impl Div {- pub(crate) fn new(tag: &'static str) -> Div {+ /// An element with any tag name (custom elements: `Div::new("my-widget")`).+ pub fn new(tag: &'static str) -> Div {Div {tag,id: None,diff --git a/bindings/rust/blenderui/src/hooks.rs b/bindings/rust/blenderui/src/hooks.rsnew file mode 100644index 0000000..29850ba--- /dev/null+++ b/bindings/rust/blenderui/src/hooks.rs@@ -0,0 +1,500 @@+//! Hooks and signals: zopra / React / Leptos-style state for components.+//!+//! ```ignore+//! #[component]+//! fn counter(start: i32) {+//! let (count, set_count) = use_state(start); // zopra / React+//! let doubled = Memo::new(move || count() * 2); // Leptos (auto-tracked)+//! Effect::new(move || println!("count = {}", count())); // Leptos (auto-tracked)+//! use_effect(move || println!("mounted"), ()); // React / zopra (deps)+//! rsx! { <button onClick={move || set_count(count() + 1)}>{doubled.get()}</button> }+//! }+//! ```+//!+//! Signals are `Copy` handles into a per-thread store: closures capture them+//! freely and they need no `cx`. Writing one re-renders the window that owns+//! it. Hook state is keyed by call site (and order, like React), and freed+//! when its component stops rendering. No `Rc` / `RefCell`: the store is+//! moved out of its `Cell` while in use, and user code never runs inside it.++use std::any::{Any, TypeId};+use std::cell::Cell;+use std::marker::PhantomData;+use std::panic::Location;++use crate::style::FnvMap;++struct Slot {+ value: Option<Box<dyn Any>>,+ generation: u32,+ version: u32,+ window: usize,+ /// rendered this frame (hook slots only; plain signals are 'static)+ seen: bool,+ hook: bool,+}++/// A deferred effect: runs after the render (with the store not borrowed).+type Job = Box<dyn FnOnce()>;++#[derive(Default)]+struct Store {+ slots: Vec<Slot>,+ free: Vec<u32>,+ /// (window, call site, occurrence) -> slot+ keys: FnvMap<(usize, usize, u32), u32>,+ /// occurrences of each call site in the current render+ occ: FnvMap<usize, u32>,+ window: Option<usize>,+ dirty: Vec<usize>,+ jobs: Vec<Job>,+ /// signals read while tracking (Effect / Memo)+ tracking: Option<Vec<(u32, u32)>>,+ /// context values (TypeId) for the components being rendered+ ctx: Vec<(TypeId, Box<dyn Any>)>,+}++thread_local! {+ static STORE: Cell<Store> = Cell::new(Store::default());+}++/// Run `f` on the store (moved out of its cell). `f` must not call user code.+fn with<R>(f: impl FnOnce(&mut Store) -> R) -> R {+ STORE.with(|c| {+ let mut s = c.take();+ let r = f(&mut s);+ c.set(s);+ r+ })+}++impl Store {+ fn alloc(&mut self, value: Box<dyn Any>, hook: bool) -> (u32, u32) {+ let window = self.window.unwrap_or(usize::MAX);+ let slot = Slot { value: Some(value), generation: 0, version: 0, window, seen: true, hook };+ match self.free.pop() {+ Some(i) => {+ let s = &mut self.slots[i as usize];+ let generation = s.generation + 1;+ *s = Slot { generation, ..slot };+ (i, generation)+ }+ None => {+ self.slots.push(slot);+ ((self.slots.len() - 1) as u32, 0)+ }+ }+ }++ /// The slot for the hook at `site` (same call site and order as last render).+ fn hook_slot(&mut self, site: &'static Location<'static>, init: impl FnOnce() -> Box<dyn Any>) -> (u32, u32) {+ let window = self.window.unwrap_or(usize::MAX);+ let site = site as *const Location as usize;+ let n = self.occ.entry(site).or_insert(0);+ let key = (window, site, *n);+ *n += 1;+ if let Some(&i) = self.keys.get(&key) {+ let s = &mut self.slots[i as usize];+ s.seen = true;+ return (i, s.generation);+ }+ let (i, generation) = self.alloc(init(), true);+ self.keys.insert(key, i);+ (i, generation)+ }+}++// ==========================================================================+// Render scopes (called by the window around its view)++pub(crate) fn begin(window: usize) {+ with(|s| {+ s.window = Some(window);+ s.occ.clear();+ s.ctx.clear();+ for slot in s.slots.iter_mut().filter(|x| x.window == window && x.hook) {+ slot.seen = false;+ }+ });+}++/// End of a window's render: free the state of components that weren't+/// rendered, then run the effects queued during the render.+pub(crate) fn end() {+ let jobs = with(|s| {+ let w = s.window.take();+ let mut gone = Vec::new();+ for (i, slot) in s.slots.iter_mut().enumerate() {+ if slot.hook && Some(slot.window) == w && !slot.seen && slot.value.is_some() {+ gone.push(slot.value.take());+ s.free.push(i as u32);+ }+ }+ s.keys.retain(|_, i| s.slots[*i as usize].value.is_some());+ s.ctx.clear();+ let jobs = std::mem::take(&mut s.jobs);+ (jobs, gone)+ });+ drop(jobs.1); // user values dropped outside the store+ for job in jobs.0 {+ job();+ }+}++/// Windows whose signals were written since the last call.+pub(crate) fn take_dirty() -> Vec<usize> {+ with(|s| std::mem::take(&mut s.dirty))+}++// ==========================================================================+// Signals++/// A `Copy` handle to a value: read with [`get`](Self::get) /+/// [`with`](Self::with), write with [`set`](Self::set) /+/// [`update`](Self::update) (which re-renders its window). Leptos' `RwSignal`.+pub struct Signal<T> {+ i: u32,+ generation: u32,+ _t: PhantomData<fn() -> T>,+}++impl<T> Clone for Signal<T> {+ fn clone(&self) -> Self {+ *self+ }+}+impl<T> Copy for Signal<T> {}++/// Leptos' name for a read-write signal.+pub type RwSignal<T> = Signal<T>;++impl<T: 'static> Signal<T> {+ /// A signal that lives until [`dispose`](Self::dispose) (inside a+ /// component, prefer [`use_signal`]: its state follows the component).+ pub fn new(value: T) -> Signal<T> {+ let (i, generation) = with(|s| s.alloc(Box::new(value), false));+ Signal { i, generation, _t: PhantomData }+ }++ fn take(self) -> Option<Box<T>> {+ with(|s| {+ let slot = s.slots.get_mut(self.i as usize).filter(|x| x.generation == self.generation)?;+ if let Some(t) = &mut s.tracking {+ t.push((self.i, slot.version));+ }+ slot.value.take()?.downcast::<T>().ok()+ })+ }++ fn put(self, v: Box<T>, changed: bool) {+ with(|s| {+ if let Some(slot) = s.slots.get_mut(self.i as usize).filter(|x| x.generation == self.generation) {+ slot.value = Some(v);+ if changed {+ slot.version = slot.version.wrapping_add(1);+ let w = slot.window;+ if w != usize::MAX && !s.dirty.contains(&w) {+ s.dirty.push(w);+ } else if w == usize::MAX {+ s.dirty.push(usize::MAX); // global signal: every window+ }+ }+ }+ })+ }++ /// Look at the value without cloning it.+ pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {+ let v = self.take().expect("signal used after its component was dropped");+ let r = f(&v);+ self.put(v, false);+ r+ }++ pub fn get(self) -> T+ where+ T: Clone,+ {+ self.with(T::clone)+ }++ /// Change the value in place and re-render.+ pub fn update(self, f: impl FnOnce(&mut T)) {+ let mut v = self.take().expect("signal used after its component was dropped");+ f(&mut v);+ self.put(v, true);+ }++ pub fn set(self, value: T) {+ self.update(|v| *v = value);+ }++ /// Leptos' read / write halves of this signal.+ pub fn split(self) -> (ReadSignal<T>, WriteSignal<T>) {+ (ReadSignal(self), WriteSignal(self))+ }++ pub fn dispose(self) {+ let v = with(|s| {+ let slot = s.slots.get_mut(self.i as usize).filter(|x| x.generation == self.generation)?;+ let v = slot.value.take();+ s.free.push(self.i);+ v+ });+ drop(v);+ }+}++/// Leptos' read half.+pub struct ReadSignal<T>(Signal<T>);+/// Leptos' write half.+pub struct WriteSignal<T>(Signal<T>);+impl<T> Clone for ReadSignal<T> {+ fn clone(&self) -> Self {+ *self+ }+}+impl<T> Copy for ReadSignal<T> {}+impl<T> Clone for WriteSignal<T> {+ fn clone(&self) -> Self {+ *self+ }+}+impl<T> Copy for WriteSignal<T> {}++impl<T: 'static> ReadSignal<T> {+ pub fn get(self) -> T+ where+ T: Clone,+ {+ self.0.get()+ }+ pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {+ self.0.with(f)+ }+}++impl<T: 'static> WriteSignal<T> {+ pub fn set(self, v: T) {+ self.0.set(v)+ }+ pub fn update(self, f: impl FnOnce(&mut T)) {+ self.0.update(f)+ }+}++// ==========================================================================+// Hooks++/// A signal owned by the calling component (the same one on every render).+#[track_caller]+pub fn use_signal<T: 'static>(init: T) -> Signal<T> {+ let site = Location::caller();+ let mut init = Some(init);+ let (i, generation) = with(|s| s.hook_slot(site, || Box::new(init.take().expect("init"))));+ Signal { i, generation, _t: PhantomData }+}++/// zopra / React state: `let (count, set_count) = use_state(0);` then+/// `count()` and `set_count(count() + 1)`. Both halves are `Copy` closures.+#[track_caller]+pub fn use_state<T: Clone + 'static>(init: T) -> (impl Fn() -> T + Copy, impl Fn(T) + Copy) {+ let s = use_signal(init);+ (move || s.get(), move |v| s.set(v))+}++/// Leptos `signal(v)` / `create_signal(v)`: read and write halves, owned+/// by the calling component.+#[track_caller]+pub fn signal<T: 'static>(init: T) -> (ReadSignal<T>, WriteSignal<T>) {+ use_signal(init).split()+}++/// Leptos 0.6 name of [`signal`].+#[track_caller]+pub fn create_signal<T: 'static>(init: T) -> (ReadSignal<T>, WriteSignal<T>) {+ use_signal(init).split()+}++/// React / zopra effect: runs after the render, and again whenever `deps`+/// differ from the previous render's (`()` = once, after the first render).+#[track_caller]+pub fn use_effect<D: PartialEq + 'static>(effect: impl FnOnce() + 'static, deps: D) {+ let site = Location::caller();+ let prev: Signal<Option<D>> = {+ let (i, generation) = with(|s| s.hook_slot(site, || Box::new(None::<D>)));+ Signal { i, generation, _t: PhantomData }+ };+ let changed = prev.with(|p| p.as_ref() != Some(&deps));+ if changed {+ let v = prev.take();+ if let Some(mut v) = v {+ *v = Some(deps);+ prev.put(v, false);+ }+ with(|s| s.jobs.push(Box::new(effect)));+ }+}++/// zopra's `use_effect!(effect, [a, b])` form.+#[macro_export]+macro_rules! use_effect {+ ($effect:expr, [$($dep:expr),* $(,)?] $(,)?) => {+ $crate::hooks::use_effect($effect, ($($dep.clone(),)*))+ };+}++/// Signals read by `f` (and their versions).+fn tracked<R>(f: impl FnOnce() -> R) -> (R, Vec<(u32, u32)>) {+ let outer = with(|s| s.tracking.replace(Vec::new()));+ let r = f();+ let deps = with(|s| std::mem::replace(&mut s.tracking, outer)).unwrap_or_default();+ (r, deps)+}++fn changed(deps: &[(u32, u32)]) -> bool {+ with(|s| deps.iter().any(|&(i, v)| s.slots.get(i as usize).is_none_or(|x| x.version != v)))+}++struct EffectState {+ f: Option<Box<dyn FnMut()>>,+ deps: Vec<(u32, u32)>,+ ran: bool,+}++/// Leptos effects: run after the render, and again after any render in+/// which a signal they read has changed.+pub struct Effect;++impl Effect {+ #[track_caller]+ #[allow(clippy::new_ret_no_self)]+ pub fn new(f: impl FnMut() + 'static) {+ let site = Location::caller();+ let mut f = Some(f);+ let (i, generation) = with(|s| s.hook_slot(site, || Box::new(EffectState { f: None, deps: Vec::new(), ran: false })));+ let st: Signal<EffectState> = Signal { i, generation, _t: PhantomData };+ let run = st.with(|e| !e.ran || changed(&e.deps));+ if let Some(f) = f.take() {+ if let Some(mut e) = st.take() {+ if e.f.is_none() {+ e.f = Some(Box::new(f));+ }+ st.put(e, false);+ }+ }+ if run {+ with(|s| s.jobs.push(Box::new(move || {+ let Some(mut e) = st.take() else { return };+ let mut f = e.f.take();+ st.put(e, false);+ let (_, deps) = tracked(|| {+ if let Some(f) = f.as_mut() {+ f();+ }+ });+ if let Some(mut e) = st.take() {+ e.f = f;+ e.deps = deps;+ e.ran = true;+ st.put(e, false);+ }+ })));+ }+ }+}++/// Leptos memos: a derived value, recomputed only when a signal it read+/// has changed. `Copy`; read with [`get`](Self::get).+pub struct Memo<T>(Signal<(Option<T>, Vec<(u32, u32)>)>);++impl<T> Clone for Memo<T> {+ fn clone(&self) -> Self {+ *self+ }+}+impl<T> Copy for Memo<T> {}++impl<T: Clone + 'static> Memo<T> {+ #[track_caller]+ pub fn new(f: impl Fn() -> T + 'static) -> Memo<T> {+ let site = Location::caller();+ let (i, generation) = with(|s| s.hook_slot(site, || Box::new((None::<T>, Vec::<(u32, u32)>::new()))));+ let m = Memo(Signal { i, generation, _t: PhantomData });+ let stale = m.0.with(|(v, deps)| v.is_none() || changed(deps));+ if stale {+ let (v, deps) = tracked(f);+ if let Some(mut slot) = m.0.take() {+ *slot = (Some(v), deps);+ m.0.put(slot, false);+ }+ }+ m+ }++ pub fn get(self) -> T {+ self.0.with(|(v, _)| v.clone().expect("memo value"))+ }+}++/// React-style memo with explicit dependencies.+#[track_caller]+pub fn use_memo<T: Clone + 'static, D: PartialEq + 'static>(f: impl FnOnce() -> T, deps: D) -> T {+ let site = Location::caller();+ let (i, generation) = with(|s| s.hook_slot(site, || Box::new(None::<(D, T)>)));+ let slot: Signal<Option<(D, T)>> = Signal { i, generation, _t: PhantomData };+ let hit = slot.with(|v| v.as_ref().filter(|(d, _)| *d == deps).map(|(_, t)| t.clone()));+ match hit {+ Some(t) => t,+ None => {+ let t = f();+ if let Some(mut b) = slot.take() {+ *b = Some((deps, t.clone()));+ slot.put(b, false);+ }+ t+ }+ }+}++// ==========================================================================+// Context++/// Make `value` available to the components rendered inside this one+/// (looked up by type; the innermost wins).+pub fn provide_context<T: 'static>(value: T) {+ with(|s| s.ctx.push((TypeId::of::<T>(), Box::new(value))));+}++pub fn try_use_context<T: Clone + 'static>() -> Option<T> {+ // take the matching value out to clone it outside the store (Clone is user code)+ let found = with(|s| {+ let k = s.ctx.iter().rposition(|(t, _)| *t == TypeId::of::<T>())?;+ Some((k, std::mem::replace(&mut s.ctx[k].1, Box::new(()))))+ });+ let (k, b) = found?;+ let v = b.downcast_ref::<T>().cloned();+ with(|s| s.ctx[k].1 = b);+ v+}++#[track_caller]+pub fn use_context<T: Clone + 'static>() -> T {+ try_use_context().unwrap_or_else(|| {+ panic!("use_context::<{}>(): no parent component provided one", std::any::type_name::<T>())+ })+}++/// Runs a component body: context it provides is visible to its children+/// only (used by `#[component]`).+#[doc(hidden)]+pub fn component<R>(body: impl FnOnce() -> R) -> R {+ let mark = with(|s| s.ctx.len());+ let r = body();+ let dropped: Vec<Box<dyn Any>> = with(|s| s.ctx.drain(mark..).map(|(_, v)| v).collect());+ drop(dropped);+ r+}++/// Children of a component (`#[component] fn card(children: Children)`).+pub type Children = Vec<crate::element::AnyElement>;diff --git a/bindings/rust/blenderui/src/lib.rs b/bindings/rust/blenderui/src/lib.rsindex 9e3f8e5..72af72c 100644--- a/bindings/rust/blenderui/src/lib.rs+++ b/bindings/rust/blenderui/src/lib.rs@@ -66,6 +66,30 @@ pub use blenderui_macros::css;/// ```pub use blenderui_macros::tw;+/// JSX-style markup lowered to builder calls (no runtime parsing):+///+/// ```+/// use blenderui::prelude::*;+/// let name = "Ada";+/// let items = vec!["a", "b"];+/// let _ = rsx! {+/// <div class="flex gap-2 p-4" onClick={|| println!("hi")}>+/// <h1 style="color: red">"Hello, " {name}</h1>+/// <input type="checkbox" checked={true} />+/// <ul>{for it in items { <li>{it}</li> }}</ul>+/// {if name.len() > 2 { <p>long name</p> }}+/// </div>+/// };+/// ```+///+/// Attributes with `{expr}` call the builder method of that name, so any+/// method works (`w={px(10.)}`, `hover={|s| s.bg(red())}`); text values+/// become HTML attributes. Components: `<Card title="x">..</Card>` builds+/// `Card { title: "x".into(), children: vec![..] }`.+pub use blenderui_macros::rsx;+/// [`rsx!`] under its zopra / Leptos name.+pub use blenderui_macros::rsx as view;+pub mod calc;pub mod color;mod color4;@@ -78,6 +102,7 @@ pub(crate) mod layout;pub mod paint;pub(crate) mod prof;mod selector;+pub mod hooks;pub mod style;pub use blenderui_tailwind as tailwind;mod tree;@@ -118,7 +143,12 @@ pub fn add_font(family: &str, bold: bool, italic: bool, data: &[u8]) -> bool {/// Everything an app needs: `use blenderui::prelude::*;`pub mod prelude {- pub use crate::{css, tw};+ pub use crate::{css, rsx, tw, view, use_effect};+ pub use crate::hooks::{+ create_signal, provide_context, signal, try_use_context, use_context, use_memo, use_signal, use_state,+ Children, Effect, Memo, ReadSignal, RwSignal, Signal, WriteSignal,+ };+ pub use blenderui_macros::component;pub use crate::color::*;pub use crate::element::*;pub use crate::events::*;diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rsindex dc35bd7..622c7ca 100644--- a/bindings/rust/blenderui/src/window.rs+++ b/bindings/rust/blenderui/src/window.rs@@ -443,6 +443,14 @@ impl App {/// Re-render dirty windows now (headless) or soon (native: next loop turn).fn flush(&mut self) {self.drain();+ // windows whose signals were written (hooks)+ for id in crate::hooks::take_dirty() {+ if id == usize::MAX {+ self.notify_all();+ } else if let Some(w) = self.windows.get_mut(id).and_then(|w| w.as_deref_mut()) {+ w.refresh();+ }+ }for id in 0..self.windows.len() {let Some(w) = self.windows[id].as_deref_mut() else { continue };if !w.dirty {@@ -859,6 +867,7 @@ impl Window {self.dirty = false;let root = {let _s = span(Phase::Render);+ crate::hooks::begin(self.id);view(self, app)};if self.view.is_none() {@@ -903,6 +912,8 @@ impl Window {self.update_hover(app, false);drop(_rest);prof::frame_done();+ // state of components that didn't render is freed; effects run now+ crate::hooks::end();}// -- events ------------------------------------------------------------------------------diff --git a/bindings/rust/blenderui/tests/hooks.rs b/bindings/rust/blenderui/tests/hooks.rsnew file mode 100644index 0000000..8c7094b--- /dev/null+++ b/bindings/rust/blenderui/tests/hooks.rs@@ -0,0 +1,113 @@+//! zopra / React / Leptos-style components and hooks, rendered headless.++use blenderui::prelude::*;+use std::sync::atomic::{AtomicUsize, Ordering};++static EFFECTS: AtomicUsize = AtomicUsize::new(0);+static LEPTOS_EFFECTS: AtomicUsize = AtomicUsize::new(0);++#[derive(Clone)]+struct Theme(&'static str);++// zopra style: lowercase component, `&str` prop, bare state closures+#[component]+fn profile(username: &str, id: String) {+ let (likes, set_likes) = use_state(0usize);+ use_effect!(move || { EFFECTS.fetch_add(1, Ordering::SeqCst); }, [likes()]);+ let theme: Theme = use_context();+ rsx! {+ <div id={id.clone()} class="h-4" onClick={move || set_likes(likes() + 1)}+ data-theme={theme.0}>+ {username.to_string()} " has " {likes().to_string()}+ {if likes() > 0 { <div id={format!("{id}-liked")} class="h-2" /> }}+ </div>+ }+}++// Leptos style: signal halves, auto-tracked memo and effect+#[component]+fn Counter(start: i32) {+ let (count, set_count) = signal(start);+ let doubled = Memo::new(move || count.get() * 2);+ Effect::new(move || {+ let _ = count.get();+ LEPTOS_EFFECTS.fetch_add(1, Ordering::SeqCst);+ });+ rsx! {+ <div id="counter" class="h-1" w={px(doubled.get() as f32)}+ onClick={move || set_count.update(|c| *c += 1)} />+ }+}++struct Page {+ show_bob: bool,+}++impl Render for Page {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ provide_context(Theme("dark"));+ let show_bob = self.show_bob;+ rsx! {+ <body style="margin: 0">+ <profile username="Alice" id={"alice".to_string()} />+ {if show_bob { <profile username="Bob" id={"bob".to_string()} /> }}+ <Counter start={5} />+ </body>+ }+ }+}++#[test]+fn hooks_state_effects_context() {+ Application::headless().run(|cx| {+ let opts = WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds {+ origin: point(px(0.0), px(0.0)),+ size: size(px(400.0), px(300.0)),+ })),+ ..Default::default()+ };+ let win = cx.open_window(opts, |_, cx| cx.new(|_| Page { show_bob: true })).unwrap();+ let id = win.id;+ cx.draw(id);+ let has = |cx: &mut App, n: &str| cx.element_bounds(id, n).is_some();+ let click = |cx: &mut App, n: &str| {+ let b = cx.element_bounds(id, n).unwrap();+ cx.simulate_click(id, b.origin.x + 2.0, b.origin.y + 2.0);+ cx.draw(id);+ };+ // effects ran once per profile after the first render+ assert_eq!(EFFECTS.load(Ordering::SeqCst), 2);+ assert_eq!(LEPTOS_EFFECTS.load(Ordering::SeqCst), 1);+ assert_eq!(cx.element_bounds(id, "counter").unwrap().size.width, 10.0, "memo: 5 * 2");+ // per-instance state: clicking Alice doesn't touch Bob+ click(cx, "alice");+ assert!(has(cx, "alice-liked") && !has(cx, "bob-liked"));+ assert_eq!(EFFECTS.load(Ordering::SeqCst), 3, "Alice's deps changed, Bob's didn't");+ // re-render without changes: no effect re-runs+ cx.notify_all();+ cx.draw(id);+ assert_eq!(EFFECTS.load(Ordering::SeqCst), 3);+ assert_eq!(LEPTOS_EFFECTS.load(Ordering::SeqCst), 1, "untracked render: effect stays");+ // Leptos: the memo and the effect follow the signal+ click(cx, "counter");+ assert_eq!(cx.element_bounds(id, "counter").unwrap().size.width, 12.0, "memo: 6 * 2");+ assert_eq!(LEPTOS_EFFECTS.load(Ordering::SeqCst), 2);+ // unmount Bob, mount him again: fresh state+ click(cx, "bob");+ assert!(has(cx, "bob-liked"));+ win.root().update(cx, |p, cx| {+ p.show_bob = false;+ cx.notify();+ });+ cx.draw(id);+ assert!(!has(cx, "bob"));+ win.root().update(cx, |p, cx| {+ p.show_bob = true;+ cx.notify();+ });+ cx.draw(id);+ assert!(has(cx, "bob") && !has(cx, "bob-liked"), "state was freed with the component");+ assert!(has(cx, "alice-liked"), "Alice kept hers");+ });+}diff --git a/bindings/rust/blenderui/tests/rsx.rs b/bindings/rust/blenderui/tests/rsx.rsnew file mode 100644index 0000000..7378c55--- /dev/null+++ b/bindings/rust/blenderui/tests/rsx.rs@@ -0,0 +1,192 @@+//! `rsx!` end to end: markup lowered to builder calls, rendered headless.++use blenderui::prelude::*;++/// A component: a struct with props and children.+struct Card {+ title: SharedString,+ children: Vec<AnyElement>,+}++impl IntoElement for Card {+ fn into_any_element(self) -> AnyElement {+ rsx! {+ <section class="p-2" id={self.title.to_string()}>+ <h2>{self.title.clone()}</h2>+ {...self.children}+ </section>+ }+ .into_any_element()+ }+}++#[derive(Clone, Copy, PartialEq)]+enum Mode {+ A,+ B,+}++struct App2 {+ count: usize,+ mode: Mode,+}++impl Render for App2 {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let items = ["x", "y", "z"];+ rsx! {+ <body style="margin: 0">+ <div id="btn" class="w-20 h-6" onClick={cx.listener(|this, _: &ClickEvent, _, cx| {+ this.count += 1;+ cx.notify();+ })}></div>+ <ul id="list">{for it in items { <li class="h-3">{it}</li> }}</ul>+ {if self.count > 0 { <div id="clicked" class="h-4"></div> }}+ {match self.mode {+ Mode::A => <div id="mode-a" class="h-5"></div>,+ Mode::B => <div id="mode-b"></div>,+ }}+ <Card title="card">+ <p id="inside" class="h-7">inside the card</p>+ </Card>+ <>+ <div id="frag1" class="h-2"></div>+ <div id="frag2" class="h-2"></div>+ </>+ <my-widget id="custom" data-x="1" class="block h-1"></my-widget>+ <input id="box" type="checkbox" checked={true} />+ <div id="noop" onClick={|| ()} w={px(33.0)} class="h-1"></div>+ </body>+ }+ }+}++#[test]+fn rsx_renders_and_reacts() {+ Application::headless().run(|cx| {+ let opts = WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds {+ origin: point(px(0.0), px(0.0)),+ size: size(px(300.0), px(400.0)),+ })),+ ..Default::default()+ };+ let win = cx.open_window(opts, |_, cx| cx.new(|_| App2 { count: 0, mode: Mode::A })).unwrap();+ let id = win.id;+ cx.draw(id);+ let r = |cx: &mut App, n: &str| cx.element_bounds(id, n).unwrap_or_else(|| panic!("{n}"));+ assert_eq!(r(cx, "btn").size.width, 80.0);+ assert_eq!(r(cx, "list").size.height, 36.0, "three li from the for loop");+ assert!(cx.element_bounds(id, "clicked").is_none(), "if without else: nothing");+ assert_eq!(r(cx, "mode-a").size.height, 20.0, "match arm");+ assert_eq!(r(cx, "inside").size.height, 28.0, "component children");+ assert!(r(cx, "card").size.height > 28.0);+ assert_eq!(r(cx, "frag2").origin.y - r(cx, "frag1").origin.y, 8.0, "fragment children");+ assert_eq!(r(cx, "custom").size.height, 4.0, "custom element");+ assert!(r(cx, "box").size.width > 0.0, "a real checkbox widget");+ assert_eq!(r(cx, "noop").size.width, 33.0, "{{expr}} attributes call builder methods");+ let b = r(cx, "btn");+ cx.simulate_click(id, b.origin.x + 5.0, b.origin.y + 3.0);+ assert_eq!(win.root().read(cx).count, 1);+ cx.draw(id);+ assert_eq!(r(cx, "clicked").size.height, 16.0, "re-rendered after the click");+ });+}++struct Variants;++impl Render for Variants {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let dynamic = "h-9";+ rsx! {+ <body style="margin: 0">+ <div id="a" class="h-4" hover:class="h-8 w-12" />+ <div id="b" class="h-4" hover:style="height: 20px; min-width: 10px" />+ <div id="c" class="h-4" hover:height="22px" />+ <div id="d" class="h-4" hover:h={px(24.0)} />+ <div id="e" class="h-4" md:class="h-6" max-sm:class="h-1" />+ <div id="f" class="h-4" md:hover:class="h-10" />+ <div id="g" class="group h-4"><div id="g1" class="h-1" group-hover:class="h-3" /></div>+ <div id="h" class="h-4" hover:class={dynamic} />+ <div id="i" class="h-2" data-on="1" data-[on]:class="h-5" 2xl:class="h-11" />+ </body>+ }+ }+}++#[test]+fn rsx_variant_attributes() {+ Application::headless().run(|cx| {+ let opts = WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds {+ origin: point(px(0.0), px(0.0)),+ size: size(px(800.0), px(600.0)),+ })),+ ..Default::default()+ };+ let win = cx.open_window(opts, |_, cx| cx.new(|_| Variants)).unwrap();+ let id = win.id;+ cx.draw(id);+ let h = |cx: &mut App, n: &str| cx.element_bounds(id, n).unwrap_or_else(|| panic!("{n}")).size.height;+ let hover = |cx: &mut App, n: &str| {+ let b = cx.element_bounds(id, n).unwrap();+ cx.simulate_mouse_move(id, b.origin.x + 1.0, b.origin.y + 1.0);+ cx.draw(id);+ };+ assert_eq!(h(cx, "e"), 24.0, "md: at 800px, max-sm: not");+ assert_eq!(h(cx, "i"), 20.0, "data-[on]: (2xl: not at 800px)");+ for (n, want) in [("a", 32.0), ("b", 20.0), ("c", 22.0), ("d", 24.0), ("f", 40.0), ("h", 36.0)] {+ assert_eq!(h(cx, n), 16.0, "{n} before hover");+ hover(cx, n);+ assert_eq!(h(cx, n), want, "{n} hovered");+ }+ hover(cx, "g1");+ assert_eq!(h(cx, "g1"), 12.0, "group-hover:");+ });+}++struct Attributify;++impl Render for Attributify {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ rsx! {+ <body style="margin: 0">+ <div id="a" w-1/2 h-[37px] bg-[#4772b3] p-2 />+ <div id="b" h-4 hover:h-[50px] hover:bg-sky-500/50 />+ <div id="c" h-4 md:h-6 max-sm:h-1 -mt-2 />+ <div id="d" class="h-2" w-[calc(100%-2rem)] />+ <div id="e" h-3 hidden md:block />+ <input id="f" type="checkbox" checked disabled />+ </body>+ }+ }+}++#[test]+fn rsx_attributify_utilities() {+ Application::headless().run(|cx| {+ let opts = WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds {+ origin: point(px(0.0), px(0.0)),+ size: size(px(800.0), px(600.0)),+ })),+ ..Default::default()+ };+ let win = cx.open_window(opts, |_, cx| cx.new(|_| Attributify)).unwrap();+ let id = win.id;+ let img = cx.draw(id);+ let r = |cx: &mut App, n: &str| cx.element_bounds(id, n).unwrap_or_else(|| panic!("{n}"));+ assert_eq!((r(cx, "a").size.width, r(cx, "a").size.height), (400.0, 37.0));+ let s = img.0 as f32 / 800.0;+ assert_eq!(img.2[(10.0 * s) as usize * img.0 + (10.0 * s) as usize], 0x4772b3, "bg-[#4772b3]");+ assert_eq!(r(cx, "c").size.height, 24.0);+ assert_eq!(r(cx, "d").size.width, 768.0);+ assert!(r(cx, "f").size.width > 0.0, "checked / disabled stay attributes");+ // `hidden` is an HTML boolean attribute: it stays an attribute (not the utility)+ assert_eq!(r(cx, "b").size.height, 16.0);+ let b = r(cx, "b");+ cx.simulate_mouse_move(id, b.origin.x + 1.0, b.origin.y + 1.0);+ cx.draw(id);+ assert_eq!(r(cx, "b").size.height, 50.0, "hover:h-[50px]");+ });+}diff --git a/bindings/rust/scripts/vendor_c.py b/bindings/rust/scripts/vendor_c.pynew file mode 100644index 0000000..e438ff6--- /dev/null+++ b/bindings/rust/scripts/vendor_c.py@@ -0,0 +1,32 @@+"""Copy the C sources blenderui-sys builds into the crate (`csrc/`), so the+published crate is self-contained. Run before `cargo package` / `cargo publish`:++ python bindings/rust/scripts/vendor_c.py++`csrc/` is git-ignored; inside the repo, build.rs uses the repo itself.+"""++import shutil+from pathlib import Path++ROOT = Path(__file__).resolve().parents[3]+DEST = ROOT / "bindings" / "rust" / "blenderui-sys" / "csrc"+DIRS = ["core", "types", "gpu", "compat", "ui", "kit", "api"]+FILES = ["CMakeLists.txt", "LICENSE", "bindings/python/bui/_version.py"]+SKIP = shutil.ignore_patterns("__pycache__", "*.pyc", "build*", "*.o", "*.obj")+++def main() -> None:+ if DEST.exists():+ shutil.rmtree(DEST)+ for d in DIRS:+ shutil.copytree(ROOT / d, DEST / d, ignore=SKIP)+ for f in FILES:+ (DEST / f).parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(ROOT / f, DEST / f)+ size = sum(p.stat().st_size for p in DEST.rglob("*") if p.is_file())+ print(f"vendored {size / 1e6:.1f} MB of C sources into {DEST}")+++if __name__ == "__main__":+ main()diff --git a/docs/images/rust-hello.png b/docs/images/rust-hello.pngnew file mode 100644index 0000000..63a4c6bBinary files /dev/null and b/docs/images/rust-hello.png differdiff --git a/docs/publishing.md b/docs/publishing.mdindex ad90d2e..03c6b18 100644--- a/docs/publishing.md+++ b/docs/publishing.md@@ -94,3 +94,52 @@ No API tokens are stored anywhere.- The README's images use relative paths. PyPI shows them once`[project.urls]` points to the public repository and the paths are madeabsolute (or the images are hosted).++# Publishing the Rust crates (crates.io)++The four crates are published in dependency order:++| Crate | What it is | Depends on |+|---|---|---|+| `blenderui-tailwind` | Tailwind v4 class compiler (std only) | none |+| `blenderui-macros` | `rsx!` / `view!`, `#[component]`, `css!`, `tw!` | `blenderui-tailwind` |+| `blenderui-sys` | FFI over the C kit; builds it with CMake | none (`cmake` at build time) |+| `blenderui` | the framework | all three |++`blenderui-sys` must carry the C sources, because a published crate can't+reach `../../..`. Vendor them first. They're git-ignored and listed in the+crate's `include`:++```sh+python bindings/rust/scripts/vendor_c.py # copies ~7 MB into blenderui-sys/csrc/+cd bindings/rust+cargo package --workspace --allow-dirty # builds each packaged crate in isolation+```++`build.rs` looks for the C sources in three places, in order:+1. `BUI_SOURCE_DIR`, if set;+2. the surrounding repository;+3. `csrc/`, the vendored copy (what a downloaded crate has).++## Release++1. Bump `version` in `bindings/rust/Cargo.toml` (`[workspace.package]`). The+ crates share one version. Then update the `version = "..."` of the path+ dependencies in `blenderui/Cargo.toml` and `blenderui-macros/Cargo.toml`.+2. `cargo login` once with a crates.io API token.+3. Vendor, then publish in order. `cargo publish --workspace` does the+ ordering itself on Cargo 1.90+:++```sh+python bindings/rust/scripts/vendor_c.py+cd bindings/rust+cargo publish --workspace --allow-dirty # or, one by one:+# cargo publish -p blenderui-tailwind+# cargo publish -p blenderui-macros+# cargo publish -p blenderui-sys --allow-dirty+# cargo publish -p blenderui+```++`--allow-dirty` is needed because `csrc/` is untracked. Users need CMake and+a C compiler (MSVC, MinGW, gcc or clang) to build `blenderui-sys`.+`bench/` is excluded from the workspace and is never published.diff --git a/docs/rust.md b/docs/rust.mdindex f1136f1..26e4d7f 100644--- a/docs/rust.md+++ b/docs/rust.md@@ -98,6 +98,113 @@ contents, a checkbox you clicked, which `<details>` are open).to the display, `set_vsync(false)` lifts the cap).A `<title>` element sets the window title too.+## Markup: `rsx!` / `view!`++JSX-style markup, lowered at compile time to the same builder calls (no runtime parsing):++```rust+rsx! {+ <div class="flex gap-2 p-4" onClick={|| println!("clicked")}>+ <h1 style="color: red">"Hello, " {name}</h1>+ <input type="checkbox" checked={done} />+ <ul>{for it in items { <li>{it}</li> }}</ul>+ {if done { <p>all done</p> }}+ {match mode { Mode::A => <A/>, Mode::B => <span>b</span> }}+ <Card title="Settings">{...rows}</Card>+ </div>+}+```++The lowering is uniform, so the whole API is reachable without special cases:+- **Tags:** any tag becomes its function (`<my-el>` becomes `Div::new("my-el")`).+- **Attributes:**+ - `name="text"` sets an HTML attribute, except `class`, `style` and `id`, which call their methods.+ - `name={expr}` calls the builder method of that name: `w={px(10.)}`, `hover={|s| s.bg(red())}`.+ - `onClick` becomes `.on_click`, and closures may omit the `(event, window, cx)` parameters.+- **Components:** an uppercase tag builds a struct, so `<Card title="x">..</Card>` becomes `Card { title: "x".into(), children: .. }`.+- **Fragments:** `<>..</>` is a `display: contents` wrapper.++Tailwind utilities can also be written as bare attributes (UnoCSS calls this "attributify"). They become classes at compile time:++```rust+rsx! { <div p-4 w-1/2 bg-[#4772b3] hover:bg-sky-500/50 md:flex -mt-2 text-sm/6 /> }+```++HTML boolean attributes (`disabled`, `checked`, `hidden`, `open` ...) stay attributes.+Anything that looks like a utility but isn't one is a compile error with suggestions,+in `rsx!` and in `tw!` alike:++```text+error: rsx!: `bg-sky-50O` is not a Tailwind utility; did you mean `bg-sky-500` or `bg-sky-50` or `bg-sky-100`?+error: rsx!: `hovr:bg-red-500` is not a Tailwind utility; did you mean `hover:bg-red-500` or `odd:bg-red-500`?+error: tw!: `roundd-lg` is not a Tailwind utility; did you mean `rounded-lg` or `rounded-s-lg` or `rounded-e-lg`?+```++Every Tailwind variant also works as an attribute prefix, chained as deep as you like:++```rust+rsx! {+ <button class="px-3 py-1 bg-zinc-800"+ hover:class="bg-sky-600 text-white" // classes, prefixed+ active:style="transform: scale(0.97)" // any CSS, as arbitrary properties+ focus-visible:outline="2px solid white" // one CSS property+ md:dark:hover:class="bg-sky-400" // chained variants+ hover:bg={rgb(0x4772b3)}> // typed value via .hover(|s| ..)+ "Save"+ </button>+}+```++`group-hover:`, `peer-checked:`, `data-[state=open]:`, `aria-expanded:`, `@md:`, `2xl:`,+`max-sm:`, `*:` and every other variant work the same way, because they all go through the+Tailwind engine. Typed `{expr}` values are limited to `hover`, `active` and `focus`; use+`variant:class` or `variant:style` with every other variant.++## Components and hooks (zopra / React / Leptos style)++```rust+use blenderui::prelude::*;++#[component] // zopra style: lowercase, &str props+fn profile(username: &str) {+ let (likes, set_likes) = use_state(0); // `likes()`, `set_likes(..)`: no cx+ use_effect!(move || println!("{} likes", likes()), [likes()]);+ let theme: Theme = use_context();+ rsx! { <div class="p-2" onClick={move || set_likes(likes() + 1)}>{username} {likes()}</div> }+}++#[component] // Leptos style+fn Counter(start: i32) {+ let (count, set_count) = signal(start);+ let doubled = Memo::new(move || count.get() * 2); // recomputed when `count` changes+ Effect::new(move || println!("count is {}", count.get())); // re-runs when `count` changes+ rsx! { <button onClick={move || set_count.update(|c| *c += 1)}>{doubled.get()}</button> }+}++// in a view: provide_context(Theme(..)); rsx! { <profile username="Ada" /> <Counter start={1} /> }+```++These are the hooks and their counterparts in other frameworks:++| Hook | Also known as |+|---|---|+| `use_state(v)` | zopra / React `useState` (a getter and a setter closure) |+| `use_signal(v)`, `Signal::new(v)` | zopra `use_signal`, Leptos `RwSignal` |+| `signal(v)`, `create_signal(v)` | Leptos read and write halves |+| `Memo::new(f)`, `Effect::new(f)` | Leptos, tracking the signals they read automatically |+| `use_effect(f, deps)`, `use_effect!(f, [a, b])` | React / zopra |+| `use_memo(f, deps)` | React `useMemo` |+| `provide_context(v)`, `use_context()`, `try_use_context()` | Leptos / zopra context |++How it behaves:+- **Signals:** signals are `Copy` handles. They don't need `cx`, and writing one re-renders its window.+- **Hook identity:** like React, a hook's state is tied to its call site and to the order in which components render. Removing a component from the middle of a list shifts the state of the components after it.+- **Components:** `#[component]` turns `fn name(props)` into a props struct with that name. Uppercase and lowercase names both work in `rsx!`, as does a body that ends in markup.+- **Lifetime:** a component's state is freed when it stops rendering.+- **Implementation:** there is no `Rc` or `RefCell` anywhere in it.++Not supported yet: optional props (pass every prop; use `Option<T>` for optional values), async resources (`use_resource`) and generic components.+## ElementsThere is **one element type, `Div`**, and a constructor for every element ofdiff --git a/pyproject.toml b/pyproject.tomlindex 5424946..321847b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -40,10 +40,10 @@ qt = ["PySide6>=6.5"] # only for bui.qt.BuiCanvas (embedding in a reatest = [][project.urls]-Documentation = "https://github.com/OWNER/BUI/tree/main/docs"-Source = "https://github.com/OWNER/BUI"-Issues = "https://github.com/OWNER/BUI/issues"-Changelog = "https://github.com/OWNER/BUI/blob/main/CHANGELOG.md"+Documentation = "https://github.com/ppmpreetham/BUI/tree/main/docs"+Source = "https://github.com/ppmpreetham/BUI"+Issues = "https://github.com/ppmpreetham/BUI/issues"+Changelog = "https://github.com/ppmpreetham/BUI/blob/main/CHANGELOG.md"[project.scripts]blenderui-tk = "bui.tksyntax.__main__:main" # blenderui-tk app.py == python -m bui.tksyntax app.py