Skip to content

armgit / BUI

Public Imported from GitHub
0

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

chore: readme & docs

Preetham Pemmasanic2c3bcdf0d04
diff --git a/README.md b/README.md
index fad6259..4d7ccab 100644
--- a/README.md
+++ b/README.md
@@ -1,234 +1,296 @@
-# BUI
+# BUI (Blender UI)
> [!NOTE]
-> This repository is built entirely using LLMs. No Human written code.
-
-A modular UI toolkit extracted from the Blender project. Core in C, widgets in
-C++, no Blender application logic — just the interface machinery. Renderable
-from C++, **Qt**, and **Python (PySide6 / PyQt6)** through one stable
-integration point.
-
-See [ARCHITECTURE.md](ARCHITECTURE.md) for the module layout and dependency
-rules, and [INTEGRATION.md](INTEGRATION.md) for host-application guides.
-
-## Quick start
+> This repository is built entirely using LLMs. No human-written code.
+
+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:
+
+- **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` ...).
+
+All three share one C runtime (`kit/`). Python builds the widget tree and
+runs your callbacks. Layout, input, drawing and presenting stay in C.
+
+<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)
+- [How it works](#how-it-works)
+- [Performance](#performance)
+- [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`) | ❌ Not yet | Build from source with CMake (below) |
+
+## Install and build
+
+Requirements: **CMake ≥ 3.20**, a **C11/C++17 compiler** (GCC / MinGW, Clang
+or MSVC), and **Python 3** with development headers (for the Python APIs).
```sh
+git clone <this repository> BUI
+cd BUI
cmake -S . -B build
cmake --build build
-ctest --test-dir build # core + Python binding tests
+ctest --test-dir build # C + Python test suites
+```
+
+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:
+
+```sh
+export PYTHONPATH=$PWD/bindings/python # Windows: set PYTHONPATH=%CD%\bindings\python
+python examples/components_demo.py
```
-With the full widget toolkit and examples:
+More detail, including environment variables and troubleshooting:
+[docs/getting-started.md](docs/getting-started.md).
+
+## Quick start
+
+### tkinter syntax
+
+Run any tkinter program on BUI **without changing it**:
```sh
-cmake -S . -B build-ui -DBUI_BUILD_UI=ON -DBUI_BUILD_EXAMPLES=ON
-cmake --build build-ui
-cmake --build build-ui --target bui_svg_demo
-./build-ui/examples/bui_svg_demo demo.svg # renders a showcase scene to SVG
+python -m bui.tksyntax examples/tk_unchanged_app.py
```
-## Modules
-
-- `core/` – pure C11 foundation (containers, memory, math, strings)
-- `types/` – shared data-type shapes (DNA structs, verbatim)
-- `gpu/` – drawing abstraction: null backend + primitive **sink dispatch**
-- `compat/` – seam headers replacing Blender-app APIs (RNA/WM/ED/BLF/IMB/CTX)
-- `ui/` – the widget toolkit sources extracted from Blender (blocks/buttons, layout, handlers, views)
-- `kit/` – **Blender's UI as a C runtime**: nodes, layout, input, widget drawing ported from `interface_widgets.cc`, damage-driven rendering
-- `api/` – stable C ABI (`bui_c_api.h`) for hosts and bindings
-- `bindings/python/` – `buipy` CPython extension + `bui` package (SVG sink, Qt canvas)
-- `backends/qt/` – C++ Qt/QPainter backend (`BuiWidget`, `BUI::QtSink`)
-
-## Rendering from any stack
-
-BUI never opens a window itself. Hosts install a **render sink** — a table of
-function pointers (`BuiGpuSink`) — and receive every primitive the toolkit
-draws (triangles, lines, points, text, scissor). One API, any renderer:
-
-| Host stack | What to use |
-| ---------------------- | ------------------------------------------------------- |
-| C / C++ (any renderer) | `bui_set_render_sink()` from `api/bui_c_api.h` |
-| Qt (C++) | `BUI::QtSink` + `BUI::BuiWidget` in `backends/qt/` |
-| Python (PySide6/PyQt6) | `bui.qt.BuiCanvas` from `bindings/python/bui/qt.py` |
-| Python (headless/CI) | `bui.svg.SvgSink` renders frames to SVG |
-| Any (no GPU) | `buipy.Raster` / `GPU_raster.h` — native frame renderer |
-
-### The fast path: native raster + damage-only present
-
-The tkinter- and Qt-syntax layers render the way Blender does, adapted to a
-CPU host: the whole UI is drawn into **one frame buffer in C**
-(`gpu/intern/gpu_raster.c` — anti-aliased SDF boxes/circles/ellipses/lines,
-polygons, and a cached native text engine), then presented with **one blit of
-just the tiles that changed** (direct GDI blit on Windows, dirty-rect
-`PhotoImage.put` elsewhere, a single `drawImage` under Qt). Redraw requests
-are coalesced into one frame per idle, and hover with no handler costs
-nothing. A 60-widget window renders a changed frame in ~1.5 ms.
+Or opt in from code, before anything imports `tkinter`:
```python
-import bui # locates the built buipy extension
-import buipy
-r = buipy.Raster(640, 480)
-buipy.set_backend(r) # draw_* calls now rasterize natively
-buipy.begin_frame(640, 480)
-buipy.draw_roundrect(20, 20, 120, 32, 6, (0.2, 0.4, 0.8, 1.0))
-buipy.draw_text(32, 41, 13, "Hello", (1, 1, 1, 1))
-buipy.end_frame()
-r.damage() # [(x, y, w, h), ...] changed since last frame
-r.present_native(hwnd) # Windows; or r.ppm(...) / r.rgb32()
+import bui.tksyntax
+bui.tksyntax.install() # `import tkinter` now returns BUI's tkinter
+
+import tkinter as tk
+from tkinter import ttk, messagebox
+
+root = 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",
+ command=lambda: messagebox.showinfo("Hi", "Hello " + name.get())).pack()
+root.mainloop()
```
-## Blender component library — `bui.components` (runs in C)
-
-Blender's UI as composable components: Blender's look _and_ Blender's
-interactions. Every component is a node of the C kit (`kit/`); Python only
-builds the tree and receives callbacks.
-
-- **Blender's code**: the widget drawing is a C port of
- `interface_widgets.cc` — `round_box_edges`, `widgetbase_draw`, the shape
- tables (number arrows, checkmark, menu chevron), `widget_state` /
- `widget_active_color` (Blender's HSL hover tint), `widget_numbut`,
- `widget_numslider`, `widget_optionbut`, `widget_menu_back` …, rendered by a
- software implementation of the `GPU_SHADER_2D_WIDGET_BASE` parameters.
- The HSV wheel uses `hsvcircle_vals_from_pos` / `hsv_cursor`; color math,
- rects and the UTF-8 word-jump text cursor are blenlib (`core/`), linked.
-- **Fast**: rendering is damage driven — state changes mark only the
- widget's rect, a frame redraws and diffs just those regions, and an idle
- UI draws nothing. Measured on the full demo (520×900): **~0.7 ms** for a
- complete frame, **~0.05 ms** for a hover/scrub frame, **~0.18 ms**
- including the Tk event and the window blit — far inside a 120 Hz (8.3 ms)
- budget, i.e. thousands of frames per second.
+Or import it directly, under its own name:
```python
-from bui.components import App, Panel, NumberSlider, EnumRow, Checkbox, Button
-
-App("Demo", (420, 600),
- Panel("Object",
- NumberSlider("Size", 1.0, min=0, max=10, on_change=print,
- description="Object size"),
- EnumRow("Mode", ["Object", "Edit"]),
- Checkbox("Smooth", True),
- Button("Apply", on_click=lambda: print("apply"))),
-).run()
+import bui.tksyntax as tk
+from bui.tksyntax import ttk
```
-| | |
-| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Layout | `Column`, `Row` (`align=True` joins; `weight=0` keeps natural width), `Split`, `Grid`, `Box`, `Panel` (sub-panels, header checkbox, icon), `Tabs`, `SideTabs` (properties-editor icon tabs), `ScrollView` |
-| Values | `NumberField`, `NumberSlider`, `VectorField`, `TextField`, `SearchField`, `HotkeyField`, `Checkbox`, `Toggle` (icon toggles), `Decorator`, `Dropdown` (icons), `EnumRow` (icons, vertical, icon-only), `ColorSwatch` |
-| Buttons | `Button` (icon, `emboss=False`), `IconButton`, `Popover`, `MenuButton` |
-| Views | `ListView` (UI list), `TreeView` + `TreeItem` (outliner, toggle columns), `GridView` (preview tiles) |
-| Menus | `Menu` / `MenuItem` (icons, shortcuts, checkboxes, submenus, type-to-search), `MenuBar`, `PieMenu`, right-click context menus |
-| Color | `ColorSwatch` picker: HSV wheel + value strip or SV square + hue strip, RGB/HSV/HSL sliders, hex, eyedropper |
-| Editors | `ColorRamp`, `CurveMapping` (channels), `NormalBall`, `Histogram` |
-| Templates | `IDSelector` (`template_ID`), `PathField` |
-| Other | `Label` (icon), `ProgressBar`, `Separator`, `Spacer`, tooltips, 120 vector icon names from Blender (`buipy.kit_icon_names()`) |
-
-Interactions, as in Blender:
-
-- **Numbers** — the cursor turns into Blender's ↔ arrows over number
- fields; dragging hides it with a continuous grab (it never hits the
- window edge and returns where it started). Shift = precise, Ctrl = snap,
- Alt = edit X/Y/Z together. Click to type (`2*pi` works).
-- **Any value** — Ctrl+Wheel steps, Ctrl+C / Ctrl+V copy/paste, Backspace
- resets, Minus negates, right-click for Copy/Paste/Reset; Ctrl+Alt+C/V
- copies a whole vector.
-- **Toggles & panels** — drag across checkboxes or panel headers to set them
- all; Ctrl+click a header to solo it; drag a panel's grip to reorder.
-- **Menus** — press-drag-release picks; hover switches between menu-bar
- menus and opens submenus; typing searches every item; `PieMenu.show()` on
- a hotkey (`app.bind("q", ...)`).
-- **Views** — double-click / F2 renames, arrows navigate, Left/Right
- collapse/expand trees, drag down outliner toggle columns.
-- **Color** — wheel with red at the bottom and Blender's cursor; the
- eyedropper samples any pixel of the window.
-
-See `examples/components_demo.py` (every component, properties-editor style).
-
-C kit (`kit/intern/`): `kit_core.c` (nodes, properties, input context,
-damage rendering, text editing, number expressions), `kit_draw.c` (theme +
-the `interface_widgets.cc` port, text, icons), `kit_widgets.c` (layouts and
-widgets), `kit_views.c`, `kit_menus.c`, `kit_color.c` (picker, eyedropper,
-ramp, curves, normal, histogram). Icons are generated into
-`kit_icons_data.c` by `tools/gen_kit_icons.py`. Python wrappers:
-`bui/components/` (`core`, `widgets`, `containers`, `views`, `menus`,
-`editors`, `templates`, `app`); the C API is `kit/include/BUI_kit.h`.
-
-## High-level syntax layers — write Qt or tkinter, render BUI
-
-BUI ships two Python facades that speak the syntax of established toolkits
-while BUI does all the rendering:
+<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)**.
+
+### Qt syntax
```python
-# Qt syntax (examples/qt_syntax_demo.py)
-from bui.qtsyntax import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout
+from bui.qtsyntax import (QApplication, QWidget, QVBoxLayout, QFormLayout,
+ QLineEdit, QSlider, QPushButton, QLabel)
+
app = QApplication([])
window = QWidget()
-layout = QVBoxLayout()
+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("Clicked!"))
-layout.addWidget(status); layout.addWidget(button)
-window.setLayout(layout); window.show()
-app.exec()
+button.clicked.connect(lambda: status.setText("Hello " + (name.text() or "BUI")))
+layout.addWidget(status)
+layout.addWidget(button)
-# tkinter syntax (examples/tk_syntax_demo.py) - the full tkinter API, incl.
-# ttk, messagebox, filedialog, simpledialog, font, scrolledtext
-from bui.tksyntax import Tk, Label, Button
-root = Tk(); root.geometry("420x260")
-Label(root, text="Hello BUI").pack()
-Button(root, text="Click me", command=on_click).pack()
-root.mainloop()
+window.show()
+app.exec()
```
-Existing tkinter programs run unchanged, Blender-styled:
-`python -m bui.tksyntax app.py` (try `examples/tk_unchanged_app.py`), or call
-`bui.tksyntax.install()` before `import tkinter`.
+<p align="center"><img src="docs/images/qt.png" width="460" alt="Qt syntax on BUI"></p>
-No Qt or Tk widgets are involved: both facades are thin Python over the C kit
-(`kit/`). Every widget is a kit node, `pack`/`grid`/`place` and Qt's
-box/grid/form layouts run on the kit's C geometry managers (a port of Tk's
-packer and gridder), `Canvas` and `QPainter` record into a kit display list,
-and windows are native Win32 windows (`kit/intern/kit_window.c`) — input,
-layout, rendering and presenting never leave C; Python only runs your
-callbacks. Elsewhere (or with `BUI_HOST=tk`) a stdlib Tk window hosts the
-frame buffer. See [SYNTAX_COVERAGE.md](SYNTAX_COVERAGE.md).
+Supported classes, signals, layouts and the known gaps:
+**[docs/qt.md](docs/qt.md)**.
-Blender's interaction polish comes for free in all three APIs: Ctrl+Z /
-Ctrl+Shift+Z undo of UI edits, Tab / Shift+Tab between fields, vertical
-multi-drag over number fields, animated panel collapse.
-
-## Low-level Python quick start
+### Blender components
```python
-import buipy
-from bui.svg import SvgSink
-
-sink = SvgSink(640, 480)
-buipy.set_backend(sink)
-buipy.demo_scene(640, 480) # drives the toolkit's draw seam
-sink.save("demo.svg") # or render into QPainter via bui.qt.BuiCanvas
+from bui.components import (App, Panel, NumberSlider, VectorField, EnumRow,
+ Checkbox, ColorSwatch, Button)
+
+App("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()
```
-See [INTEGRATION.md](INTEGRATION.md) for installing/testing `buipy`.
+Component reference and Blender interaction details:
+**[docs/components.md](docs/components.md)**.
-## Qt quick start (C++)
+## How it works
-```cmake
-set(BUI_BUILD_QT_BACKEND ON) # requires Qt5/Qt6 Widgets
-add_subdirectory(BUI)
-target_link_libraries(myapp PRIVATE bui::qt)
```
+ 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)
+```
+
+- **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 native text engine). 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.
+
+More: [ARCHITECTURE.md](ARCHITECTURE.md).
+
+## Performance
+
+Measured on the full component demo (520×900) on a desktop CPU:
+
+| 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 |
+
+The test suite enforces a 120 Hz budget: full frames under 8.3 ms, and
+interaction frames under 1 ms.
+
+## Documentation
+
+| 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 |
+| [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 |
+| `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`), 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 |
+| `examples/`, `tools/` | Demos, the icon generator, the docs screenshot generator |
+
+## Testing
-```cpp
-BUI::BuiWidget canvas(parent);
-canvas.render_func = [&](int w, int h) { /* BUI draw calls */ };
+```sh
+ctest --test-dir build --output-on-failure
```
-The pure-Python path needs no C++ build at all — see
-`bindings/python/bui/qt.py`.
+| 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 |
## License
-Derived from Blender sources: GPL-2.0-or-later (see upstream `COPYING` and the
-SPDX headers preserved in every file).
+Derived from Blender sources: **GPL-2.0-or-later** (see `LICENSE` and the SPDX
+headers kept in every file).
diff --git a/docs/c-api.md b/docs/c-api.md
new file mode 100644
index 0000000..bbd0394
--- /dev/null
+++ b/docs/c-api.md
@@ -0,0 +1,99 @@
+# The C kit (`kit/include/BUI_kit.h`)
+
+Everything the Python APIs draw is a tree of kit nodes. You can use the kit
+directly from C: link `bui::kit` (it pulls in `bui::gpu` and `bui::core`).
+
+```cmake
+add_subdirectory(BUI)
+target_link_libraries(myapp PRIVATE bui::kit)
+```
+
+## Hello from C
+
+`examples/kit_hello.c` (`cmake --build build --target bui_kit_hello`, with
+`-DBUI_BUILD_EXAMPLES=ON`):
+
+```c
+#include <stdio.h>
+#include "BUI_kit.h"
+
+static void on_event(void *data, BKNode *node, int kind, void *ref, double a, double b)
+{
+ if (kind == BK_EV_CLICK) {
+ printf("clicked %s\n", BK_get_str(node, "text"));
+ }
+ else if (kind == BK_EV_CHANGE) {
+ printf("%s = %g\n", BK_get_str(node, "label"), BK_get_num(node, "value"));
+ }
+}
+
+int main(void)
+{
+ BKNode *root = BK_node_new("frame");
+ BK_set_num(root, "padding", 8);
+
+ BKNode *size = BK_node_new("slider");
+ BK_set_str(size, "label", "Size");
+ BK_set_num(size, "min", 0);
+ BK_set_num(size, "max", 10);
+ BK_set_num(size, "value", 2.5);
+ BK_node_add(root, size, -1); /* -1: append */
+ BK_geom_set_manager(size, BK_GEOM_PACK); /* Tk's packer */
+ BK_geom_set(size, "fill", 1); /* fill x */
+
+ BKNode *apply = BK_node_new("button");
+ BK_set_str(apply, "text", "Apply");
+ BK_node_add(root, apply, -1);
+ BK_geom_set_manager(apply, BK_GEOM_PACK);
+ BK_geom_set(apply, "fill", 1);
+ BK_geom_set(apply, "pady0", 6);
+
+ BKContext *ctx = BK_context_new(root);
+ BKHost host = {0};
+ host.emit = on_event; /* the window fills in the rest */
+ BK_context_set_host(ctx, &host);
+
+ if (BK_window_supported()) { /* Windows: native window */
+ BKWindow *win = BK_window_new(ctx, "BUI from C", 320, 120);
+ BK_window_show(win);
+ BK_window_run();
+ BK_window_free(win);
+ }
+ else { /* elsewhere: render to a raster */
+ BuiRaster *r = BUI_raster_create(320, 120);
+ BK_render(ctx, r, 320, 120, 1);
+ BUI_raster_free(r);
+ }
+ BK_context_free(ctx);
+ BK_node_free(root);
+ return 0;
+}
+```
+
+## Concepts
+
+| Concept | API |
+|---|---|
+| **Nodes** | `BK_node_new(type)`, `BK_node_add(parent, child, index)`, `BK_node_remove`, `BK_node_child(_count)`, `BK_node_parent`, `BK_node_rect`, `BK_node_natural`, `BK_node_invalidate`, `BK_node_relayout`, `BK_node_free` |
+| **Properties** | `BK_set_num / BK_set_str / BK_set_color / BK_set_strs` and `BK_get_*`, by name (`"value"`, `"text"`, `"label"`, `"min"`, `"items"`, `"enabled"` ...). `"set_value"` sets a value *and* notifies. |
+| **Geometry** | `BK_geom_set_manager(node, BK_GEOM_PACK / GRID / PLACE)`, `BK_geom_set(node, key, v)` (`side`, `fill`, `expand`, `anchor`, `padx0`..., `row`, `column`, `sticky`, `x`, `relx`, `reqwidth` ...), `BK_frame_grid_weight`. Children of `frame` and `canvas` nodes. |
+| **Context** | `BK_context_new(root)`: input state, popups, focus, undo. Input goes in with `BK_press`, `BK_release`, `BK_motion`, `BK_wheel`, `BK_key`, `BK_key_release`, `BK_button`, `BK_context_menu`; frames come out of `BK_render(ctx, raster, w, h, full)`, which returns the number of redrawn regions (0 means nothing changed). |
+| **Host** | `BKHost`: `request` (schedule a render), `set_cursor`, `warp`, clipboard, `schedule` (timers), `emit` (events). A `BKWindow` provides all of them. |
+| **Events** | `emit(data, node, kind, ref, a, b)`. Kinds: `BK_EV_CHANGE`, `CLICK`, `CALL` (menu item or hotkey), `RENAME`, `ACTIVATE`, `TOGGLE`, `BROWSE`, `SUBMIT`. With the `"events"` property you also get raw `PRESS` / `RELEASE` / `DOUBLE` / `MOTION` / `ENTER` / `LEAVE` / `KEY` / `KEYRELEASE` / `WHEEL` / `CONFIGURE`, plus `VIEW` and `SCROLL` for scrolling. |
+| **Windows** | `BK_window_new`, `show`, `close`, `set_title`, `set_size`, `wm(key, a, b)` (position, topmost, alpha, resizable, minsize, state ...), `timer`, `run`, `pump`, `quit` |
+| **Specialised** | Canvas display list (`BK_canvas_set_item`), text area (`BK_textarea_*`), trees (`BK_tree_item_*`), menus (`BK_open_menu`, `BK_open_pie`), color ramps and curves, `BK_undo` / `BK_redo` |
+
+Node types: `frame column row grid box panel tabs sidetabs scroll scrollbar
+label separator progress button toggle checkbox radio decorator text search
+hotkey number slider dropdown enum swatch popover menubutton menubar list
+tree gridview canvas textarea image ramp curve normal histogram`.
+
+Read the header for the full list. It is the reference: every function
+has a one-line comment.
+
+## Lower level: render sinks
+
+The kit draws through `gpu/` into a `BuiRaster`. If you have your own
+renderer (OpenGL, Vulkan, a game engine, Qt's `QPainter`), you can receive
+BUI's primitives instead through a render sink. See
+[../INTEGRATION.md](../INTEGRATION.md).
diff --git a/docs/components.md b/docs/components.md
new file mode 100644
index 0000000..7222182
--- /dev/null
+++ b/docs/components.md
@@ -0,0 +1,216 @@
+# Blender components (`bui.components`)
+
+A component library built from Blender's interface: the widgets, layouts,
+menus and editors of Blender's properties editor and outliner, with
+Blender's interaction rules. Each component is a node of the C kit. Python
+builds the tree and receives callbacks; everything else runs in C.
+
+![Blender components](images/components.png)
+
+## Hello, components
+
+```python
+from bui.components import App, Panel, NumberSlider, Checkbox, Button
+
+def on_size(value):
+ print("size is now", value)
+
+App("Demo", (360, 260),
+ Panel("Object",
+ NumberSlider("Size", 1.0, min=0, max=10, on_change=on_size,
+ description="Object size"), # tooltip
+ Checkbox("Smooth", True),
+ Button("Apply", on_click=lambda: print("apply"))),
+).run()
+```
+
+## App
+
+```text
+App(title="BUI", size=(420, 640), *children, padding=None, spacing=None, header=None)
+```
+
+| Member | |
+|---|---|
+| `app.root` | The root `Column`, holding `children` |
+| `app.add(*components)` | Append to the root |
+| `app.bind("ctrl+s", fn)` | Window hotkey (`"q"`, `"shift+f3"`, `"ctrl+alt+z"` ...) |
+| `app.run(native=None)` | Open the window and run the loop. `native=False` forces the Tk host. |
+| `app.open(native=None)` | Open the window without running the loop. Returns the `bui.host.Window`. |
+| `app.ctx` | The C kit context (popups, focus, undo: `ctx.undo()` / `ctx.redo()`) |
+| `app.render_raster(w, h)` | Render headlessly into a `buipy.Raster` (tests, screenshots) |
+| `app.press / release / motion / key / wheel / context_menu` | Drive input headlessly (tests) |
+
+Pass a `MenuBar` as `header=` for a Blender top bar.
+
+## Common component API
+
+Every component has:
+
+| Member | |
+|---|---|
+| `description=` | Tooltip text, shown after hovering |
+| `enabled` / `visible` | Properties, also constructor keywords |
+| `weight=` | Share of the width in a `Row` (`0` keeps the natural width) |
+| `x, y, w, h`, `rect` | Geometry after layout |
+| `add(*children)`, `remove(c)`, `children` | Tree editing (containers) |
+
+Value components (`NumberField`, `NumberSlider`, `Checkbox`, `Toggle`,
+`TextField`, `Dropdown`, `EnumRow`, `ColorSwatch` ...) also have:
+
+| Member | |
+|---|---|
+| `value` | Current value (assigning it notifies `on_change`) |
+| `set_value(v, notify=True)` | Set, optionally without the callback |
+| `reset()` | Back to the default (also Backspace over the widget) |
+| `on_change=` | `fn(value)`, called when the user or code changes it |
+
+## Layout
+
+| Component | Signature | Notes |
+|---|---|---|
+| `Column` | `Column(*children, align=False, spacing=None, padding=0)` | Vertical stack. `align=True` joins widgets like Blender's `column(align=True)`. |
+| `Row` | `Row(*children, align=False, spacing=None, padding=0)` | Horizontal. Each child's `weight` is its share of the width. |
+| `Split` | `Split(left, right, factor=0.4)` | Label / value split used by property rows |
+| `Grid` | `Grid(*children, columns=2)` | |
+| `Box` | `Box(*children, align=False, ...)` | Blender's `layout.box()` |
+| `Panel` | `Panel(title, *children, collapsed=False, icon=None, header=(), on_toggle=None)` | Collapsible, with sub-panels, a header checkbox (`header=[Checkbox("", True)]`), drag-to-reorder grips, Ctrl+click to solo and an animated collapse |
+| `Tabs` | `Tabs([("Title", component), ...], current=0, on_change=None)` | |
+| `SideTabs` | `SideTabs([("ICON", "Title", component), ...])` | The properties editor's icon tabs |
+| `ScrollView` | `ScrollView(child, height=None, rows=8)` | |
+| `VectorField` | `VectorField(label, (x, y, z), axes="XYZW", **number_kw)` | Aligned number fields; Alt edits all of them |
+
+## Values
+
+| Component | Signature |
+|---|---|
+| `NumberField` | `NumberField(label, value, *, min=None, max=None, step=None, precision=None, integer=None, suffix="")` |
+| `NumberSlider` | `NumberSlider(label, value, *, min=0, max=1)` |
+| `TextField` | `TextField(label, value, *, placeholder="", icon=None, live=False)` |
+| `SearchField` | `SearchField(value="", *, placeholder="Search")` |
+| `HotkeyField` | `HotkeyField(label, value)`: click, then press a key combination |
+| `Checkbox` | `Checkbox(label, value=False)` |
+| `Toggle` | `Toggle(label, value=False, *, icon=None, icon_on=None, emboss=True)` |
+| `Decorator` | `Decorator(label, value)`: the keyframe dot next to a property |
+| `Dropdown` | `Dropdown(label, items, value=None, *, icon_only=False)` |
+| `EnumRow` | `EnumRow(label, items, value=None, *, vertical=False, icon_only=False)` |
+| `ColorSwatch` | `ColorSwatch(label, (r, g, b, a), *, picker="circle" or "square", alpha=True)` |
+
+Items can be strings or `(text, "ICON")` pairs. Icon names come from
+Blender (`buipy.kit_icon_names()` lists all 120).
+
+## Buttons, labels, feedback
+
+| Component | Signature |
+|---|---|
+| `Button` | `Button(text, on_click=None, *, icon=None, emboss=True)` |
+| `IconButton` | `IconButton("ICON", on_click=None, *, emboss=False)` |
+| `Popover` | `Popover(text, *children, icon=None)`: a button that opens a panel |
+| `MenuButton` | `MenuButton(text, items, *, icon=None)` |
+| `Label` | `Label(text, *, icon=None, align="left", color=None, bold=False)` |
+| `ProgressBar` | `ProgressBar(value=0.0, text=None)` |
+| `Separator`, `Spacer` | `Separator(factor=0.5, line=False)` / `Spacer()` |
+
+## Views
+
+```python
+from bui.components import ListView, TreeView, TreeItem, GridView
+
+ListView(["Cube", "Light", "Camera"], rows=5, on_rename=lambda i, s: print(i, s))
+
+TreeView([TreeItem("Collection",
+ TreeItem("Cube", icon="MESH_DATA"),
+ TreeItem("Light", icon="LIGHT"),
+ icon="OUTLINER_COLLECTION")],
+ columns=["hide", "render"], # outliner toggle columns
+ on_toggle=lambda item, col, on: print(item.label, col, on))
+
+GridView([("Metal", (0.7, 0.72, 0.75, 1)), ("Gold", (0.95, 0.75, 0.3, 1))], # preview tiles
+ tile=4, on_activate=print)
+```
+
+Double-click or F2 renames. Arrow keys navigate, Left and Right collapse
+and expand, and you can drag down a toggle column to set it on several rows.
+
+## Menus
+
+```python
+from bui.components import App, IconButton, MenuBar, MenuItem, PieMenu
+
+def new_file(): print("new")
+def quit_app(): print("quit")
+def search(): print("search")
+
+menubar = MenuBar(
+ ("File", [MenuItem("New", new_file, icon="FILE", shortcut="Ctrl N"),
+ MenuItem("Open Recent", submenu=[MenuItem("a.blend"), MenuItem("b.blend")]),
+ "-", # separator
+ MenuItem("Auto Save", checked=True),
+ MenuItem("Quit", quit_app, shortcut="Ctrl Q")]),
+ right=[IconButton("SEARCH", search)])
+app = App("Tool", (480, 600), header=menubar)
+
+app.bind("q", lambda: PieMenu.show(app.ctx, [MenuItem("Object Mode"),
+ MenuItem("Edit Mode")], "Mode"))
+app.run()
+```
+
+Menus behave as in Blender. Press-drag-release picks an item. Hovering
+switches between menu-bar menus and opens submenus. Typing searches every
+item. Right-clicking a value opens its context menu (Copy, Paste, Reset).
+
+## Color and editors
+
+| Component | Signature |
+|---|---|
+| `ColorSwatch` | Click to open the picker: an HSV wheel and value strip, or an SV square and hue strip, plus RGB / HSV / HSL sliders, a hex field and the eyedropper |
+| `ColorRamp` | `ColorRamp(stops=((0.0, rgba), (1.0, rgba)), *, interpolation="Linear", on_change=None)` |
+| `CurveMapping` | `CurveMapping(points=((0, 0), (1, 1)), *, channels=(), height=8.0, on_change=None)` |
+| `NormalBall` | `NormalBall(label, (x, y, z), *, size=4.0)` |
+| `Histogram` | `Histogram(bins, *, height=5.0)` |
+| `IDSelector` | `IDSelector(items, value, *, icon="MESH_DATA", fake_user=False, on_change, on_new, on_unlink)`: Blender's `template_ID` |
+| `PathField` | `PathField(label, value, *, directory=False, on_browse=None, on_change=None)` |
+
+## Interactions
+
+All of these come from Blender and run in C, in every API (components,
+tkinter and Qt).
+
+- **Number fields.** The cursor turns into ↔ arrows over them. Dragging
+ hides the cursor and grabs it continuously, so it never hits the window
+ edge and comes back where it started. Shift drags precisely, Ctrl snaps
+ to increments, Alt edits all linked fields (X/Y/Z) together. Click to
+ type a value; expressions such as `2*pi`, `90/4` or `1e3` work
+ (`buipy.kit_eval_number`).
+- **Any value.** Ctrl+Wheel steps it, Ctrl+C / Ctrl+V copy and paste it,
+ Ctrl+Alt+C / V copy a whole vector, Backspace resets, Minus negates, and
+ right-click opens Copy / Paste / Reset.
+- **Several fields at once.** Press a number field and drag down over the
+ others to collect them, then sideways to change them all.
+- **Toggles and panels.** Drag across checkboxes or panel headers to set
+ them all. Ctrl+click a panel header to solo it, and drag the grip to
+ reorder panels.
+- **Undo.** Ctrl+Z / Ctrl+Shift+Z (or Ctrl+Y) undo and redo UI edits. A
+ burst of typing is one step, and so is a multi-field drag.
+- **Keyboard.** Tab and Shift+Tab move to the next or previous field while
+ editing. Escape cancels.
+
+## Headless use (tests, screenshots)
+
+```python
+from bui.components import App, NumberField
+
+field = NumberField("Size", 1.0)
+app = App("Test", (400, 300), field)
+raster = app.render_raster() # lays out and draws without a window
+x, y = field.x + field.w // 2, field.y + field.h // 2
+app.press(x, y) # simulate a drag to the right
+app.motion(x + 40, y)
+app.release(x + 40, y)
+print(field.value) # > 1.0
+raster = app.render_raster() # redraws only what changed
+raster.pixel(x, y) # -> (r, g, b)
+```
+
+`bindings/python/tests/test_components.py` uses this to test every
+component and to enforce the 120 Hz frame budgets.
diff --git a/docs/getting-started.md b/docs/getting-started.md
new file mode 100644
index 0000000..8ba5a3e
--- /dev/null
+++ b/docs/getting-started.md
@@ -0,0 +1,104 @@
+# Getting started
+
+## 1. Build
+
+Requirements:
+
+- CMake ≥ 3.20
+- A C11 / C++17 compiler: GCC (MinGW-w64 on Windows), Clang or MSVC
+- Python 3 with development headers, for the Python APIs (`buipy`)
+
+```sh
+cmake -S . -B build
+cmake --build build
+ctest --test-dir build --output-on-failure
+```
+
+On Windows with MSYS2 / MinGW-w64:
+
+```sh
+cmake -S . -B build -G "MinGW Makefiles"
+cmake --build build
+```
+
+### Build options
+
+| Option | Default | Effect |
+|---|---|---|
+| `BUI_BUILD_PYTHON_BINDINGS` | `ON` | Build the `buipy` CPython extension. It is skipped with a message if the Python dev files are missing. |
+| `BUI_BUILD_TESTS` | `ON` | C test executables and the ctest suites |
+| `BUI_BUILD_EXAMPLES` | `OFF` | C examples (`bui_svg_demo`) |
+| `BUI_BUILD_UI` | `OFF` | Compile Blender's original `ui/` sources as well (not needed for the kit) |
+| `BUI_BUILD_QT_BACKEND` | `OFF` | The C++ Qt/QPainter render-sink backend (needs Qt 5/6 Widgets) |
+| `BUI_WARNINGS_AS_ERRORS` | `OFF` | `-Werror` / `/WX` |
+
+## 2. Use it from Python
+
+The pure-Python package is `bindings/python/bui`. Put that directory on the
+path:
+
+```sh
+export PYTHONPATH=/path/to/BUI/bindings/python # Windows: set PYTHONPATH=C:\path\to\BUI\bindings\python
+```
+
+`import bui` (and anything under it) finds the compiled `buipy` extension
+in your CMake build directory by itself (`build*/bindings/python/`). If you
+keep the build somewhere else, point to it:
+
+```sh
+export BUIPY_BUILD_DIR=/path/to/build/bindings/python
+```
+
+Check the setup:
+
+```sh
+python -c "import bui, buipy; print(buipy.kit_window_supported(), len(buipy.kit_icon_names()))"
+python examples/components_demo.py
+python -m bui.tksyntax examples/tk_unchanged_app.py
+python examples/qt_syntax_demo.py
+```
+
+## 3. Pick an API
+
+| You have / want | Use | Guide |
+|---|---|---|
+| An existing tkinter app | `python -m bui.tksyntax app.py`, or `bui.tksyntax.install()` | [tkinter.md](tkinter.md) |
+| New code, tkinter style | `import bui.tksyntax as tk` | [tkinter.md](tkinter.md) |
+| Qt-style code | `from bui.qtsyntax import ...` | [qt.md](qt.md) |
+| A Blender-like tool panel | `from bui.components import ...` | [components.md](components.md) |
+| BUI drawing inside your own renderer | Render sinks | [../INTEGRATION.md](../INTEGRATION.md) |
+| C only | `kit/include/BUI_kit.h` | [c-api.md](c-api.md) |
+
+You can mix them in one process. Windows, timers and the event loop are
+shared (`bui.host`).
+
+## Environment variables
+
+| Variable | Effect |
+|---|---|
+| `BUIPY_BUILD_DIR` | Directory containing the built `buipy` extension |
+| `BUI_HOST=tk` | Force the stdlib-Tk window host even where the native host exists (Windows) |
+| `BUI_UI_SCALE` | Fix the UI scale (for example `1.5`) instead of following the monitor's DPI |
+
+## Window hosts
+
+`bui.host.Window` puts a kit context in a top-level window.
+
+- **Native (Windows).** A Win32 window written in C. Input goes straight
+ into the kit, and frames are presented by blitting only the changed tiles.
+ It follows per-monitor DPI and syncs animations to vsync.
+- **Tk (everywhere else, or with `BUI_HOST=tk`).** A stdlib `tkinter`
+ window that shows the kit's frame buffer and forwards input to it.
+ The UI and the API are identical, but presenting is a little slower.
+
+`bui.host.run()` runs one loop for all windows, `bui.host.update()` processes
+pending events once, and `bui.host.quit()` stops the loop.
+
+## Troubleshooting
+
+| Symptom | Fix |
+|---|---|
+| `ImportError: buipy` | Build first (`cmake --build build`) or set `BUIPY_BUILD_DIR`. The extension must match your Python version: a `cp314` build needs Python 3.14. |
+| Window doesn't appear | Call `mainloop()` / `app.exec()` / `App.run()`. Without a loop, windows only show during `update()`. |
+| Blurry or tiny UI | Set `BUI_UI_SCALE`. On Windows the native host is DPI-aware by default. |
+| A tkinter feature behaves differently | See the behaviour notes in [tkinter.md](tkinter.md#behaviour). If stdlib tkinter does something else, that is a bug; `tests/test_tk_compat.py` shows how to write a side-by-side check. |
diff --git a/docs/images/components.png b/docs/images/components.png
new file mode 100644
index 0000000..902cf34
Binary files /dev/null and b/docs/images/components.png differ
diff --git a/docs/images/qt.png b/docs/images/qt.png
new file mode 100644
index 0000000..7539549
Binary files /dev/null and b/docs/images/qt.png differ
diff --git a/docs/images/tkinter_canvas.png b/docs/images/tkinter_canvas.png
new file mode 100644
index 0000000..67ead57
Binary files /dev/null and b/docs/images/tkinter_canvas.png differ
diff --git a/docs/images/tkinter_items.png b/docs/images/tkinter_items.png
new file mode 100644
index 0000000..0840463
Binary files /dev/null and b/docs/images/tkinter_items.png differ
diff --git a/docs/images/tkinter_messagebox.png b/docs/images/tkinter_messagebox.png
new file mode 100644
index 0000000..a9941ec
Binary files /dev/null and b/docs/images/tkinter_messagebox.png differ
diff --git a/docs/images/tkinter_notes.png b/docs/images/tkinter_notes.png
new file mode 100644
index 0000000..57a3e7e
Binary files /dev/null and b/docs/images/tkinter_notes.png differ
diff --git a/docs/qt.md b/docs/qt.md
new file mode 100644
index 0000000..9e31fb1
--- /dev/null
+++ b/docs/qt.md
@@ -0,0 +1,145 @@
+# Qt syntax on BUI
+
+`bui.qtsyntax` lets you write Qt-style Python (`QApplication`, `QWidget`,
+layouts, `clicked.connect(...)`) that runs on BUI's C kit, with Blender's
+look. Neither Qt nor PySide is needed.
+
+> **Status: partial.** The everyday subset below works and is tested.
+> Measured against Qt's widget headers, about a quarter of the method names
+> on the main widget classes exist. See [Coverage](#coverage) for what's
+> missing and the plan.
+
+![Qt syntax on BUI](images/qt.png)
+
+## Example
+
+```python
+from bui.qtsyntax import (QApplication, QMainWindow, QWidget, QVBoxLayout,
+ QHBoxLayout, QFormLayout, QLabel, QLineEdit, QComboBox,
+ QSlider, QProgressBar, QPushButton, QTreeWidget,
+ QTreeWidgetItem, QMessageBox, Qt)
+
+app = QApplication([])
+win = QMainWindow()
+win.setWindowTitle("Qt syntax on BUI")
+
+central = QWidget()
+layout = QVBoxLayout(central)
+
+form = QFormLayout()
+name = QLineEdit()
+name.setPlaceholderText("name")
+kind = QComboBox()
+kind.addItems(["Mesh", "Light", "Camera"])
+level = QSlider(Qt.Horizontal)
+level.setRange(0, 100)
+form.addRow("Name:", name)
+form.addRow("Kind:", kind)
+form.addRow("Level:", level)
+layout.addLayout(form)
+
+bar = QProgressBar()
+level.valueChanged.connect(bar.setValue) # signals connect to any callable
+layout.addWidget(bar)
+
+tree = QTreeWidget()
+tree.setHeaderLabels(["Name", "Kind"])
+layout.addWidget(tree)
+
+buttons = QHBoxLayout()
+add = QPushButton("Add")
+add.clicked.connect(lambda: QTreeWidgetItem(tree, [name.text(), kind.currentText()]))
+buttons.addWidget(add)
+layout.addLayout(buttons)
+
+menu = win.menuBar().addMenu("File")
+menu.addAction("Quit", app.quit, "Ctrl+Q")
+win.statusBar().showMessage("Ready")
+
+win.setCentralWidget(central)
+win.resize(420, 420)
+win.show()
+app.exec()
+```
+
+## How it maps
+
+| Qt | On BUI |
+|---|---|
+| `QWidget` | A kit frame. A subclass that overrides `paintEvent` becomes a kit canvas, and `QPainter` records into its display list. |
+| `QVBoxLayout` / `QHBoxLayout` | Tk's packer in C, with Qt semantics: stretch factors, expanding size policies, spacing between items only, margins on top-level layouts only |
+| `QGridLayout` / `QFormLayout` | Tk's gridder in C (`setColumnStretch` maps to column weights) |
+| Signals | Plain Python (`Signal` / `pyqtSignal`). Slots that take fewer arguments than the signal sends get fewer. |
+| `QApplication.exec()` | `bui.host.run()`: a native window on Windows, a Tk-hosted window elsewhere |
+| `QTimer`, `QPropertyAnimation` | Window timers; animations step at 120 Hz with easing curves |
+
+## Supported classes
+
+| Area | Classes |
+|---|---|
+| Application | `QApplication` (`exec`, `quit`, `processEvents`), `QTimer` (`singleShot`, `start`, `stop`, `timeout`), `QPropertyAnimation`, `QEasingCurve` |
+| Windows | `QWidget`, `QMainWindow` (`setCentralWidget`, `menuBar`, `statusBar`), `QDialog` (`exec`, `accept`, `reject`), `QFrame` |
+| Layouts | `QVBoxLayout`, `QHBoxLayout` (`addWidget(stretch)`, `addLayout`, `addStretch`, `addSpacing`, `insertWidget`, `setSpacing`, `setContentsMargins`), `QGridLayout` (spans, alignment, stretch), `QFormLayout.addRow`, `QStackedLayout` |
+| Widgets | `QLabel` (text, alignment, pixmap), `QPushButton` / `QToolButton`, `QCheckBox`, `QRadioButton` + `QButtonGroup` (auto-exclusive), `QLineEdit` (`textChanged`, `returnPressed`, `editingFinished`), `QTextEdit` / `QPlainTextEdit`, `QSlider` / `QDial`, `QSpinBox` / `QDoubleSpinBox`, `QProgressBar` (format), `QComboBox` (items, data, `currentIndexChanged`) |
+| Views | `QListWidget` / `QListWidgetItem`, `QTreeWidget` / `QTreeWidgetItem` (columns, expand), `QTableWidget` / `QTableWidgetItem` |
+| Containers | `QTabWidget`, `QGroupBox` (a Blender panel), `QScrollArea`, `QStatusBar` |
+| Menus | `QMenuBar`, `QMenu` (`addAction(text, slot, shortcut)`, submenus, separators, `popup`), `QAction` (checkable, shortcuts) |
+| Painting | `QPainter` (`fillRect`, `drawRect`, `drawRoundedRect`, `drawEllipse`, `drawLine`, `drawPolyline`, `drawPolygon`, `drawArc`, `drawPie`, `drawText`, `drawPixmap`, `translate`, `save`, `restore`, `setOpacity`), `QPen`, `QBrush`, `QColor`, `QFont`, `QPixmap` / `QImage` |
+| Events | Override `mousePressEvent`, `mouseReleaseEvent`, `mouseMoveEvent`, `mouseDoubleClickEvent`, `keyPressEvent`, `wheelEvent`, `enterEvent`, `leaveEvent`, `closeEvent`, `paintEvent`. Event types: `QMouseEvent`, `QKeyEvent`, `QWheelEvent`, `QPaintEvent`, `QCloseEvent`. |
+| Values | `Qt` constants (alignment, keys, orientation, check states), `QPoint`, `QSize`, `QRect`, `QMargins`, `QSizePolicy`, `QIcon` |
+| Dialogs | `QMessageBox` (static calls return immediately; not drawn yet), `QFileDialog` (the OS file dialogs) |
+
+Member-by-member tables: [../SYNTAX_COVERAGE.md](../SYNTAX_COVERAGE.md#qt-syntax-buiqtsyntax).
+
+### Custom painting
+
+```python
+from bui.qtsyntax import QApplication, QWidget, QPainter, QColor, QPen
+
+class Gauge(QWidget):
+ def __init__(self):
+ super().__init__()
+ self.value = 0.6
+
+ def paintEvent(self, event):
+ p = QPainter(self)
+ p.setBrush(QColor("#282828"))
+ p.drawRoundedRect(0, 0, self.width(), 24, 6, 6)
+ p.setBrush(QColor("#4772b3"))
+ p.drawRoundedRect(0, 0, int(self.width() * self.value), 24, 6, 6)
+ p.setPen(QPen(QColor("white")))
+ p.drawText(8, 17, "%d%%" % (self.value * 100))
+ p.end()
+
+ def mousePressEvent(self, e):
+ self.value = e.x() / max(1, self.width())
+ self.update() # repaints the display list
+```
+
+## Coverage
+
+There is no Qt installed in the test environment, so coverage was counted
+from Qt's own widget headers (`reference/qtbase`): **about 220 of 920
+public method names** across 25 core widget classes (~24%).
+
+**Missing:**
+
+- Model/view: `QAbstractItemModel`, `QListView`, `QTreeView`,
+ `QTableView`, delegates
+- `QSplitter`, `QDockWidget`, `QToolBar`, `QStackedWidget` (as a real
+ class), `QToolBox`, `QDateEdit` and friends, `QCalendarWidget`
+- Most of `QWidget`'s surface: focus policy details, `setWindowFlags`,
+ geometry helpers, `grab`
+- Stylesheets beyond `color`, `background` and `font-weight`; `QPalette`
+- `QSettings`, `QThread`, `QClipboard`, drag-and-drop, `QShortcut`
+- `QMessageBox` and `QInputDialog` as drawn dialogs (the tkinter layer
+ already has Blender-styled dialogs that can be reused)
+
+**Plan.** Reach parity with the tkinter layer:
+
+1. Measure against PySide6 itself, and run the same programs on real Qt
+ and on BUI to compare, as `test_tk_compat.py` does for tkinter.
+2. Make widgets wrap kit nodes instead of being them (as `bui.tksyntax`
+ does), which removes name clashes like `rect()` and `children()`.
+3. Fill in the classes above, then add `install()` so `import PySide6`
+ programs run unchanged.
diff --git a/docs/tkinter.md b/docs/tkinter.md
new file mode 100644
index 0000000..03d120a
--- /dev/null
+++ b/docs/tkinter.md
@@ -0,0 +1,227 @@
+# tkinter on BUI
+
+`bui.tksyntax` is a complete implementation of the `tkinter` API on BUI's C
+kit. Programs keep their tkinter code and get Blender's look and interactions.
+
+![A plain tkinter program on BUI](images/tkinter_items.png)
+
+## Three ways to use it
+
+**1. Run an existing program unchanged**
+
+```sh
+python -m bui.tksyntax my_app.py [args...]
+```
+
+This runs the script with `tkinter` (and `tkinter.ttk`, `tkinter.messagebox`
+...) pointing to BUI. `sys.argv` is passed through, so the script sees its
+own arguments.
+
+**2. Switch inside your program**
+
+```python
+import bui.tksyntax
+bui.tksyntax.install() # before the first `import tkinter`
+
+import tkinter as tk
+from tkinter import ttk
+```
+
+`install()` covers `tkinter` and its submodules: `ttk`, `messagebox`,
+`filedialog`, `simpledialog`, `colorchooser`, `commondialog`, `dialog`,
+`font`, `scrolledtext` and `constants`.
+
+**3. Import it by name**
+
+```python
+import bui.tksyntax as tk
+from bui.tksyntax import ttk, messagebox, filedialog
+```
+
+## Example
+
+```python
+import tkinter as tk
+from tkinter import ttk, messagebox
+
+root = tk.Tk()
+root.title("Inventory")
+
+# menus become a Blender menu bar
+menubar = tk.Menu(root)
+filemenu = tk.Menu(menubar, tearoff=0)
+filemenu.add_command(label="Quit", accelerator="Ctrl+Q", command=root.destroy)
+menubar.add_cascade(label="File", menu=filemenu)
+root.config(menu=menubar)
+
+form = ttk.LabelFrame(root, text="New item") # a Blender panel
+form.pack(fill="x", padx=6, pady=6)
+name = tk.StringVar(value="Cube")
+ttk.Label(form, text="Name").grid(row=0, column=0, sticky="e", padx=4)
+ttk.Entry(form, textvariable=name).grid(row=0, column=1, sticky="we")
+ttk.Label(form, text="Count").grid(row=1, column=0, sticky="e", padx=4)
+tk.Spinbox(form, from_=1, to=99).grid(row=1, column=1, sticky="we") # a number field
+form.columnconfigure(1, weight=1)
+
+tree = ttk.Treeview(root, columns=("name", "kind"), show="headings", height=5)
+for col in ("name", "kind"):
+ tree.heading(col, text=col.title())
+tree.insert("", "end", values=("Cube", "Mesh"))
+sb = ttk.Scrollbar(root, orient="vertical", command=tree.yview)
+tree.configure(yscrollcommand=sb.set)
+tree.pack(side="left", fill="both", expand=True)
+sb.pack(side="right", fill="y")
+
+ttk.Button(root, text="About",
+ command=lambda: messagebox.showinfo("About", "Plain tkinter")).pack()
+root.mainloop()
+```
+
+The full version is `examples/tk_unchanged_app.py`.
+
+## Module map
+
+| tkinter | BUI | Notes |
+|---|---|---|
+| `tkinter` | `bui.tksyntax` | `Tk`, `Toplevel`, every classic widget, variables, `Event`, `PhotoImage`, `BitmapImage`, `mainloop`, constants |
+| `tkinter.ttk` | `bui.tksyntax.ttk` | Themed widgets including `Treeview`, `Notebook`, `Progressbar`, `Combobox`, `Separator`, `Sizegrip`, `LabeledScale`, `Panedwindow`, `Style`. `state()` / `instate()` work. |
+| `tkinter.messagebox` | `.messagebox` | Blender-styled modal dialogs with the same return values (`"ok"`, `True`, `None` ...) |
+| `tkinter.simpledialog` | `.simpledialog` | `Dialog` (override `body` / `validate` / `apply`), `SimpleDialog`, `askstring`, `askinteger`, `askfloat` |
+| `tkinter.filedialog` | `.filedialog` | The operating system's file dialogs, as with Tk on Windows and macOS |
+| `tkinter.colorchooser` | `.colorchooser` | `askcolor` with Blender's color picker; returns `((r, g, b), "#rrggbb")` |
+| `tkinter.font` | `.font` | `Font`, named fonts (`TkDefaultFont` ...), `measure` / `metrics` through the native text engine |
+| `tkinter.scrolledtext` | `.scrolledtext` | `ScrolledText`, as in tkinter |
+| `tkinter.dialog`, `.commondialog`, `.constants` | same names | |
+
+## What you get
+
+- **Geometry managers.** `pack`, `grid` and `place` with every option:
+ `in_`, `before`/`after`, `ipadx`, `sticky`, spans, `columnconfigure`
+ weights and `minsize`, `grid_remove`, `*_info`, `*_slaves`, `grid_bbox`,
+ `grid_location`, `grid_size`, and `pack_propagate(False)`. The packer and
+ gridder are C ports of Tk's own algorithms.
+- **Scrolling.** `xview` / `yview` / `*_moveto` / `*_scroll` and
+ `x/yscrollcommand` work on `Listbox`, `Text`, `Treeview` and `Canvas`.
+ `Canvas` adds `scrollregion`, `confine`, scroll increments and `scan_*`.
+ `Scrollbar` is drawn as a Blender scroller and speaks Tk's protocol, so
+ `sb.config(command=lb.yview); lb.config(yscrollcommand=sb.set)` works.
+ Scrollable frames (Canvas + `create_window` + `<Configure>` →
+ `scrollregion=bbox("all")`) work too.
+- **Bindings.** `bind`, `bind_all`, `bind_class`, `bindtags`, `unbind*`,
+ `event_add` and `event_generate`:
+ - modifiers (`Control`, `Shift`, `Alt`, `B1`), `Double-`, buttons 1–3,
+ `<B1-Motion>`, `<KeyPress>` / `<KeyRelease>`;
+ - `<MouseWheel>` (Button-4/5 on X11), `<Enter>` / `<Leave>`, `<Configure>`,
+ `<Map>`, `<Destroy>`, `<FocusIn/Out>`, and virtual events;
+ - callbacks run once per bindtag and stop on `"break"`;
+ - `Event` carries Tk's fields.
+- **Widgets.** `Entry` supports `show="*"` and `validate` /
+ `validatecommand` with `%P %s %S %d %i %V %W`. `Listbox` supports
+ `selectmode` single / browse / multiple / extended, with Ctrl and Shift
+ clicks. `Treeview` has sortable headings (`heading(command=...)`),
+ `show="headings"` tables, `<<TreeviewOpen>>` / `<<TreeviewClose>>`, and
+ `move` / `detach` / `reattach`. Also included: `Notebook`, `PanedWindow`
+ with draggable sashes, `OptionMenu` (a Blender enum dropdown),
+ `Menubutton`, and `Message`.
+- **Canvas.**
+ - Items: all types, including `window`, smoothed lines and arrowheads.
+ - Tags: tag expressions (`"a&&!b"`), `find_*` / `addtag_*`, and
+ `tag_bind` with `current` plus per-item `<Enter>` / `<Leave>`.
+ - Editing: shape-accurate hit tests, `move` / `moveto` / `scale` /
+ `coords`, and editing text items in place.
+- **Text.**
+ - Indices: the full grammar (`3.5`, `end-1c`, `insert lineend`, `@x,y`,
+ `tag.first`, marks, `+N lines`, `wordstart` ...).
+ - Tags: foreground and background colors, priorities, and `tag_bind`.
+ - Also: marks with gravity, `search` (regexp, backwards, `count`), `dump`,
+ `count`, the undo stack, `<<Modified>>`, and peers.
+- **Windows.** `geometry` (size and `+x+y`), `attributes` (`-topmost`,
+ `-alpha`, `-fullscreen`, `-disabled`), `resizable`, `minsize` / `maxsize`,
+ `overrideredirect`, `state` / `iconify` / `withdraw`, `transient`,
+ `protocol("WM_DELETE_WINDOW")`, `grab_set` (disables the other windows),
+ clipboard, `after` / `after_idle` / `after_info`, `wait_window`,
+ `wait_variable` and every `winfo_*`.
+- **Images.** `PhotoImage` reads PNG / PPM / PGM in pure Python and GIF
+ through Tk. It supports `put` / `get` / `copy` / `zoom` / `subsample` /
+ `copy_replace` / `data` and `write` (PNG, PPM). `BitmapImage` reads XBM.
+
+## The Blender look
+
+The look always comes from Blender's theme:
+
+- `tk.Scale` and `ttk.Scale` are Blender sliders (drag to scrub, click to
+ type).
+- `Spinbox` is a Blender number field.
+- `Combobox` and `OptionMenu` are Blender enum dropdowns.
+- `LabelFrame` is a Blender panel.
+- `Checkbutton(indicatoron=0)` is a Blender toggle button.
+
+Some options only change Tk's appearance: `relief`, `borderwidth`,
+`highlightthickness`, `activebackground`, `selectcolor`, `ttk.Style`
+settings and similar. They are accepted and returned by `cget`, but they
+don't change what's drawn.
+
+These options do apply:
+
+- `bg` on `Frame`, `Canvas` and windows
+- `fg` on text
+- `font` (size and bold: `font=("Arial", 18, "bold")`)
+- `cursor` (`"hand2"`, `"xterm"`, `"fleur"` ...)
+- `width` / `height` (characters or pixels, as in Tk)
+- `image`
+- `state`
+
+On top of that, every widget gets Blender's interactions (see
+[components.md](components.md#interactions)). Number fields scrub,
+Ctrl+Z / Ctrl+Shift+Z undo edits, and Tab moves to the next field.
+
+## Behaviour
+
+BUI follows Tk's semantics, checked against the stdlib by
+`tests/test_tk_compat.py`. Some of them are easy to miss:
+
+- `textvariable` overrides `text`, and `cget("text")` returns the
+ variable's value.
+- A `Scale`'s `command` and `<<TreeviewSelect>>` run when the loop is idle,
+ not inside `set()` / `selection_set()`.
+- `validatecommand` also sees programmatic `insert` / `delete`.
+- Generated key events (`event_generate("<Control-q>")`) go to the widget
+ with keyboard focus.
+- Menus keep Tk's tearoff entry at index 0 unless you pass `tearoff=0`.
+- `Text` keeps the trailing newline: `get("1.0", "end")` ends with `"\n"`,
+ so use `"end-1c"`.
+- `edit_undo()` does nothing while `undo` is off.
+- A `Notebook` requests the size of its largest page.
+- A `Toplevel` appears when the loop is next idle, sized to its content.
+- `Checkbutton` and `Radiobutton` create a variable if you don't give one,
+ as Tk does.
+
+## Limitations
+
+- `send` raises `TclError`, as on Windows Tk.
+- Images and windows embedded in a `Text` (`image_create`, `window_create`)
+ are kept and listed, but not drawn.
+- There's no Tcl interpreter. `root.tk.call(...)` handles a few common
+ commands (`tk scaling`, `wm ...`, `set`, `info patchlevel`) and raises
+ `TclError` for the rest.
+- Canvas `dash` / `stipple` and `postscript` output are accepted but not
+ rendered.
+
+## Testing your app against tkinter
+
+`tests/test_tk_compat.py` runs programs on both the stdlib and BUI and
+compares what they observe:
+
+```python
+def prog_mine(tk, ttk):
+ root = tk.Tk()
+ lb = tk.Listbox(root)
+ lb.insert("end", "a", "b")
+ lb.selection_set(1)
+ result = {"sel": lb.curselection()}
+ root.destroy()
+ return result
+```
+
+Add your function to `PROGRAMS` and run
+`python bindings/python/tests/test_tk_compat.py`.
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
index c3d6e0b..ed94e0b 100644
--- a/examples/CMakeLists.txt
+++ b/examples/CMakeLists.txt
@@ -5,3 +5,7 @@
# the null backend, no window system needed.
add_executable(bui_svg_demo svg_demo.c)
target_link_libraries(bui_svg_demo PRIVATE bui_api bui_gpu)
+
+# The C kit from C: nodes, geometry, events, native window (docs/c-api.md).
+add_executable(bui_kit_hello kit_hello.c)
+target_link_libraries(bui_kit_hello PRIVATE bui::kit)
diff --git a/examples/__pycache__/qt_syntax_demo.cpython-314.pyc b/examples/__pycache__/qt_syntax_demo.cpython-314.pyc
new file mode 100644
index 0000000..6b5e887
Binary files /dev/null and b/examples/__pycache__/qt_syntax_demo.cpython-314.pyc differ
diff --git a/examples/kit_hello.c b/examples/kit_hello.c
new file mode 100644
index 0000000..8de5480
--- /dev/null
+++ b/examples/kit_hello.c
@@ -0,0 +1,60 @@
+/* BUI kit from C: a slider and a button in a native window.
+ *
+ * cmake -S . -B build -DBUI_BUILD_EXAMPLES=ON && cmake --build build --target bui_kit_hello
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <stdio.h>
+#include "BUI_kit.h"
+
+static void on_event(void *data, BKNode *node, int kind, void *ref, double a, double b)
+{
+ if (kind == BK_EV_CLICK) {
+ printf("clicked %s\n", BK_get_str(node, "text"));
+ }
+ else if (kind == BK_EV_CHANGE) {
+ printf("%s = %g\n", BK_get_str(node, "label"), BK_get_num(node, "value"));
+ }
+}
+
+int main(void)
+{
+ BKNode *root = BK_node_new("frame");
+ BK_set_num(root, "padding", 8);
+
+ BKNode *size = BK_node_new("slider");
+ BK_set_str(size, "label", "Size");
+ BK_set_num(size, "min", 0);
+ BK_set_num(size, "max", 10);
+ BK_set_num(size, "value", 2.5);
+ BK_node_add(root, size, -1);
+ BK_geom_set_manager(size, BK_GEOM_PACK);
+ BK_geom_set(size, "fill", 1); /* fill x */
+
+ BKNode *apply = BK_node_new("button");
+ BK_set_str(apply, "text", "Apply");
+ BK_node_add(root, apply, -1);
+ BK_geom_set_manager(apply, BK_GEOM_PACK);
+ BK_geom_set(apply, "fill", 1);
+ BK_geom_set(apply, "pady0", 6);
+
+ BKContext *ctx = BK_context_new(root);
+ BKHost host = {0};
+ host.emit = on_event; /* callbacks; the window adds the rest */
+ BK_context_set_host(ctx, &host);
+
+ if (BK_window_supported()) { /* Windows: a native window */
+ BKWindow *win = BK_window_new(ctx, "BUI from C", 320, 120);
+ BK_window_show(win);
+ BK_window_run();
+ BK_window_free(win);
+ }
+ else { /* elsewhere: render a frame into a raster */
+ BuiRaster *r = BUI_raster_create(320, 120);
+ BK_render(ctx, r, 320, 120, 1);
+ BUI_raster_free(r);
+ }
+ BK_context_free(ctx);
+ BK_node_free(root);
+ return 0;
+}
diff --git a/tools/gen_doc_images.py b/tools/gen_doc_images.py
new file mode 100644
index 0000000..8f0ccc8
--- /dev/null
+++ b/tools/gen_doc_images.py
@@ -0,0 +1,70 @@
+"""Render the examples into docs/images/ (headless, no window shown).
+
+ python tools/gen_doc_images.py
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+import os, sys
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+OUT = os.path.join(ROOT, "docs", "images")
+sys.path.insert(0, os.path.join(ROOT, "bindings", "python"))
+sys.path.insert(0, os.path.join(ROOT, "examples"))
+import bui, buipy
+from bui.tksyntax._images import _encode_png
+
+def save(raster, w, h, name):
+ px = b"".join(bytes(raster.pixel(x, y)) + b"\xff" for y in range(h) for x in range(w))
+ with open(os.path.join(OUT, name), "wb") as fh:
+ fh.write(_encode_png(w, h, px))
+ print("saved", name, w, h)
+
+def ctx_shot(ctx, w, h, name):
+ r = buipy.Raster(w, h)
+ ctx.render(w, h, r, True)
+ save(r, w, h, name)
+
+# 1. components demo
+import components_demo
+app = components_demo.build()
+r = app.render_raster(520, 690, True)
+save(r, 520, 690, "components.png")
+
+# 2. unchanged tkinter app (+ each tab)
+import bui.tksyntax as tks
+tks.install()
+import tkinter as tk
+import tk_unchanged_app
+for i, name in enumerate(("tkinter_items.png", "tkinter_notes.png", "tkinter_canvas.png")):
+ root = tk_unchanged_app.build(tk.Tk())
+ nb = [w for w in root.winfo_children() if w.winfo_class() == "TNotebook"][0]
+ nb.select(i)
+ root.update()
+ ctx_shot(root._ctx, *root._window.size, name)
+ root.destroy()
+
+# 3. messagebox
+from tkinter import messagebox
+from bui.tksyntax import _core
+root = tk.Tk(); tk.Label(root, text=" ").pack(); root.update()
+def shoot():
+ top = [w for w in _core._windows() if w is not root][-1]
+ ctx_shot(top._ctx, *top._window.size, "tkinter_messagebox.png")
+ for d in top._descendants():
+ if isinstance(d, tk.Button) and d.cget("text") == "No":
+ d.invoke()
+root.after(150, shoot)
+messagebox.askyesno("Unsaved changes", "Save changes to the inventory before closing?",
+ detail="Your changes will be lost if you don't save them.")
+root.destroy()
+
+# 4. Qt demo
+import bui.qtsyntax as qt
+import qt_syntax_demo
+def fake_exec(self):
+ w = [o for o in qt._custom_or_top()][-1]
+ w._window.render_now()
+ ctx_shot(w._ctx, w._window.size[0], 222, "qt.png")
+ w.close()
+ return 0
+qt.QApplication.exec = fake_exec
+qt_syntax_demo.main()