Skip to content

armgit / BUI

Public Imported from GitHub
0

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

feat: 1:1 parity with tkinter

Preetham Pemmasanic0ed2dffbf82
diff --git a/.gitignore b/.gitignore
index c4895ee..3a9d18e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
-build/
+build*/
build-ui/
*.obj
*.o
+reference/
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 59bcc6a..7d07f6d 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -6,26 +6,27 @@ reusable interface machinery — no Blender application logic (no scene graph,
depsgraph, nodes, operators-on-datablocks, file loading, Python).
```
-┌─────────────────────────────────────────────────────────────┐
-│ ui/ widget toolkit: blocks/buttons, layout engine, │
-│ widget drawing, handlers, views, view2d │
-└──────┬───────────────┬──────────────┬───────────────────────┘
- │ │ │
-┌──────▼──────┐ ┌──────▼──────┐ ┌─────▼───────────────────────┐
-│ types/ │ │ gpu/ │ │ compat/ │
-│ DNA data │ │ draw seam │ │ RNA / CTX / WM / ED / BLF / │
-│ shapes │ │ (null │ │ IMB seams (stubs & hooks) │
-│ (verbatim │ │ backend; │ │ │
-│ structs) │ │ plug real │ │ │
-│ │ │ renderer) │ │ │
-└──────┬──────┘ └──────┬──────┘ └─────┬───────────────────────┘
- │ │ │
-┌──────▼───────────────▼──────────────▼───────────────────────┐
-│ core/ pure C11 foundation extracted from blenlib │
-│ listbase · ghash · mempool · memarena · dynstr │
-│ math (vec/mat/rot/color/geom) · strings · rct │
-│ guarded-allocator shim · threads stubs │
-└─────────────────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────────────────────┐
+│ ui/ widget toolkit: blocks/buttons, layout engine, │
+│ widget drawing, handlers, views, view2d │
+└──────┬───────────────┬──────────────┬─────────────┬──────────────┘
+ │ │ │ │
+┌──────▼──────┐ ┌──────▼──────┐ ┌─────▼──────────┐ ┌▼──────────────────┐
+│ types/ │ │ gpu/ │ │ compat/ │ │ api/ stable C │
+│ DNA data │ │ draw seam │ │ RNA / CTX / WM │ │ ABI for hosts │
+│ shapes │ │ (null back- │ │ / ED / BLF / │ │ & bindings │
+│ (verbatim) │ │ end + sink │ │ IMB seams │ └───┬─────────┬─────┘
+│ │ │ dispatch) │ │ (stubs & hooks)│ │ │
+└──────┬──────┘ └──────┬──────┘ └─────┬──────────┘ ┌───▼───┐ ┌───▼──────┐
+ │ │ │ │buipy │ │bui_qt │
+ │ │ │ │Python │ │QPainter │
+ │ │ │ │binding│ │backend │
+┌──────▼───────────────▼──────────────▼──────────┐└───────┘ └──────────┘
+│ core/ pure C11 foundation extracted from blenlib │
+│ listbase · ghash · mempool · memarena · dynstr │
+│ math (vec/mat/rot/color/geom) · strings · rct │
+│ guarded-allocator shim · threads stubs │
+└────────────────────────────────────────────────────────────────┘
```
Dependency rule: arrows point downward only. `ui/` never includes Blender
@@ -37,29 +38,59 @@ application code; everything it needs arrives through `types/`, `gpu/`, or
| Module | Contents | Status |
|---|---|---|
| `core/` | C11 subset of blenlib, de-C++ified with mechanical transforms (namespaces stripped, casts normalized, MEM API mapped). Inline math lives in `include/intern/*.c` included by headers (`MINLINE` = `static inline` in C). | **Builds + tested** |
-| `types/` | Verbatim `DNA_*_types.h` struct definitions (regions, areas, themes, events). Data shapes only; no serialization runtime. | Headers ready |
-| `gpu/` | The 90-symbol draw surface used by the toolkit (`GPU_*`, `imm*`) behind seam headers + a null backend. Real renderers implement the same headers. Theme colors reach the GPU layer through function-pointer hooks to avoid a `gpu→ui` dependency. | **Builds** |
-| `compat/` | Seam headers carrying upstream API names (`RNA_access.hh`, `BLF_api.hh`, …) with BUI-owned opaque types/stubs. | Skeleton staged |
-| `ui/` | The toolkit sources from `editors/interface`: interface.cc family, widgets, handlers, regions, view2d, views, textbox. Option-gated (`-DBUI_BUILD_UI=ON`). | Sources staged; compile WIP |
+| `types/` | Verbatim `DNA_*_types.h` struct definitions. `DNA_listBase.h` aliases `blender::{Link,LinkData,ListBase}` onto the core's C structs so DNA structs and the C listbase API share one type. | **Builds** |
+| `gpu/` | The draw surface used by the toolkit (`GPU_*`, `imm*`) behind seam headers + a null backend that *records and forwards*: with a sink installed it emits screen-space primitives (`GPU_backend_sink.h`); without one it discards them. Theme colors reach the GPU layer through function-pointer hooks. | **Builds + tested** |
+| `compat/` | Seam headers carrying upstream API names (`RNA_access.hh`, `BLF_api.hh`, …) with BUI-owned opaque types and stub implementations (`intern/bui_stubs.cc`). | **Builds** |
+| `ui/` | The toolkit sources from `editors/interface`: interface.cc family, widgets, handlers, regions, view2d, views, textbox. Option-gated (`-DBUI_BUILD_UI=ON`). | **Compiles + links** |
+| `kit/` | Blender's UI as a retained-mode C runtime: node tree, uiLayout-style layout, `interface_handlers.cc` interaction rules, widget drawing ported from `interface_widgets.cc` (widget-base shader parameters rendered by `gpu/` raster), menus, color picker, views, editors; Tk-style pack/grid/place geometry managers, canvas display list, multi-line text area; UI undo/redo, Tab field traversal, vertical multi-drag, panel animation; damage-driven rendering; native Win32 window host (`kit_window.c`). C API: `kit/include/BUI_kit.h`. | **Builds + tested** |
+| `api/` | `bui_c_api.h` — small stable C ABI: version info + sink/viewport plumbing for hosts and bindings. | **Builds + tested** |
+| `bindings/python/` | `buipy` CPython extension (no third-party deps) + `bui` package: `bui.components` (Blender component library), `bui.qtsyntax` / `bui.tksyntax` (Qt / tkinter APIs as thin facades over the kit), `bui.host` (native or Tk windows), `SvgSink` headless renderer, `bui.qt.BuiCanvas` PySide6/PyQt6 widget. | **Builds + tested** |
+| `backends/qt/` | C++ Qt backend: `BUI::QtSink` (BuiGpuSink → QPainter) + `BUI::BuiWidget` (QWidget host, no moc needed). Gate: `-DBUI_BUILD_QT_BACKEND=ON`. | **Shipped** (builds where Qt exists) |
+| `examples/` | `bui_svg_demo.c` (C, sink → SVG), `python_demo.py` (buipy → SVG). | **Builds + run** |
+
+## Render-sink dispatch
+
+The null backend is the integration seam. `gpu/include/GPU_backend_sink.h`
+defines `BuiGpuSink` — a function-pointer table (`triangles`, `lines`,
+`points`, `text`, `scissor`, `begin_frame`, `end_frame`). The null backend:
+
+- records immediate-mode vertices (`immBegin/immAttr*/immVertex*/immEnd`),
+- decodes vertex batches (pos/color attributes, index buffers),
+- applies the model matrix and forwards screen-space primitives to the sink,
+- or, with no sink installed, discards everything (pure null).
+
+Real renderers plug in at three levels: C (`bui_set_render_sink`), Qt/C++
+(`BUI::QtSink`), Python (`buipy.set_backend`). See INTEGRATION.md.
## Build
```sh
cmake -S . -B build -G "MinGW Makefiles" # or any generator
cmake --build build
-ctest --test-dir build # core tests
-cmake -S . -B build-ui -DBUI_BUILD_UI=ON # work on the ui module
-cmake --build build-ui --target bui_ui
+ctest --test-dir build # core tests + buipy tests
+cmake -S . -B build-ui -DBUI_BUILD_UI=ON -DBUI_BUILD_EXAMPLES=ON
+cmake --build build-ui # + widget toolkit (bui_ui)
```
+Options: `BUI_BUILD_PYTHON_BINDINGS` (ON; auto-skips without Python dev
+files), `BUI_BUILD_QT_BACKEND` (OFF; needs Qt5/Qt6 Widgets),
+`BUI_BUILD_EXAMPLES`, `BUI_BUILD_TESTS`.
+
+Windows note: the toolchain must resolve MinGW runtime DLLs from
+`/c/msys64/ucrt64/bin` **before** `/mingw64/bin` or other vendors' paths
+(cc1.exe loads zlib1/gmp from PATH). If builds fail silently, prepend the
+ucrt64 dir: `export PATH="/c/msys64/ucrt64/bin:$PATH"`.
+
## Decoupling inventory (what was cut, what remains)
Cut entirely (Blender application logic): scene/mesh/node/depsgraph/modifiers,
-animrig, asset system, sequencer, render, Python, file I/O (BLO), eyedroppers,
-app-specific UI templates, window manager backends (GHOST), operator system.
+animrig (only the DNA structs + a minimal `animrig::Slot` wrapper remain),
+asset system, sequencer, render, Python-in-Blender, file I/O (BLO),
+eyedroppers, app-specific UI templates, window manager backends (GHOST),
+operator system.
-Remaining seams before `bui_ui` compiles end-to-end (call-site counts measured
-from the copied sources):
+Remaining seams before a *hosted* toolkit (real widgets on screen) works —
+call-site counts measured from the copied sources:
| Seam | Touchpoints | Notes |
|---|---|---|
@@ -70,9 +101,11 @@ from the copied sources):
| IMB (images/icons) | ~23 | Icon texture registration hook |
| RNA (properties) | ~16 entry points | Opaque `PropertyRNA` + accessor vtable |
-Plus link-stage items: BLI C++ utilities used by `views/*.cc` (Vector/Map/Set —
-header-only templates already vendored under `core/include`),
-`DNA_*` runtime (only needed if persistence is wanted), icon/font assets.
+These seams block *widget-tree hosting* (creating blocks/buttons driven by
+events), not compilation: all five libraries — `bui_core`, `bui_gpu`,
+`bui_compat`, `bui_api`, `bui_ui` — build and link cleanly today, and the
+render pipeline is exercisable end-to-end through the sink (see
+`examples/`).
## Porting notes
@@ -80,4 +113,8 @@ header-only templates already vendored under `core/include`),
mechanical de-C++ pass is intentionally boring so future syncs stay easy.
- `core/include/fmt/*` is a declaration-level stand-in for the external {fmt}
library; swap for real {fmt} if you need formatted strings.
-- `MEM_guardedalloc.h` is a plain-malloc shim; leak tracking is out of scope.
+- `MEM_guardedalloc.h` is a plain-malloc shim with the upstream C++ template
+ surface (`MEM_new<T>`, `MEM_new_zeroed<T>`, `MEM_new_array_uninitialized<T>`,
+ `MEM_delete<T>`, `MEM_SAFE_DELETE`).
+- `GPU_batch.hh` carries a layout contract: the first four members of
+ `blender::gpu::VertBuf` must match `GPUVertBufInternal` in `gpu_null.c`.
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 6a43ef8..5596087 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -14,6 +14,8 @@ project(bui LANGUAGES C CXX VERSION 0.1.0)
option(BUI_BUILD_TESTS "Build BUI test executables" ON)
option(BUI_BUILD_EXAMPLES "Build BUI example applications" OFF)
option(BUI_WARNINGS_AS_ERRORS "Treat compiler warnings as errors" OFF)
+option(BUI_BUILD_PYTHON_BINDINGS "Build the buipy CPython bindings (needs Python3 dev files)" ON)
+option(BUI_BUILD_QT_BACKEND "Build the Qt/QPainter backend (needs Qt5/Qt6 with Widgets)" OFF)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
@@ -21,7 +23,7 @@ endif()
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
-set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(MSVC)
@@ -38,15 +40,25 @@ set(BUI_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
# Dependency order matters: each layer may only use layers above it in this list.
add_subdirectory(core) # pure C foundation
add_subdirectory(types) # BUI-owned shared data types
-add_subdirectory(gpu) # draw abstraction (null backend for now)
+add_subdirectory(gpu) # draw abstraction (null backend + sink dispatch)
add_subdirectory(compat) # seam headers/stubs replacing Blender-app APIs
add_subdirectory(ui) # the widget toolkit
+add_subdirectory(kit) # Blender UI runtime in C (widgets, input, damage rendering)
+add_subdirectory(api) # stable C ABI for hosts & bindings
if(BUI_BUILD_TESTS)
enable_testing()
add_subdirectory(core/tests)
endif()
+if(BUI_BUILD_PYTHON_BINDINGS)
+ add_subdirectory(bindings/python)
+endif()
+
+if(BUI_BUILD_QT_BACKEND)
+ add_subdirectory(backends/qt)
+endif()
+
if(BUI_BUILD_EXAMPLES)
add_subdirectory(examples)
endif()
diff --git a/INTEGRATION.md b/INTEGRATION.md
new file mode 100644
index 0000000..5ca7334
--- /dev/null
+++ b/INTEGRATION.md
@@ -0,0 +1,234 @@
+# Host integration guide
+
+> **High-level syntax layers (recommended):** you may not need any of the
+> plumbing below. `bindings/python` ships two application-facing APIs that
+> render through BUI — **Qt syntax** (`bui.qtsyntax`) and **tkinter syntax**
+> (`bui.tksyntax`). See "High-level syntax layers" at the bottom, and
+> "Testing the Python bindings" for the one setup step they need.
+
+BUI draws; you present. The toolkit never opens a window, creates a GL
+context, or picks a UI framework. Instead, every draw call funnels through the
+**GPU seam** into a render **sink** you install. This document covers the
+three supported paths: plain C/C++, Qt (C++), and Python (PySide6/PyQt6 or
+headless).
+
+```
+ ┌────────────────────────┐
+ your host │ sink (BuiGpuSink) │
+ ┌────────────────┐ │ triangles() │ renderer
+ │ ui toolkit ────┼─┼─▶ lines() ────────────┼──▶ Qt QPainter /
+ │ (bui_ui) │ │ points() │ PySide6 QPainter /
+ │ gpu seam │ │ text() scissor() │ OpenGL / SVG / console
+ │ (gpu_null.c) │ │ begin/end_frame() │ — anything
+ └────────────────┘ └────────────────────────┘
+```
+
+## 1. Plain C / C++
+
+```c
+#include "bui_c_api.h"
+
+static void my_triangles(void *user, const float (*coords)[2],
+ const float (*colors)[4], int count) {
+ /* rasterize / record / forward `count` vertices */
+}
+
+BuiGpuSink sink = {0};
+sink.user = my_renderer_state;
+sink.triangles = my_triangles;
+/* sink.lines, sink.points, sink.text, sink.scissor,
+ sink.begin_frame, sink.end_frame are optional */
+bui_set_render_sink(&sink);
+
+bui_set_viewport(1280, 720); /* pixels */
+/* ... drive BUI drawing ... */
+bui_set_render_sink(NULL); /* restore the discarding backend */
+```
+
+The coordinate contract: 2D positions transformed by the current model matrix
+(identity matrices → pixel coordinates), colors as RGBA floats 0..1.
+
+A complete minimal example is `examples/svg_demo.c` — it installs an SVG
+recorder and draws through the immediate-mode seam:
+
+```sh
+cmake --build build --target bui_svg_demo
+./build/examples/bui_svg_demo out.svg
+```
+
+## 2. Qt (C++)
+
+Enable the backend and link it:
+
+```sh
+cmake -S . -B build-qt -DBUI_BUILD_QT_BACKEND=ON # needs Qt5/Qt6 Widgets
+cmake --build build-qt
+```
+
+```cpp
+#include "BuiWidget.h" // backends/qt
+
+BUI::BuiWidget *canvas = new BUI::BuiWidget(window);
+canvas->render_func = [&](int w, int h) {
+ // BUI draw calls; primitives land on QPainter automatically.
+};
+```
+
+`BUI::BuiWidget` handles paint/resize/mouse plumbing; `BUI::QtSink` maps BUI
+primitives onto `QPainter` (per-vertex colors reduce to the first vertex color
+per primitive, which matches how the toolkit draws shapes). The backend does
+not require moc or OpenGL.
+
+## 3. Python
+
+The `buipy` extension (built by default when Python development files are
+found) exposes the same sink protocol to Python — no third-party packages.
+
+### Headless / CI — SVG output
+
+```python
+import buipy
+from bui.svg import SvgSink
+
+sink = SvgSink(640, 480)
+buipy.set_backend(sink)
+buipy.demo_scene(640, 480) # or your own draw calls
+sink.save("frame.svg")
+```
+
+### PySide6 / PyQt6 window
+
+```python
+import sys
+from PySide6.QtWidgets import QApplication # PyQt6 works identically
+import buipy
+from bui.qt import BuiCanvas
+
+app = QApplication(sys.argv)
+canvas = BuiCanvas() # default renders the demo scene
+# canvas.render_func = lambda: <BUI draw calls>
+canvas.resize(800, 600)
+canvas.show()
+sys.exit(app.exec())
+```
+
+`BuiCanvas` installs a `QtPainterBackend` for each paint pass, so the toolkit
+renders through the same QPainter path as the C++ backend — pure Python, no
+shiboken build.
+
+## High-level syntax layers
+
+Two facades speak the syntax of established toolkits on top of the C kit
+(`kit/`, exposed to Python as `buipy.KitNode` / `buipy.KitContext`): widgets
+are kit nodes, layouts are the kit's C geometry managers, and windows come
+from `bui.host` (native Win32 on Windows, Tk elsewhere or with
+`BUI_HOST=tk`):
+
+### Qt syntax — `bui.qtsyntax`
+
+```python
+from bui.qtsyntax import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout
+
+app = QApplication([])
+window = QWidget()
+window.setWindowTitle("BUI — Qt syntax")
+layout = QVBoxLayout()
+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()
+```
+
+Supported surface: see [SYNTAX_COVERAGE.md](SYNTAX_COVERAGE.md) for the
+exact, honest list (the daily-driver core: windows, labels, buttons,
+checkboxes, box layouts, signals, a `setStyleSheet` subset). Anything not
+yet implemented raises a clear error naming that file. The window host is
+chosen at runtime: **PySide6/PyQt6** if installed, otherwise a stdlib
+tkinter window — the same code runs either way, always rendered by BUI.
+
+### tkinter syntax — `bui.tksyntax`
+
+```python
+from bui.tksyntax import Tk, Label, Button, Checkbutton
+
+root = Tk()
+root.title("BUI — tkinter syntax")
+root.geometry("420x260")
+status = Label(root, text="")
+status.pack()
+Button(root, text="Click me", command=lambda: status.setText("Clicked!")).pack(pady=4)
+Checkbutton(root, text="Enable feature").pack()
+root.mainloop()
+```
+
+Runs on the Python standard library alone. `pack(side=, padx=, pady=)`,
+`place(x=, y=)`, `config(**kw)`, `invoke()` are supported; widgets render onto
+a tk.Canvas **via the BUI sink**, so swapping the host renderer (Qt, SVG,
+custom) changes nothing in app code.
+
+## Testing the Python bindings
+
+`buipy` is a **compiled extension** — it lives in the CMake build tree and is
+built for one specific interpreter. `ModuleNotFoundError: No module named
+'buipy'` means Python cannot find (or cannot load) that file. Three ways to
+fix, fastest first:
+
+**1. Nothing to install (auto-locate).** `import bui` finds the extension in
+`build*/bindings/python` automatically. Just build and run:
+
+```sh
+cmake -S . -B build -G "MinGW Makefiles"
+cmake --build build --target buipy
+python examples/python_demo.py # needs the interpreter CMake used
+```
+
+**2. Match the interpreter.** The extension only loads in the interpreter it
+was built for (CMake found Python 3.14 on this machine →
+`buipy.cp314-win_amd64.pyd`). Check which one CMake picked and run that one:
+
+```sh
+grep Python3_EXECUTABLE build/CMakeCache.txt
+C:/Users/ppmpr/AppData/Local/Programs/Python/Python314/python.exe examples/python_demo.py
+```
+
+To target a different interpreter, point CMake at it explicitly:
+
+```sh
+cmake -S . -B build-py312 -DPython3_EXECUTABLE="C:/Path/Python312/python.exe"
+cmake --build build-py312 --target buipy
+```
+
+**3. pip install (no PYTHONPATH ever again):**
+
+```sh
+cmake --build build --target buipy
+python -m pip install bindings/python # stages bui/ + the .pyd into site-packages
+python -c "import bui; print(bui.version())"
+```
+
+Sanity check either way:
+
+```sh
+python -c "import bui; print(bui.version())" # -> 0.1.0
+python -m pytest bindings/python/tests # or: ctest --test-dir build
+```
+
+## Wire format reference
+
+| Callback | Payload |
+|---|---|
+| `begin_frame(w, h)` | Start of a frame batch; viewport in pixels |
+| `scissor(x, y, w, h)` | Clip rect; `w`/`h` ≤ 0 clears clipping |
+| `triangles(coords, colors, n)` | Non-indexed triangles, 3 vertices each |
+| `lines(coords, colors, n)` | Line list, endpoints in pairs |
+| `points(coords, colors, n, size)` | Points at `size` pixels |
+| `text(x, y, text, size, rgba)` | UTF-8 text run at baseline |
+| `end_frame()` | End of frame batch |
+
+All coordinates are 2D floats; colors RGBA floats 0..1. Callbacks may be
+invoked with or without the GIL held — the Python bindings handle this
+internally.
diff --git a/README.md b/README.md
index 21aa83e..6b83887 100644
--- a/README.md
+++ b/README.md
@@ -1,26 +1,229 @@
# BUI
A modular UI toolkit extracted from the Blender project. Core in C, widgets in
-C++, no Blender application logic — just the interface machinery.
+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, dependency
-rules, and the exact decoupling status.
+See [ARCHITECTURE.md](ARCHITECTURE.md) for the module layout and dependency
+rules, and [INTEGRATION.md](INTEGRATION.md) for host-application guides.
## Quick start
```sh
cmake -S . -B build
cmake --build build
-ctest --test-dir build # core foundation tests pass
+ctest --test-dir build # core + Python binding tests
+```
+
+With the full widget toolkit and examples:
+
+```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
```
## Modules
-- `core/` – pure C11 foundation (containers, memory, math, strings)
-- `types/` – shared data-type shapes (DNA structs, verbatim)
-- `gpu/` – drawing abstraction + null backend (plug your renderer here)
-- `compat/` – seam headers replacing Blender-app APIs (RNA/WM/ED/BLF/IMB/CTX)
-- `ui/` – the widget toolkit (blocks/buttons, layout, handlers, views)
+- `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.
+
+```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()
+```
+
+## 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.
+
+```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()
+```
+
+| | |
+|---|---|
+| 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:
+
+```python
+# Qt syntax (examples/qt_syntax_demo.py)
+from bui.qtsyntax import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout
+app = QApplication([])
+window = QWidget()
+layout = QVBoxLayout()
+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()
+
+# 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()
+```
+
+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`.
+
+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).
+
+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
+
+```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
+```
+
+See [INTEGRATION.md](INTEGRATION.md) for installing/testing `buipy`.
+
+## Qt quick start (C++)
+
+```cmake
+set(BUI_BUILD_QT_BACKEND ON) # requires Qt5/Qt6 Widgets
+add_subdirectory(BUI)
+target_link_libraries(myapp PRIVATE bui::qt)
+```
+
+```cpp
+BUI::BuiWidget canvas(parent);
+canvas.render_func = [&](int w, int h) { /* BUI draw calls */ };
+```
+
+The pure-Python path needs no C++ build at all — see
+`bindings/python/bui/qt.py`.
## License
diff --git a/SYNTAX_COVERAGE.md b/SYNTAX_COVERAGE.md
new file mode 100644
index 0000000..0431731
--- /dev/null
+++ b/SYNTAX_COVERAGE.md
@@ -0,0 +1,110 @@
+# Syntax layer coverage
+
+`bui.qtsyntax` and `bui.tksyntax` are thin Python facades over the C kit
+(`kit/`, Python: `buipy.KitNode` / `buipy.KitContext`). They own no layout,
+drawing or input code:
+
+| Concern | Where it runs |
+|---|---|
+| Widgets | one kit node each (`label`, `button`, `number`, `slider`, `text`, `textarea`, `list`, `tree`, `tabs`, `canvas`, …) |
+| `pack` / `grid` / `place`, Qt box / grid / form layouts | kit C geometry managers (`kit/intern/kit_frame.c`, a port of Tk's packer and gridder) |
+| `Canvas` items, `QPainter` | kit canvas display list (rect, round rect, oval, line, polygon, arc, text, image) |
+| Input, hover, focus, popups, menus, undo | `BKContext` in C |
+| Windows, timers | `bui.host` → native Win32 window (`kit/intern/kit_window.c`) or Tk fallback |
+| Signals, variables, traces, item/tag models | Python (small) |
+
+Anything not listed raises `AttributeError` — nothing fails silently.
+
+## Qt syntax (`bui.qtsyntax`)
+
+| Class | Members |
+|---|---|
+| `QApplication` | `exec/exec_`, `quit/exit`, `processEvents`, `instance` |
+| `QWidget` (+ `QMainWindow`, `QDialog`, `QFrame`) | `show/hide/close/setVisible/isVisible`, `resize/move/setGeometry/setFixedSize/Width/Height/setMinimumWidth/Height`, `width/height/x/y/pos/size/geometry/rect/sizeHint`, `setLayout/layout/setParent/parentWidget/children/window`, `setEnabled/isEnabled`, `setToolTip`, `setStyleSheet`¹, `setFont`, `setSizePolicy`, `setWindowTitle`, `setMenuBar`, `update/repaint`; overridable `paintEvent`, `mousePress/Release/Move/DoubleClickEvent`, `keyPressEvent`, `wheelEvent`, `enter/leaveEvent`, `closeEvent`; `QMainWindow.setCentralWidget/menuBar/statusBar`; `QDialog.exec/accept/reject` |
+| Layouts | `QVBoxLayout/QHBoxLayout`: `addWidget(stretch)/addLayout/insertWidget/addStretch/addSpacing/removeWidget/setStretch/setSpacing/setContentsMargins/count/itemAt`; `QGridLayout`: `addWidget/addLayout(r, c, rowspan, colspan, alignment)`, `setRow/ColumnStretch`, `rowCount/columnCount`; `QFormLayout.addRow`; `QStackedLayout`. Qt size policies: line edits, sliders, combos, progress bars expand horizontally; text edits, lists, trees, tabs, custom-painted widgets vertically |
+| `QLabel` | `setText/text`, `setAlignment`, `setPixmap` |
+| `QPushButton` / `QToolButton` | `clicked/pressed/released`, `click`, `setText/text`, `setIcon` |
+| `QCheckBox` | `isChecked/setChecked/checkState/setCheckState/toggle`, `toggled/stateChanged/clicked` |
+| `QRadioButton`, `QButtonGroup` | auto-exclusive among siblings or within a group; `toggled/clicked`, `buttonClicked/idClicked/checkedButton` |
+| `QLineEdit` | `text/setText/clear/setPlaceholderText/setReadOnly`, `textChanged/textEdited/returnPressed/editingFinished` |
+| `QTextEdit` / `QPlainTextEdit` | `toPlainText/setPlainText/setText/append/insertPlainText/clear/setReadOnly`, `textChanged` |
+| `QSlider` / `QDial` / `QSpinBox` / `QDoubleSpinBox` | `setRange/setMinimum/setMaximum/setValue/value/setSingleStep`, `setSuffix/setPrefix/setDecimals/stepUp/stepDown`, `valueChanged/sliderMoved/rangeChanged` |
+| `QProgressBar` | `setRange/setValue/value/setFormat/setTextVisible/reset`, `valueChanged` |
+| `QComboBox` | `addItem(s)/insertItem/removeItem/clear/count/itemText/itemData/currentIndex/setCurrentIndex/currentText/setCurrentText/currentData/findText`, `currentIndexChanged/currentTextChanged/activated` |
+| `QListWidget` / `QListWidgetItem` | `addItem(s)/insertItem/takeItem/clear/count/item/currentRow/setCurrentRow/currentItem/row/selectedItems`, `currentRowChanged/itemClicked/itemDoubleClicked/itemSelectionChanged` |
+| `QTreeWidget` / `QTreeWidgetItem` | `setHeaderLabels` (column headers), `addTopLevelItem(s)/topLevelItem/topLevelItemCount/clear/currentItem/setCurrentItem/expandAll/collapseAll`; items: `text/setText(col)/addChild/child/childCount/parent/setExpanded/isExpanded` |
+| `QTableWidget` / `QTableWidgetItem` | `setRowCount/setColumnCount/setHorizontalHeaderLabels/setItem/item/currentRow/setCurrentCell/clear`, `cellClicked/cellDoubleClicked/currentCellChanged` |
+| `QTabWidget`, `QGroupBox`, `QScrollArea`, `QStatusBar` | `addTab/currentIndex/setCurrentIndex/widget/tabText/setTabText`; `setTitle/title`; `setWidget`; `showMessage/clearMessage` |
+| `QMenuBar` / `QMenu` / `QAction` | `addMenu/addAction(text, slot, shortcut)/addSeparator/popup/exec`; actions: `triggered/toggled`, checkable, shortcuts (shown in Blender menus) |
+| `QPainter` | `setPen/setBrush/setFont/setOpacity/save/restore/translate`, `fillRect/drawRect/drawRoundedRect/drawEllipse/drawLine/drawPolyline/drawPolygon/drawPoint/drawArc/drawPie/drawText/drawPixmap` |
+| `Signal` (`pyqtSignal`, `Signal_`) | class-level signals; `connect/disconnect/emit`; slots taking fewer arguments are called with fewer |
+| `QTimer`, `QPropertyAnimation`, `QEasingCurve` | `start/stop/singleShot/setInterval/setSingleShot`, `timeout`; animation at 120 Hz with easing, `finished/valueChanged` |
+| Value types | `QColor`, `QPen`, `QBrush`, `QFont`, `QPoint`, `QSize`, `QRect`, `QPixmap`/`QImage`, `QIcon`, `QMargins`, `QSizePolicy`, `Qt` constants, events (`QMouseEvent`, `QKeyEvent`, `QWheelEvent`, `QPaintEvent`, `QCloseEvent`) |
+| `QMessageBox` / `QFileDialog` | non-blocking stubs / stdlib file dialogs |
+
+¹ `setStyleSheet`: `color`, `background(-color)` on containers, `font-weight: bold`.
+
+## tkinter syntax (`bui.tksyntax`)
+
+`bui.tksyntax` is a package laid out like `tkinter` itself: the package
+(`Tk`, widgets, variables, `mainloop` ...) plus `ttk`, `messagebox`,
+`filedialog`, `simpledialog`, `colorchooser`, `commondialog`, `dialog`,
+`font`, `scrolledtext` and `constants`. Existing programs run unchanged:
+
+```
+python -m bui.tksyntax my_tk_app.py # or call bui.tksyntax.install() first
+```
+
+**Coverage:** every public member of every tkinter / ttk widget class,
+`Tk`, `Toplevel`, the variables, `Event`, `PhotoImage` and `BitmapImage`
+exists (7846 of 7846 names, measured against the stdlib), and
+`tests/test_tk_compat.py` runs nine real tkinter programs (calculator,
+to-do list with scrollbar, validated form, text editor with menus, sortable
+table, canvas, scrollable frame, notebook/paned window/option menu, events and
+variables) on both the stdlib and BUI and requires identical results.
+
+**Look:** always Blender's theme. Options that only change Tk's look
+(`relief`, `borderwidth`, `highlightthickness`, `activebackground`, `ttk.Style`
+settings ...) are accepted and returned by `cget`; `bg` colours frames and
+canvases, `fg` colours text, `font` sets size and bold, `cursor` sets the
+pointer.
+
+**Behaviour follows Tk** (checked against the stdlib): `textvariable`
+overrides `text` (also in `cget`), `Scale` commands and
+`<<TreeviewSelect>>` run when idle, `validatecommand` sees programmatic
+`insert`/`delete`, generated key events go to the focus widget, bindings run
+per bindtag (widget, class, toplevel, `all`) and stop on `"break"`, a
+`Notebook` requests its largest page, menus keep Tk's tearoff index 0,
+`Text` keeps the trailing newline (`"end-1c"`), `edit_undo` is a no-op while
+`undo` is off, ttk `item()` converts integers.
+
+| Area | What runs where |
+|---|---|
+| Geometry | `pack` / `grid` / `place` (all options, `in_`, `before`/`after`, propagation, `grid_remove`, `*_info`, `*_slaves`, `grid_bbox/location/size`): Tk's packer and gridder ported to C |
+| Scrolling | `xview`/`yview`/`*_moveto`/`*_scroll` and `x/yscrollcommand` for Listbox, Text, Treeview, Canvas (`scrollregion`, `confine`, increments, `scan_*`): the kit's view protocol reports view changes after input and layout; `Scrollbar` is a Blender scroller following Tk's scrollbar protocol |
+| Selection | `Listbox` `selectmode` browse / single / multiple / extended, `Treeview` extended / browse / none (Ctrl/Shift clicks in C) |
+| Events | `bind` / `bind_all` / `bind_class` / `bindtags` / `event_add` / `event_generate` with modifiers, `Double-`, `<Button-1..3>`, `<B1-Motion>`, `<KeyPress>` / `<KeyRelease>`, `<MouseWheel>` (Button-4/5 on X11), `<Enter>` / `<Leave>`, `<Configure>`, `<Map>`, `<Destroy>`, `<FocusIn/Out>`, virtual events; `Event` has Tk's fields |
+| Canvas | all item types (incl. `window` for scrollable frames, smoothed lines, arrows), tags and tag expressions, `find_*` / `addtag_*`, `tag_bind` with `current` and `<Enter>`/`<Leave>` per item, shape-accurate hit tests, `move` / `moveto` / `scale` / `coords`, text-item editing |
+| Text | full index grammar (`line.char`, `end`, marks, `tag.first`, `@x,y`, `+N chars/lines`, `linestart`, `wordend` ...), tags with foreground/background and priorities, `tag_bind`, marks with gravity, `search` (regexp, backwards, count), `dump`, `count`, undo stack, `<<Modified>>`, peers |
+| Windows | native window: `geometry` (size and position), `attributes` (`-topmost`, `-alpha`, `-fullscreen`, `-disabled`), `resizable`, `minsize` / `maxsize`, `overrideredirect`, `state` / `iconify` / `withdraw`, `transient`, `protocol`, `grab_set` (disables other windows), clipboard |
+| Dialogs | `messagebox` and `simpledialog` (`Dialog`, `SimpleDialog`, `ask*`) as Blender-styled modal windows, `colorchooser` with Blender's color picker, `filedialog` with the OS dialogs |
+| Images | `PhotoImage` (PNG and PPM/PGM read and written in Python, GIF through Tk; `put`/`get`/`copy`/`zoom`/`subsample`/`copy_replace`/`data`/`write`), `BitmapImage` (XBM) |
+
+Not supported, because nothing in the kit corresponds: `send` (raises like
+Windows Tk), embedded windows and images inside `Text` (accepted and listed,
+but not drawn), Tcl itself (`root.tk.call` handles a few common commands such
+as `tk scaling` and `wm`).
+
+## Not implemented
+
+- **Qt:** QSS selectors/pseudo-states, `QGraphicsScene`, model/view
+ (`QAbstractItemModel`), rich text, `QThread`, OpenGL widgets.
+
+## Extending
+
+Add the member to the facade class in `bindings/python/bui/qtsyntax.py` or
+`bindings/python/bui/tksyntax/`, mapping it onto kit node properties
+(`set/get`), geometry (`geom`), or the canvas/text-area calls. New drawing or
+interaction belongs in the C kit (`kit/intern/`). Add a test in
+`bindings/python/tests/` (for tkinter, a program in `test_tk_compat.py` that
+must behave like the stdlib).
diff --git a/api/CMakeLists.txt b/api/CMakeLists.txt
new file mode 100644
index 0000000..942e609
--- /dev/null
+++ b/api/CMakeLists.txt
@@ -0,0 +1,6 @@
+# BUI stable C API — a thin facade for hosts and language bindings.
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+add_library(bui_api STATIC bui_c_api.c)
+target_include_directories(bui_api PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
+target_link_libraries(bui_api PUBLIC bui_gpu)
diff --git a/api/bui_c_api.c b/api/bui_c_api.c
new file mode 100644
index 0000000..8cbce6c
--- /dev/null
+++ b/api/bui_c_api.c
@@ -0,0 +1,42 @@
+/* BUI stable C API implementation: thin forwarders into the toolkit.
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#include "bui_c_api.h"
+
+#include "GPU_backend_sink.h"
+
+#define BUI_VERSION_MAJOR 0
+#define BUI_VERSION_MINOR 1
+#define BUI_VERSION_PATCH 0
+
+void bui_get_version(int *r_major, int *r_minor, int *r_patch)
+{
+ if (r_major) {
+ *r_major = BUI_VERSION_MAJOR;
+ }
+ if (r_minor) {
+ *r_minor = BUI_VERSION_MINOR;
+ }
+ if (r_patch) {
+ *r_patch = BUI_VERSION_PATCH;
+ }
+}
+
+const char *bui_version_string(void)
+{
+ return "BUI 0.1.0";
+}
+
+void bui_set_render_sink(const BuiGpuSink *sink)
+{
+ GPU_backend_sink_set(sink);
+}
+
+const BuiGpuSink *bui_get_render_sink(void)
+{
+ return GPU_backend_sink_get();
+}
+
+void bui_set_viewport(int width, int height)
+{
+ GPU_viewport_size_set(width, height);
+}
diff --git a/api/bui_c_api.h b/api/bui_c_api.h
new file mode 100644
index 0000000..8cd365b
--- /dev/null
+++ b/api/bui_c_api.h
@@ -0,0 +1,33 @@
+/* BUI stable C API.
+ *
+ * A small, ABI-stable facade for hosts that embed BUI without compiling
+ * against the full toolkit headers: version info plus the render-sink
+ * installation that makes the toolkit renderable by any technology
+ * (Qt/QPainter, PySide6, SVG recorder, terminal grid, ...).
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#ifndef __BUI_C_API_H__
+#define __BUI_C_API_H__
+
+#include "GPU_backend_sink.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Library version, mirroring the CMake project() version. */
+void bui_get_version(int *r_major, int *r_minor, int *r_patch);
+const char *bui_version_string(void);
+
+/* Install the primitive sink that receives everything the toolkit draws. */
+void bui_set_render_sink(const BuiGpuSink *sink);
+const BuiGpuSink *bui_get_render_sink(void);
+
+/* Record the viewport the host renders into (pixels). */
+void bui_set_viewport(int width, int height);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BUI_C_API_H__ */
diff --git a/backends/qt/BuiQtSink.cpp b/backends/qt/BuiQtSink.cpp
new file mode 100644
index 0000000..01dbbfb
--- /dev/null
+++ b/backends/qt/BuiQtSink.cpp
@@ -0,0 +1,105 @@
+/* BUI Qt backend implementation.
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#include "BuiQtSink.h"
+
+#include <QPen>
+
+#include <cmath>
+
+namespace BUI {
+
+static QColor to_qcolor(const float rgba[4])
+{
+ auto clamp01 = [](float v) {
+ return static_cast<int>(std::max(0.0f, std::min(1.0f, v)) * 255.0f + 0.5f);
+ };
+ return QColor(clamp01(rgba[0]), clamp01(rgba[1]), clamp01(rgba[2]), clamp01(rgba[3]));
+}
+
+QtSink::QtSink(QPainter *painter, int viewport_w, int viewport_h) : painter_(painter)
+{
+ sink_.user = this;
+ sink_.begin_frame = &QtSink::begin_frame;
+ sink_.scissor = &QtSink::scissor;
+ sink_.triangles = &QtSink::triangles;
+ sink_.lines = &QtSink::lines;
+ sink_.points = &QtSink::points;
+ sink_.text = &QtSink::text;
+ sink_.end_frame = &QtSink::end_frame;
+ begin_frame(this, viewport_w, viewport_h);
+}
+
+void QtSink::begin_frame(void *user, int w, int h)
+{
+ auto *self = static_cast<QtSink *>(user);
+ if (w > 0 && h > 0) {
+ bui_set_viewport(w, h);
+ }
+ self->painter_->save();
+}
+
+void QtSink::scissor(void *user, int x, int y, int w, int h)
+{
+ auto *self = static_cast<QtSink *>(user);
+ if (w > 0 && h > 0) {
+ self->painter_->setClipRect(QRect(x, y, w, h), Qt::IntersectClip);
+ }
+ else {
+ self->painter_->setClipRect(QRect(), Qt::NoClip);
+ }
+}
+
+void QtSink::triangles(void *user, const float (*coords)[2], const float (*colors)[4], int count)
+{
+ auto *self = static_cast<QtSink *>(user);
+ QPainter &p = *self->painter_;
+ p.setPen(Qt::NoPen);
+ for (int i = 0; i < count; i += 3) {
+ p.setBrush(to_qcolor(colors[i]));
+ QPolygonF tri;
+ for (int v = 0; v < 3 && i + v < count; v++) {
+ tri.append(QPointF(coords[i + v][0], coords[i + v][1]));
+ }
+ p.drawPolygon(tri);
+ }
+}
+
+void QtSink::lines(void *user, const float (*coords)[2], const float (*colors)[4], int count)
+{
+ auto *self = static_cast<QtSink *>(user);
+ QPainter &p = *self->painter_;
+ for (int i = 0; i + 1 < count; i += 2) {
+ p.setPen(QPen(to_qcolor(colors[i]), 1));
+ p.drawLine(QPointF(coords[i][0], coords[i][1]), QPointF(coords[i + 1][0], coords[i + 1][1]));
+ }
+}
+
+void QtSink::points(void *user, const float (*coords)[2], const float (*colors)[4], int count, float size)
+{
+ auto *self = static_cast<QtSink *>(user);
+ QPainter &p = *self->painter_;
+ p.setPen(Qt::NoPen);
+ const float d = size > 0.0f ? size : 1.0f;
+ for (int i = 0; i < count; i++) {
+ p.setBrush(to_qcolor(colors[i]));
+ p.drawEllipse(QRectF(coords[i][0] - d / 2.0f, coords[i][1] - d / 2.0f, d, d));
+ }
+}
+
+void QtSink::text(void *user, float x, float y, const char *text, float size, const float rgba[4])
+{
+ auto *self = static_cast<QtSink *>(user);
+ QPainter &p = *self->painter_;
+ p.setPen(QPen(to_qcolor(rgba), 1));
+ QFont f = p.font();
+ f.setPixelSize(size > 0.0f ? int(size) : 12);
+ p.setFont(f);
+ p.drawText(QPointF(x, y), QString::fromUtf8(text));
+}
+
+void QtSink::end_frame(void *user)
+{
+ static_cast<QtSink *>(user)->painter_->restore();
+}
+
+} // namespace BUI
diff --git a/backends/qt/BuiQtSink.h b/backends/qt/BuiQtSink.h
new file mode 100644
index 0000000..e605e5e
--- /dev/null
+++ b/backends/qt/BuiQtSink.h
@@ -0,0 +1,50 @@
+/* BUI Qt backend: forwards BUI primitives to a QPainter.
+ *
+ * Implements the BuiGpuSink contract (gpu/include/GPU_backend_sink.h) on top
+ * of Qt's 2D raster engine, so the toolkit renders inside any Qt window
+ * without OpenGL.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#include <QColor>
+#include <QPainter>
+#include <QPolygonF>
+
+#include "GPU_backend_sink.h"
+
+/* Renders BUI primitives with a QPainter. Install per paint pass:
+ *
+ * QPainter p(widget);
+ * BUI::QtSink sink(&p);
+ * bui_set_render_sink(sink.gpuSink());
+ * ... draw BUI content ...
+ * bui_set_render_sink(nullptr);
+ */
+namespace BUI {
+
+class QtSink {
+ public:
+ explicit QtSink(QPainter *painter, int viewport_w = 0, int viewport_h = 0);
+
+ const BuiGpuSink *gpuSink() const
+ {
+ return &sink_;
+ }
+
+ private:
+ static void begin_frame(void *user, int w, int h);
+ static void scissor(void *user, int x, int y, int w, int h);
+ static void triangles(void *user, const float (*coords)[2], const float (*colors)[4], int count);
+ static void lines(void *user, const float (*coords)[2], const float (*colors)[4], int count);
+ static void points(
+ void *user, const float (*coords)[2], const float (*colors)[4], int count, float size);
+ static void text(
+ void *user, float x, float y, const char *text, float size, const float rgba[4]);
+ static void end_frame(void *user);
+
+ QPainter *painter_;
+ BuiGpuSink sink_;
+};
+
+} // namespace BUI
diff --git a/backends/qt/BuiWidget.cpp b/backends/qt/BuiWidget.cpp
new file mode 100644
index 0000000..45438a8
--- /dev/null
+++ b/backends/qt/BuiWidget.cpp
@@ -0,0 +1,56 @@
+/* BUI Qt widget implementation.
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#include "BuiWidget.h"
+
+#include "bui_c_api.h"
+
+namespace BUI {
+
+BuiWidget::BuiWidget(QWidget *parent) : QWidget(parent)
+{
+ setMouseTracking(true);
+ setMinimumSize(200, 150);
+}
+
+void BuiWidget::paintEvent(QPaintEvent * /*event*/)
+{
+ QPainter painter(this);
+ QtSink sink(&painter, width(), height());
+ bui_set_render_sink(sink.gpuSink());
+ if (render_func) {
+ render_func(width(), height());
+ }
+ bui_set_render_sink(nullptr);
+}
+
+void BuiWidget::resizeEvent(QResizeEvent *event)
+{
+ QWidget::resizeEvent(event);
+ bui_set_viewport(width(), height());
+}
+
+void BuiWidget::mouseMoveEvent(QMouseEvent *event)
+{
+ QWidget::mouseMoveEvent(event);
+ if (mouse_moved) {
+ mouse_moved(event->position().x(), event->position().y());
+ }
+}
+
+void BuiWidget::mousePressEvent(QMouseEvent *event)
+{
+ QWidget::mousePressEvent(event);
+ if (mouse_button) {
+ mouse_button(event->position().x(), event->position().y(), int(event->button()), true);
+ }
+}
+
+void BuiWidget::mouseReleaseEvent(QMouseEvent *event)
+{
+ QWidget::mouseReleaseEvent(event);
+ if (mouse_button) {
+ mouse_button(event->position().x(), event->position().y(), int(event->button()), false);
+ }
+}
+
+} // namespace BUI
diff --git a/backends/qt/BuiWidget.h b/backends/qt/BuiWidget.h
new file mode 100644
index 0000000..0bfde29
--- /dev/null
+++ b/backends/qt/BuiWidget.h
@@ -0,0 +1,37 @@
+/* BUI Qt widget: a QWidget that hosts the BUI toolkit's drawing.
+ *
+ * No Q_OBJECT is used, so no moc pass is required. Connect to Qt signals by
+ * subclassing with Q_OBJECT if you prefer signals over callbacks.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#include <QWidget>
+
+#include <functional>
+
+#include "BuiQtSink.h"
+
+namespace BUI {
+
+class BuiWidget : public QWidget {
+ public:
+ explicit BuiWidget(QWidget *parent = nullptr);
+
+ /** Called during each paint pass with the widget's current size; draw your
+ * BUI content here (or set render_func instead). */
+ std::function<void(int width, int height)> render_func;
+
+ /** Mouse position in widget pixels (useful to hit-test BUI layouts). */
+ std::function<void(int x, int y)> mouse_moved;
+ std::function<void(int x, int y, int button, bool pressed)> mouse_button;
+
+ protected:
+ void paintEvent(QPaintEvent *event) override;
+ void resizeEvent(QResizeEvent *event) override;
+ void mouseMoveEvent(QMouseEvent *event) override;
+ void mousePressEvent(QMouseEvent *event) override;
+ void mouseReleaseEvent(QMouseEvent *event) override;
+};
+
+} // namespace BUI
diff --git a/backends/qt/CMakeLists.txt b/backends/qt/CMakeLists.txt
new file mode 100644
index 0000000..584a8eb
--- /dev/null
+++ b/backends/qt/CMakeLists.txt
@@ -0,0 +1,28 @@
+# BUI Qt backend — renders the toolkit through QPainter.
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+find_package(Qt6 QUIET COMPONENTS Widgets)
+if(Qt6_FOUND)
+ message(STATUS "BUI: Qt backend using Qt6 ${Qt6_VERSION}")
+ set(BUI_QT_TARGET Qt6::Widgets)
+else()
+ find_package(Qt5 QUIET COMPONENTS Widgets)
+ if(Qt5_FOUND)
+ message(STATUS "BUI: Qt backend using Qt5 ${Qt5_VERSION}")
+ set(BUI_QT_TARGET Qt5::Widgets)
+ else()
+ message(FATAL_ERROR "BUI_BUILD_QT_BACKEND is ON but no Qt5/Qt6 with Widgets was found")
+ endif()
+endif()
+
+set(SRC
+ BuiQtSink.h
+ BuiQtSink.cpp
+ BuiWidget.h
+ BuiWidget.cpp
+)
+
+add_library(bui_qt STATIC ${SRC})
+add_library(bui::qt ALIAS bui_qt)
+target_include_directories(bui_qt PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
+target_link_libraries(bui_qt PUBLIC bui_api bui_gpu ${BUI_QT_TARGET})
diff --git a/bindings/python/CMakeLists.txt b/bindings/python/CMakeLists.txt
new file mode 100644
index 0000000..2ad45ca
--- /dev/null
+++ b/bindings/python/CMakeLists.txt
@@ -0,0 +1,79 @@
+# buipy — CPython bindings for BUI (no third-party build dependencies).
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+find_package(Python3 QUIET COMPONENTS Interpreter Development.Module)
+
+if(NOT Python3_FOUND)
+ message(STATUS "BUI: Python3 development files not found — buipy bindings skipped")
+ return()
+endif()
+
+message(STATUS "BUI: building buipy Python bindings for Python ${Python3_VERSION}")
+
+Python3_add_library(buipy MODULE WITH_SOABI src/buipy_module.c src/buipy_kit.c)
+target_link_libraries(buipy PRIVATE bui_api bui_gpu bui_kit)
+
+# Keep the extension next to the pure-Python 'bui' package in the build tree so
+# tests and examples can import both with a single sys.path entry.
+set_target_properties(buipy PROPERTIES
+ LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bindings/python
+ RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bindings/python
+)
+
+if(BUI_BUILD_TESTS)
+ # buipy comes from the build dir; the 'bui' package from this source dir.
+ if(WIN32)
+ set(BUIPY_TEST_PYTHONPATH "${CMAKE_BINARY_DIR}/bindings/python\;${CMAKE_CURRENT_SOURCE_DIR}")
+ else()
+ set(BUIPY_TEST_PYTHONPATH "${CMAKE_BINARY_DIR}/bindings/python:${CMAKE_CURRENT_SOURCE_DIR}")
+ endif()
+ add_test(
+ NAME buipy
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_buipy.py
+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
+ )
+ set_tests_properties(buipy PROPERTIES ENVIRONMENT "PYTHONPATH=${BUIPY_TEST_PYTHONPATH}")
+
+ # High-level syntax layers (Qt syntax + tkinter syntax), rendered headless.
+ add_test(
+ NAME buipy_syntax
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_syntax.py
+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
+ )
+ set_tests_properties(buipy_syntax PROPERTIES ENVIRONMENT "PYTHONPATH=${BUIPY_TEST_PYTHONPATH}")
+
+ # Advanced surface: Text/Treeview/Table/Notebook/Menu/PhotoImage/QPainter.
+ add_test(
+ NAME buipy_advanced
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_advanced.py
+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
+ )
+ set_tests_properties(buipy_advanced PROPERTIES ENVIRONMENT "PYTHONPATH=${BUIPY_TEST_PYTHONPATH}")
+
+ # Native raster pipeline, damage tracking, redraw coalescing, input/layout
+ # regressions (hover vs drag, popup z-order, Toplevel, nested layouts).
+ add_test(
+ NAME buipy_render
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_render.py
+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
+ )
+ set_tests_properties(buipy_render PROPERTIES ENVIRONMENT "PYTHONPATH=${BUIPY_TEST_PYTHONPATH}")
+
+ # bui.components: Blender component library (layout, interactions, popups).
+ add_test(
+ NAME buipy_components
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_components.py
+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
+ )
+ set_tests_properties(buipy_components PROPERTIES ENVIRONMENT "PYTHONPATH=${BUIPY_TEST_PYTHONPATH}")
+ add_test(
+ NAME buipy_tk_compat
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_tk_compat.py
+ )
+ set_tests_properties(buipy_tk_compat PROPERTIES ENVIRONMENT "PYTHONPATH=${BUIPY_TEST_PYTHONPATH}")
+ add_test(
+ NAME buipy_tk_input
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_tk_input.py
+ )
+ set_tests_properties(buipy_tk_input PROPERTIES ENVIRONMENT "PYTHONPATH=${BUIPY_TEST_PYTHONPATH}")
+endif()
diff --git a/bindings/python/bui/__init__.py b/bindings/python/bui/__init__.py
new file mode 100644
index 0000000..893d7db
--- /dev/null
+++ b/bindings/python/bui/__init__.py
@@ -0,0 +1,122 @@
+"""bui — Python companion package for the BUI UI toolkit.
+
+High-level syntax layers (the recommended way to write apps):
+
+* :mod:`bui.qtsyntax` — Qt syntax: ``QApplication``, ``QWidget``,
+ ``QPushButton``, ``QVBoxLayout``, ``clicked.connect(...)``.
+* :mod:`bui.tksyntax` — tkinter syntax: ``Tk()``, ``Button(command=...)``,
+ ``pack()``, ``mainloop()``.
+
+Lower-level pieces:
+
+* :class:`bui.svg.SvgSink` — record a frame to an SVG file (no dependencies).
+* :class:`bui.qt.BuiCanvas` — embed BUI in a real PySide6/PyQt6 widget.
+
+Everything renders through the BUI engine (buipy, a small extension module).
+If ``import buipy`` fails, this package looks for the compiled extension in
+the CMake build tree automatically; you can point it at a build dir with the
+``BUIPY_BUILD_DIR`` environment variable.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import glob
+import os
+import sys
+
+class Backend:
+ """Protocol BUI calls with everything the toolkit draws.
+
+ All coordinates are 2D pixels. Colors are RGBA floats in 0..1.
+ Override only what you need; unimplemented methods are skipped.
+ """
+
+ def begin_frame(self, width: int, height: int) -> None:
+ """Called before a batch of primitives."""
+
+ def scissor(self, x: int, y: int, w: int, h: int) -> None:
+ """Clip rect; ``w``/``h`` <= 0 removes the clip."""
+
+ def triangles(self, coords, colors) -> None:
+ """Non-indexed triangles: ``coords``/``colors`` are per vertex."""
+
+ def lines(self, coords, colors) -> None:
+ """Line list: vertices come in endpoint pairs."""
+
+ def points(self, coords, colors, size) -> None:
+ """Points at ``size`` pixels."""
+
+ def text(self, x, y, text, size, color) -> None:
+ """Text run at baseline position."""
+
+ def end_frame(self) -> None:
+ """Called after a batch of primitives."""
+
+
+def _ensure_buipy_importable() -> None:
+ """Make `import buipy` work when running from the source tree.
+
+ The compiled extension lives in the CMake build tree
+ (build*/bindings/python). Locating it here means apps can simply
+ `import bui` — no PYTHONPATH juggling. Set BUIPY_BUILD_DIR to override.
+ """
+ try:
+ import buipy # noqa: F401
+
+ return
+ except ImportError:
+ pass
+
+ # __file__ = <repo>/bindings/python/bui/__init__.py → repo root is up 3 dirs.
+ pkg_dir = os.path.dirname(os.path.abspath(__file__))
+ repo = os.path.abspath(os.path.join(pkg_dir, "..", "..", ".."))
+ import importlib.machinery
+
+ # Only extensions built for THIS interpreter (e.g. .cp314-win_amd64.pyd).
+ suffixes = importlib.machinery.EXTENSION_SUFFIXES
+
+ def _ext_in(d):
+ found = []
+ for suf in suffixes:
+ found += glob.glob(os.path.join(d, "buipy" + suf))
+ return found
+
+ override = os.environ.get("BUIPY_BUILD_DIR", "")
+ if override and _ext_in(override):
+ best_dir = override
+ else:
+ # Several build trees may exist (build, build-ui, ...): use the most
+ # recently built extension so a stale tree never shadows a fresh one.
+ best_dir, best_mtime = None, -1.0
+ for cand in glob.glob(os.path.join(repo, "build*", "bindings", "python")):
+ for ext in _ext_in(cand):
+ mtime = os.path.getmtime(ext)
+ if mtime > best_mtime:
+ best_dir, best_mtime = cand, mtime
+ if best_dir and best_dir not in sys.path:
+ sys.path.insert(0, best_dir)
+
+
+_ensure_buipy_importable()
+
+try:
+ import buipy # noqa: F401
+except ImportError as _e: # pragma: no cover
+ raise ImportError(
+ "buipy (the BUI engine extension) was not found. Build it with CMake "
+ "(cmake --build build --target buipy) and/or set BUIPY_BUILD_DIR to the "
+ "directory containing the built buipy.pyd. Note: the extension must be "
+ "built for the Python interpreter you are running."
+ ) from _e
+
+
+def version() -> str:
+ """BUI library version as a string."""
+ return buipy.version()
+
+
+def set_backend(backend) -> None:
+ """Route BUI drawing into ``backend`` (or None to disable rendering)."""
+ buipy.set_backend(backend)
diff --git a/bindings/python/bui/__pycache__/__init__.cpython-312.pyc b/bindings/python/bui/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000..0399b9b
Binary files /dev/null and b/bindings/python/bui/__pycache__/__init__.cpython-312.pyc differ
diff --git a/bindings/python/bui/__pycache__/__init__.cpython-314.pyc b/bindings/python/bui/__pycache__/__init__.cpython-314.pyc
new file mode 100644
index 0000000..c5aab02
Binary files /dev/null and b/bindings/python/bui/__pycache__/__init__.cpython-314.pyc differ
diff --git a/bindings/python/bui/__pycache__/_model.cpython-312.pyc b/bindings/python/bui/__pycache__/_model.cpython-312.pyc
new file mode 100644
index 0000000..702c6e0
Binary files /dev/null and b/bindings/python/bui/__pycache__/_model.cpython-312.pyc differ
diff --git a/bindings/python/bui/__pycache__/_model.cpython-314.pyc b/bindings/python/bui/__pycache__/_model.cpython-314.pyc
new file mode 100644
index 0000000..07d0b2b
Binary files /dev/null and b/bindings/python/bui/__pycache__/_model.cpython-314.pyc differ
diff --git a/bindings/python/bui/__pycache__/_realtk.cpython-314.pyc b/bindings/python/bui/__pycache__/_realtk.cpython-314.pyc
new file mode 100644
index 0000000..5ed79f3
Binary files /dev/null and b/bindings/python/bui/__pycache__/_realtk.cpython-314.pyc differ
diff --git a/bindings/python/bui/__pycache__/_surface.cpython-314.pyc b/bindings/python/bui/__pycache__/_surface.cpython-314.pyc
new file mode 100644
index 0000000..1ab37a9
Binary files /dev/null and b/bindings/python/bui/__pycache__/_surface.cpython-314.pyc differ
diff --git a/bindings/python/bui/__pycache__/host.cpython-314.pyc b/bindings/python/bui/__pycache__/host.cpython-314.pyc
new file mode 100644
index 0000000..b664507
Binary files /dev/null and b/bindings/python/bui/__pycache__/host.cpython-314.pyc differ
diff --git a/bindings/python/bui/__pycache__/qt.cpython-312.pyc b/bindings/python/bui/__pycache__/qt.cpython-312.pyc
new file mode 100644
index 0000000..2d6d8dd
Binary files /dev/null and b/bindings/python/bui/__pycache__/qt.cpython-312.pyc differ
diff --git a/bindings/python/bui/__pycache__/qt.cpython-314.pyc b/bindings/python/bui/__pycache__/qt.cpython-314.pyc
new file mode 100644
index 0000000..60053f6
Binary files /dev/null and b/bindings/python/bui/__pycache__/qt.cpython-314.pyc differ
diff --git a/bindings/python/bui/__pycache__/qtsyntax.cpython-312.pyc b/bindings/python/bui/__pycache__/qtsyntax.cpython-312.pyc
new file mode 100644
index 0000000..3b42516
Binary files /dev/null and b/bindings/python/bui/__pycache__/qtsyntax.cpython-312.pyc differ
diff --git a/bindings/python/bui/__pycache__/qtsyntax.cpython-314.pyc b/bindings/python/bui/__pycache__/qtsyntax.cpython-314.pyc
new file mode 100644
index 0000000..f0b2af5
Binary files /dev/null and b/bindings/python/bui/__pycache__/qtsyntax.cpython-314.pyc differ
diff --git a/bindings/python/bui/__pycache__/svg.cpython-312.pyc b/bindings/python/bui/__pycache__/svg.cpython-312.pyc
new file mode 100644
index 0000000..77f676c
Binary files /dev/null and b/bindings/python/bui/__pycache__/svg.cpython-312.pyc differ
diff --git a/bindings/python/bui/__pycache__/svg.cpython-314.pyc b/bindings/python/bui/__pycache__/svg.cpython-314.pyc
new file mode 100644
index 0000000..cf42a3a
Binary files /dev/null and b/bindings/python/bui/__pycache__/svg.cpython-314.pyc differ
diff --git a/bindings/python/bui/__pycache__/theme.cpython-314.pyc b/bindings/python/bui/__pycache__/theme.cpython-314.pyc
new file mode 100644
index 0000000..5e69745
Binary files /dev/null and b/bindings/python/bui/__pycache__/theme.cpython-314.pyc differ
diff --git a/bindings/python/bui/__pycache__/tkbackend.cpython-312.pyc b/bindings/python/bui/__pycache__/tkbackend.cpython-312.pyc
new file mode 100644
index 0000000..1209d6a
Binary files /dev/null and b/bindings/python/bui/__pycache__/tkbackend.cpython-312.pyc differ
diff --git a/bindings/python/bui/__pycache__/tkbackend.cpython-314.pyc b/bindings/python/bui/__pycache__/tkbackend.cpython-314.pyc
new file mode 100644
index 0000000..e010ed7
Binary files /dev/null and b/bindings/python/bui/__pycache__/tkbackend.cpython-314.pyc differ
diff --git a/bindings/python/bui/_realtk.py b/bindings/python/bui/_realtk.py
new file mode 100644
index 0000000..a505146
--- /dev/null
+++ b/bindings/python/bui/_realtk.py
@@ -0,0 +1,40 @@
+"""The stdlib tkinter, pinned.
+
+:func:`bui.tksyntax.install` makes ``import tkinter`` return BUI's tkinter.
+BUI itself still needs the real one in a few places (the Tk fallback window
+host, OS file dialogs, decoding PNG/GIF), so it always goes through here.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import importlib
+import sys
+
+_pinned: dict = {}
+
+_NAMES = ("tkinter", "tkinter.font", "tkinter.filedialog", "tkinter.colorchooser")
+
+
+def pin() -> None:
+ """Import and remember the real modules (before anything aliases them)."""
+ for name in _NAMES:
+ if name not in _pinned:
+ mod = sys.modules.get(name)
+ if mod is None or getattr(mod, "__bui__", False):
+ saved = {n: sys.modules.pop(n) for n in list(sys.modules)
+ if n == "tkinter" or n.startswith("tkinter.")}
+ try:
+ mod = importlib.import_module(name)
+ finally:
+ for n, m in saved.items():
+ sys.modules[n] = m
+ _pinned[name] = mod
+
+
+def module(name: str = "tkinter"):
+ """The real ``tkinter`` (or ``tkinter.font`` ...)."""
+ if name not in _pinned:
+ pin()
+ return _pinned[name]
diff --git a/bindings/python/bui/_surface.py b/bindings/python/bui/_surface.py
new file mode 100644
index 0000000..4c90023
--- /dev/null
+++ b/bindings/python/bui/_surface.py
@@ -0,0 +1,309 @@
+"""TkSurface — hosts one BUI widget tree in a real tk window.
+
+This is the fast path behind ``bui.tksyntax`` and the tk fallback of
+``bui.qtsyntax``. It renders the way Blender does, adapted to a CPU host:
+
+* **One native frame.** The whole tree is rasterized in C into a single
+ frame buffer (``buipy.Raster``: anti-aliased SDF boxes/circles/lines and a
+ cached native text engine) — no per-primitive Tk canvas items.
+* **One present.** Only the tiles that changed since the last frame are
+ sent to the screen: a direct GDI blit to the window on Windows, otherwise
+ a dirty-rect ``PhotoImage.put`` of binary PPM.
+* **Coalesced redraws.** Input, timers and ``widget.update()`` only mark the
+ surface dirty; one render runs when Tk goes idle, however many events
+ arrived. Hover with no handler costs nothing.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import sys
+from bui import _realtk
+
+tk = _realtk.module()
+tkfont = _realtk.module("tkinter.font")
+
+import buipy
+
+
+_BG = "#1d1d22"
+_BUTTON1_MASK = 0x0100
+
+# Native present + native text exist together (Win32 GDI) — see GPU_raster.h.
+NATIVE_PRESENT = sys.platform == "win32" and buipy.has_native_text()
+
+
+def _hex(rgba) -> str:
+ r, g, b = (max(0, min(255, int(c * 255 + 0.5))) for c in rgba[:3])
+ return "#%02x%02x%02x" % (r, g, b)
+
+
+class _TkTextOverlay:
+ """Host-drawn text for platforms without a native text engine.
+
+ Canvas text items are pooled and only reconfigured when a run changes,
+ so a steady frame costs no Tk calls.
+ """
+
+ def __init__(self, canvas: tk.Canvas):
+ self._c = canvas
+ self._items: list = [] # [(item_id, spec)]
+ self._fonts: dict = {}
+
+ def _font(self, family, size, flags):
+ key = (family, int(round(size)), flags)
+ f = self._fonts.get(key)
+ if f is None:
+ f = tkfont.Font(root=self._c, family=family or "TkDefaultFont",
+ size=-max(1, key[1]),
+ weight="bold" if flags & 1 else "normal",
+ slant="italic" if flags & 2 else "roman",
+ underline=bool(flags & 4))
+ self._fonts[key] = (f, f.metrics("descent"))
+ f = self._fonts[key]
+ return f
+
+ def update(self, runs) -> None:
+ c = self._c
+ for i, run in enumerate(runs):
+ x, y, text, size, rgba, family, flags = run
+ font, descent = self._font(family, size, flags)
+ if i < len(self._items):
+ item, old = self._items[i]
+ if old == run:
+ continue
+ c.coords(item, x, y + descent)
+ c.itemconfigure(item, text=text, fill=_hex(rgba), font=font,
+ state="normal")
+ self._items[i] = (item, run)
+ else:
+ item = c.create_text(x, y + descent, text=text, fill=_hex(rgba),
+ font=font, anchor="sw")
+ self._items.append((item, run))
+ for i in range(len(runs), len(self._items)):
+ item, old = self._items[i]
+ if old is not None:
+ c.itemconfigure(item, state="hidden")
+ self._items[i] = (item, None)
+
+
+def parse_geometry(spec):
+ """'420x480+10+10' -> (420, 480); None when no size is given."""
+ try:
+ size = str(spec).split("+")[0].split("-")[0]
+ gw, gh = (int(v) for v in size.split("x"))
+ return gw, gh
+ except ValueError:
+ return None
+
+
+class Modifiers:
+ """Keyboard modifier + button state decoded from a Tk event."""
+
+ __slots__ = ("shift", "ctrl", "alt", "button1")
+
+ _ALT = 0x20000 if sys.platform == "win32" else 0x0008
+
+ def __init__(self, state=0):
+ state = state if isinstance(state, int) else 0
+ self.shift = bool(state & 0x0001)
+ self.ctrl = bool(state & 0x0004)
+ self.alt = bool(state & self._ALT)
+ self.button1 = bool(state & _BUTTON1_MASK)
+
+
+class TkSurface:
+ """A tk widget that displays (and feeds input to) a BUI scene.
+
+ ``scene`` is any object implementing the scene protocol:
+
+ render(w, h) -> int draw one frame; 0 = nothing changed
+ press / release / motion / context_menu(x, y, mods)
+ key(char, keysym, keycode, mods)
+ wheel(x, y, delta, mods) delta: +1 up / -1 down
+ """
+
+ def __init__(self, master, scene, width=None, height=None):
+ self.master = master
+ self.scene = scene
+ self.raster = buipy.Raster(1, 1)
+ self._pending = None
+ self._rendered = False
+ self._size = (0, 0)
+ self.frames = 0 # rendered frame count (diagnostics/tests)
+ # Requested window size (from geometry()) used until the window is
+ # mapped — Tk reports 1x1 before that.
+ self.size_hint = None
+
+ opts = {"highlightthickness": 0, "borderwidth": 0}
+ if width:
+ opts["width"] = int(width)
+ if height:
+ opts["height"] = int(height)
+ if NATIVE_PRESENT:
+ # bg="" — Tk never paints this window; every pixel is ours.
+ self.widget = tk.Frame(master, bg="", takefocus=1, **opts)
+ self._photo = None
+ self._overlay = None
+ else:
+ self.widget = tk.Canvas(master, bg=_BG, takefocus=1, **opts)
+ self._photo = tk.PhotoImage(master=self.widget, width=1, height=1)
+ self.widget.create_image(0, 0, image=self._photo, anchor="nw")
+ self._overlay = None if buipy.has_native_text() else _TkTextOverlay(self.widget)
+ self.widget.pack(fill="both", expand=True)
+
+ w = self.widget
+ w.bind("<ButtonPress-1>", self.on_press)
+ w.bind("<ButtonRelease-1>", self.on_release)
+ if hasattr(scene, "context_menu"): # right click (Button-2 on macOS)
+ w.bind("<ButtonPress-2>" if sys.platform == "darwin" else "<ButtonPress-3>",
+ self.on_context)
+ if hasattr(scene, "button"): # raw <Button-2>, <ButtonRelease-2/3>
+ for num in (2, 3):
+ w.bind("<ButtonRelease-%d>" % num,
+ lambda e, n=num: self._raw_button(e, n, True))
+ w.bind("<ButtonPress-2>", lambda e: self._raw_button(e, 2, False))
+ if hasattr(scene, "key_release"):
+ w.bind("<KeyRelease>", self._on_key_release)
+ w.bind("<Motion>", self.on_motion)
+ w.bind("<Key>", self.on_key)
+ w.bind("<MouseWheel>", self.on_wheel) # Windows / macOS
+ w.bind("<Button-4>", lambda e: self._wheel(e, +1)) # X11
+ w.bind("<Button-5>", lambda e: self._wheel(e, -1))
+ w.bind("<Configure>", self._on_configure)
+ w.bind("<Expose>", self._on_expose)
+ w.focus_set()
+
+ # -- size -------------------------------------------------------------------
+ def size(self):
+ w = self.widget.winfo_width()
+ h = self.widget.winfo_height()
+ if w <= 1 or h <= 1:
+ # Not mapped yet (headless/tests): use requested/geometry size.
+ if self.size_hint is not None:
+ return self.size_hint
+ w = max(w, self.widget.winfo_reqwidth())
+ h = max(h, self.widget.winfo_reqheight())
+ w, h = max(w, 400), max(h, 300)
+ return w, h
+
+ # -- redraw scheduling ------------------------------------------------------
+ def request(self) -> None:
+ """Mark dirty; one render runs when Tk is idle (coalesces bursts)."""
+ if self._pending is None:
+ try:
+ self._pending = self.widget.after_idle(self._flush)
+ except tk.TclError: # window destroyed
+ self._pending = None
+
+ def _flush(self) -> None:
+ self._pending = None
+ self.render()
+
+ def render(self) -> None:
+ """Render now and present the changed regions."""
+ try:
+ self._render()
+ except tk.TclError:
+ pass # window destroyed while a redraw was queued
+
+ def _render(self) -> None:
+ if self._pending is not None:
+ try:
+ self.widget.after_cancel(self._pending)
+ except tk.TclError:
+ pass
+ self._pending = None
+ w, h = self.size()
+ resized = (w, h) != self._size
+ self._size = (w, h)
+ buipy.set_backend(self.raster)
+ try:
+ regions = self.scene.render(w, h)
+ finally:
+ buipy.set_backend(None)
+ if regions == 0 and not resized and self._rendered:
+ return # damage-driven scene: nothing changed, nothing to blit
+ self.frames += 1
+ self._rendered = True
+ self._present(full=resized)
+
+ def _present(self, full=False) -> None:
+ r = self.raster
+ try:
+ if NATIVE_PRESENT:
+ if not self.widget.winfo_ismapped():
+ return # Expose will present once it is on screen
+ r.present_native(self.widget.winfo_id(), full)
+ return
+ w, h = r.size
+ if full or self._photo.width() != w or self._photo.height() != h:
+ self._photo.configure(width=w, height=h)
+ rects = [(0, 0, w, h)]
+ else:
+ rects = r.damage()
+ for x, y, rw, rh in rects:
+ self._photo.put(r.ppm(x, y, rw, rh), to=(x, y))
+ if self._overlay is not None:
+ self._overlay.update(r.text_runs())
+ except tk.TclError:
+ pass # window destroyed mid-frame
+
+ # -- tk events --------------------------------------------------------------
+ def _on_configure(self, event) -> None:
+ self.request()
+
+ def _on_expose(self, event) -> None:
+ if not self._rendered:
+ self.request()
+ elif NATIVE_PRESENT:
+ # The OS lost our pixels (uncovered/restored): re-blit, no render.
+ self.raster.present_native(self.widget.winfo_id(), True)
+
+ @staticmethod
+ def _mods(event):
+ state = getattr(event, "state", None)
+ return Modifiers(state) if isinstance(state, int) else None
+
+ def on_press(self, event) -> None:
+ try:
+ self.widget.focus_set()
+ except tk.TclError:
+ pass
+ self.scene.press(event.x, event.y, self._mods(event))
+ self.request()
+
+ def on_context(self, event) -> None:
+ self.scene.context_menu(event.x, event.y, self._mods(event))
+ self.request()
+
+ def on_release(self, event) -> None:
+ self.scene.release(event.x, event.y, self._mods(event))
+ self.request()
+
+ def _raw_button(self, e, num, release):
+ if num == 2 and sys.platform == "darwin":
+ num = 3 # macOS reports the right button as 2
+ self.scene.button(e.x, e.y, num, release, Modifiers(e.state))
+ self.request()
+
+ def _on_key_release(self, e):
+ self.scene.key_release(e.keysym, Modifiers(e.state))
+ self.request()
+
+ def on_motion(self, event) -> None:
+ if self.scene.motion(event.x, event.y, self._mods(event)):
+ self.request()
+
+ def on_key(self, event) -> None:
+ self.scene.key(event.char, event.keysym, getattr(event, "keycode", 0),
+ self._mods(event))
+ self.request()
+
+ def on_wheel(self, event) -> None:
+ self._wheel(event, 1 if getattr(event, "delta", 0) > 0 else -1)
+
+ def _wheel(self, event, delta) -> None:
+ if self.scene.wheel(event.x, event.y, delta, self._mods(event)):
+ self.request()
diff --git a/bindings/python/bui/components/__init__.py b/bindings/python/bui/components/__init__.py
new file mode 100644
index 0000000..c9bb561
--- /dev/null
+++ b/bindings/python/bui/components/__init__.py
@@ -0,0 +1,58 @@
+"""bui.components — Blender's UI as a component library, running in C.
+
+Compose components into a tree and hand it to an :class:`App`::
+
+ 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),
+ EnumRow("Mode", ["Object", "Edit"]),
+ Checkbox("Smooth", True),
+ Button("Apply", on_click=lambda: print("apply"))),
+ ).run()
+
+Each component is a node of the C kit (``kit/``): Blender's widget drawing
+ported from ``interface_widgets.cc``, Blender's interaction rules, and
+damage-driven rendering — an idle UI costs nothing, a hover or a scrub
+redraws only the touched widget. Python builds the tree and receives
+callbacks.
+
+Modules: ``core`` (base classes), ``widgets``, ``containers``, ``views``,
+``menus``, ``editors``, ``templates``, ``app``.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from bui.components.app import App
+from bui.components.containers import (Box, Column, Grid, Panel, Row, ScrollView, SideTabs,
+ Split, Tabs, VectorField)
+from bui.components.core import Component, ValueComponent, unit
+from bui.components.editors import (ColorRamp, ColorStop, CurveMapping, Histogram, NormalBall,
+ Popover)
+from bui.components.menus import Menu, MenuBar, MenuButton, MenuItem, PieMenu
+from bui.components.templates import IDSelector, PathField
+from bui.components.views import GridView, ListView, TreeItem, TreeView
+from bui.components.widgets import (Button, Checkbox, ColorSwatch, Decorator, Dropdown,
+ EnumRow, HotkeyField, IconButton, Label, NumberField,
+ NumberSlider, ProgressBar, SearchField, Separator, Spacer,
+ TextField, Toggle, eval_number)
+
+__all__ = [
+ "App", "Component", "ValueComponent", "unit",
+ # layout
+ "Column", "Row", "Split", "Grid", "Box", "Panel", "Tabs", "SideTabs", "ScrollView",
+ "VectorField",
+ # widgets
+ "Label", "Separator", "Spacer", "ProgressBar", "Button", "IconButton", "Toggle",
+ "Checkbox", "Decorator", "TextField", "SearchField", "HotkeyField", "NumberField",
+ "NumberSlider", "Dropdown", "EnumRow", "ColorSwatch", "eval_number",
+ # views
+ "ListView", "TreeView", "TreeItem", "GridView",
+ # menus & popups
+ "Menu", "MenuItem", "MenuButton", "MenuBar", "PieMenu", "Popover",
+ # editors & templates
+ "ColorRamp", "ColorStop", "CurveMapping", "NormalBall", "Histogram",
+ "IDSelector", "PathField",
+]
diff --git a/bindings/python/bui/components/__pycache__/__init__.cpython-314.pyc b/bindings/python/bui/components/__pycache__/__init__.cpython-314.pyc
new file mode 100644
index 0000000..fc58a80
Binary files /dev/null and b/bindings/python/bui/components/__pycache__/__init__.cpython-314.pyc differ
diff --git a/bindings/python/bui/components/__pycache__/app.cpython-314.pyc b/bindings/python/bui/components/__pycache__/app.cpython-314.pyc
new file mode 100644
index 0000000..c91e690
Binary files /dev/null and b/bindings/python/bui/components/__pycache__/app.cpython-314.pyc differ
diff --git a/bindings/python/bui/components/__pycache__/containers.cpython-314.pyc b/bindings/python/bui/components/__pycache__/containers.cpython-314.pyc
new file mode 100644
index 0000000..f3939a8
Binary files /dev/null and b/bindings/python/bui/components/__pycache__/containers.cpython-314.pyc differ
diff --git a/bindings/python/bui/components/__pycache__/core.cpython-314.pyc b/bindings/python/bui/components/__pycache__/core.cpython-314.pyc
new file mode 100644
index 0000000..8868cc2
Binary files /dev/null and b/bindings/python/bui/components/__pycache__/core.cpython-314.pyc differ
diff --git a/bindings/python/bui/components/__pycache__/editors.cpython-314.pyc b/bindings/python/bui/components/__pycache__/editors.cpython-314.pyc
new file mode 100644
index 0000000..c47c47e
Binary files /dev/null and b/bindings/python/bui/components/__pycache__/editors.cpython-314.pyc differ
diff --git a/bindings/python/bui/components/__pycache__/menus.cpython-314.pyc b/bindings/python/bui/components/__pycache__/menus.cpython-314.pyc
new file mode 100644
index 0000000..e8f3fe4
Binary files /dev/null and b/bindings/python/bui/components/__pycache__/menus.cpython-314.pyc differ
diff --git a/bindings/python/bui/components/__pycache__/templates.cpython-314.pyc b/bindings/python/bui/components/__pycache__/templates.cpython-314.pyc
new file mode 100644
index 0000000..0d4998c
Binary files /dev/null and b/bindings/python/bui/components/__pycache__/templates.cpython-314.pyc differ
diff --git a/bindings/python/bui/components/__pycache__/views.cpython-314.pyc b/bindings/python/bui/components/__pycache__/views.cpython-314.pyc
new file mode 100644
index 0000000..b3f6e2a
Binary files /dev/null and b/bindings/python/bui/components/__pycache__/views.cpython-314.pyc differ
diff --git a/bindings/python/bui/components/__pycache__/widgets.cpython-314.pyc b/bindings/python/bui/components/__pycache__/widgets.cpython-314.pyc
new file mode 100644
index 0000000..1b51f15
Binary files /dev/null and b/bindings/python/bui/components/__pycache__/widgets.cpython-314.pyc differ
diff --git a/bindings/python/bui/components/app.py b/bindings/python/bui/components/app.py
new file mode 100644
index 0000000..58e11fc
--- /dev/null
+++ b/bindings/python/bui/components/app.py
@@ -0,0 +1,94 @@
+"""App: a window hosting a component tree.
+
+The window's whole runtime — layout, input state, drawing, damage tracking
+— is the C kit (``buipy.KitContext``). :meth:`App.run` opens it in a
+native window (Windows: input -> render -> present never leaves C) or a Tk
+window elsewhere (:mod:`bui.host`). The input methods below drive the same
+context headlessly (tests, tools).
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Optional
+
+import buipy
+
+from bui.components.containers import Column
+from bui.components.core import CURSORS, Component, mods_bits # noqa: F401
+
+class App:
+ def __init__(self, title: str = "BUI", size=(420, 640), *children: Component,
+ padding=None, spacing=None, header: Optional[Component] = None):
+ self.title, self.size = title, tuple(size)
+ u = buipy.kit_unit()
+ self.root = Column(*children,
+ padding=round(0.4 * u) if padding is None else padding,
+ spacing=round(0.3 * u) if spacing is None else spacing)
+ self.header = header
+ self.ctx = buipy.KitContext(self.root)
+ if header is not None:
+ self.ctx.set_header(header)
+ self.window = None
+ self._raster = None
+ self._timers = [] # (ms, id) when there is no host loop
+
+ def add(self, *components: Component):
+ return self.root.add(*components)
+
+ def bind(self, combo: str, fn: Callable[[], None]) -> None:
+ """Window hotkey: ``app.bind("ctrl+s", save)``."""
+ self.ctx.bind(combo, fn)
+
+ @property
+ def cursor(self) -> Optional[str]:
+ return CURSORS[self.ctx.cursor]
+
+ # -- scene protocol (driven by TkSurface) ---------------------------------------
+ def render(self, w: int, h: int, full: bool = False) -> int:
+ """Render into the active raster; returns the number of redrawn regions
+ (0 = nothing changed, nothing to present)."""
+ return self.ctx.render(w, h, None, full)
+
+ def press(self, x, y, mods=None):
+ return self.ctx.press(x, y, mods_bits(mods))
+
+ def release(self, x, y, mods=None):
+ return self.ctx.release(x, y, mods_bits(mods))
+
+ def motion(self, x, y, mods=None):
+ return self.ctx.motion(x, y, mods_bits(mods))
+
+ def context_menu(self, x, y, mods=None):
+ return self.ctx.context_menu(x, y, mods_bits(mods))
+
+ def key(self, char, keysym, keycode=0, mods=None):
+ return self.ctx.key(char or "", keysym or "", mods_bits(mods))
+
+ def wheel(self, x, y, delta, mods=None):
+ return self.ctx.wheel(x, y, delta, mods_bits(mods))
+
+ # -- running ---------------------------------------------------------------------
+ def render_raster(self, w: int = None, h: int = None, full: bool = False) -> "buipy.Raster":
+ """Render one frame headlessly (tests, screenshots). The raster is
+ kept, so later calls redraw only what changed."""
+ w, h = w or self.size[0], h or self.size[1]
+ if self._raster is None or self._raster.size != (w, h):
+ self._raster = buipy.Raster(w, h)
+ self.ctx.render(w, h, self._raster, full)
+ return self._raster
+
+ def open(self, native: bool = None):
+ """Create (and show) the window without running the loop."""
+ from bui import host
+ self.window = host.Window(self.ctx, self.title, self.size, native=native)
+ self.window.show()
+ return self.window
+
+ def run(self, native: bool = None) -> None:
+ """Open the window and run the event loop (native on Windows; Tk
+ elsewhere or with ``BUI_HOST=tk``)."""
+ from bui import host
+ self.open(native)
+ host.run()
diff --git a/bindings/python/bui/components/containers.py b/bindings/python/bui/components/containers.py
new file mode 100644
index 0000000..b0d982b
--- /dev/null
+++ b/bindings/python/bui/components/containers.py
@@ -0,0 +1,216 @@
+"""Layouts and containers (C node types in ``kit/intern/kit_widgets.c``).
+
+* :class:`Column` / :class:`Row` — Blender's uiLayout column/row;
+ ``align=True`` joins children into one block. Row children share the
+ width by ``weight`` (``weight=0`` keeps the natural width).
+* :class:`Split` (property split), :class:`Grid`, :class:`Box`.
+* :class:`Panel` — collapsible (Ctrl+click solo, drag over headers,
+ drag the grip to reorder, header components, sub-panels).
+* :class:`Tabs`, :class:`SideTabs` (properties-editor icon tabs),
+ :class:`ScrollView`, :class:`VectorField`.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Optional, Sequence
+
+import buipy
+
+from bui.components.core import EV_CHANGE, Component
+from bui.components.widgets import Label, NumberField
+
+
+class _Stack(Component):
+ def __init__(self, *children: Component, align: bool = False, spacing=None,
+ padding=0, **kw):
+ super().__init__(**kw)
+ if align:
+ self.set("align", True)
+ if spacing is not None:
+ self.set("spacing", int(spacing))
+ if padding:
+ self.set("padding", int(padding))
+ self.add(*children)
+
+
+class Column(_Stack):
+ TYPE = "column"
+
+
+class Row(_Stack):
+ TYPE = "row"
+
+
+class Split(Row):
+ """Property split: ``left`` gets ``factor`` of the width."""
+
+ def __init__(self, left: Component, right: Component, factor: float = 0.4, **kw):
+ left.weight, right.weight = factor, 1.0 - factor
+ super().__init__(left, right, **kw)
+
+
+class Box(_Stack):
+ """A padded column on Blender's box background."""
+
+ TYPE = "box"
+
+
+class Grid(_Stack):
+ """Grid flow: children in ``columns`` equal-width columns."""
+
+ TYPE = "grid"
+
+ def __init__(self, *children: Component, columns: int = 2, **kw):
+ super().__init__(*children, **kw)
+ self.set("columns", columns)
+
+
+class Panel(Component):
+ """Collapsible panel. ``header=[Checkbox("", True)]`` puts components in
+ the header; ``icon=`` shows an icon; a Panel in a Panel is a sub-panel."""
+
+ TYPE = "panel"
+
+ def __init__(self, title: str, *children: Component, collapsed: bool = False,
+ icon: str = None, header: Sequence[Component] = (),
+ on_toggle: Optional[Callable[[bool], None]] = None, **kw):
+ super().__init__(**kw)
+ self.on_toggle = on_toggle
+ self.set("text", title)
+ if icon:
+ self.set("icon", icon)
+ if collapsed:
+ self.set("collapsed", True)
+ for h in header:
+ buipy.KitNode.add(self, h)
+ body = self.body
+ for c in children:
+ body.add(c)
+
+ @property
+ def body(self) -> Component:
+ return self.children[0]
+
+ def add(self, *components):
+ for c in components:
+ buipy.KitNode.add(self.body, c)
+ return components[0] if len(components) == 1 else self
+
+ @property
+ def title(self) -> str:
+ return self.get_str("text")
+
+ @property
+ def collapsed(self) -> bool:
+ return bool(self.get("collapsed"))
+
+ @collapsed.setter
+ def collapsed(self, v: bool) -> None:
+ self.set("collapsed", bool(v))
+
+ def toggle(self) -> None:
+ self.collapsed = not self.collapsed
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_CHANGE and self.on_toggle is not None:
+ self.on_toggle(bool(a))
+
+
+class Tabs(Component):
+ """Tabbed pages: ``Tabs([("Object", page), ("Modifiers", page2)])``."""
+
+ TYPE = "tabs"
+
+ def __init__(self, pages: Sequence, current: int = 0,
+ on_change: Optional[Callable[[int], None]] = None, **kw):
+ super().__init__(**kw)
+ self.on_change = on_change
+ self.set("items", [str(t) for t, _ in pages])
+ self.add(*[c for _, c in pages])
+ self.set("current", current)
+
+ @property
+ def current(self) -> int:
+ return int(self.get("current"))
+
+ def select(self, i: int) -> None:
+ if i != self.current and 0 <= i < len(self.children):
+ self.set("current", i)
+ if self.on_change is not None:
+ self.on_change(i)
+
+ @property
+ def titles(self):
+ return self.strs("items")
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_CHANGE and self.on_change is not None:
+ self.on_change(int(a))
+
+
+class SideTabs(Tabs):
+ """Properties-editor navigation: ``SideTabs([("OBJECT_DATA", "Object",
+ page), ...])`` — icon tabs on the left; hover for the name."""
+
+ TYPE = "sidetabs"
+
+ def __init__(self, pages: Sequence, current: int = 0, on_change=None, **kw):
+ Component.__init__(self, **kw)
+ self.on_change = on_change
+ self.set("items", [str(t) for _, t, _ in pages])
+ self.set("icons", [str(i) for i, _, _ in pages])
+ self.add(*[c for _, _, c in pages])
+ self.set("current", current)
+
+ def page(self) -> Component:
+ return self.children[self.current]
+
+
+class ScrollView(Component):
+ """Fixed-height viewport over a taller child (wheel, draggable bar)."""
+
+ TYPE = "scroll"
+
+ def __init__(self, child: Component, height: int = None, rows: float = 8, **kw):
+ super().__init__(**kw)
+ if height:
+ self.set("height", height / buipy.kit_unit())
+ else:
+ self.set("rows", int(rows))
+ self.add(child)
+
+ @property
+ def scroll(self) -> int:
+ return int(self.get("scroll"))
+
+
+class VectorField(Column):
+ """Label + aligned number fields (X/Y/Z). Alt+drag edits all components;
+ Ctrl+Alt+C / Ctrl+Alt+V copy/paste the whole vector."""
+
+ def __init__(self, label: str = "", value=(0.0, 0.0, 0.0), *, axes: str = "XYZW",
+ on_change: Optional[Callable] = None, **number_kw):
+ self.on_change = on_change
+ self.fields = [NumberField(axes[i] if i < len(axes) else str(i), v,
+ on_change=self._field_changed, **number_kw)
+ for i, v in enumerate(value)]
+ block = Column(*self.fields, align=True)
+ children = ([Label(label)] if label else []) + [block]
+ super().__init__(*children, spacing=max(1, round(0.1 * buipy.kit_unit())))
+ buipy.kit_link_fields(self.fields)
+
+ @property
+ def value(self):
+ return tuple(f.value for f in self.fields)
+
+ def set_value(self, value, notify: bool = True) -> None:
+ for f, v in zip(self.fields, value):
+ f.set_value(v, notify=False)
+ if notify and self.on_change is not None:
+ self.on_change(self.value)
+
+ def _field_changed(self, _v):
+ if self.on_change is not None:
+ self.on_change(self.value)
diff --git a/bindings/python/bui/components/core.py b/bindings/python/bui/components/core.py
new file mode 100644
index 0000000..a47293f
--- /dev/null
+++ b/bindings/python/bui/components/core.py
@@ -0,0 +1,165 @@
+"""Component base classes over the C kit (``buipy.KitNode``).
+
+Every component *is* a C node: layout, input handling and drawing run in
+``kit/`` (C). The Python classes only map constructor arguments to node
+properties and turn C events into ``on_change`` / ``on_click`` callbacks.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Optional
+
+import buipy
+
+# Event kinds delivered to Component._on_event (BUI_kit.h BK_EV_*).
+EV_CHANGE, EV_CLICK, EV_CALL, EV_RENAME, EV_ACTIVATE, EV_TOGGLE, EV_BROWSE = range(1, 8)
+# Raw events for nodes with the "events" property (Tk bind, Qt event handlers).
+(EV_PRESS, EV_RELEASE, EV_DOUBLE, EV_MOTION, EV_ENTER, EV_LEAVE, EV_KEY, EV_WHEEL,
+ EV_SUBMIT, EV_VIEW, EV_SCROLL, EV_CONFIGURE) = range(8, 20)
+
+# Modifier bits for KitContext input calls.
+SHIFT, CTRL, ALT, BUTTON1 = 1, 2, 4, 8
+
+# Cursor ids (BK_CURSOR_*).
+CURSORS = (None, "ew", "ns", "text", "crosshair", "hand", "move", "none")
+
+
+def mods_bits(mods) -> int:
+ """Modifier object (shift/ctrl/alt/button1 attributes) -> kit bits."""
+ if mods is None:
+ return 0
+ if isinstance(mods, int):
+ return mods
+ return ((SHIFT if getattr(mods, "shift", False) else 0)
+ | (CTRL if getattr(mods, "ctrl", False) else 0)
+ | (ALT if getattr(mods, "alt", False) else 0)
+ | (BUTTON1 if getattr(mods, "button1", False) else 0))
+
+
+def unit() -> int:
+ """U.widget_unit in pixels (20 at scale 1)."""
+ return buipy.kit_unit()
+
+
+class Component(buipy.KitNode):
+ """Base of every component. ``x, y, w, h`` / ``rect`` come from the last
+ layout (provided by the C node)."""
+
+ TYPE = "column"
+
+ def __init__(self, *, description: str = "", enabled: bool = True,
+ visible: bool = True, weight: float = 1.0):
+ super().__init__(self.TYPE)
+ if description:
+ self.set("description", description)
+ if not enabled:
+ self.set("enabled", False)
+ if not visible:
+ self.set("visible", False)
+ if weight != 1.0:
+ self.set("weight", weight)
+
+ # -- common properties ---------------------------------------------------------
+ @property
+ def enabled(self) -> bool:
+ return bool(self.get("enabled"))
+
+ @enabled.setter
+ def enabled(self, v: bool) -> None:
+ self.set("enabled", bool(v))
+
+ @property
+ def visible(self) -> bool:
+ return bool(self.get("visible"))
+
+ @visible.setter
+ def visible(self, v: bool) -> None:
+ self.set("visible", bool(v))
+
+ @property
+ def description(self) -> str:
+ return self.get_str("description")
+
+ @description.setter
+ def description(self, text: str) -> None:
+ self.set("description", text or "")
+
+ @property
+ def weight(self) -> float:
+ return self.get("weight")
+
+ @weight.setter
+ def weight(self, v: float) -> None:
+ self.set("weight", float(v))
+
+ @property
+ def corners(self) -> int:
+ return int(self.get("corners"))
+
+ def add(self, *components: "Component"):
+ for c in components:
+ buipy.KitNode.add(self, c)
+ return components[0] if len(components) == 1 else self
+
+ def _on_event(self, kind, ref, a, b):
+ pass
+
+
+class ValueComponent(Component):
+ """A component holding a value: ``value``, ``set_value``, ``on_change``
+ and Blender's value shortcuts (Ctrl+C/V, Backspace, Ctrl+Wheel, right
+ click menu) — all handled in C."""
+
+ def __init__(self, label: str = "", value=None, *, default=None,
+ on_change: Optional[Callable] = None, **kw):
+ super().__init__(**kw)
+ self.on_change = on_change
+ if label:
+ self.set("label", label)
+ if value is not None:
+ self._store(value, notify=False)
+ self._set_default(self.value if default is None else default)
+
+ # per-type value mapping (override) ---------------------------------------------
+ def _store(self, v, notify: bool) -> None:
+ self.set("set_value" if notify else "value", v)
+
+ def _load(self):
+ return self.get("value")
+
+ def _set_default(self, v) -> None:
+ if isinstance(v, (int, float, bool)):
+ self.set("default", float(v))
+
+ # API ------------------------------------------------------------------------------
+ @property
+ def value(self):
+ return self._load()
+
+ @value.setter
+ def value(self, v) -> None:
+ self.set_value(v)
+
+ def set_value(self, v, notify: bool = True) -> None:
+ self._store(v, notify)
+
+ def reset(self) -> None:
+ """Back to the default value."""
+ self._store(self._default(), True)
+
+ def _default(self):
+ return self.get("default")
+
+ @property
+ def label(self) -> str:
+ return self.get_str("label")
+
+ @label.setter
+ def label(self, text: str) -> None:
+ self.set("label", text or "")
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_CHANGE and self.on_change is not None:
+ self.on_change(self.value)
diff --git a/bindings/python/bui/components/editors.py b/bindings/python/bui/components/editors.py
new file mode 100644
index 0000000..f6b0d1a
--- /dev/null
+++ b/bindings/python/bui/components/editors.py
@@ -0,0 +1,241 @@
+"""Blender's data editors (C: ``kit/intern/kit_color.c``): color ramp,
+curve mapping, normal ball, histogram, and the Popover button.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Optional, Sequence
+
+from bui.components.containers import Column, Row
+from bui.components.core import EV_CHANGE, Component, ValueComponent
+from bui.components.widgets import ColorSwatch, Dropdown, EnumRow, IconButton, NumberField, Spacer
+
+INTERPOLATIONS = ["Linear", "Ease", "B-Spline", "Constant"]
+
+
+class _RampBand(Component):
+ TYPE = "ramp"
+
+ def __init__(self, owner: "ColorRamp"):
+ super().__init__()
+ self._owner = owner
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ self._owner._band_changed()
+
+
+class ColorStop:
+ __slots__ = ("pos", "color")
+
+ def __init__(self, pos: float, color):
+ self.pos, self.color = float(pos), tuple(color)
+
+ def __repr__(self):
+ return "ColorStop(%.3f, %r)" % (self.pos, self.color)
+
+
+class ColorRamp(Column):
+ """Blender's color ramp: add/remove, interpolation, the band (click a
+ stop to select, drag to move, Ctrl+click to add, X/Delete to remove) and
+ the active stop's position and color."""
+
+ def __init__(self, stops=((0.0, (0, 0, 0, 1)), (1.0, (1, 1, 1, 1))), *,
+ interpolation: str = "Linear",
+ on_change: Optional[Callable[[list], None]] = None, **kw):
+ self.on_change = on_change
+ self.band = _RampBand(self)
+ self.band.set_ramp([(p, tuple(c) + ((1.0,) if len(c) == 3 else ())) for p, c in stops])
+ self.pos_field = NumberField("Pos", 0.0, min=0.0, max=1.0, step=0.01,
+ on_change=self._pos_changed)
+ self.swatch = ColorSwatch("", (0, 0, 0, 1), on_change=self._color_changed)
+ self.interp = Dropdown("", INTERPOLATIONS, interpolation,
+ on_change=self._interp_changed, weight=3)
+ tools = Row(IconButton("ADD", self.add_stop, emboss=True, weight=0,
+ description="Add a stop after the active one"),
+ IconButton("REMOVE", self.remove_stop, emboss=True, weight=0,
+ description="Delete the active stop"),
+ Spacer(weight=3), self.interp)
+ super().__init__(tools, self.band, Row(self.pos_field, self.swatch), **kw)
+ self._interp_changed(interpolation, notify=False)
+ self._sync()
+
+ # model ------------------------------------------------------------------------
+ @property
+ def stops(self):
+ return [ColorStop(p, c) for p, c in self.band.ramp()]
+
+ def sorted_stops(self):
+ return sorted(self.stops, key=lambda s: s.pos)
+
+ @property
+ def active(self) -> ColorStop:
+ p, c = self.band.ramp()[int(self.band.get("active"))]
+ return ColorStop(p, c)
+
+ @property
+ def interpolation(self) -> str:
+ return INTERPOLATIONS[int(self.band.get("interpolation"))]
+
+ @interpolation.setter
+ def interpolation(self, name: str) -> None:
+ self.interp.set_value(name)
+
+ def evaluate(self, t: float):
+ return self.band.ramp_eval(t)
+
+ def add_stop(self, pos: float = None) -> None:
+ if pos is None: # Blender adds halfway after the active stop
+ a = self.active.pos
+ later = [s.pos for s in self.stops if s.pos > a]
+ pos = (a + min(later)) / 2 if later else a
+ self.band.set("add", pos)
+ self._band_changed()
+
+ def remove_stop(self) -> None:
+ self.band.set("remove", 1)
+ self._band_changed()
+
+ # wiring ------------------------------------------------------------------------
+ def _sync(self):
+ st = self.active
+ self.pos_field.set_value(st.pos, notify=False)
+ self.swatch.set_value(st.color, notify=False)
+
+ def _band_changed(self):
+ self._sync()
+ if self.on_change is not None:
+ self.on_change(self.sorted_stops())
+
+ def _pos_changed(self, v):
+ self.band.set("active_pos", v)
+ self._band_changed()
+
+ def _color_changed(self, c):
+ self.band.set_ramp_color(c)
+ if self.on_change is not None:
+ self.on_change(self.sorted_stops())
+
+ def _interp_changed(self, name, notify=True):
+ self.band.set("interpolation", INTERPOLATIONS.index(name))
+ if notify and self.on_change is not None:
+ self.on_change(self.sorted_stops())
+
+
+class _CurveGraph(Component):
+ TYPE = "curve"
+
+ def __init__(self, owner: "CurveMapping", height: float):
+ super().__init__()
+ self._owner = owner
+ self.set("height", height)
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_CHANGE and self._owner.on_change is not None:
+ self._owner.on_change(self._owner.channel, self._owner.points)
+
+
+class CurveMapping(Column):
+ """Blender's curve widget: click the curve to add a point, Ctrl+click to
+ add anywhere, drag points (Ctrl snaps), X/Delete removes the selected
+ point. ``channels=("C", "R", "G", "B")`` adds channel tabs."""
+
+ def __init__(self, points=((0.0, 0.0), (1.0, 1.0)), *, channels: Sequence[str] = (),
+ height: float = 8.0,
+ on_change: Optional[Callable[[str, list], None]] = None, **kw):
+ self.on_change = on_change
+ self.channels = list(channels) or ["C"]
+ self.graph = _CurveGraph(self, height)
+ self.graph.set("channels", len(self.channels))
+ for ch in range(len(self.channels)):
+ self.graph.set_curve(ch, list(points))
+ first = (EnumRow("", self.channels, self.channels[0], on_change=self._set_channel,
+ weight=4) if len(self.channels) > 1 else Spacer(weight=4))
+ tools = Row(first, IconButton("LOOP_BACK", self.reset, emboss=True, weight=0,
+ description="Reset the curve"))
+ super().__init__(tools, self.graph, **kw)
+
+ @property
+ def channel(self) -> str:
+ return self.channels[int(self.graph.get("channel"))]
+
+ @property
+ def points(self):
+ return self.graph.curve(int(self.graph.get("channel")))
+
+ def evaluate(self, x: float, channel: str = None) -> float:
+ ch = self.channels.index(channel) if channel else int(self.graph.get("channel"))
+ return self.graph.curve_eval(ch, x)
+
+ def _set_channel(self, name):
+ self.graph.set("channel", self.channels.index(name))
+
+ def reset(self):
+ self.graph.set_curve(int(self.graph.get("channel")), [(0.0, 0.0), (1.0, 1.0)])
+ if self.on_change is not None:
+ self.on_change(self.channel, self.points)
+
+ def remove_selected(self):
+ self.graph.set("remove_selected", 1)
+
+
+class NormalBall(ValueComponent):
+ """Direction picker drawn as a lit sphere; drag to aim."""
+
+ TYPE = "normal"
+
+ def __init__(self, label: str = "", value=(0.0, 0.0, 1.0), *, size: float = 4.0, **kw):
+ Component.__init__(self, **{k: v for k, v in kw.items()
+ if k in ("description", "enabled", "visible", "weight")})
+ self.on_change = kw.get("on_change")
+ self.set("height", size)
+ self._store(value, False)
+
+ def _store(self, v, notify):
+ x, y, z = (float(c) for c in v)
+ n = (x * x + y * y + z * z) ** 0.5 or 1.0
+ self.set("color", (x / n, y / n, z / n, 1.0))
+ if notify and self.on_change is not None:
+ self.on_change(self.value)
+
+ def _load(self):
+ return self.get_color("color")[:3]
+
+
+class Histogram(Component):
+ """Image histogram (display only): ``bins`` are luma values or
+ ``(r, g, b)`` triples, each 0..1."""
+
+ TYPE = "histogram"
+
+ def __init__(self, bins: Sequence = (), *, height: float = 5.0, **kw):
+ super().__init__(**kw)
+ self.set("height", height)
+ self.set_bins(bins)
+
+ def set_bins(self, bins) -> None:
+ bins = list(bins)
+ channels = 3 if bins and isinstance(bins[0], (tuple, list)) else 1
+ self.set_histogram(bins, channels)
+
+
+class Popover(Component):
+ """Button that opens a panel of components (Blender popover)."""
+
+ TYPE = "popover"
+
+ def __init__(self, text: str, *children: Component, icon: str = None, **kw):
+ kw.pop("width", None)
+ super().__init__(**kw)
+ self.set("text", text)
+ if icon:
+ self.set("icon", icon)
+ body = self.body
+ for c in children:
+ body.add(c)
+
+ @property
+ def body(self) -> Component:
+ return self.children[0]
diff --git a/bindings/python/bui/components/menus.py b/bindings/python/bui/components/menus.py
new file mode 100644
index 0000000..6eb7fb9
--- /dev/null
+++ b/bindings/python/bui/components/menus.py
@@ -0,0 +1,102 @@
+"""Menus (C: ``kit/intern/kit_menus.c``): items, menu buttons, the header
+menu bar and pie menus.
+
+Items are :class:`MenuItem` objects, plain strings or ``"-"``::
+
+ MenuBar(("File", [MenuItem("New", new, icon="FILE", shortcut="Ctrl N"),
+ MenuItem("Open Recent", submenu=[...]),
+ "-",
+ MenuItem("Quit", quit)]))
+
+As in Blender: press-drag-release picks, hover switches between menu-bar
+menus and opens submenus, typing searches every item.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Optional, Sequence
+
+from bui.components.core import Component
+
+SEPARATOR = "-"
+
+
+class MenuItem:
+ """One menu entry. ``checked`` (True/False) shows a checkbox; ``submenu``
+ (a list of items) opens another menu."""
+
+ def __init__(self, text: str, on_click: Optional[Callable[[], None]] = None, *,
+ icon: str = None, shortcut: str = None, checked=None, submenu=None,
+ enabled: bool = True, description: str = ""):
+ self.text, self.on_click, self.icon = text, on_click, icon
+ self.shortcut, self.checked, self.submenu = shortcut, checked, submenu
+ self.enabled, self.description = enabled, description
+
+ def __repr__(self):
+ return "MenuItem(%r)" % self.text
+
+
+def menu_items(items, on_pick: Optional[Callable[[str], None]] = None):
+ """Normalize items; plain strings call ``on_pick(text)``."""
+ out = []
+ for it in items:
+ if it == SEPARATOR or it is None:
+ out.append(SEPARATOR)
+ elif isinstance(it, MenuItem):
+ if it.submenu:
+ it.submenu = menu_items(it.submenu, on_pick)
+ out.append(it)
+ else:
+ text = str(it)
+ out.append(MenuItem(text, (lambda t=text: on_pick(t)) if on_pick else None))
+ return out
+
+
+class MenuButton(Component):
+ """Header pulldown (``File``, ``Edit`` ...)."""
+
+ TYPE = "menubutton"
+
+ def __init__(self, text: str, items: Sequence, *, icon: str = None, **kw):
+ super().__init__(**kw)
+ self.set("text", text)
+ if icon:
+ self.set("icon", icon)
+ self.items = menu_items(items)
+ self.set_menu(self.items)
+
+
+class MenuBar(Component):
+ """Blender's top bar: ``MenuBar(("File", [...]), ("Edit", [...]),
+ right=[components])``."""
+
+ TYPE = "menubar"
+
+ def __init__(self, *menus, right: Sequence[Component] = (), **kw):
+ super().__init__(**kw)
+ self.buttons = [m if isinstance(m, Component) else MenuButton(m[0], m[1])
+ for m in menus]
+ self.right = list(right)
+ for c in self.right:
+ c.weight = 0
+ self.add(*self.buttons, *self.right)
+
+
+class Menu:
+ """Open a popup menu from code: ``Menu.show(ctx, owner, items, at=(x, y))``."""
+
+ @staticmethod
+ def show(ctx, owner, items, title: str = None, at=None, on_pick=None) -> None:
+ ctx.open_menu(owner, menu_items(items, on_pick), title, at)
+
+
+class PieMenu:
+ """Radial menu around the pointer: ``PieMenu.show(ctx, items, "Mode")``.
+ Up to 8 items in Blender's order W, E, S, N, NW, NE, SW, SE; move toward
+ an item and click, or press 1-8."""
+
+ @staticmethod
+ def show(ctx, items, title: str = "") -> None:
+ ctx.open_pie(menu_items(items), title or None)
diff --git a/bindings/python/bui/components/templates.py b/bindings/python/bui/components/templates.py
new file mode 100644
index 0000000..7525233
--- /dev/null
+++ b/bindings/python/bui/components/templates.py
@@ -0,0 +1,126 @@
+"""Templates: Blender's composite property layouts, built from C nodes.
+
+* :class:`IDSelector` — ``template_ID``: browse menu, name, fake user,
+ duplicate, unlink.
+* :class:`PathField` — a path with a folder button.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Optional, Sequence
+
+from bui.components.containers import Row
+from bui.components.widgets import Dropdown, IconButton, TextField, Toggle
+
+
+class IDSelector(Row):
+ """Data-block selector: ``IDSelector(["Metal", "Glass"], "Metal",
+ icon="MATERIAL")``."""
+
+ def __init__(self, items: Sequence[str] = (), value: str = None, *,
+ icon: str = "MESH_DATA", fake_user: bool = False,
+ on_change: Optional[Callable[[str], None]] = None,
+ on_new: Optional[Callable[[str], None]] = None,
+ on_unlink: Optional[Callable[[], None]] = None, **kw):
+ self.icon = icon
+ self.on_change, self.on_new, self.on_unlink = on_change, on_new, on_unlink
+ items = list(items)
+ value = value if value is not None else (items[0] if items else "")
+ self.browse = Dropdown("", items, value or None, icons=[icon] * len(items),
+ icon_only=True, on_change=self._picked, weight=0,
+ description="Browse data-blocks")
+ self.name = TextField("", value, on_change=self._renamed, weight=6,
+ description="Data-block name")
+ self.fake_user = Toggle("", fake_user, icon="FAKE_USER_OFF", icon_on="FAKE_USER_ON",
+ weight=0, description="Save this data-block even if it "
+ "has no users")
+ self.new = IconButton("DUPLICATE", self._duplicate, emboss=True, weight=0,
+ description="Duplicate the data-block")
+ self.unlink = IconButton("X", self._unlink, emboss=True, weight=0,
+ description="Unlink the data-block")
+ super().__init__(self.browse, self.name, self.fake_user, self.new, self.unlink,
+ align=True, **kw)
+
+ @property
+ def items(self):
+ return self.browse.items
+
+ @property
+ def value(self) -> str:
+ return self.name.value
+
+ def set_value(self, name: str, notify: bool = True) -> None:
+ self.name.set_value(name, notify=False)
+ if name in self.items:
+ self.browse.set_value(name, notify=False)
+ if notify and self.on_change is not None:
+ self.on_change(name)
+
+ def _set_items(self, items):
+ self.browse.items = items
+ self.browse.set("icons", [self.icon] * len(items))
+
+ def _picked(self, name):
+ self.set_value(name)
+
+ def _renamed(self, new):
+ items, old = self.items, self.browse.value
+ if old in items and new and new not in items:
+ items[items.index(old)] = new
+ self._set_items(items)
+ self.browse.set_value(new, notify=False)
+ if self.on_change is not None:
+ self.on_change(new)
+
+ def _duplicate(self):
+ base, items = self.value or "Data", self.items
+ n = 1
+ while "%s.%03d" % (base, n) in items:
+ n += 1
+ name = "%s.%03d" % (base, n)
+ self._set_items(items + [name])
+ self.set_value(name)
+ if self.on_new is not None:
+ self.on_new(name)
+
+ def _unlink(self):
+ self.name.set_value("", notify=False)
+ if self.on_unlink is not None:
+ self.on_unlink()
+
+
+class PathField(Row):
+ """File path with a folder button (``directory=True`` picks folders).
+ ``on_browse()`` may return a path; without it a native dialog opens."""
+
+ def __init__(self, label: str = "", value: str = "", *, directory: bool = False,
+ on_browse: Optional[Callable[[], Optional[str]]] = None,
+ on_change: Optional[Callable[[str], None]] = None, **kw):
+ self.directory, self.on_browse = directory, on_browse
+ self.field = TextField(label, value, on_change=on_change, weight=8)
+ self.button = IconButton("FILE_FOLDER", self.browse, emboss=True, weight=0,
+ description="Open the file browser")
+ super().__init__(self.field, self.button, align=True, **kw)
+
+ @property
+ def value(self) -> str:
+ return self.field.value
+
+ def set_value(self, path: str, notify: bool = True) -> None:
+ self.field.set_value(path, notify)
+
+ def browse(self) -> None:
+ path = None
+ if self.on_browse is not None:
+ path = self.on_browse()
+ else:
+ try:
+ from tkinter import filedialog
+ path = (filedialog.askdirectory() if self.directory
+ else filedialog.askopenfilename())
+ except Exception: # headless / no tk
+ path = None
+ if path:
+ self.set_value(path)
diff --git a/bindings/python/bui/components/views.py b/bindings/python/bui/components/views.py
new file mode 100644
index 0000000..6c7e7fa
--- /dev/null
+++ b/bindings/python/bui/components/views.py
@@ -0,0 +1,218 @@
+"""Data views (C: ``kit/intern/kit_views.c``): UI list, tree view, grid view.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Optional, Sequence
+
+import buipy
+
+from bui.components.core import (EV_ACTIVATE, EV_CHANGE, EV_RENAME, EV_TOGGLE, Component,
+ ValueComponent)
+
+
+class ListView(ValueComponent):
+ """Blender UI list: wheel scrolls, Ctrl+Wheel / Up / Down select,
+ double-click or F2 renames (``on_rename(index, name)``). Value = index."""
+
+ TYPE = "list"
+
+ def __init__(self, items: Sequence[str] = (), value: int = 0, *, rows: int = 5,
+ on_rename: Optional[Callable[[int, str], None]] = None, icons=None, **kw):
+ Component.__init__(self, **{k: v for k, v in kw.items()
+ if k in ("description", "enabled", "visible", "weight")})
+ self.on_change = kw.get("on_change")
+ self.on_rename = on_rename
+ self.set("rows", rows)
+ self.items = items
+ if icons:
+ self.set("icons", list(icons))
+ self.set("value", value)
+
+ @property
+ def items(self):
+ return self.strs("items")
+
+ @items.setter
+ def items(self, items) -> None:
+ self.set("items", [str(i) for i in items])
+
+ def _load(self):
+ return int(self.get("value"))
+
+ @property
+ def scroll(self) -> int:
+ return int(self.get("scroll"))
+
+ @property
+ def editing(self) -> bool:
+ return bool(self.get("editing"))
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_RENAME and self.on_rename is not None:
+ self.on_rename(int(a), self.items[int(a)])
+ else:
+ super()._on_event(kind, ref, a, b)
+
+
+# Outliner toggle columns: (off, on) icons.
+TOGGLE_ICONS = {
+ "hide": ("HIDE_OFF", "HIDE_ON"),
+ "select": ("RESTRICT_SELECT_OFF", "RESTRICT_SELECT_ON"),
+ "render": ("RESTRICT_RENDER_OFF", "RESTRICT_RENDER_ON"),
+ "lock": ("UNLOCKED", "LOCKED"),
+}
+
+
+class TreeItem(buipy.KitTreeItem):
+ """Tree view item: ``TreeItem("Cube", child, ..., icon=, expanded=,
+ toggles={"hide": False})``."""
+
+ def __init__(self, label: str, *children: "TreeItem", icon: str = None,
+ expanded: bool = True, data=None, toggles: dict = None):
+ super().__init__(label, icon)
+ self.data = data
+ self.toggles = dict(toggles or {})
+ self.set("expanded", 1.0 if expanded else 0.0)
+ self.add(*children)
+
+ def add(self, *items: "TreeItem"):
+ for c in items:
+ buipy.KitTreeItem.add(self, c)
+ return items[0] if len(items) == 1 else self
+
+ @property
+ def expanded(self) -> bool:
+ return bool(self.get("expanded"))
+
+ @expanded.setter
+ def expanded(self, v: bool) -> None:
+ self.set("expanded", 1.0 if v else 0.0)
+
+ def __repr__(self):
+ return "TreeItem(%r)" % self.label
+
+
+def _walk(items):
+ for it in items:
+ yield it
+ yield from _walk(it.children)
+
+
+class TreeView(ValueComponent):
+ """Hierarchical view (outliner): arrows expand (Shift: recursive),
+ Left/Right collapse/expand, double-click/F2 renames, toggle columns
+ (``columns=("hide", "render")``) clicked or dragged down. Value = the
+ selected TreeItem."""
+
+ TYPE = "tree"
+
+ def __init__(self, roots: Sequence[TreeItem] = (), *, rows: int = 8,
+ columns: Sequence[str] = (),
+ on_toggle: Optional[Callable[[TreeItem, str, bool], None]] = None,
+ on_rename: Optional[Callable[[TreeItem, str], None]] = None, **kw):
+ Component.__init__(self, **{k: v for k, v in kw.items()
+ if k in ("description", "enabled", "visible", "weight")})
+ self.on_change = kw.get("on_change")
+ self.on_toggle, self.on_rename = on_toggle, on_rename
+ self.columns = list(columns)
+ self.set("rows", rows)
+ icons = []
+ for c in self.columns:
+ icons.extend(TOGGLE_ICONS.get(c, ("CHECKMARK", "X")))
+ if icons:
+ self.set("icons", icons)
+ self.roots = roots
+
+ @property
+ def roots(self):
+ return list(self._roots)
+
+ @roots.setter
+ def roots(self, roots) -> None:
+ self._roots = list(roots)
+ for it in _walk(self._roots): # push toggle states to C
+ for k, name in enumerate(self.columns):
+ it.set("toggle%d" % k, 1.0 if it.toggles.get(name) else 0.0)
+ self.set_tree_roots(self._roots)
+
+ def _load(self):
+ return self.tree_selected()
+
+ def _store(self, v, notify):
+ self.tree_select(v)
+
+ def _set_default(self, v):
+ pass
+
+ def row_count(self) -> int:
+ return len(self.tree_rows())
+
+ def rows_info(self):
+ """[(item, (x, y, w, h))] of the visible rows."""
+ return self.tree_rows()
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_TOGGLE:
+ name = self.columns[int(a)] if int(a) < len(self.columns) else str(int(a))
+ ref.toggles[name] = bool(b)
+ if self.on_toggle is not None:
+ self.on_toggle(ref, name, bool(b))
+ elif kind == EV_RENAME:
+ item = self.tree_rows()[int(a)][0]
+ if self.on_rename is not None:
+ self.on_rename(item, item.label)
+ elif kind == EV_CHANGE and self.on_change is not None:
+ self.on_change(ref)
+
+
+class GridView(ValueComponent):
+ """Preview tiles: ``items`` are ``(label, preview)`` where preview is an
+ icon name or an RGBA color. Double-click / Return: ``on_activate(i)``."""
+
+ TYPE = "gridview"
+
+ def __init__(self, items: Sequence = (), value: int = 0, *, tile: float = 4.0,
+ rows: float = 2.0, on_activate: Optional[Callable[[int], None]] = None,
+ **kw):
+ Component.__init__(self, **{k: v for k, v in kw.items()
+ if k in ("description", "enabled", "visible", "weight")})
+ self.on_change = kw.get("on_change")
+ self.on_activate = on_activate
+ self.set("tile", tile)
+ self.set("height", rows)
+ self.items = items
+ self.set("value", value)
+
+ @property
+ def items(self):
+ return list(self._items)
+
+ @items.setter
+ def items(self, items) -> None:
+ self._items = [i if isinstance(i, tuple) else (str(i), None) for i in items]
+ self.set("items", [label for label, _ in self._items])
+ self.set("icons", [p if isinstance(p, str) else "" for _, p in self._items])
+ self.set_grid_colors([p if isinstance(p, tuple) else (0, 0, 0, 0)
+ for _, p in self._items])
+
+ def _load(self):
+ return int(self.get("value"))
+
+ def tile_rect(self, i: int):
+ """Tile rect (mirrors the C layout; for tests and tools)."""
+ u = buipy.kit_unit()
+ t = round(self.get("tile") * u)
+ p = round(0.4 * u)
+ cols = max(1, (self.w - p) // (t + p))
+ gap = (self.w - cols * t) / (cols + 1)
+ r, c = divmod(i, cols)
+ return (round(self.x + gap + c * (t + gap)), self.y + p + r * (t + p), t, t)
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_ACTIVATE and self.on_activate is not None:
+ self.on_activate(int(a))
+ else:
+ super()._on_event(kind, ref, a, b)
diff --git a/bindings/python/bui/components/widgets.py b/bindings/python/bui/components/widgets.py
new file mode 100644
index 0000000..53193e0
--- /dev/null
+++ b/bindings/python/bui/components/widgets.py
@@ -0,0 +1,432 @@
+"""Leaf components: labels, buttons, toggles, fields, sliders, enums, colors.
+
+Each class is a C node type (``kit/intern/kit_widgets.c``) with Blender's
+drawing and behavior; Python maps arguments and callbacks.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Optional, Sequence
+
+import buipy
+
+from bui.components.core import EV_CLICK, Component, ValueComponent
+
+
+def eval_number(text: str) -> Optional[float]:
+ """Blender-style number input: ``2*pi``, ``1/3 + 2^2``, ``sqrt(2)``."""
+ return buipy.kit_eval_number(text)
+
+
+# ==========================================================================
+# Static
+
+
+class Label(Component):
+ TYPE = "label"
+
+ def __init__(self, text: str = "", *, icon: str = None, align: str = "left",
+ color=None, bold: bool = False, **kw):
+ super().__init__(**kw)
+ self.set("text", text)
+ if icon:
+ self.set("icon", icon)
+ if align != "left":
+ self.set("text_align", align)
+ if color is not None:
+ self.set("text_color", color)
+ if bold:
+ self.set("bold", True)
+
+ @property
+ def text(self) -> str:
+ return self.get_str("text")
+
+ @text.setter
+ def text(self, s: str) -> None:
+ self.set("text", s)
+
+
+class Separator(Component):
+ """Vertical space (``factor`` widget units), optionally with a line."""
+
+ TYPE = "separator"
+
+ def __init__(self, factor: float = 0.5, line: bool = False, **kw):
+ super().__init__(**kw)
+ self.set("factor", factor)
+ if line:
+ self.set("line", True)
+
+
+class Spacer(Separator):
+ """Empty space that takes its ``weight`` share of a Row."""
+
+ def __init__(self, **kw):
+ super().__init__(1.0, **kw)
+
+
+class ProgressBar(Component):
+ TYPE = "progress"
+
+ def __init__(self, value: float = 0.0, text: Optional[str] = None, **kw):
+ super().__init__(**kw)
+ self.set("factor", value)
+ if text is not None:
+ self.set("text", text)
+
+ @property
+ def value(self) -> float:
+ return self.get("factor")
+
+ def set_value(self, value: float) -> None:
+ self.set("factor", max(0.0, min(1.0, float(value))))
+
+ @property
+ def text(self) -> str:
+ return self.get_str("text")
+
+ @text.setter
+ def text(self, s: str) -> None:
+ self.set("text", s)
+
+
+# ==========================================================================
+# Buttons
+
+
+class Button(Component):
+ """Operator button: ``on_click`` runs when released over it. ``icon``
+ adds a Blender icon; ``emboss=False`` draws it flat."""
+
+ TYPE = "button"
+
+ def __init__(self, text: str = "", on_click: Optional[Callable[[], None]] = None, *,
+ icon: str = None, emboss: bool = True, **kw):
+ super().__init__(**kw)
+ self.on_click = on_click
+ self.set("text", text)
+ if icon:
+ self.set("icon", icon)
+ if not emboss:
+ self.set("emboss", False)
+
+ @property
+ def text(self) -> str:
+ return self.get_str("text")
+
+ @text.setter
+ def text(self, s: str) -> None:
+ self.set("text", s)
+
+ def click(self) -> None:
+ if self.enabled and self.on_click is not None:
+ self.on_click()
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_CLICK and self.on_click is not None:
+ self.on_click()
+
+
+class IconButton(Button):
+ """Icon-only button (flat unless ``emboss=True``)."""
+
+ def __init__(self, icon: str, on_click=None, *, emboss: bool = False, **kw):
+ super().__init__("", on_click, icon=icon, emboss=emboss, **kw)
+
+
+# ==========================================================================
+# Booleans
+
+
+class Checkbox(ValueComponent):
+ """Option box. Press and drag across other toggles to set them all."""
+
+ TYPE = "checkbox"
+
+ def __init__(self, label: str = "", value: bool = False, **kw):
+ super().__init__(label, bool(value), **kw)
+
+ def _store(self, v, notify):
+ self.set("set_value" if notify else "value", 1.0 if v else 0.0)
+
+ def _load(self):
+ return self.get("value") != 0
+
+ def _default(self):
+ return self.get("default") != 0
+
+ def toggle(self) -> None:
+ self.set_value(not self.value)
+
+
+class Toggle(Checkbox):
+ """Button that stays pressed. ``icon``/``icon_on`` for icon toggles,
+ ``emboss=False`` for Blender's flat outliner/header toggles."""
+
+ TYPE = "toggle"
+
+ def __init__(self, label: str = "", value: bool = False, *, icon: str = None,
+ icon_on: str = None, emboss: bool = True, **kw):
+ super().__init__(label, value, **kw)
+ if icon:
+ self.set("icon", icon)
+ if icon_on:
+ self.set("icon_on", icon_on)
+ if not emboss:
+ self.set("emboss", False)
+
+
+class Decorator(Checkbox):
+ """Blender's property decorator: a dot that becomes a keyframe diamond."""
+
+ TYPE = "decorator"
+
+
+# ==========================================================================
+# Numbers
+
+
+class NumberField(ValueComponent):
+ """Blender number field: drag to scrub (cursor hidden, continuous grab;
+ Shift precise, Ctrl snap, Alt all linked), arrows to step, click to type
+ (``2*pi``), Ctrl+Wheel, Ctrl+C/V, Backspace, Minus."""
+
+ TYPE = "number"
+
+ def __init__(self, label: str = "", value=0.0, *, min=None, max=None, step=None,
+ precision=None, integer=None, suffix: str = "", **kw):
+ if integer is None:
+ integer = isinstance(value, int) and not isinstance(value, bool)
+ self._integer = integer
+ Component.__init__(self, **{k: v for k, v in kw.items()
+ if k in ("description", "enabled", "visible", "weight")})
+ if integer:
+ self.set("integer", True)
+ if min is not None:
+ self.set("min", min)
+ if max is not None:
+ self.set("max", max)
+ self.set("step", step if step is not None else (1 if integer else 0.1))
+ self.set("precision", 0 if integer else (3 if precision is None else precision))
+ if suffix:
+ self.set("suffix", suffix)
+ rest = {k: v for k, v in kw.items()
+ if k not in ("description", "enabled", "visible", "weight")}
+ self.on_change = rest.pop("on_change", None)
+ default = rest.pop("default", None)
+ if label:
+ self.set("label", label)
+ self.set("value", value)
+ self.set("default", float(value if default is None else default))
+
+ def _load(self):
+ v = self.get("value")
+ return int(round(v)) if self._integer else v
+
+ def _default(self):
+ return self.get("default")
+
+ @property
+ def editing(self) -> bool:
+ return bool(self.get("editing"))
+
+
+class NumberSlider(NumberField):
+ """Blender number slider: the field fills with the value."""
+
+ TYPE = "slider"
+
+ def __init__(self, label: str = "", value=0.0, *, min=0.0, max=1.0, **kw):
+ super().__init__(label, value, min=min, max=max, **kw)
+
+
+# ==========================================================================
+# Text
+
+
+class TextField(ValueComponent):
+ """Single-line text (Blender's text editing: word jumps with Ctrl,
+ selection, clipboard, double-click word). ``live=True`` reports every
+ keystroke."""
+
+ TYPE = "text"
+
+ def __init__(self, label: str = "", value: str = "", *, placeholder: str = "",
+ icon: str = None, live: bool = False, **kw):
+ Component.__init__(self, **{k: v for k, v in kw.items()
+ if k in ("description", "enabled", "visible", "weight")})
+ self.on_change = kw.get("on_change")
+ if label:
+ self.set("label", label)
+ if placeholder:
+ self.set("placeholder", placeholder)
+ if icon:
+ self.set("icon", icon)
+ if live:
+ self.set("live", True)
+ self.set("value", value or "")
+
+ def _store(self, v, notify):
+ self.set("set_value" if notify else "value", "" if v is None else str(v))
+
+ def _load(self):
+ return self.get_str("value")
+
+ def _default(self):
+ return ""
+
+ @property
+ def editing(self) -> bool:
+ return bool(self.get("editing"))
+
+
+class SearchField(TextField):
+ """Blender search box: magnifier icon, live filtering."""
+
+ TYPE = "search"
+
+ def __init__(self, value: str = "", *, placeholder: str = "Search", **kw):
+ super().__init__("", value, placeholder=placeholder, **kw)
+
+
+class HotkeyField(TextField):
+ """Key binding: click, then press a combination (Esc cancels)."""
+
+ TYPE = "hotkey"
+
+ def __init__(self, label: str = "", value: str = "", **kw):
+ super().__init__(label, value, **kw)
+
+ @property
+ def capturing(self) -> bool:
+ return bool(self.get("editing"))
+
+
+# ==========================================================================
+# Choices
+
+
+def _icon_list(items, icons):
+ if not icons:
+ return None
+ if isinstance(icons, dict):
+ return [icons.get(i) or "" for i in items]
+ return [i or "" for i in icons]
+
+
+class _Choice(ValueComponent):
+ """One of ``items`` (strings); value is the item string."""
+
+ def __init__(self, label: str = "", items: Sequence[str] = (), value=None, *,
+ icons=None, **kw):
+ Component.__init__(self, **{k: v for k, v in kw.items()
+ if k in ("description", "enabled", "visible", "weight")})
+ self.on_change = kw.get("on_change")
+ if label:
+ self.set("label", label)
+ self.set("items", [str(i) for i in items])
+ icon_names = _icon_list(self.items, icons)
+ if icon_names:
+ self.set("icons", icon_names)
+ if value is not None:
+ self._store(value, notify=False)
+ self.set("default", self.get("value"))
+
+ @property
+ def items(self):
+ return self.strs("items")
+
+ @items.setter
+ def items(self, items) -> None:
+ self.set("items", [str(i) for i in items])
+
+ def _store(self, v, notify):
+ items = self.items
+ if v in items:
+ self.set("set_value" if notify else "value", float(items.index(v)))
+
+ def _load(self):
+ items = self.items
+ i = int(self.get("value"))
+ return items[i] if 0 <= i < len(items) else None
+
+ def _default(self):
+ items = self.items
+ i = int(self.get("default"))
+ return items[i] if 0 <= i < len(items) else None
+
+ @property
+ def index(self) -> int:
+ return int(self.get("value"))
+
+
+class Dropdown(_Choice):
+ """Enum menu button: click to open a menu of ``items`` (type to search).
+ ``icon_only=True`` shows just the current item's icon."""
+
+ TYPE = "dropdown"
+
+ def __init__(self, label: str = "", items: Sequence[str] = (), value=None, *,
+ icon_only: bool = False, **kw):
+ super().__init__(label, items, value, **kw)
+ if icon_only:
+ self.set("icon_only", True)
+
+
+class EnumRow(_Choice):
+ """Expanded enum: joined radio buttons. ``vertical=True`` stacks them,
+ ``icon_only=True`` shows only icons."""
+
+ TYPE = "enum"
+
+ def __init__(self, label: str = "", items: Sequence[str] = (), value=None, *,
+ vertical: bool = False, icon_only: bool = False, **kw):
+ super().__init__(label, items, value, **kw)
+ if vertical:
+ self.set("vertical", True)
+ if icon_only:
+ self.set("icon_only", True)
+
+
+# ==========================================================================
+# Color
+
+
+class ColorSwatch(ValueComponent):
+ """RGBA color (0..1). Click opens Blender's color picker (``picker=
+ "circle"`` HSV wheel or ``"square"``) with RGB/HSV/HSL, hex and an
+ eyedropper; Ctrl+C copies hex."""
+
+ TYPE = "swatch"
+
+ def __init__(self, label: str = "", value=(1.0, 1.0, 1.0, 1.0), *,
+ picker: str = "circle", alpha: bool = True, **kw):
+ Component.__init__(self, **{k: v for k, v in kw.items()
+ if k in ("description", "enabled", "visible", "weight")})
+ self.on_change = kw.get("on_change")
+ if label:
+ self.set("label", label)
+ if picker == "square":
+ self.set("square", True)
+ if not alpha:
+ self.set("alpha", False)
+ self._store(value, notify=False)
+
+ def _store(self, v, notify):
+ v = tuple(float(c) for c in v)
+ if len(v) == 3:
+ v += (1.0,)
+ self.set("set_value" if notify else "color", v)
+
+ def _load(self):
+ return self.get_color("color")
+
+ def _default(self):
+ return (0.0, 0.0, 0.0, 1.0)
+
+ @staticmethod
+ def to_text(v) -> str:
+ return "#" + "".join("%02x" % int(round(c * 255)) for c in v)
diff --git a/bindings/python/bui/host.py b/bindings/python/bui/host.py
new file mode 100644
index 0000000..22e8ca3
--- /dev/null
+++ b/bindings/python/bui/host.py
@@ -0,0 +1,304 @@
+"""Window hosts for kit trees.
+
+:class:`Window` shows a ``buipy.KitContext`` in a top-level window:
+
+* **native** (Windows): ``buipy.KitWindow`` — input, layout, rendering and
+ presenting all stay in C; Python only runs callbacks.
+* **tk** (elsewhere, or ``BUI_HOST=tk``): a stdlib Tk window with
+ :class:`bui._surface.TkSurface` blitting the raster.
+
+Both give the same API: ``after``, ``after_cancel``, ``show``, ``close``,
+``title``, ``size``, ``on_close``, ``run`` (one loop for all windows),
+``update`` (pump pending events).
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Callable, Optional
+
+import buipy
+
+from bui import _realtk
+
+from bui.components.core import CURSORS, mods_bits
+
+TK_CURSORS = {None: "", "ew": "sb_h_double_arrow", "ns": "sb_v_double_arrow",
+ "text": "xterm", "crosshair": "crosshair", "hand": "hand2", "move": "fleur",
+ "none": "none"}
+
+
+def native_available() -> bool:
+ return buipy.kit_window_supported() and os.environ.get("BUI_HOST", "").lower() != "tk"
+
+
+class _Scene:
+ """TkSurface scene protocol over a KitContext."""
+
+ def __init__(self, ctx):
+ self.ctx = ctx
+
+ def render(self, w, h):
+ return self.ctx.render(w, h)
+
+ def press(self, x, y, mods):
+ return self.ctx.press(x, y, mods_bits(mods))
+
+ def release(self, x, y, mods):
+ return self.ctx.release(x, y, mods_bits(mods))
+
+ def motion(self, x, y, mods):
+ return self.ctx.motion(x, y, mods_bits(mods))
+
+ def context_menu(self, x, y, mods):
+ return self.ctx.context_menu(x, y, mods_bits(mods))
+
+ def key(self, char, keysym, keycode, mods):
+ return self.ctx.key(char or "", keysym or "", mods_bits(mods))
+
+ def wheel(self, x, y, delta, mods):
+ return self.ctx.wheel(x, y, delta, mods_bits(mods))
+
+ def key_release(self, keysym, mods):
+ return self.ctx.key_release(keysym or "", mods_bits(mods))
+
+ def button(self, x, y, button, release, mods):
+ return self.ctx.button(x, y, button, release, mods_bits(mods))
+
+
+_tk_root = None # one hidden Tk interpreter shared by all tk-hosted windows
+_windows = []
+
+
+def _tk():
+ global _tk_root
+ tk = _realtk.module()
+ if _tk_root is None:
+ _tk_root = tk.Tk()
+ _tk_root.withdraw()
+ return _tk_root
+
+
+class Window:
+ def __init__(self, ctx, title: str = "BUI", size=(640, 480), native: bool = None):
+ self.ctx = ctx
+ self._title, self._size = title, tuple(size)
+ self.native = native_available() if native is None else native
+ self.on_close: Optional[Callable[[], object]] = None
+ self._closed = False
+ self._win = None
+ self._top = self._surface = None
+ if self.native:
+ self._win = buipy.KitWindow(ctx, title, *self._size)
+ self._win.on_close = self._close_requested
+ else:
+ self._make_tk()
+ _windows.append(self)
+
+ # -- tk host ----------------------------------------------------------------
+ def _make_tk(self):
+ tk = _realtk.module()
+
+ from bui._surface import TkSurface
+ top = tk.Toplevel(_tk())
+ top.title(self._title)
+ top.geometry("%dx%d" % self._size)
+ top.configure(bg="#303030")
+ top.protocol("WM_DELETE_WINDOW", self._tk_close)
+ top.withdraw()
+ surface = TkSurface(top, _Scene(self.ctx), width=self._size[0], height=self._size[1])
+ surface.size_hint = self._size
+ widget = surface.widget
+
+ def set_cursor(cid):
+ try:
+ widget.configure(cursor=TK_CURSORS.get(CURSORS[cid], ""))
+ except tk.TclError:
+ pass
+
+ def warp(x, y):
+ try:
+ widget.event_generate("<Motion>", warp=True, x=x, y=y)
+ except tk.TclError:
+ pass
+
+ def set_clip(text):
+ top.clipboard_clear()
+ top.clipboard_append(text)
+
+ def schedule(ms, timer_id):
+ def fire():
+ self.ctx.timer(timer_id)
+ surface.request()
+ top.after(ms, fire)
+
+ self.ctx.set_host(request=surface.request, cursor=set_cursor, warp=warp,
+ clipboard_get=top.clipboard_get, clipboard_set=set_clip,
+ schedule=schedule)
+ self._top, self._surface = top, surface
+
+ def _tk_close(self):
+ if self._close_requested():
+ self.close()
+
+ def _close_requested(self):
+ if self.on_close is not None:
+ return bool(self.on_close())
+ return True
+
+ # -- API --------------------------------------------------------------------------
+ def show(self) -> None:
+ if self.native:
+ self._win.show()
+ else:
+ self._top.deiconify()
+ self._surface.request()
+
+ def close(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ if self.native:
+ self._win.close()
+ elif self._top is not None:
+ try:
+ self._top.destroy()
+ except Exception:
+ pass
+ if self in _windows:
+ _windows.remove(self)
+ if not self.native and not _windows and _tk_root is not None:
+ _tk_root.quit()
+
+ @property
+ def is_open(self) -> bool:
+ if self.native:
+ return self._win.is_open()
+ return not self._closed
+
+ def title(self, text: str = None):
+ if text is None:
+ return self._title
+ self._title = text
+ if self.native:
+ self._win.set_title(text)
+ else:
+ self._top.title(text)
+
+ def set_size(self, w: int, h: int) -> None:
+ self._size = (w, h)
+ if self.native:
+ self._win.set_size(w, h)
+ else:
+ self._top.geometry("%dx%d" % (w, h))
+ self._surface.size_hint = (w, h)
+
+ @property
+ def size(self):
+ if self.native:
+ s = self._win.size
+ return s if s[0] > 1 else self._size
+ return self._surface.size()
+
+ def after(self, ms: int, fn: Callable[[], None]):
+ if self.native:
+ return self._win.after(int(ms), fn)
+ return self._top.after(int(ms), fn)
+
+ def after_cancel(self, ident) -> None:
+ if self.native:
+ self._win.after_cancel(ident)
+ else:
+ self._top.after_cancel(ident)
+
+ def request(self) -> None:
+ """Ask for a redraw (the kit also does this on every change)."""
+ if not self.native and self._surface is not None:
+ self._surface.request()
+
+ def render_now(self) -> None:
+ if self.native:
+ self._win.render_now()
+ else:
+ self._surface.render()
+
+ @property
+ def frames(self) -> int:
+ return self._win.frames if self.native else self._surface.frames
+
+ def pixel(self, x: int, y: int):
+ if self.native:
+ return self._win.pixel(x, y)
+ return self._surface.raster.pixel(x, y)
+
+ # -- window manager (Tk's wm) ---------------------------------------------------
+ _TK_STATES = ("normal", "iconic", "withdrawn", "zoomed")
+
+ def wm(self, key: str, a: float = 0.0, b: float = 0.0) -> None:
+ """Window-manager request: pos, minsize, maxsize, resizable, topmost,
+ alpha, override, state (0 normal, 1 iconic, 2 withdrawn, 3 zoomed),
+ lift, lower, focus."""
+ if self.native:
+ self._win.wm(key, float(a), float(b))
+ return
+ t = self._top
+ actions = {
+ "pos": lambda: t.geometry("+%d+%d" % (a, b)),
+ "minsize": lambda: t.minsize(int(a), int(b)),
+ "maxsize": lambda: t.maxsize(int(a) or 100000, int(b) or 100000),
+ "resizable": lambda: t.resizable(bool(a), bool(b)),
+ "topmost": lambda: t.attributes("-topmost", bool(a)),
+ "alpha": lambda: t.attributes("-alpha", float(a)),
+ "override": lambda: t.overrideredirect(bool(a)),
+ "state": lambda: t.state(self._TK_STATES[int(a)]),
+ "lift": t.lift, "lower": t.lower, "focus": t.focus_force,
+ }
+ try:
+ actions[key]()
+ except Exception: # e.g. "zoomed" on X11
+ pass
+
+ def wm_get(self, key: str):
+ """(a, b) for pos, state, screen, pointer, scale; None if unknown."""
+ if self.native:
+ return self._win.wm_get(key)
+ t = self._top
+ values = {
+ "pos": lambda: (t.winfo_rootx(), t.winfo_rooty()),
+ "state": lambda: (self._TK_STATES.index(t.state()), 0),
+ "screen": lambda: (t.winfo_screenwidth(), t.winfo_screenheight()),
+ "pointer": lambda: t.winfo_pointerxy(),
+ "scale": lambda: (1.0, 0.0),
+ }
+ try:
+ return tuple(float(v) for v in values[key]())
+ except Exception:
+ return None
+
+ @property
+ def handle(self):
+ return self._win.hwnd if self.native else self._top.winfo_id()
+
+
+def run() -> None:
+ """Run the event loop until every window is closed."""
+ if any(w.native for w in _windows):
+ buipy.kit_run()
+ if any(not w.native for w in _windows) and _tk_root is not None:
+ _tk_root.mainloop()
+
+
+def update() -> None:
+ """Handle pending events and redraws once (like tkinter's update())."""
+ if any(w.native for w in _windows):
+ buipy.kit_pump()
+ if _tk_root is not None:
+ _tk_root.update()
+
+
+def quit() -> None: # noqa: A001 - tkinter-style name
+ buipy.kit_quit()
+ if _tk_root is not None:
+ _tk_root.quit()
diff --git a/bindings/python/bui/qt.py b/bindings/python/bui/qt.py
new file mode 100644
index 0000000..fb2dbec
--- /dev/null
+++ b/bindings/python/bui/qt.py
@@ -0,0 +1,178 @@
+"""Embed BUI in a Qt application with PySide6 or PyQt6 — pure Python.
+
+The widget installs a QPainter backend into buipy, so everything the BUI
+toolkit draws is rendered by Qt. No C++ compilation or shiboken tooling needed.
+
+ import sys
+ from PySide6.QtWidgets import QApplication
+ import buipy
+ from bui.qt import BuiCanvas
+
+ app = QApplication(sys.argv)
+ canvas = BuiCanvas()
+ canvas.resize(800, 600)
+ canvas.show()
+ sys.exit(app.exec())
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import buipy
+from bui import Backend
+
+try:
+ from PySide6.QtCore import QPointF, QRectF, Qt, QTimer
+ from PySide6.QtGui import QColor, QFont, QImage, QPainter, QPen, QPolygonF
+ from PySide6.QtWidgets import QApplication, QWidget
+
+ QT_BACKEND = "PySide6"
+except ImportError: # pragma: no cover - PyQt6 fallback
+ from PyQt6.QtCore import QPointF, QRectF, Qt, QTimer
+ from PyQt6.QtGui import QColor, QFont, QImage, QPainter, QPen, QPolygonF
+ from PyQt6.QtWidgets import QApplication, QWidget
+
+ QT_BACKEND = "PyQt6"
+
+
+def _qcolor(color) -> QColor:
+ r, g, b, a = (int(max(0.0, min(1.0, c)) * 255 + 0.5) for c in color)
+ return QColor(r, g, b, a)
+
+
+class QtPainterBackend(Backend):
+ """Draws BUI primitives with a live QPainter.
+
+ Per-vertex colors are reduced to the first vertex color of each primitive;
+ toolkit primitives are solid-color per shape in practice.
+ """
+
+ def __init__(self, painter: QPainter):
+ self._p = painter
+
+ def triangles(self, coords, colors) -> None:
+ painter = self._p
+ painter.setPen(Qt.PenStyle.NoPen)
+ for i in range(0, len(coords), 3):
+ painter.setBrush(_qcolor(colors[i]))
+ painter.drawPolygon(
+ QPolygonF([QPointF(*coords[i]), QPointF(*coords[i + 1]), QPointF(*coords[i + 2])])
+ )
+
+ def lines(self, coords, colors) -> None:
+ painter = self._p
+ for i in range(0, len(coords), 2):
+ painter.setPen(QPen(_qcolor(colors[i]), 1))
+ painter.drawLine(int(coords[i][0]), int(coords[i][1]),
+ int(coords[i + 1][0]), int(coords[i + 1][1]))
+
+ def points(self, coords, colors, size) -> None:
+ painter = self._p
+ painter.setPen(Qt.PenStyle.NoPen)
+ d = max(1.0, size)
+ for (x, y), color in zip(coords, colors):
+ painter.setBrush(_qcolor(color))
+ painter.drawEllipse(QRectF(x - d / 2, y - d / 2, d, d))
+
+ def text(self, x, y, text, size, color) -> None:
+ painter = self._p
+ painter.setPen(QPen(_qcolor(color), 1))
+ f = painter.font()
+ f.setPixelSize(max(1, int(size)))
+ painter.setFont(f)
+ painter.drawText(int(x), int(y), text)
+
+
+class BuiCanvas(QWidget):
+ """A QWidget that renders BUI through the native raster.
+
+ Each paint renders the whole UI into one ``buipy.Raster`` frame in C and
+ draws it with a single ``QPainter.drawImage`` — the per-primitive
+ QPainter path (``QtPainterBackend``) remains available for custom use.
+
+ Subclass (or set ``render_func``) to emit BUI draw calls; the default
+ renders the toolkit's demo scene. Event hooks (``on_press``,
+ ``on_release``, ``on_motion``, ``on_key``) let hosts forward input into
+ the widget model — bui.qtsyntax wires these automatically.
+ """
+
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self.render_func = None # Optional[Callable[[], None]]
+ self.on_press = None # Optional[Callable[[int, int], None]]
+ self.on_release = None # Optional[Callable[[int, int], None]]
+ self.on_motion = None # Optional[Callable[[int, int(, bool)], None]]
+ self.on_key = None # Optional[Callable[[str, int], None]]
+ self.setMinimumSize(200, 150)
+ self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
+ self.setMouseTracking(True)
+ # We paint every pixel ourselves: skip Qt's background fill.
+ self.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent, True)
+ self._raster = buipy.Raster(1, 1)
+ self._image_bytes = None # keeps QImage's buffer alive while painting
+
+ # -- Qt events ---------------------------------------------------------
+ def paintEvent(self, event): # noqa: N802 (Qt naming)
+ w, h = max(1, self.width()), max(1, self.height())
+ buipy.set_backend(self._raster)
+ try:
+ buipy.begin_frame(w, h) # sizes the raster even if render_func doesn't
+ if self.render_func is not None:
+ self.render_func()
+ else:
+ buipy.demo_scene(w, h)
+ buipy.end_frame()
+ finally:
+ buipy.set_backend(None)
+ rw, rh = self._raster.size
+ self._image_bytes = self._raster.rgb32()
+ image = QImage(self._image_bytes, rw, rh, rw * 4, QImage.Format.Format_RGB32)
+ painter = QPainter(self)
+ try:
+ painter.drawImage(0, 0, image)
+ runs = self._raster.text_runs()
+ if runs: # platforms without a native text engine
+ for x, y, text, size, rgba, family, flags in runs:
+ font = QFont(family) if family else QFont()
+ font.setPixelSize(max(1, int(size)))
+ font.setBold(bool(flags & 1))
+ font.setItalic(bool(flags & 2))
+ font.setUnderline(bool(flags & 4))
+ painter.setFont(font)
+ painter.setPen(QPen(_qcolor(rgba), 1))
+ painter.drawText(QPointF(x, y), text)
+ finally:
+ painter.end()
+
+ def resizeEvent(self, event): # noqa: N802 (Qt naming)
+ buipy.set_viewport(event.size().width(), event.size().height())
+ super().resizeEvent(event)
+
+ def mousePressEvent(self, event): # noqa: N802 (Qt naming)
+ if self.on_press:
+ self.on_press(event.position().x(), event.position().y())
+ super().mousePressEvent(event)
+
+ def mouseReleaseEvent(self, event): # noqa: N802 (Qt naming)
+ if self.on_release:
+ self.on_release(event.position().x(), event.position().y())
+ super().mouseReleaseEvent(event)
+
+ def mouseMoveEvent(self, event): # noqa: N802 (Qt naming)
+ if self.on_motion:
+ held = bool(event.buttons() & Qt.MouseButton.LeftButton)
+ try:
+ self.on_motion(event.position().x(), event.position().y(), held)
+ except TypeError: # legacy 2-argument hook
+ self.on_motion(event.position().x(), event.position().y())
+ super().mouseMoveEvent(event)
+
+ def keyPressEvent(self, event): # noqa: N802 (Qt naming)
+ if self.on_key:
+ self.on_key(event.text(), event.key())
+ super().keyPressEvent(event)
+
+ def request_update(self) -> None:
+ """Schedule a repaint; Qt coalesces repeated requests into one."""
+ self.update()
diff --git a/bindings/python/bui/qtsyntax.py b/bindings/python/bui/qtsyntax.py
new file mode 100644
index 0000000..a02764b
--- /dev/null
+++ b/bindings/python/bui/qtsyntax.py
@@ -0,0 +1,2767 @@
+"""BUI with Qt syntax — Qt's widget API on the C kit.
+
+Every QWidget is a kit node; QBoxLayout / QGridLayout / QFormLayout run on
+the kit's C geometry managers, ``paintEvent`` + QPainter record into a kit
+canvas, and top-level windows are native (Windows) or Tk (:mod:`bui.host`).
+Signals, timers and animations are plain Python (as in PySide's Python
+layer)::
+
+ from bui.qtsyntax import QApplication, QWidget, QPushButton, QVBoxLayout
+
+ app = QApplication([])
+ w = QWidget()
+ layout = QVBoxLayout(w)
+ button = QPushButton("Click me")
+ button.clicked.connect(lambda: print("clicked"))
+ layout.addWidget(button)
+ w.show()
+ app.exec()
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Callable, List, Optional
+
+import buipy
+
+from bui import _realtk, host
+from bui.components.core import (EV_ACTIVATE, EV_CHANGE, EV_CLICK, EV_DOUBLE, EV_ENTER, # noqa: F401
+ EV_KEY, EV_LEAVE, EV_MOTION, EV_PRESS, EV_RELEASE,
+ EV_RENAME, EV_SUBMIT, EV_TOGGLE, EV_WHEEL)
+from bui.components.menus import MenuItem
+from bui.tksyntax import PhotoImage, color as _tk_color
+
+PACK, GRID, PLACE = 1, 2, 3
+N, S, W, E = 1, 2, 4, 8
+
+
+# ==========================================================================
+# Namespace and value types
+
+
+class Qt:
+ AlignLeft, AlignRight, AlignHCenter, AlignJustify = 0x1, 0x2, 0x4, 0x8
+ AlignTop, AlignBottom, AlignVCenter = 0x20, 0x40, 0x80
+ AlignCenter = AlignHCenter | AlignVCenter
+ Horizontal, Vertical = 1, 2
+ Unchecked, PartiallyChecked, Checked = 0, 1, 2
+ NoPen, NoBrush = "nopen", "nobrush"
+ LeftButton, RightButton, MiddleButton = 1, 2, 4
+ NoModifier, ShiftModifier, ControlModifier, AltModifier = 0, 0x02000000, 0x04000000, \
+ 0x08000000
+ Key_Return, Key_Enter, Key_Escape, Key_Tab, Key_Backspace, Key_Delete = \
+ 0x01000004, 0x01000005, 0x01000000, 0x01000001, 0x01000003, 0x01000007
+ Key_Left, Key_Up, Key_Right, Key_Down, Key_Home, Key_End = \
+ 0x01000012, 0x01000013, 0x01000014, 0x01000015, 0x01000010, 0x01000011
+ Key_Space = 0x20
+ WA_DeleteOnClose = 55
+ ScrollBarAlwaysOff, ScrollBarAsNeeded = 1, 0
+ ItemIsEditable, ItemIsSelectable, ItemIsEnabled = 2, 1, 32
+ DisplayRole, UserRole = 0, 256
+ white, black, red, green, blue, gray = "#ffffff", "#000000", "#ff0000", "#00ff00", \
+ "#0000ff", "#808080"
+
+
+for _c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
+ setattr(Qt, "Key_" + _c, ord(_c))
+for _d in range(10):
+ setattr(Qt, "Key_%d" % _d, ord(str(_d)))
+
+_KEYSYM_TO_QT = {"Return": Qt.Key_Return, "KP_Enter": Qt.Key_Enter, "Escape": Qt.Key_Escape,
+ "Tab": Qt.Key_Tab, "BackSpace": Qt.Key_Backspace, "Delete": Qt.Key_Delete,
+ "Left": Qt.Key_Left, "Up": Qt.Key_Up, "Right": Qt.Key_Right,
+ "Down": Qt.Key_Down, "Home": Qt.Key_Home, "End": Qt.Key_End,
+ "space": Qt.Key_Space}
+
+
+class Signal:
+ """Qt signal: ``clicked = Signal()`` on a class, then
+ ``obj.clicked.connect(fn)`` / ``.emit(...)``."""
+
+ def __init__(self, *types, name=None):
+ self._types = types
+ self._name = None
+
+ def __set_name__(self, owner, name):
+ self._name = "_sig_" + name
+
+ def __get__(self, obj, owner=None):
+ if obj is None:
+ return self
+ bound = obj.__dict__.get(self._name)
+ if bound is None:
+ bound = BoundSignal(self._types)
+ obj.__dict__[self._name] = bound
+ return bound
+
+
+Signal_ = pyqtSignal = Signal
+
+
+class BoundSignal:
+ def __init__(self, types=()):
+ self._slots: List[Callable] = []
+ self._types = types
+
+ def connect(self, slot):
+ self._slots.append(slot)
+ return slot
+
+ def disconnect(self, slot=None):
+ if slot is None:
+ self._slots.clear()
+ elif slot in self._slots:
+ self._slots.remove(slot)
+
+ def emit(self, *args):
+ for slot in list(self._slots):
+ try:
+ slot(*args)
+ except TypeError:
+ # Qt drops extra signal arguments a slot does not take
+ if args:
+ slot(*args[:max(0, _arity(slot))])
+ else:
+ raise
+
+
+def _arity(fn) -> int:
+ import inspect
+ try:
+ return len([p for p in inspect.signature(fn).parameters.values()
+ if p.default is p.empty and p.kind in (p.POSITIONAL_ONLY,
+ p.POSITIONAL_OR_KEYWORD)])
+ except (TypeError, ValueError):
+ return 0
+
+
+class QColor:
+ def __init__(self, *args):
+ if len(args) == 1 and isinstance(args[0], QColor):
+ self._rgba = args[0]._rgba
+ elif len(args) == 1:
+ c = _tk_color(args[0]) or (0, 0, 0, 1)
+ self._rgba = tuple(c)
+ elif len(args) >= 3:
+ a = args[3] if len(args) > 3 else 255
+ self._rgba = (args[0] / 255.0, args[1] / 255.0, args[2] / 255.0, a / 255.0)
+ else:
+ self._rgba = (0.0, 0.0, 0.0, 1.0)
+
+ @staticmethod
+ def fromRgb(r, g, b, a=255): # noqa: N802
+ return QColor(r, g, b, a)
+
+ def red(self):
+ return round(self._rgba[0] * 255)
+
+ def green(self):
+ return round(self._rgba[1] * 255)
+
+ def blue(self):
+ return round(self._rgba[2] * 255)
+
+ def alpha(self):
+ return round(self._rgba[3] * 255)
+
+ def setAlpha(self, a): # noqa: N802
+ self._rgba = self._rgba[:3] + (a / 255.0,)
+
+ def name(self):
+ return "#%02x%02x%02x" % (self.red(), self.green(), self.blue())
+
+ def lighter(self, f=150):
+ k = f / 100.0
+ return QColor(*(min(255, round(c * 255 * k)) for c in self._rgba[:3]), self.alpha())
+
+ def darker(self, f=200):
+ k = 100.0 / f
+ return QColor(*(round(c * 255 * k) for c in self._rgba[:3]), self.alpha())
+
+ def rgba(self):
+ return self._rgba
+
+
+def _rgba(c):
+ if c is None or c in (Qt.NoPen, Qt.NoBrush):
+ return None
+ if isinstance(c, QColor):
+ return c._rgba
+ if isinstance(c, (QPen, QBrush)):
+ return _rgba(c._color)
+ return QColor(c)._rgba
+
+
+class QPen:
+ def __init__(self, color=None, width=1, *args):
+ self._color = color if color is not None else QColor("#000000")
+ self._width = width
+
+ def setWidth(self, w): # noqa: N802
+ self._width = w
+
+ def setColor(self, c): # noqa: N802
+ self._color = c
+
+ def color(self):
+ return QColor(self._color) if not isinstance(self._color, QColor) else self._color
+
+
+class QBrush:
+ def __init__(self, color=None, *args):
+ self._color = color
+
+ def color(self):
+ return QColor(self._color) if not isinstance(self._color, QColor) else self._color
+
+
+class QFont:
+ Bold, Normal = 75, 50
+
+ def __init__(self, family="", size=-1, weight=-1, italic=False):
+ self._family, self._size, self._bold = family, size, weight >= 75
+
+ def setPointSize(self, s): # noqa: N802
+ self._size = s
+
+ def pointSize(self): # noqa: N802
+ return self._size
+
+ def setPixelSize(self, s): # noqa: N802
+ self._size = s * 0.75
+
+ def setBold(self, b): # noqa: N802
+ self._bold = bool(b)
+
+ def bold(self):
+ return self._bold
+
+ def setFamily(self, f): # noqa: N802
+ self._family = f
+
+
+class QPoint:
+ def __init__(self, x=0, y=0):
+ self._x, self._y = int(x), int(y)
+
+ def x(self):
+ return self._x
+
+ def y(self):
+ return self._y
+
+
+QPointF = QPoint
+
+
+class QSize:
+ def __init__(self, w=0, h=0):
+ self._w, self._h = int(w), int(h)
+
+ def width(self):
+ return self._w
+
+ def height(self):
+ return self._h
+
+
+class QRect:
+ def __init__(self, x=0, y=0, w=0, h=0):
+ self._x, self._y, self._w, self._h = int(x), int(y), int(w), int(h)
+
+ def x(self):
+ return self._x
+
+ def y(self):
+ return self._y
+
+ def width(self):
+ return self._w
+
+ def height(self):
+ return self._h
+
+ left, top = x, y
+
+ def right(self):
+ return self._x + self._w - 1
+
+ def bottom(self):
+ return self._y + self._h - 1
+
+ def center(self):
+ return QPoint(self._x + self._w // 2, self._y + self._h // 2)
+
+ def contains(self, p, y=None):
+ px, py = (p.x(), p.y()) if y is None else (p, y)
+ return self._x <= px < self._x + self._w and self._y <= py < self._y + self._h
+
+ def adjusted(self, dx1, dy1, dx2, dy2):
+ return QRect(self._x + dx1, self._y + dy1, self._w - dx1 + dx2, self._h - dy1 + dy2)
+
+
+QRectF = QRect
+
+
+class QPixmap:
+ """Image backed by RGBA pixels (shared with tksyntax.PhotoImage)."""
+
+ def __init__(self, *args):
+ if args and isinstance(args[0], str):
+ self._img = PhotoImage(file=args[0])
+ elif len(args) >= 2:
+ self._img = PhotoImage(width=int(args[0]), height=int(args[1]))
+ elif args and isinstance(args[0], QSize):
+ self._img = PhotoImage(width=args[0].width(), height=args[0].height())
+ else:
+ self._img = PhotoImage(width=0, height=0)
+
+ def width(self):
+ return self._img.width()
+
+ def height(self):
+ return self._img.height()
+
+ def isNull(self): # noqa: N802
+ return self._img.width() == 0
+
+ def fill(self, c=None):
+ rgba = bytes(round(v * 255) for v in (_rgba(c) or (1, 1, 1, 1)))
+ self._img._px = bytearray(rgba * (self._img.width() * self._img.height()))
+
+ def load(self, path):
+ self._img = PhotoImage(file=path)
+ return True
+
+
+QImage = QPixmap
+
+
+class QIcon:
+ def __init__(self, *args):
+ self.name = args[0] if args else ""
+
+
+# ==========================================================================
+# Events
+
+
+class QEvent:
+ def __init__(self, kind=0):
+ self._type, self._accepted = kind, True
+
+ def type(self):
+ return self._type
+
+ def accept(self):
+ self._accepted = True
+
+ def ignore(self):
+ self._accepted = False
+
+ def isAccepted(self): # noqa: N802
+ return self._accepted
+
+
+class QCloseEvent(QEvent):
+ pass
+
+
+class QPaintEvent(QEvent):
+ def __init__(self, rect):
+ super().__init__()
+ self._rect = rect
+
+ def rect(self):
+ return self._rect
+
+
+class QMouseEvent(QEvent):
+ def __init__(self, x, y, button=Qt.LeftButton, modifiers=0):
+ super().__init__()
+ self._x, self._y, self._button, self._mods = int(x), int(y), button, modifiers
+
+ def pos(self):
+ return QPoint(self._x, self._y)
+
+ position = pos
+
+ def x(self):
+ return self._x
+
+ def y(self):
+ return self._y
+
+ def button(self):
+ return self._button
+
+ def modifiers(self):
+ return self._mods
+
+
+class QKeyEvent(QEvent):
+ def __init__(self, key, text="", modifiers=0):
+ super().__init__()
+ self._key, self._text, self._mods = key, text, modifiers
+
+ def key(self):
+ return self._key
+
+ def text(self):
+ return self._text
+
+ def modifiers(self):
+ return self._mods
+
+
+class QWheelEvent(QEvent):
+ def __init__(self, delta):
+ super().__init__()
+ self._delta = delta
+
+ def angleDelta(self): # noqa: N802
+ return QPoint(0, self._delta)
+
+
+def _mods_qt(bits):
+ return ((Qt.ShiftModifier if bits & 1 else 0) | (Qt.ControlModifier if bits & 2 else 0)
+ | (Qt.AltModifier if bits & 4 else 0))
+
+
+# ==========================================================================
+# QApplication, timers
+
+
+class QApplication:
+ _instance: Optional["QApplication"] = None
+
+ def __init__(self, argv=None):
+ QApplication._instance = self
+ self._windows: list = []
+
+ @staticmethod
+ def instance():
+ return QApplication._instance
+
+ def exec(self) -> int:
+ for w in list(_pending_show):
+ w._open()
+ _pending_show.clear()
+ _timers.flush()
+ host.run()
+ return 0
+
+ exec_ = exec
+
+ def quit(self) -> None:
+ host.quit()
+
+ exit = quit
+
+ @staticmethod
+ def processEvents(): # noqa: N802
+ _timers.flush()
+ host.update()
+
+ def setStyle(self, *a): # noqa: N802
+ pass
+
+ setStyleSheet = setApplicationName = setStyle
+
+
+QCoreApplication = QApplication
+
+
+class _TimerService:
+ """Timers run on a top-level window's clock; until one exists they wait."""
+
+ def __init__(self):
+ self.queue = []
+
+ def window(self):
+ for w in host._windows:
+ if w.is_open:
+ return w
+ return None
+
+ def after(self, ms, fn):
+ win = self.window()
+ if win is None:
+ self.queue.append((ms, fn))
+ return ("q", fn)
+ return ("w", win, win.after(int(ms), fn))
+
+ def cancel(self, token):
+ if token is None:
+ return
+ if token[0] == "q":
+ self.queue = [(m, f) for m, f in self.queue if f is not token[1]]
+ else:
+ try:
+ token[1].after_cancel(token[2])
+ except Exception:
+ pass
+
+ def flush(self):
+ win = self.window()
+ if win is None:
+ return
+ queue, self.queue = self.queue, []
+ for ms, fn in queue:
+ win.after(int(ms), fn)
+
+
+_timers = _TimerService()
+
+
+class QTimer:
+ timeout = Signal()
+
+ def __init__(self, parent=None):
+ self._interval, self._single, self._token = 0, False, None
+
+ @staticmethod
+ def singleShot(ms, fn): # noqa: N802
+ _timers.after(ms, fn)
+
+ def setInterval(self, ms): # noqa: N802
+ self._interval = int(ms)
+
+ def interval(self):
+ return self._interval
+
+ def setSingleShot(self, b): # noqa: N802
+ self._single = bool(b)
+
+ def isActive(self): # noqa: N802
+ return self._token is not None
+
+ def start(self, ms=None):
+ if ms is not None:
+ self._interval = int(ms)
+ self.stop()
+ self._token = _timers.after(self._interval, self._fire)
+
+ def stop(self):
+ _timers.cancel(self._token)
+ self._token = None
+
+ def _fire(self):
+ self._token = None
+ if not self._single:
+ self._token = _timers.after(max(1, self._interval), self._fire)
+ self.timeout.emit()
+
+
+class QEasingCurve:
+ Linear, InOutQuad, OutCubic, InQuad, OutQuad = range(5)
+
+ def __init__(self, kind=0):
+ self._kind = kind
+
+ def valueForProgress(self, t): # noqa: N802
+ k = self._kind
+ if k == QEasingCurve.InOutQuad:
+ return 2 * t * t if t < 0.5 else 1 - (-2 * t + 2) ** 2 / 2
+ if k == QEasingCurve.OutCubic:
+ return 1 - (1 - t) ** 3
+ if k == QEasingCurve.InQuad:
+ return t * t
+ if k == QEasingCurve.OutQuad:
+ return 1 - (1 - t) ** 2
+ return t
+
+
+class QPropertyAnimation:
+ finished = Signal()
+ valueChanged = Signal(object)
+
+ def __init__(self, target=None, prop=b"", parent=None):
+ self._target = target
+ self._prop = prop.decode() if isinstance(prop, bytes) else prop
+ self._start = self._end = 0
+ self._duration = 250
+ self._easing = QEasingCurve()
+ self._running = False
+ self._timer = QTimer()
+ self._timer.setInterval(8) # 120 Hz
+ self._timer.timeout.connect(self._tick)
+
+ def setTargetObject(self, o): # noqa: N802
+ self._target = o
+
+ def setPropertyName(self, name): # noqa: N802
+ self._prop = name.decode() if isinstance(name, bytes) else name
+
+ def setStartValue(self, v): # noqa: N802
+ self._start = v
+
+ def setEndValue(self, v): # noqa: N802
+ self._end = v
+
+ def setDuration(self, ms): # noqa: N802
+ self._duration = max(1, int(ms))
+
+ def setEasingCurve(self, e): # noqa: N802
+ self._easing = e if isinstance(e, QEasingCurve) else QEasingCurve(e)
+
+ def start(self):
+ self._t0 = time.perf_counter()
+ self._running = True
+ self._apply(self._start)
+ self._timer.start()
+
+ def stop(self):
+ self._running = False
+ self._timer.stop()
+
+ def state(self):
+ return 2 if self._running else 0
+
+ def _apply(self, v):
+ setter = getattr(self._target, "set" + self._prop[:1].upper() + self._prop[1:], None)
+ if callable(setter):
+ setter(v)
+ else:
+ setattr(self._target, self._prop, v)
+ self.valueChanged.emit(v)
+
+ def _tick(self):
+ t = min(1.0, (time.perf_counter() - self._t0) * 1000 / self._duration)
+ k = self._easing.valueForProgress(t)
+ if isinstance(self._start, (int, float)):
+ v = self._start + (self._end - self._start) * k
+ if isinstance(self._start, int) and isinstance(self._end, int):
+ v = round(v)
+ else:
+ v = self._end if t >= 1 else self._start
+ self._apply(v)
+ if t >= 1.0:
+ self.stop()
+ self.finished.emit()
+
+
+# ==========================================================================
+# QWidget
+
+_pending_show: list = []
+
+
+def _kids(node):
+ return buipy.KitNode.children.__get__(node)
+
+_EVENT_METHODS = ("mousePressEvent", "mouseReleaseEvent", "mouseMoveEvent",
+ "mouseDoubleClickEvent", "keyPressEvent", "wheelEvent", "enterEvent",
+ "leaveEvent")
+
+
+class QWidget(buipy.KitNode):
+ KIND = "frame"
+
+ def __init__(self, parent=None, *args, **kw):
+ cls = type(self)
+ custom_paint = cls.paintEvent is not QWidget.paintEvent
+ super().__init__("canvas" if custom_paint and self.KIND == "frame" else self.KIND)
+ self._custom_paint = custom_paint
+ self._layout = None
+ self._title = ""
+ self._size = None
+ self._window = None
+ self._ctx = None
+ self._policy = None
+ self._menubar = None
+ self._painted_size = None
+ if custom_paint:
+ self.set("bg", (0, 0, 0, 0))
+ if any(getattr(cls, m) is not getattr(QWidget, m) for m in _EVENT_METHODS):
+ self.set("events", True)
+ self._setup()
+ if parent is not None:
+ self.setParent(parent)
+
+ def _setup(self):
+ pass
+
+ @property
+ def _parent_widget(self):
+ p = buipy.KitNode.parent.__get__(self)
+ while p is not None and not isinstance(p, QWidget):
+ p = buipy.KitNode.parent.__get__(p)
+ return p
+
+ @property
+ def _r(self):
+ return buipy.KitNode.rect.__get__(self)
+
+ # -- tree ----------------------------------------------------------------------
+ def setParent(self, parent): # noqa: N802
+ if self.parent is not None:
+ self.parent.remove(self)
+ if parent is not None:
+ target = parent._content_node()
+ target.add(self)
+ if target.type == "frame" and self.geom_get("manager") == 0:
+ self.geom(PLACE, reset_place=1, x=0, y=0) # free child: placed at (0, 0)
+
+ def _content_node(self):
+ return self
+
+ def parentWidget(self): # noqa: N802
+ return self._parent_widget
+
+ def children(self):
+ return [c for c in _kids(self) if isinstance(c, QWidget)]
+
+ def setLayout(self, layout): # noqa: N802
+ if self._layout is not None:
+ self.remove(self._layout)
+ self._layout = layout
+ layout._owner = self
+ if layout._margins is None: # top-level layouts get Qt's default margin
+ layout.set("padding", round(0.45 * buipy.kit_unit()))
+ self._content_node().add(layout)
+ layout.geom(PACK, fill=3, expand=1)
+
+ def layout(self):
+ return self._layout
+
+ # -- geometry --------------------------------------------------------------------
+ def resize(self, w, h=None):
+ if h is None:
+ w, h = w.width(), w.height()
+ self._size = (int(w), int(h))
+ if self._window is not None:
+ self._window.set_size(*self._size)
+ elif self.geom_get("manager") == PLACE:
+ self.geom(PLACE, width=int(w), height=int(h))
+ else:
+ self.geom(int(self.geom_get("manager")), reqwidth=int(w), reqheight=int(h))
+
+ def move(self, x, y=None):
+ if y is None:
+ x, y = x.x(), x.y()
+ if self.geom_get("manager") in (0, PLACE):
+ self.geom(PLACE, x=int(x), y=int(y))
+
+ def setGeometry(self, x, y=None, w=None, h=None): # noqa: N802
+ if isinstance(x, QRect):
+ x, y, w, h = x.x(), x.y(), x.width(), x.height()
+ self.geom(PLACE, x=int(x), y=int(y), width=int(w), height=int(h))
+ self._size = (int(w), int(h))
+
+ def setFixedSize(self, w, h=None): # noqa: N802
+ if h is None:
+ w, h = w.width(), w.height()
+ self.geom(int(self.geom_get("manager")), reqwidth=int(w), reqheight=int(h))
+ self._size = (int(w), int(h))
+ self._fixed(0)
+ self._fixed(1)
+
+ def setFixedWidth(self, w): # noqa: N802
+ self.geom(int(self.geom_get("manager")), reqwidth=int(w))
+ self._fixed(0)
+
+ def setFixedHeight(self, h): # noqa: N802
+ self.geom(int(self.geom_get("manager")), reqheight=int(h))
+ self._fixed(1)
+
+ def _fixed(self, axis):
+ p = list(self._policy or (None, None))
+ p[axis] = QSizePolicy.Fixed
+ self._policy = tuple(p)
+ lay = self._parent_layout()
+ if isinstance(lay, QBoxLayout):
+ lay._policies()
+
+ def setMinimumWidth(self, w): # noqa: N802
+ self.geom(int(self.geom_get("manager")), reqwidth=int(w))
+
+ def setMinimumHeight(self, h): # noqa: N802
+ self.geom(int(self.geom_get("manager")), reqheight=int(h))
+
+ def setMinimumSize(self, w, h=None): # noqa: N802
+ pass
+
+ setMaximumSize = setMaximumWidth = setMaximumHeight = setMinimumSize
+
+ def width(self):
+ if self._window is not None:
+ return self._window.size[0]
+ return self._r[2] or (self._size or self.natural())[0]
+
+ def height(self):
+ if self._window is not None:
+ return self._window.size[1]
+ return self._r[3] or (self._size or self.natural())[1]
+
+ def x(self):
+ return self._r[0]
+
+ def y(self):
+ return self._r[1]
+
+ def pos(self):
+ return QPoint(self._r[0], self._r[1])
+
+ def size(self):
+ return QSize(self.width(), self.height())
+
+ def geometry(self):
+ return QRect(*self._r)
+
+ def rect(self): # noqa: F811 - Qt API (QWidget.rect())
+ return QRect(0, 0, self.width(), self.height())
+
+ def sizeHint(self): # noqa: N802
+ return QSize(*self.natural())
+
+ def absolutePos(self): # noqa: N802 - tools/tests
+ r = self._r
+ return r[0], r[1]
+
+ def setSizePolicy(self, h, v=None): # noqa: N802
+ self._policy = (h._h, h._v) if isinstance(h, QSizePolicy) else (h, v)
+ if isinstance(self._parent_layout(), QBoxLayout):
+ self._parent_layout()._policies()
+
+ def _parent_layout(self):
+ p = self.parent
+ return p if isinstance(p, QLayout) else None
+
+ # -- state ------------------------------------------------------------------------
+ def setEnabled(self, b): # noqa: N802
+ self.set("enabled", bool(b))
+
+ def isEnabled(self): # noqa: N802
+ return bool(self.get("enabled"))
+
+ def setVisible(self, b): # noqa: N802
+ if self._parent_widget is None and self._layout is not None or self._window:
+ self.show() if b else self.hide()
+ return
+ self.set("visible", bool(b))
+
+ def isVisible(self): # noqa: N802
+ return bool(self.get("visible"))
+
+ def hide(self):
+ if self._window is not None:
+ self._window.close()
+ self._window = None
+ else:
+ self.set("visible", False)
+
+ def setToolTip(self, text): # noqa: N802
+ self.set("description", str(text))
+
+ def setStyleSheet(self, css): # noqa: N802
+ for decl in str(css).split(";"):
+ k, _, v = decl.partition(":")
+ k, v = k.strip().lower(), v.strip()
+ if k == "color":
+ c = _tk_color(v)
+ if c:
+ try:
+ self.set("text_color", c)
+ except KeyError:
+ pass
+ elif k in ("background", "background-color"):
+ c = _tk_color(v)
+ if c and self.type in ("frame", "canvas"):
+ self.set("bg", c)
+ elif k == "font-weight" and "bold" in v:
+ try:
+ self.set("bold", True)
+ except KeyError:
+ pass
+
+ def setFont(self, font): # noqa: N802
+ if isinstance(font, QFont) and font.bold():
+ try:
+ self.set("bold", True)
+ except KeyError:
+ pass
+
+ def setObjectName(self, name): # noqa: N802
+ self._object_name = name
+
+ def objectName(self): # noqa: N802
+ return getattr(self, "_object_name", "")
+
+ def setAttribute(self, *a): # noqa: N802
+ pass
+
+ setWindowIcon = setWindowFlags = setFocusPolicy = setContentsMargins = setAttribute
+ installEventFilter = setMouseTracking = setAutoFillBackground = setAttribute
+
+ def setFocus(self, *a): # noqa: N802
+ pass
+
+ def setCursor(self, *a): # noqa: N802
+ pass
+
+ # -- window -------------------------------------------------------------------------
+ def setWindowTitle(self, title): # noqa: N802
+ self._title = str(title)
+ if self._window is not None:
+ self._window.title(self._title)
+
+ def windowTitle(self): # noqa: N802
+ return self._title
+
+ def show(self):
+ if self._parent_widget is not None:
+ self.set("visible", True)
+ return
+ if QApplication._instance is None or getattr(QApplication, "_running", False) \
+ or host._windows:
+ self._open()
+ else:
+ _pending_show.append(self)
+ self._open()
+
+ def _open(self):
+ if self._window is not None:
+ return
+ self._ctx = buipy.KitContext(self)
+ if self._menubar is not None:
+ self._ctx.set_header(self._menubar._node)
+ size = self._size or tuple(max(a, b) for a, b in zip(self.natural(), (200, 100)))
+ self._window = host.Window(self._ctx, self._title or "BUI", size)
+ self._window.on_close = self._close_requested
+ self._window.show()
+ _timers.flush()
+ _schedule_paint()
+
+ def _close_requested(self):
+ ev = QCloseEvent()
+ self.closeEvent(ev)
+ if ev.isAccepted():
+ self._window = None
+ return True
+ return False
+
+ def close(self):
+ if self._window is not None:
+ w, self._window = self._window, None
+ w.close()
+ return True
+
+ def isWindow(self): # noqa: N802
+ return self._parent_widget is None
+
+ def window(self):
+ w = self
+ while w._parent_widget is not None:
+ w = w._parent_widget
+ return w
+
+ def _host_window(self):
+ return self.window()._window
+
+ def setMenuBar(self, menubar): # noqa: N802
+ self._menubar = menubar
+ if self._ctx is not None:
+ self._ctx.set_header(menubar._node)
+
+ # -- painting --------------------------------------------------------------------
+ def paintEvent(self, event): # noqa: N802
+ pass
+
+ def update(self, *args):
+ if self._custom_paint:
+ self._repaint()
+ else:
+ self.invalidate()
+
+ repaint = update
+
+ def _repaint(self):
+ w, h = self._r[2], self._r[3]
+ if w <= 0 or h <= 0:
+ return
+ self._painted_size = (w, h)
+ self.canvas_delete(-1)
+ self._paint_id = 0
+ self.paintEvent(QPaintEvent(QRect(0, 0, w, h)))
+
+ def closeEvent(self, event): # noqa: N802
+ event.accept()
+
+ # -- input overrides ----------------------------------------------------------------
+ def mousePressEvent(self, e): # noqa: N802
+ pass
+
+ def mouseReleaseEvent(self, e): # noqa: N802
+ pass
+
+ def mouseMoveEvent(self, e): # noqa: N802
+ pass
+
+ def mouseDoubleClickEvent(self, e): # noqa: N802
+ pass
+
+ def keyPressEvent(self, e): # noqa: N802
+ pass
+
+ def wheelEvent(self, e): # noqa: N802
+ pass
+
+ def enterEvent(self, e): # noqa: N802
+ pass
+
+ def leaveEvent(self, e): # noqa: N802
+ pass
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_PRESS:
+ self.mousePressEvent(QMouseEvent(a, b))
+ elif kind == EV_RELEASE:
+ self.mouseReleaseEvent(QMouseEvent(a, b))
+ elif kind == EV_MOTION:
+ self.mouseMoveEvent(QMouseEvent(a, b))
+ elif kind == EV_DOUBLE:
+ self.mouseDoubleClickEvent(QMouseEvent(a, b))
+ elif kind == EV_ENTER:
+ self.enterEvent(QEvent())
+ elif kind == EV_LEAVE:
+ self.leaveEvent(QEvent())
+ elif kind == EV_WHEEL:
+ self.wheelEvent(QWheelEvent(int(a) * 120))
+ elif kind == EV_KEY:
+ text, _, keysym = (ref or "").partition("\t")
+ key = _KEYSYM_TO_QT.get(keysym, ord(keysym.upper()) if len(keysym) == 1 else 0)
+ self.keyPressEvent(QKeyEvent(key, text, _mods_qt(int(a))))
+ else:
+ self._event(kind, ref, a, b)
+
+ def _event(self, kind, ref, a, b):
+ pass
+
+
+def _schedule_paint():
+ """Custom-painted widgets paint once their size is known (after layout)."""
+ _timers.after(0, _paint_pending)
+
+
+def _paint_pending():
+ for w in list(host._windows):
+ w.render_now()
+ for w in _custom_widgets():
+ if w._painted_size != (w._r[2], w._r[3]):
+ w._repaint()
+
+
+def _custom_widgets():
+ import gc
+ return [o for o in gc.get_objects() if isinstance(o, QWidget) and o._custom_paint]
+
+
+class QMainWindow(QWidget):
+ def _setup(self):
+ self._central = None
+ self._status = None
+
+ def setCentralWidget(self, w): # noqa: N802
+ if self._central is not None:
+ self.remove(self._central)
+ self._central = w
+ self.add(w)
+ w.geom(PACK, fill=3, expand=1)
+
+ def centralWidget(self): # noqa: N802
+ return self._central
+
+ def menuBar(self): # noqa: N802
+ if self._menubar is None:
+ self.setMenuBar(QMenuBar())
+ return self._menubar
+
+ def statusBar(self): # noqa: N802
+ if self._status is None:
+ self._status = QStatusBar()
+ self.add(self._status)
+ self._status.geom(PACK, side=1, fill=1)
+ return self._status
+
+
+class QDialog(QWidget):
+ accepted = Signal()
+ rejected = Signal()
+
+ def exec(self):
+ self.show()
+ while self._window is not None and self._window.is_open:
+ host.update()
+ time.sleep(0.004)
+ return getattr(self, "_result", 0)
+
+ exec_ = exec
+
+ def accept(self):
+ self._result = 1
+ self.accepted.emit()
+ self.close()
+
+ def reject(self):
+ self._result = 0
+ self.rejected.emit()
+ self.close()
+
+
+class QFrame(QWidget):
+ NoFrame, Box, Panel, StyledPanel, HLine, VLine = range(6)
+
+ def setFrameShape(self, *a): # noqa: N802
+ pass
+
+ setFrameShadow = setLineWidth = setFrameShape
+
+
+# ==========================================================================
+# Layouts
+
+
+class QLayout(buipy.KitNode):
+ def __init__(self, parent=None):
+ super().__init__("frame")
+ self._owner = None
+ self._items = []
+ self._spacing = round(0.3 * buipy.kit_unit())
+ self._margins = None
+ if isinstance(parent, QWidget):
+ parent.setLayout(self)
+
+ def setSpacing(self, s): # noqa: N802
+ self._spacing = int(s)
+ self._relayout()
+
+ def spacing(self):
+ return self._spacing
+
+ def setContentsMargins(self, left, top=None, right=None, bottom=None): # noqa: N802
+ if isinstance(left, QMargins):
+ left = left._v
+ self._margins = int(left)
+ self.set("padding", int(left))
+
+ def count(self):
+ return len(self._items)
+
+ def itemAt(self, i): # noqa: N802
+ return _LayoutItem(self._items[i][0]) if 0 <= i < len(self._items) else None
+
+ def _relayout(self):
+ pass
+
+ def _adopt(self, w):
+ if isinstance(w, QWidget):
+ if w.parent is not None:
+ w.parent.remove(w)
+ self.add(w)
+
+
+class _LayoutItem:
+ def __init__(self, w):
+ self._w = w
+
+ def widget(self):
+ return self._w if isinstance(self._w, QWidget) else None
+
+ def layout(self):
+ return self._w if isinstance(self._w, QLayout) else None
+
+
+# Size policies (Qt defaults): which widgets take extra space.
+_H_EXPANDING = ("text", "slider", "progress", "dropdown", "textarea", "list", "tree", "tabs",
+ "canvas", "scroll", "number")
+_V_EXPANDING = ("textarea", "list", "tree", "tabs", "canvas", "scroll")
+
+
+def _expands(node, horizontal):
+ if isinstance(node, QLayout):
+ return any(_expands(c, horizontal) for c, _ in node._items)
+ if isinstance(node, QWidget) and node._policy is not None and node._policy[0 if horizontal else 1] is not None:
+ p = node._policy[0 if horizontal else 1]
+ return p in (QSizePolicy.Expanding, QSizePolicy.MinimumExpanding)
+ kinds = _H_EXPANDING if horizontal else _V_EXPANDING
+ if isinstance(node, QWidget) and node._layout is not None:
+ return _expands(node._layout, horizontal)
+ return getattr(node, "type", "") in kinds or (
+ isinstance(node, QWidget) and node._custom_paint and not horizontal)
+
+
+class QMargins:
+ def __init__(self, left=0, top=0, right=0, bottom=0):
+ self._v = left
+
+
+class QSizePolicy:
+ Fixed, Minimum, Maximum, Preferred, Expanding, MinimumExpanding, Ignored = range(7)
+
+ def __init__(self, h=3, v=3):
+ self._h, self._v = h, v
+
+
+class QBoxLayout(QLayout):
+ LeftToRight, RightToLeft, TopToBottom, BottomToTop = range(4)
+ _vertical = True
+
+ def addWidget(self, w, stretch=0, alignment=0): # noqa: N802
+ self._adopt(w)
+ self._items.append((w, stretch))
+ self._policies()
+
+ def addLayout(self, layout, stretch=0): # noqa: N802
+ layout._owner = self._owner
+ self.add(layout)
+ self._items.append((layout, stretch))
+ self._policies()
+
+ def insertWidget(self, index, w, stretch=0, alignment=0): # noqa: N802
+ self._adopt(w)
+ self._items.insert(index, (w, stretch))
+ self._reorder()
+ self._policies()
+
+ def addStretch(self, stretch=1): # noqa: N802
+ spacer = buipy.KitNode("frame")
+ self.add(spacer)
+ self._items.append((spacer, max(1, stretch)))
+ self._policies()
+
+ def addSpacing(self, size): # noqa: N802
+ spacer = buipy.KitNode("frame")
+ spacer.geom(0, **({"reqheight": int(size)} if self._vertical else
+ {"reqwidth": int(size)}))
+ self.add(spacer)
+ self._items.append((spacer, 0))
+ self._policies()
+
+ def removeWidget(self, w): # noqa: N802
+ self._items = [(i, s) for i, s in self._items if i is not w]
+ self.remove(w)
+ self._policies()
+
+ def setStretch(self, index, stretch): # noqa: N802
+ w, _ = self._items[index]
+ self._items[index] = (w, stretch)
+ self._policies()
+
+ def _reorder(self):
+ for i, (w, _) in enumerate(self._items):
+ buipy.KitNode.add(self, w, i)
+
+ def _relayout(self):
+ self._policies()
+
+ def _policies(self):
+ """Qt box semantics on Tk's packer: items stack along the axis; extra
+ space goes to stretch factors, else to expanding widgets, else (for
+ horizontal boxes) is shared by all."""
+ v = self._vertical
+ any_stretch = any(s > 0 for _, s in self._items)
+ expanders = [w for w, s in self._items if (s > 0 if any_stretch else _expands(w, not v))]
+ if not v and not expanders:
+ expanders = [w for w, _ in self._items]
+ for k, (w, s) in enumerate(self._items):
+ gap = self._spacing if k else 0
+ w.geom(PACK, side=0 if v else 2, fill=1 if v else 2,
+ expand=1 if w in expanders else 0,
+ pady0=gap if v else 0, padx0=0 if v else gap)
+ if (v and _expands(w, True)) or not v:
+ w.geom(PACK, fill=3)
+ if v and w in expanders:
+ w.geom(PACK, fill=3)
+
+
+class QVBoxLayout(QBoxLayout):
+ _vertical = True
+
+
+class QHBoxLayout(QBoxLayout):
+ _vertical = False
+
+
+class QGridLayout(QLayout):
+ def addWidget(self, w, row=0, column=0, rowspan=1, columnspan=1, alignment=0): # noqa: N802
+ self._adopt(w)
+ self._place(w, row, column, rowspan, columnspan, alignment)
+
+ def addLayout(self, layout, row=0, column=0, rowspan=1, columnspan=1, alignment=0): # noqa: N802
+ layout._owner = self._owner
+ self.add(layout)
+ self._place(layout, row, column, rowspan, columnspan, alignment)
+
+ def _place(self, w, row, column, rowspan, columnspan, alignment):
+ self._items.append((w, (row, column)))
+ sticky = W | E | ((N | S) if _expands(w, False) else 0)
+ if alignment & Qt.AlignLeft:
+ sticky &= ~E
+ if alignment & Qt.AlignRight:
+ sticky &= ~W
+ g = self._spacing # Qt spacing goes between cells, not around the edges
+ w.geom(GRID, row=row, column=column, rowspan=rowspan, columnspan=columnspan,
+ sticky=sticky, padx0=g if column else 0, pady0=g if row else 0)
+ if _expands(w, True):
+ self.grid_weight(1, column + columnspan - 1, 1.0)
+ if _expands(w, False):
+ self.grid_weight(0, row + rowspan - 1, 1.0)
+
+ def setColumnStretch(self, column, stretch): # noqa: N802
+ self.grid_weight(1, int(column), float(stretch))
+
+ def setRowStretch(self, row, stretch): # noqa: N802
+ self.grid_weight(0, int(row), float(stretch))
+
+ def setHorizontalSpacing(self, s): # noqa: N802
+ self._spacing = int(s)
+
+ setVerticalSpacing = setHorizontalSpacing
+
+ def rowCount(self): # noqa: N802
+ return 1 + max((r for _, (r, c) in self._items), default=-1)
+
+ def columnCount(self): # noqa: N802
+ return 1 + max((c for _, (r, c) in self._items), default=-1)
+
+
+class QFormLayout(QGridLayout):
+ def addRow(self, label, field=None): # noqa: N802
+ row = self.rowCount()
+ if field is None:
+ self.addWidget(label, row, 0, 1, 2)
+ return
+ if isinstance(label, str):
+ label = QLabel(label)
+ label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
+ self.addWidget(label, row, 0)
+ if isinstance(field, QLayout):
+ self.addLayout(field, row, 1)
+ else:
+ self.addWidget(field, row, 1)
+ self.setColumnStretch(1, 1)
+
+
+class QStackedLayout(QLayout):
+ def addWidget(self, w): # noqa: N802
+ self._adopt(w)
+ self._items.append((w, 0))
+ w.geom(PACK, fill=3, expand=1)
+ self.setCurrentIndex(getattr(self, "_current", 0))
+ return len(self._items) - 1
+
+ def setCurrentIndex(self, i): # noqa: N802
+ self._current = i
+ for k, (w, _) in enumerate(self._items):
+ w.set("visible", k == i)
+
+ def currentIndex(self): # noqa: N802
+ return getattr(self, "_current", 0)
+
+
+# ==========================================================================
+# Widgets
+
+
+class QLabel(QWidget):
+ KIND = "label"
+
+ def __init__(self, text="", parent=None, **kw):
+ super().__init__(parent)
+ self.set("text", str(text))
+
+ def setText(self, t): # noqa: N802
+ self.set("text", str(t))
+
+ def text(self):
+ return self.get_str("text")
+
+ def setAlignment(self, a): # noqa: N802
+ if isinstance(a, str):
+ a = {"center": Qt.AlignCenter, "right": Qt.AlignRight}.get(a, Qt.AlignLeft)
+ self.set("text_align", "right" if a & Qt.AlignRight else
+ ("center" if a & Qt.AlignHCenter else "left"))
+
+ def setPixmap(self, pm): # noqa: N802
+ self.set_image(pm.width(), pm.height(), pm._img.rgba())
+
+ def setWordWrap(self, b): # noqa: N802
+ pass
+
+ setTextFormat = setOpenExternalLinks = setWordWrap
+
+
+class QAbstractButton(QWidget):
+ clicked = Signal(bool)
+ pressed = Signal()
+ released = Signal()
+ toggled = Signal(bool)
+
+ def setText(self, t): # noqa: N802
+ self.set("text", str(t))
+
+ def text(self):
+ return self.get_str("text")
+
+ def setIcon(self, icon): # noqa: N802
+ name = getattr(icon, "name", "")
+ if name:
+ self.set("icon", name)
+
+ def click(self):
+ self._event(EV_CLICK, None, 0, 0)
+
+ def animateClick(self, *a): # noqa: N802
+ self.click()
+
+ def setShortcut(self, *a): # noqa: N802
+ pass
+
+
+class QPushButton(QAbstractButton):
+ KIND = "button"
+
+ def __init__(self, text="", parent=None, **kw):
+ if isinstance(text, QWidget):
+ text, parent = "", text
+ super().__init__(parent)
+ self.set("text", str(text))
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CLICK:
+ self.clicked.emit(False)
+
+ def setDefault(self, b): # noqa: N802
+ pass
+
+ setAutoDefault = setFlat = setDefault
+
+
+QToolButton = QPushButton
+
+
+class QCheckBox(QAbstractButton):
+ KIND = "checkbox"
+ stateChanged = Signal(int)
+ checkStateChanged = Signal(int)
+
+ def __init__(self, text="", parent=None):
+ super().__init__(parent)
+ self.set("label", str(text))
+
+ def setText(self, t): # noqa: N802
+ self.set("label", str(t))
+
+ def text(self):
+ return self.get_str("label")
+
+ def isChecked(self): # noqa: N802
+ return self.get("value") != 0
+
+ def setChecked(self, b): # noqa: N802
+ self.set("set_value", 1.0 if b else 0.0)
+
+ def checkState(self): # noqa: N802
+ return Qt.Checked if self.isChecked() else Qt.Unchecked
+
+ def setCheckState(self, s): # noqa: N802
+ self.setChecked(s == Qt.Checked or s is True)
+
+ def toggle(self):
+ self.setChecked(not self.isChecked())
+
+ def click(self):
+ self.toggle()
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ on = self.isChecked()
+ self.toggled.emit(on)
+ self.stateChanged.emit(Qt.Checked if on else Qt.Unchecked)
+ self.checkStateChanged.emit(Qt.Checked if on else Qt.Unchecked)
+ self.clicked.emit(on)
+
+
+class QRadioButton(QAbstractButton):
+ KIND = "radio"
+
+ def __init__(self, text="", parent=None):
+ super().__init__(parent)
+ self.set("label", str(text))
+ self._group = None
+
+ def setText(self, t): # noqa: N802
+ self.set("label", str(t))
+
+ def text(self):
+ return self.get_str("label")
+
+ def isChecked(self): # noqa: N802
+ return self.get("value") != 0
+
+ def setChecked(self, b): # noqa: N802
+ if bool(b) != self.isChecked():
+ self.set("set_value", 1.0 if b else 0.0)
+
+ def click(self):
+ self.setChecked(True)
+
+ def _siblings(self):
+ if self._group is not None:
+ return [r for r in self._group._buttons if r is not self]
+ container = self.parent
+ if container is None:
+ return []
+ return [c for c in _kids(container) if isinstance(c, QRadioButton) and c is not self]
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ on = self.isChecked()
+ if on: # Qt auto-exclusive: siblings turn off
+ for r in self._siblings():
+ if r.isChecked():
+ r.set("set_value", 0.0)
+ self.toggled.emit(on)
+ if on:
+ self.clicked.emit(True)
+
+
+class QButtonGroup:
+ buttonClicked = Signal(object)
+ idClicked = Signal(int)
+
+ def __init__(self, parent=None):
+ self._buttons = []
+
+ def addButton(self, b, id=-1): # noqa: N802, A002
+ self._buttons.append(b)
+ b._group = self
+ b.clicked.connect(lambda *a, b=b: (self.buttonClicked.emit(b),
+ self.idClicked.emit(self._buttons.index(b))))
+
+ def buttons(self):
+ return list(self._buttons)
+
+ def checkedButton(self): # noqa: N802
+ for b in self._buttons:
+ if b.isChecked():
+ return b
+ return None
+
+
+class QLineEdit(QWidget):
+ KIND = "text"
+ textChanged = Signal(str)
+ textEdited = Signal(str)
+ returnPressed = Signal()
+ editingFinished = Signal()
+
+ def __init__(self, text="", parent=None):
+ if isinstance(text, QWidget):
+ text, parent = "", text
+ super().__init__(parent)
+ self.set("live", True)
+ self.set("events", True)
+ self.set("value", str(text))
+
+ def text(self):
+ return self.get_str("value")
+
+ def setText(self, t): # noqa: N802
+ self.set("set_value", str(t))
+
+ def clear(self):
+ self.setText("")
+
+ def setPlaceholderText(self, t): # noqa: N802
+ self.set("placeholder", str(t))
+
+ def setReadOnly(self, b): # noqa: N802
+ self.set("enabled", not b)
+
+ def setEchoMode(self, m): # noqa: N802
+ pass
+
+ setMaxLength = setValidator = setClearButtonEnabled = setAlignment = setEchoMode
+
+ def keyPressEvent(self, e): # noqa: N802
+ pass
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ self.textChanged.emit(self.text())
+ self.textEdited.emit(self.text())
+ elif kind == EV_SUBMIT:
+ self.returnPressed.emit()
+ self.editingFinished.emit()
+ elif kind == EV_KEY:
+ QWidget._on_event(self, kind, ref, a, b)
+
+
+class QTextEdit(QWidget):
+ KIND = "textarea"
+ textChanged = Signal()
+
+ def __init__(self, text="", parent=None):
+ if isinstance(text, QWidget):
+ text, parent = "", text
+ super().__init__(parent)
+ self.set("value", str(text))
+
+ def toPlainText(self): # noqa: N802
+ return self.get_str("value")
+
+ def setPlainText(self, t): # noqa: N802
+ self.set("value", str(t))
+ self.textChanged.emit()
+
+ setText = setHtml = setPlainText
+
+ def append(self, t):
+ cur = self.toPlainText()
+ self.setPlainText(cur + ("\n" if cur else "") + str(t))
+
+ def insertPlainText(self, t): # noqa: N802
+ caret = self.ta_caret()
+ self.ta_insert(caret, str(t))
+ self.textChanged.emit()
+
+ def clear(self):
+ self.setPlainText("")
+
+ def setReadOnly(self, b): # noqa: N802
+ self.set("enabled", not b)
+
+ def setPlaceholderText(self, t): # noqa: N802
+ pass
+
+ setLineWrapMode = setWordWrapMode = setPlaceholderText
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ self.textChanged.emit()
+
+
+QPlainTextEdit = QTextEdit
+
+
+class QAbstractSlider(QWidget):
+ valueChanged = Signal(int)
+ sliderMoved = Signal(int)
+ sliderReleased = Signal()
+ rangeChanged = Signal(int, int)
+
+ def _setup(self):
+ self.set("integer", True)
+ self.set("precision", 0)
+ self.set("min", 0.0)
+ self.set("max", 99.0)
+ self.set("step", 1.0)
+
+ def setRange(self, lo, hi): # noqa: N802
+ self.set("min", float(lo))
+ self.set("max", float(hi))
+ self.rangeChanged.emit(int(lo), int(hi))
+
+ def setMinimum(self, v): # noqa: N802
+ self.set("min", float(v))
+
+ def setMaximum(self, v): # noqa: N802
+ self.set("max", float(v))
+
+ def minimum(self):
+ return int(self.get("min"))
+
+ def maximum(self):
+ return int(self.get("max"))
+
+ def value(self):
+ return int(round(self.get("value")))
+
+ def setValue(self, v): # noqa: N802
+ self.set("set_value", float(v))
+
+ def setSingleStep(self, s): # noqa: N802
+ self.set("step", float(s))
+
+ def setPageStep(self, s): # noqa: N802
+ pass
+
+ setTickPosition = setTickInterval = setTracking = setPageStep
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ self.valueChanged.emit(self.value())
+ self.sliderMoved.emit(self.value())
+
+
+class QSlider(QAbstractSlider):
+ KIND = "slider"
+
+ def __init__(self, orientation=Qt.Horizontal, parent=None):
+ if isinstance(orientation, QWidget):
+ orientation, parent = Qt.Horizontal, orientation
+ super().__init__(parent)
+
+ def setOrientation(self, o): # noqa: N802
+ pass
+
+
+class QDial(QSlider):
+ pass
+
+
+class QSpinBox(QAbstractSlider):
+ KIND = "number"
+
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self._prefix = ""
+
+ def setSuffix(self, s): # noqa: N802
+ self.set("suffix", str(s))
+
+ def setPrefix(self, p): # noqa: N802
+ self.set("label", str(p).rstrip(": "))
+
+ def stepUp(self): # noqa: N802
+ self.setValue(self.value() + int(self.get("step")))
+
+ def stepDown(self): # noqa: N802
+ self.setValue(self.value() - int(self.get("step")))
+
+ def text(self):
+ return str(self.value())
+
+
+class QDoubleSpinBox(QSpinBox):
+ valueChanged = Signal(float)
+
+ def _setup(self):
+ super()._setup()
+ self.set("integer", False)
+ self.set("precision", 2)
+ self.set("step", 0.1)
+
+ def value(self):
+ return self.get("value")
+
+ def setDecimals(self, d): # noqa: N802
+ self.set("precision", int(d))
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ self.valueChanged.emit(self.value())
+
+
+class QProgressBar(QWidget):
+ KIND = "progress"
+ valueChanged = Signal(int)
+
+ def _setup(self):
+ self._min, self._max, self._value = 0, 100, 0
+ self._format = "%p%"
+ self._text_visible = True
+ self._update()
+
+ def setRange(self, lo, hi): # noqa: N802
+ self._min, self._max = lo, hi
+ self._update()
+
+ def setMinimum(self, v): # noqa: N802
+ self._min = v
+ self._update()
+
+ def setMaximum(self, v): # noqa: N802
+ self._max = v
+ self._update()
+
+ def setValue(self, v): # noqa: N802
+ self._value = int(v)
+ self._update()
+ self.valueChanged.emit(self._value)
+
+ def value(self):
+ return self._value
+
+ def minimum(self):
+ return self._min
+
+ def maximum(self):
+ return self._max
+
+ def setFormat(self, f): # noqa: N802
+ self._format = f
+ self._update()
+
+ def setTextVisible(self, b): # noqa: N802
+ self._text_visible = bool(b)
+ self._update()
+
+ def reset(self):
+ self.setValue(self._min)
+
+ def _update(self):
+ span = (self._max - self._min) or 1
+ frac = max(0.0, min(1.0, (self._value - self._min) / span))
+ self.set("factor", frac)
+ pct = int(round(frac * 100))
+ text = self._format.replace("%p", str(pct)).replace("%v", str(self._value)) \
+ .replace("%m", str(self._max))
+ self.set("text", text if self._text_visible else "")
+
+
+class QComboBox(QWidget):
+ KIND = "dropdown"
+ currentIndexChanged = Signal(int)
+ currentTextChanged = Signal(str)
+ activated = Signal(int)
+
+ def _setup(self):
+ self._items = []
+ self._data = []
+
+ def addItem(self, text, data=None): # noqa: N802
+ if isinstance(text, QIcon):
+ text, data = data, None
+ self._items.append(str(text))
+ self._data.append(data)
+ self.set("items", self._items)
+
+ def addItems(self, texts): # noqa: N802
+ for t in texts:
+ self.addItem(t)
+
+ def insertItem(self, index, text, data=None): # noqa: N802
+ self._items.insert(index, str(text))
+ self._data.insert(index, data)
+ self.set("items", self._items)
+
+ def removeItem(self, index): # noqa: N802
+ del self._items[index]
+ del self._data[index]
+ self.set("items", self._items)
+
+ def clear(self):
+ self._items, self._data = [], []
+ self.set("items", [])
+
+ def count(self):
+ return len(self._items)
+
+ def itemText(self, i): # noqa: N802
+ return self._items[i]
+
+ def itemData(self, i, role=None): # noqa: N802
+ return self._data[i]
+
+ def currentIndex(self): # noqa: N802
+ return int(self.get("value")) if self._items else -1
+
+ def setCurrentIndex(self, i): # noqa: N802
+ self.set("set_value", float(i))
+
+ def currentText(self): # noqa: N802
+ i = self.currentIndex()
+ return self._items[i] if 0 <= i < len(self._items) else ""
+
+ def setCurrentText(self, t): # noqa: N802
+ if t in self._items:
+ self.setCurrentIndex(self._items.index(t))
+
+ def currentData(self, role=None): # noqa: N802
+ i = self.currentIndex()
+ return self._data[i] if 0 <= i < len(self._data) else None
+
+ def findText(self, t): # noqa: N802
+ return self._items.index(t) if t in self._items else -1
+
+ def setEditable(self, b): # noqa: N802
+ pass
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ i = self.currentIndex()
+ self.currentIndexChanged.emit(i)
+ self.currentTextChanged.emit(self.currentText())
+ self.activated.emit(i)
+
+
+class QListWidgetItem:
+ def __init__(self, text="", parent=None):
+ self._text = str(text)
+ self._data = {}
+ if isinstance(parent, QListWidget):
+ parent.addItem(self)
+
+ def text(self):
+ return self._text
+
+ def setText(self, t): # noqa: N802
+ self._text = str(t)
+ lw = getattr(self, "_list", None)
+ if lw is not None:
+ lw._push()
+
+ def setData(self, role, value): # noqa: N802
+ self._data[role] = value
+
+ def data(self, role):
+ return self._data.get(role)
+
+ def setFlags(self, f): # noqa: N802
+ pass
+
+ def setIcon(self, *a): # noqa: N802
+ pass
+
+
+class QListWidget(QWidget):
+ KIND = "list"
+ currentRowChanged = Signal(int)
+ currentItemChanged = Signal(object, object)
+ itemClicked = Signal(object)
+ itemDoubleClicked = Signal(object)
+ itemSelectionChanged = Signal()
+
+ def _setup(self):
+ self._items: List[QListWidgetItem] = []
+ self.set("rows", 6)
+ self.set("events", True)
+
+ def _push(self):
+ self.set("items", [i.text() for i in self._items])
+
+ def addItem(self, item): # noqa: N802
+ if not isinstance(item, QListWidgetItem):
+ item = QListWidgetItem(item)
+ item._list = self
+ self._items.append(item)
+ self._push()
+
+ def addItems(self, texts): # noqa: N802
+ for t in texts:
+ self.addItem(t)
+
+ def insertItem(self, row, item): # noqa: N802
+ if not isinstance(item, QListWidgetItem):
+ item = QListWidgetItem(item)
+ item._list = self
+ self._items.insert(row, item)
+ self._push()
+
+ def takeItem(self, row): # noqa: N802
+ it = self._items.pop(row)
+ self._push()
+ return it
+
+ def clear(self):
+ self._items = []
+ self._push()
+
+ def count(self):
+ return len(self._items)
+
+ def item(self, row):
+ return self._items[row] if 0 <= row < len(self._items) else None
+
+ def currentRow(self): # noqa: N802
+ return int(self.get("value")) if self._items else -1
+
+ def setCurrentRow(self, row): # noqa: N802
+ self.set("set_value", float(row))
+
+ def currentItem(self): # noqa: N802
+ return self.item(self.currentRow())
+
+ def row(self, item):
+ return self._items.index(item)
+
+ def selectedItems(self): # noqa: N802
+ it = self.currentItem()
+ return [it] if it else []
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ self.currentRowChanged.emit(self.currentRow())
+ self.currentItemChanged.emit(self.currentItem(), None)
+ self.itemSelectionChanged.emit()
+ elif kind == EV_PRESS:
+ if self.currentItem() is not None:
+ self.itemClicked.emit(self.currentItem())
+ elif kind == EV_DOUBLE:
+ if self.currentItem() is not None:
+ self.itemDoubleClicked.emit(self.currentItem())
+ elif kind == EV_RENAME:
+ self._items[int(a)]._text = self.strs("items")[int(a)]
+
+
+class QTreeWidgetItem:
+ def __init__(self, parent_or_texts=None, texts=None):
+ texts_ = texts if texts is not None else (
+ parent_or_texts if isinstance(parent_or_texts, (list, tuple)) else [])
+ texts_ = [str(t) for t in texts_]
+ self._node = buipy.KitTreeItem(texts_[0] if texts_ else "")
+ self._node._qitem = self
+ self._texts = texts_
+ self._children: list = []
+ self._parent = None
+ self._node.set_values(texts_[1:])
+ if isinstance(parent_or_texts, QTreeWidgetItem):
+ parent_or_texts.addChild(self)
+ elif isinstance(parent_or_texts, QTreeWidget):
+ parent_or_texts.addTopLevelItem(self)
+
+ def text(self, col):
+ return self._texts[col] if col < len(self._texts) else ""
+
+ def setText(self, col, text): # noqa: N802
+ while len(self._texts) <= col:
+ self._texts.append("")
+ self._texts[col] = str(text)
+ self._node.label = self._texts[0]
+ self._node.set_values(self._texts[1:])
+
+ def addChild(self, child): # noqa: N802
+ child._parent = self
+ self._children.append(child)
+ self._node.add(child._node)
+
+ def child(self, i):
+ return self._children[i]
+
+ def childCount(self): # noqa: N802
+ return len(self._children)
+
+ def parent(self):
+ return self._parent
+
+ def setExpanded(self, b): # noqa: N802
+ self._node.set("expanded", 1.0 if b else 0.0)
+
+ def isExpanded(self): # noqa: N802
+ return bool(self._node.get("expanded"))
+
+ def setBackground(self, *a): # noqa: N802
+ pass
+
+ setForeground = setFlags = setIcon = setData = setBackground
+
+
+class QTreeWidget(QWidget):
+ KIND = "tree"
+ itemClicked = Signal(object, int)
+ itemDoubleClicked = Signal(object, int)
+ currentItemChanged = Signal(object, object)
+ itemSelectionChanged = Signal()
+
+ def _setup(self):
+ self._top: List[QTreeWidgetItem] = []
+ self._headers = []
+ self.set("rows", 8)
+ self.set("events", True)
+
+ def setHeaderLabels(self, labels): # noqa: N802
+ self._headers = [str(l) for l in labels]
+ self.set("headers", self._headers)
+
+ def setColumnCount(self, n): # noqa: N802
+ pass
+
+ def setHeaderHidden(self, b): # noqa: N802
+ if b:
+ self.set("headers", [])
+
+ def addTopLevelItem(self, item): # noqa: N802
+ self._top.append(item)
+ self.set_tree_roots([i._node for i in self._top])
+ return item
+
+ def addTopLevelItems(self, items): # noqa: N802
+ for i in items:
+ self.addTopLevelItem(i)
+
+ def topLevelItem(self, i): # noqa: N802
+ return self._top[i]
+
+ def topLevelItemCount(self): # noqa: N802
+ return len(self._top)
+
+ def clear(self):
+ self._top = []
+ self.set_tree_roots([])
+
+ def currentItem(self): # noqa: N802
+ n = self.tree_selected()
+ return getattr(n, "_qitem", None) if n is not None else None
+
+ def setCurrentItem(self, item): # noqa: N802
+ self.tree_select(item._node if item is not None else None)
+
+ def expandAll(self): # noqa: N802
+ def walk(items):
+ for it in items:
+ it.setExpanded(True)
+ walk(it._children)
+ walk(self._top)
+ self.invalidate()
+
+ def collapseAll(self): # noqa: N802
+ def walk(items):
+ for it in items:
+ it.setExpanded(False)
+ walk(it._children)
+ walk(self._top)
+ self.invalidate()
+
+ def selectedItems(self): # noqa: N802
+ it = self.currentItem()
+ return [it] if it else []
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ self.currentItemChanged.emit(self.currentItem(), None)
+ self.itemSelectionChanged.emit()
+ elif kind == EV_PRESS and self.currentItem() is not None:
+ self.itemClicked.emit(self.currentItem(), 0)
+ elif kind == EV_DOUBLE and self.currentItem() is not None:
+ self.itemDoubleClicked.emit(self.currentItem(), 0)
+
+
+class QTableWidgetItem:
+ def __init__(self, text=""):
+ self._text = str(text)
+
+ def text(self):
+ return self._text
+
+ def setText(self, t): # noqa: N802
+ self._text = str(t)
+
+ def setFlags(self, *a): # noqa: N802
+ pass
+
+ setData = setBackground = setForeground = setTextAlignment = setFlags
+
+
+class QTableWidget(QWidget):
+ """A flat table: one tree row per table row, columns from the headers."""
+
+ KIND = "tree"
+ cellClicked = Signal(int, int)
+ cellDoubleClicked = Signal(int, int)
+ currentCellChanged = Signal(int, int, int, int)
+ itemSelectionChanged = Signal()
+
+ def __init__(self, rows=0, columns=0, parent=None):
+ if isinstance(rows, QWidget):
+ rows, columns, parent = 0, 0, rows
+ super().__init__(parent)
+ self._rows, self._cols = int(rows), int(columns)
+ self._cells = {}
+ self._headers = [str(c + 1) for c in range(self._cols)]
+ self._row_nodes = []
+ self.set("rows", 8)
+ self.set("events", True)
+ self._rebuild()
+
+ def _rebuild(self):
+ self.set("headers", self._headers[:self._cols] or [""])
+ self._row_nodes = []
+ for r in range(self._rows):
+ texts = [self._cells[(r, c)].text() if (r, c) in self._cells else ""
+ for c in range(max(1, self._cols))]
+ node = buipy.KitTreeItem(texts[0])
+ node.set_values(texts[1:])
+ node._row = r
+ self._row_nodes.append(node)
+ self.set_tree_roots(self._row_nodes)
+
+ def setRowCount(self, n): # noqa: N802
+ self._rows = int(n)
+ self._rebuild()
+
+ def setColumnCount(self, n): # noqa: N802
+ self._cols = int(n)
+ while len(self._headers) < self._cols:
+ self._headers.append(str(len(self._headers) + 1))
+ self._rebuild()
+
+ def rowCount(self): # noqa: N802
+ return self._rows
+
+ def columnCount(self): # noqa: N802
+ return self._cols
+
+ def setHorizontalHeaderLabels(self, labels): # noqa: N802
+ self._headers = [str(l) for l in labels]
+ self._rebuild()
+
+ def setItem(self, row, col, item): # noqa: N802
+ self._cells[(row, col)] = item
+ node = self._row_nodes[row]
+ texts = [self._cells[(row, c)].text() if (row, c) in self._cells else ""
+ for c in range(max(1, self._cols))]
+ node.label = texts[0]
+ node.set_values(texts[1:])
+ self.invalidate()
+
+ def item(self, row, col):
+ return self._cells.get((row, col))
+
+ def currentRow(self): # noqa: N802
+ n = self.tree_selected()
+ return getattr(n, "_row", -1) if n is not None else -1
+
+ def currentColumn(self): # noqa: N802
+ return 0
+
+ def setCurrentCell(self, row, col): # noqa: N802
+ if 0 <= row < len(self._row_nodes):
+ self.tree_select(self._row_nodes[row])
+
+ def clear(self):
+ self._cells = {}
+ self._rebuild()
+
+ def _on_event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ self.itemSelectionChanged.emit()
+ self.currentCellChanged.emit(self.currentRow(), 0, -1, -1)
+ elif kind == EV_PRESS and self.currentRow() >= 0:
+ self.cellClicked.emit(self.currentRow(), 0)
+ elif kind == EV_DOUBLE and self.currentRow() >= 0:
+ self.cellDoubleClicked.emit(self.currentRow(), 0)
+
+
+class QTabWidget(QWidget):
+ KIND = "tabs"
+ currentChanged = Signal(int)
+
+ def _setup(self):
+ self._pages, self._titles = [], []
+
+ def addTab(self, w, title): # noqa: N802
+ if w.parent is not None:
+ w.parent.remove(w)
+ self.add(w)
+ self._pages.append(w)
+ self._titles.append(str(title))
+ self.set("items", self._titles)
+ return len(self._pages) - 1
+
+ def currentIndex(self): # noqa: N802
+ return int(self.get("current"))
+
+ def setCurrentIndex(self, i): # noqa: N802
+ self.set("current", float(i))
+ self.currentChanged.emit(int(i))
+
+ def count(self):
+ return len(self._pages)
+
+ def widget(self, i):
+ return self._pages[i]
+
+ def tabText(self, i): # noqa: N802
+ return self._titles[i]
+
+ def setTabText(self, i, t): # noqa: N802
+ self._titles[i] = str(t)
+ self.set("items", self._titles)
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ self.currentChanged.emit(int(a))
+
+
+class QGroupBox(QWidget):
+ """Drawn as a Blender panel (header + body)."""
+
+ def __init__(self, title="", parent=None):
+ if isinstance(title, QWidget):
+ title, parent = "", title
+ super().__init__(parent)
+ self.set("text", str(title))
+ self.set("padding", round(0.3 * buipy.kit_unit()))
+
+ def setTitle(self, t): # noqa: N802
+ self.set("text", str(t))
+
+ def title(self):
+ return self.get_str("text")
+
+
+class QScrollArea(QWidget):
+ KIND = "scroll"
+
+ def _setup(self):
+ self.set("rows", 10)
+
+ def setWidget(self, w): # noqa: N802
+ for c in _kids(self):
+ self.remove(c)
+ self.add(w)
+
+ def setWidgetResizable(self, b): # noqa: N802
+ pass
+
+ setHorizontalScrollBarPolicy = setVerticalScrollBarPolicy = setWidgetResizable
+
+
+class QStatusBar(QWidget):
+ KIND = "label"
+
+ def showMessage(self, text, timeout=0): # noqa: N802
+ self.set("text", str(text))
+ if timeout:
+ _timers.after(timeout, self.clearMessage)
+
+ def clearMessage(self): # noqa: N802
+ self.set("text", "")
+
+ def currentMessage(self): # noqa: N802
+ return self.get_str("text")
+
+
+# ==========================================================================
+# Menus & actions
+
+
+class QAction:
+ triggered = Signal(bool)
+ toggled = Signal(bool)
+
+ def __init__(self, text="", parent=None, triggered=None):
+ if isinstance(text, QIcon):
+ text = parent if isinstance(parent, str) else ""
+ self._text = str(text)
+ self._shortcut = ""
+ self._checkable = False
+ self._checked = False
+ self._enabled = True
+ if triggered is not None:
+ self.triggered.connect(triggered)
+
+ def text(self):
+ return self._text
+
+ def setText(self, t): # noqa: N802
+ self._text = str(t)
+
+ def setShortcut(self, s): # noqa: N802
+ self._shortcut = str(s)
+
+ def shortcut(self):
+ return self._shortcut
+
+ def setCheckable(self, b): # noqa: N802
+ self._checkable = bool(b)
+
+ def isCheckable(self): # noqa: N802
+ return self._checkable
+
+ def setChecked(self, b): # noqa: N802
+ self._checked = bool(b)
+ self.toggled.emit(self._checked)
+
+ def isChecked(self): # noqa: N802
+ return self._checked
+
+ def setEnabled(self, b): # noqa: N802
+ self._enabled = bool(b)
+
+ def isEnabled(self): # noqa: N802
+ return self._enabled
+
+ def trigger(self):
+ if self._checkable:
+ self.setChecked(not self._checked)
+ self.triggered.emit(self._checked)
+
+ def setStatusTip(self, *a): # noqa: N802
+ pass
+
+ setToolTip = setIcon = setStatusTip
+
+ def _item(self):
+ return MenuItem(self._text, self.trigger, shortcut=self._shortcut.replace("+", " ")
+ if self._shortcut else None,
+ checked=self._checked if self._checkable else None,
+ enabled=self._enabled)
+
+
+class QMenu:
+ aboutToShow = Signal()
+ triggered = Signal(object)
+
+ def __init__(self, title="", parent=None):
+ if isinstance(title, QWidget):
+ title, parent = "", title
+ self._title = str(title)
+ self._actions = []
+ self._parent = parent
+
+ def title(self):
+ return self._title
+
+ def addAction(self, action, slot=None, shortcut=None): # noqa: N802
+ if not isinstance(action, QAction):
+ action = QAction(action)
+ if slot is not None:
+ action.triggered.connect(lambda *a: slot())
+ if shortcut:
+ action.setShortcut(shortcut)
+ self._actions.append(action)
+ self._changed()
+ return action
+
+ def addMenu(self, menu): # noqa: N802
+ if not isinstance(menu, QMenu):
+ menu = QMenu(menu)
+ menu._owner_menu = self
+ self._actions.append(menu)
+ self._changed()
+ return menu
+
+ def addSeparator(self): # noqa: N802
+ self._actions.append("-")
+ self._changed()
+
+ def actions(self):
+ return [a for a in self._actions if isinstance(a, QAction)]
+
+ def clear(self):
+ self._actions = []
+ self._changed()
+
+ def _items(self):
+ out = []
+ for a in self._actions:
+ if a == "-":
+ out.append("-")
+ elif isinstance(a, QMenu):
+ out.append(MenuItem(a._title, submenu=a._items()))
+ else:
+ out.append(a._item())
+ return out
+
+ def _changed(self):
+ bar = getattr(self, "_bar", None) or getattr(getattr(self, "_owner_menu", None),
+ "_bar", None)
+ if bar is not None:
+ bar._rebuild()
+
+ def exec(self, pos=None):
+ self.popup(pos)
+
+ exec_ = exec
+
+ def popup(self, pos=None):
+ win = self._window_widget()
+ if win is None or win._ctx is None:
+ return
+ at = (pos.x(), pos.y()) if pos is not None else None
+ self.aboutToShow.emit()
+ win._ctx.open_menu(None, self._items(), None, at)
+
+ def _window_widget(self):
+ p = self._parent
+ while p is not None and isinstance(p, QWidget) and p._parent_widget is not None:
+ p = p._parent_widget
+ if p is None:
+ for w in _custom_or_top():
+ return w
+ return p
+
+
+def _custom_or_top():
+ import gc
+ return [o for o in gc.get_objects() if isinstance(o, QWidget) and o._window is not None]
+
+
+class QMenuBar:
+ def __init__(self, parent=None):
+ self._menus: List[QMenu] = []
+ self._node = buipy.KitNode("menubar")
+
+ def addMenu(self, menu): # noqa: N802
+ if not isinstance(menu, QMenu):
+ menu = QMenu(menu)
+ menu._bar = self
+ self._menus.append(menu)
+ self._rebuild()
+ return menu
+
+ def addAction(self, action): # noqa: N802
+ return action
+
+ def _rebuild(self):
+ for c in self._node.children:
+ self._node.remove(c)
+ for m in self._menus:
+ b = buipy.KitNode("menubutton")
+ b.set("text", m._title)
+ b.set_menu(m._items())
+ self._node.add(b)
+
+ def absolutePos(self): # noqa: N802
+ r = self._node.rect
+ return r[0], r[1]
+
+
+# ==========================================================================
+# QPainter (records into the widget's kit canvas)
+
+
+class QPainter:
+ Antialiasing = TextAntialiasing = SmoothPixmapTransform = 1
+
+ def __init__(self, device=None):
+ self._dev = None
+ self._pen = QPen(QColor("#000000"), 1)
+ self._brush = None
+ self._font = QFont()
+ self._opacity = 1.0
+ self._dx = self._dy = 0.0
+ self._stack = []
+ if device is not None:
+ self.begin(device)
+
+ def begin(self, device):
+ self._dev = device
+ return True
+
+ def end(self):
+ self._dev = None
+ return True
+
+ def isActive(self): # noqa: N802
+ return self._dev is not None
+
+ def setRenderHint(self, *a): # noqa: N802
+ pass
+
+ setRenderHints = setRenderHint
+
+ def save(self):
+ self._stack.append((self._pen, self._brush, self._font, self._opacity, self._dx,
+ self._dy))
+
+ def restore(self):
+ if self._stack:
+ (self._pen, self._brush, self._font, self._opacity, self._dx,
+ self._dy) = self._stack.pop()
+
+ def translate(self, dx, dy=None):
+ if dy is None:
+ dx, dy = dx.x(), dx.y()
+ self._dx += dx
+ self._dy += dy
+
+ def setPen(self, p): # noqa: N802
+ if p is None or p == Qt.NoPen:
+ self._pen = None
+ elif isinstance(p, QPen):
+ self._pen = p
+ else:
+ self._pen = QPen(p, 1)
+
+ def setBrush(self, b): # noqa: N802
+ if b is None or b == Qt.NoBrush:
+ self._brush = None
+ else:
+ self._brush = b if isinstance(b, QBrush) else QBrush(b)
+
+ def setFont(self, f): # noqa: N802
+ self._font = f
+
+ def setOpacity(self, o): # noqa: N802
+ self._opacity = float(o)
+
+ def _c(self, c):
+ rgba = _rgba(c)
+ if rgba is None:
+ return None
+ return rgba[:3] + (rgba[3] * self._opacity,)
+
+ def _add(self, kind, coords, fill=None, outline=None, width=1.0, text=None, **kw):
+ dev = self._dev
+ if dev is None:
+ return
+ dev._paint_id = getattr(dev, "_paint_id", 0) + 1
+ xy = [v + (self._dx if i % 2 == 0 else self._dy) for i, v in enumerate(coords)]
+ dev.canvas_set(dev._paint_id, kind, xy, fill=fill, outline=outline, width=width,
+ text=text, **kw)
+
+ def _pen_rgba(self):
+ return self._c(self._pen._color) if self._pen is not None else None
+
+ def _pen_w(self):
+ return float(self._pen._width or 1) if self._pen is not None else 1.0
+
+ def _brush_rgba(self):
+ return self._c(self._brush._color) if self._brush is not None else None
+
+ @staticmethod
+ def _rect_args(args):
+ if len(args) == 1 and isinstance(args[0], QRect):
+ r = args[0]
+ return r.x(), r.y(), r.width(), r.height()
+ return args[:4]
+
+ def fillRect(self, *args): # noqa: N802
+ if isinstance(args[0], QRect):
+ x, y, w, h = self._rect_args(args[:1])
+ c = args[1]
+ else:
+ x, y, w, h, c = args[:5]
+ self._add(0, [x, y, x + w, y + h], fill=self._c(c.color() if isinstance(c, QBrush)
+ else c))
+
+ def drawRect(self, *args): # noqa: N802
+ x, y, w, h = self._rect_args(args)
+ self._add(0, [x, y, x + w, y + h], fill=self._brush_rgba(), outline=self._pen_rgba(),
+ width=self._pen_w())
+
+ def drawRoundedRect(self, *args): # noqa: N802
+ if isinstance(args[0], QRect):
+ x, y, w, h = self._rect_args(args[:1])
+ rx = args[1]
+ else:
+ x, y, w, h, rx = args[:5]
+ self._add(7, [x, y, x + w, y + h], fill=self._brush_rgba(), outline=self._pen_rgba(),
+ width=self._pen_w(), radius=float(rx))
+
+ def drawEllipse(self, *args): # noqa: N802
+ if len(args) == 3 and isinstance(args[0], QPoint):
+ c, rx, ry = args
+ x, y, w, h = c.x() - rx, c.y() - ry, 2 * rx, 2 * ry
+ else:
+ x, y, w, h = self._rect_args(args)
+ self._add(1, [x, y, x + w, y + h], fill=self._brush_rgba(), outline=self._pen_rgba(),
+ width=self._pen_w())
+
+ def drawLine(self, *args): # noqa: N802
+ if len(args) == 2:
+ p1, p2 = args
+ args = (p1.x(), p1.y(), p2.x(), p2.y())
+ x1, y1, x2, y2 = args
+ self._add(2, [x1, y1, x2, y2], outline=self._pen_rgba(), width=self._pen_w())
+
+ def drawPolyline(self, points): # noqa: N802
+ flat = []
+ for p in points:
+ flat += [p.x(), p.y()] if isinstance(p, QPoint) else list(p)
+ self._add(2, flat, outline=self._pen_rgba(), width=self._pen_w())
+
+ def drawPolygon(self, points, *a): # noqa: N802
+ flat = []
+ for p in points:
+ flat += [p.x(), p.y()] if isinstance(p, QPoint) else list(p)
+ self._add(3, flat, fill=self._brush_rgba(), outline=self._pen_rgba(),
+ width=self._pen_w())
+
+ def drawPoint(self, x, y=None): # noqa: N802
+ if y is None:
+ x, y = x.x(), x.y()
+ self._add(0, [x, y, x + 1, y + 1], fill=self._pen_rgba())
+
+ def _arc(self, kind_fill, args):
+ if isinstance(args[0], QRect):
+ x, y, w, h = self._rect_args(args[:1])
+ start, span = args[1], args[2]
+ else:
+ x, y, w, h, start, span = args[:6]
+ self._add(5, [x, y, x + w, y + h], fill=self._brush_rgba() if kind_fill else None,
+ outline=self._pen_rgba(), width=self._pen_w(), start=start / 16.0,
+ extent=span / 16.0)
+
+ def drawArc(self, *args): # noqa: N802
+ self._arc(False, args)
+
+ def drawPie(self, *args): # noqa: N802
+ self._arc(True, args)
+
+ def drawText(self, *args): # noqa: N802
+ size = float(self._font._size) * 1.33 if self._font._size and self._font._size > 0 \
+ else 0.0
+ if isinstance(args[0], QRect):
+ r, flags, text = args[0], args[1], args[2]
+ ax = (r.x() + r.width() / 2 if flags & Qt.AlignHCenter else
+ (r.x() + r.width() if flags & Qt.AlignRight else r.x()))
+ ay = (r.y() if flags & Qt.AlignTop else
+ (r.y() + r.height() if flags & Qt.AlignBottom else r.y() + r.height() / 2))
+ anchor = (0 if flags & Qt.AlignHCenter else (E if flags & Qt.AlignRight else W)) | \
+ (N if flags & Qt.AlignTop else (S if flags & Qt.AlignBottom else 0))
+ self._add(4, [ax, ay], fill=self._pen_rgba(), text=str(text), size=size,
+ anchor=anchor)
+ else:
+ if isinstance(args[0], QPoint):
+ x, y, text = args[0].x(), args[0].y(), args[1]
+ else:
+ x, y, text = args[:3]
+ # Qt draws text at its baseline: anchor south-west on the baseline
+ self._add(4, [x, y], fill=self._pen_rgba(), text=str(text), size=size,
+ anchor=S | W)
+
+ def drawPixmap(self, *args): # noqa: N802
+ if isinstance(args[0], QPoint):
+ x, y, pm = args[0].x(), args[0].y(), args[1]
+ else:
+ x, y, pm = args[0], args[1], args[2]
+ img = pm._img
+ self._add(6, [x, y], image=(img.width(), img.height(), img.rgba()), anchor=N | W)
+
+ drawImage = drawPixmap
+
+
+# ==========================================================================
+# Dialog stubs (no blocking native dialogs)
+
+
+class QMessageBox:
+ Ok, Cancel, Yes, No = 0x400, 0x400000, 0x4000, 0x10000
+
+ @staticmethod
+ def information(parent, title, text, *a, **kw):
+ return QMessageBox.Ok
+
+ warning = critical = about = information
+
+ @staticmethod
+ def question(parent, title, text, *a, **kw):
+ return QMessageBox.Yes
+
+
+class QFileDialog:
+ @staticmethod
+ def getOpenFileName(parent=None, caption="", directory="", filter="", *a): # noqa: N802,A002
+ try:
+ filedialog = _realtk.module("tkinter.filedialog")
+ return filedialog.askopenfilename(title=caption), ""
+ except Exception:
+ return "", ""
+
+ @staticmethod
+ def getSaveFileName(parent=None, caption="", directory="", filter="", *a): # noqa: N802,A002
+ try:
+ filedialog = _realtk.module("tkinter.filedialog")
+ return filedialog.asksaveasfilename(title=caption), ""
+ except Exception:
+ return "", ""
+
+ @staticmethod
+ def getExistingDirectory(parent=None, caption="", directory="", *a): # noqa: N802
+ try:
+ filedialog = _realtk.module("tkinter.filedialog")
+ return filedialog.askdirectory(title=caption)
+ except Exception:
+ return ""
+
+
+QStackedWidget = QWidget
diff --git a/bindings/python/bui/svg.py b/bindings/python/bui/svg.py
new file mode 100644
index 0000000..3d2ff91
--- /dev/null
+++ b/bindings/python/bui/svg.py
@@ -0,0 +1,99 @@
+"""SVG recorder backend for BUI — zero dependencies.
+
+Useful for tests, CI snapshots, and documentation figures:
+
+ import buipy, bui
+ from bui.svg import SvgSink
+
+ sink = SvgSink(640, 480)
+ buipy.set_backend(sink)
+ buipy.demo_scene(640, 480)
+ open("demo.svg", "w", encoding="utf-8").write(sink.to_svg())
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+from bui import Backend
+
+
+def _hex_color(color) -> str:
+ r, g, b, a = (max(0.0, min(1.0, c)) for c in color)
+ return "#{:02x}{:02x}{:02x}".format(int(r * 255 + 0.5), int(g * 255 + 0.5), int(b * 255 + 0.5))
+
+
+class SvgSink(Backend):
+ """Collects BUI primitives and renders them as an SVG document."""
+
+ def __init__(self, width: int, height: int):
+ self.width = width
+ self.height = height
+ self._shapes: list[str] = []
+ self._clip: tuple[int, int, int, int] | None = None
+
+ # -- Backend protocol ------------------------------------------------
+ def begin_frame(self, width: int, height: int) -> None:
+ self.width = width
+ self.height = height
+ self._shapes = []
+
+ def scissor(self, x: int, y: int, w: int, h: int) -> None:
+ self._clip = (x, y, w, h) if w > 0 and h > 0 else None
+
+ def triangles(self, coords, colors) -> None:
+ for i in range(0, len(coords), 3):
+ tri = coords[i : i + 3]
+ pts = " ".join("{:.1f},{:.1f}".format(x, y) for x, y in tri)
+ self._shapes.append(
+ '<polygon points="{}" fill="{}"/>'.format(pts, _hex_color(colors[i]))
+ )
+
+ def lines(self, coords, colors) -> None:
+ for i in range(0, len(coords), 2):
+ (x1, y1), (x2, y2) = coords[i], coords[i + 1]
+ self._shapes.append(
+ '<line x1="{:.1f}" y1="{:.1f}" x2="{:.1f}" y2="{:.1f}" '
+ 'stroke="{}" stroke-width="1"/>'.format(x1, y1, x2, y2, _hex_color(colors[i]))
+ )
+
+ def points(self, coords, colors, size) -> None:
+ for (x, y), color in zip(coords, colors):
+ self._shapes.append(
+ '<circle cx="{:.1f}" cy="{:.1f}" r="{:.1f}" fill="{}"/>'.format(
+ x, y, size / 2.0, _hex_color(color)
+ )
+ )
+
+ def text(self, x, y, text, size, color) -> None:
+ self._shapes.append(
+ '<text x="{:.1f}" y="{:.1f}" font-size="{:.0f}" fill="{}">{}</text>'.format(
+ x, y, size, _hex_color(color), text
+ )
+ )
+
+ # -- Output -----------------------------------------------------------
+ def to_svg(self) -> str:
+ body = "\n ".join(self._shapes)
+ clip = ""
+ if self._clip:
+ x, y, w, h = self._clip
+ clip = '<clipPath id="clip"><rect x="{}" y="{}" width="{}" height="{}"/></clipPath>'.format(
+ x, y, w, h
+ )
+ return (
+ '<svg xmlns="http://www.w3.org/2000/svg" width="{}" height="{}" '
+ 'viewBox="0 0 {} {}">\n {}<g clip-path="url(#clip)">\n {}\n </g>\n</svg>\n'.format(
+ self.width, self.height, self.width, self.height, clip, body
+ )
+ )
+ return (
+ '<svg xmlns="http://www.w3.org/2000/svg" width="{}" height="{}" '
+ 'viewBox="0 0 {} {}">\n {}\n</svg>\n'.format(
+ self.width, self.height, self.width, self.height, body
+ )
+ )
+
+ def save(self, path: str) -> None:
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(self.to_svg())
diff --git a/bindings/python/bui/theme.py b/bindings/python/bui/theme.py
new file mode 100644
index 0000000..df594cb
--- /dev/null
+++ b/bindings/python/bui/theme.py
@@ -0,0 +1,186 @@
+"""Blender's default UI theme and metrics, for the BUI widget model.
+
+Values follow Blender 4.x's default theme (``userdef_default_theme.c``:
+``wcol_regular``, ``wcol_text``, ``wcol_numslider`` ...) and its interface
+metrics (``U.widget_unit`` = 20 px at scale 1, 11 pt UI text, roundness as a
+fraction of the widget unit). Widgets read these at paint time, so changing
+:data:`SCALE` or a color set restyles everything.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import glob
+import os
+import sys
+from dataclasses import dataclass
+
+
+def _rgba(hex_rgba: int):
+ return (((hex_rgba >> 24) & 255) / 255.0, ((hex_rgba >> 16) & 255) / 255.0,
+ ((hex_rgba >> 8) & 255) / 255.0, (hex_rgba & 255) / 255.0)
+
+
+@dataclass
+class WidgetColors:
+ """uiWidgetColors: one Blender widget color set."""
+ outline: tuple
+ inner: tuple
+ inner_sel: tuple
+ item: tuple
+ text: tuple
+ text_sel: tuple
+ roundness: float = 0.2
+ shadetop: int = 0
+ shadedown: int = 0
+
+
+def _wcol(outline, inner, inner_sel, item, text, text_sel, roundness=0.2,
+ shadetop=0, shadedown=0) -> WidgetColors:
+ return WidgetColors(_rgba(outline), _rgba(inner), _rgba(inner_sel), _rgba(item),
+ _rgba(text), _rgba(text_sel), roundness, shadetop, shadedown)
+
+
+# --- color sets (Blender 4.x default theme) ---------------------------------
+WCOL = {
+ "regular": _wcol(0x3d3d3dff, 0x545454ff, 0x4772b3ff, 0x191919ff, 0xe6e6e6ff, 0xffffffff),
+ "tool": _wcol(0x3d3d3dff, 0x545454ff, 0x4772b3ff, 0x191919ff, 0xe6e6e6ff, 0xffffffff),
+ "toggle": _wcol(0x3d3d3dff, 0x545454ff, 0x4772b3ff, 0x191919ff, 0xe6e6e6ff, 0xffffffff),
+ "radio": _wcol(0x3d3d3dff, 0x545454ff, 0x4772b3ff, 0xffffffff, 0xe6e6e6ff, 0xffffffff),
+ "option": _wcol(0x3d3d3dff, 0x545454ff, 0x4772b3ff, 0xffffffff, 0xe6e6e6ff, 0xffffffff,
+ roundness=0.3),
+ "text": _wcol(0x3d3d3dff, 0x1d1d1dff, 0x181818ff, 0x4772b3ff, 0xe6e6e6ff, 0xffffffff),
+ "num": _wcol(0x3d3d3dff, 0x545454ff, 0x656565ff, 0xe6e6e6ff, 0xe6e6e6ff, 0xffffffff),
+ "numslider": _wcol(0x3d3d3dff, 0x545454ff, 0x999999ff, 0x4772b3ff, 0xe6e6e6ff,
+ 0xffffffff),
+ "menu": _wcol(0x3d3d3dff, 0x282828ff, 0x303030ff, 0xe6e6e6ff, 0xe6e6e6ff, 0xffffffff),
+ "pulldown": _wcol(0x3d3d3d00, 0x00000000, 0x4772b3ff, 0xffffffff, 0xd9d9d9ff,
+ 0xffffffff),
+ "menu_back": _wcol(0x242424ff, 0x181818ef, 0x2d2d2dff, 0x656565ff,
+ 0xa5a5a5ff, 0xffffffff, roundness=0.25),
+ "menu_item": _wcol(0x00000000, 0x00000000, 0x4772b3ff, 0xffffff8f, 0xe6e6e6ff,
+ 0xffffffff),
+ "list_item": _wcol(0x00000000, 0x00000000, 0x334d80ff, 0x4772b3ff, 0xe6e6e6ff,
+ 0xffffffff),
+ "box": _wcol(0x3d3d3dff, 0x282828ff, 0x4772b3ff, 0x191919ff, 0xe6e6e6ff, 0xffffffff),
+ "progress": _wcol(0x3d3d3dff, 0x1d1d1dff, 0x4772b3ff, 0x4772b3ff, 0xe6e6e6ff,
+ 0xffffffff),
+ "scroll": _wcol(0x00000000, 0x00000000, 0x646464b4, 0x545454ff, 0xe6e6e6ff,
+ 0xffffffff, roundness=0.5),
+ "tooltip": _wcol(0x3d3d3dff, 0x1d1d1dff, 0x1d1d1dff, 0x1d1d1dff, 0xe6e6e6ff, 0xffffffff,
+ roundness=0.25),
+ "tab": _wcol(0x1d1d1dff, 0x2a2a2aff, 0x3d3d3dff, 0x28292dff, 0x989898ff, 0xffffffff),
+}
+
+# --- region / panel colors ----------------------------------------------------
+REGION_BG = _rgba(0x303030ff) # editor region background
+TOPBAR_BG = _rgba(0x181818ff) # top bar / menubar header
+PANEL_HEADER = _rgba(0x3d3d3dff)
+PANEL_BACK = _rgba(0x3d3d3dff)
+PANEL_OUTLINE = _rgba(0x2a2a2aff)
+TEXT = _rgba(0xe6e6e6ff) # labels
+TEXT_DISABLED_FAC = 0.5 # Blender draws inactive widgets at 50% alpha
+WIDGET_EMBOSS = _rgba(0x00000026)
+TEXT_CURSOR = _rgba(0x71a8ffff)
+TEXT_SELECTION = _rgba(0x4772b380)
+MENU_SHADOW_FAC = 0.4
+MENU_SHADOW_WIDTH = 6
+HOVER_LIGHTEN = 15 / 255.0 # widget_active_color(): inner + 15
+
+
+# --- metrics ------------------------------------------------------------------
+def _detect_scale() -> float:
+ env = os.environ.get("BUI_UI_SCALE")
+ if env:
+ try:
+ return max(0.5, min(4.0, float(env)))
+ except ValueError:
+ pass
+ if sys.platform == "win32":
+ try:
+ import ctypes
+ dpi = ctypes.windll.user32.GetDpiForSystem()
+ return max(1.0, dpi / 96.0)
+ except Exception: # pragma: no cover - older Windows
+ return 1.0
+ return 1.0
+
+
+def _detect_font() -> str:
+ """Blender 4.x ships Inter; use it when installed, else the OS UI font."""
+ if sys.platform == "win32":
+ dirs = [os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts"),
+ os.path.join(os.environ.get("LOCALAPPDATA", ""), "Microsoft", "Windows",
+ "Fonts")]
+ for d in dirs:
+ if d and glob.glob(os.path.join(d, "Inter*")):
+ return "Inter"
+ return "Segoe UI"
+ for d in ("/usr/share/fonts", "/usr/local/share/fonts",
+ os.path.expanduser("~/.fonts"), "/Library/Fonts",
+ os.path.expanduser("~/Library/Fonts")):
+ if glob.glob(os.path.join(d, "**", "Inter*"), recursive=True):
+ return "Inter"
+ return "" # host default UI font
+
+
+SCALE = _detect_scale()
+FONT_FAMILY = _detect_font()
+
+
+# Scale-derived metrics, recomputed only when the scale changes (they are
+# read hundreds of times per frame).
+_UNIT = _FONT = _PAD = 0
+
+
+def _update_metrics() -> None:
+ global _UNIT, _FONT, _PAD
+ _UNIT = int(round(20 * SCALE))
+ _FONT = round(11 * SCALE)
+ _PAD = int(round(0.4 * _UNIT))
+
+
+def unit() -> int:
+ """U.widget_unit: standard widget height in pixels."""
+ return _UNIT
+
+
+def font_size() -> float:
+ """UI text size in pixels (11 pt at Blender's 72-dpi base)."""
+ return _FONT
+
+
+def pad() -> int:
+ """UI_TEXT_MARGIN_X: horizontal text inset inside widgets."""
+ return _PAD
+
+
+def radius(wcol: WidgetColors) -> float:
+ return wcol.roundness * unit()
+
+
+def set_scale(scale: float) -> None:
+ """Change the UI scale (like Blender's Resolution Scale)."""
+ global SCALE
+ SCALE = max(0.5, min(4.0, float(scale)))
+ _update_metrics()
+
+
+# --- color helpers --------------------------------------------------------------
+def lighten(c, amount=HOVER_LIGHTEN):
+ return (min(1.0, c[0] + amount), min(1.0, c[1] + amount), min(1.0, c[2] + amount), c[3])
+
+
+def shade(c, delta: int):
+ """Blender's shadetop/shadedown: add `delta` (-100..100) in 0..255 units."""
+ d = delta / 255.0
+ return (max(0.0, min(1.0, c[0] + d)), max(0.0, min(1.0, c[1] + d)),
+ max(0.0, min(1.0, c[2] + d)), c[3])
+
+
+def with_alpha(c, a):
+ return (c[0], c[1], c[2], c[3] * a)
+
+
+_update_metrics()
diff --git a/bindings/python/bui/tksyntax/__init__.py b/bindings/python/bui/tksyntax/__init__.py
new file mode 100644
index 0000000..7be9199
--- /dev/null
+++ b/bindings/python/bui/tksyntax/__init__.py
@@ -0,0 +1,79 @@
+"""BUI with tkinter syntax: tkinter's API, Blender's look, the C kit underneath.
+
+Write plain tkinter; widgets are BUI kit nodes (pack / grid / place, input
+and drawing run in C), windows are native on Windows::
+
+ import bui.tksyntax as tk
+ from bui.tksyntax import ttk, messagebox
+
+ root = tk.Tk()
+ tk.Button(root, text="Hello", command=root.destroy).pack()
+ root.mainloop()
+
+Existing tkinter programs run unchanged with ``python -m bui.tksyntax
+script.py``, or after :func:`install` (``import tkinter`` then returns this
+package).
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import importlib
+import sys
+
+from .constants import * # noqa: F401,F403
+from ._core import (BaseWidget, BooleanVar, CallWrapper, DoubleVar, Event, EventType, # noqa: F401
+ EXCEPTION, Grid, IntVar, Misc, NoDefaultRoot, Pack, Place, READABLE,
+ StringVar, TclError, TclVersion, Tk, TkVersion, Toplevel, Variable,
+ WRITABLE, Widget, Wm, XView, YView, _get_default_root, _get_temp_root,
+ _setit, color, getboolean, getdouble, getint, mainloop, wantobjects)
+from ._images import BitmapImage, Image, PhotoImage, image_names, image_types # noqa: F401
+from ._widgets import (Button, Canvas, Checkbutton, Entry, Frame, Label, LabelFrame, # noqa: F401
+ Listbox, Menu, Menubutton, Message, OptionMenu, PanedWindow,
+ Radiobutton, Scale, Scrollbar, Spinbox, Text)
+
+__bui__ = True # marks this package where it stands in for tkinter
+
+__all__ = [name for name, obj in globals().items()
+ if not name.startswith("_") and not isinstance(obj, type(sys))
+ and name not in ("TYPE_CHECKING", "annotations", "importlib", "sys")]
+
+
+def Tcl(screenName=None, baseName=None, className="Tk", useTk=False): # noqa: N802
+ """An interpreter without a window (it opens only if used like a Tk)."""
+ return Tk(screenName, baseName, className, useTk)
+
+
+Studbutton = Button
+Tributton = Button
+
+# ttk widgets were reachable from bui.tksyntax before the ttk module existed
+_TTK_COMPAT = ("Progressbar", "Combobox", "Treeview", "Notebook", "Separator", "Sizegrip",
+ "Style", "LabeledScale")
+
+_SUBMODULES = ("constants", "ttk", "font", "messagebox", "filedialog", "simpledialog",
+ "colorchooser", "commondialog", "dialog", "scrolledtext")
+
+
+def __getattr__(name):
+ if name == "_default_root": # tkinter._default_root is read by some programs
+ from . import _core
+ return _core._default_root
+ if name in _TTK_COMPAT:
+ from . import ttk
+ return getattr(ttk, name)
+ if name in _SUBMODULES:
+ return importlib.import_module(__name__ + "." + name)
+ raise AttributeError("module %r has no attribute %r" % (__name__, name))
+
+
+def install() -> None:
+ """Make ``import tkinter`` (and ``tkinter.ttk``, ``tkinter.messagebox``
+ ...) return BUI's tkinter for the rest of the process."""
+ from bui import _realtk
+ _realtk.pin() # BUI keeps using the real Tk for OS dialogs / GIF decoding
+ pkg = sys.modules[__name__]
+ sys.modules["tkinter"] = pkg
+ for sub in _SUBMODULES:
+ sys.modules["tkinter." + sub] = importlib.import_module(__name__ + "." + sub)
diff --git a/bindings/python/bui/tksyntax/__main__.py b/bindings/python/bui/tksyntax/__main__.py
new file mode 100644
index 0000000..97ae4e5
--- /dev/null
+++ b/bindings/python/bui/tksyntax/__main__.py
@@ -0,0 +1,26 @@
+"""Run a tkinter program on BUI, unchanged: ``python -m bui.tksyntax app.py [args]``.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import os
+import runpy
+import sys
+
+from bui import tksyntax
+
+
+def main() -> int:
+ if len(sys.argv) < 2:
+ sys.stderr.write("usage: python -m bui.tksyntax script.py [args...]\n")
+ return 2
+ script = sys.argv[1]
+ sys.argv = sys.argv[1:]
+ sys.path.insert(0, os.path.dirname(os.path.abspath(script)))
+ tksyntax.install()
+ runpy.run_path(script, run_name="__main__")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bindings/python/bui/tksyntax/__pycache__/__init__.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/__init__.cpython-314.pyc
new file mode 100644
index 0000000..b0542e6
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/__init__.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/__main__.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/__main__.cpython-314.pyc
new file mode 100644
index 0000000..c3e3959
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/__main__.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/_core.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/_core.cpython-314.pyc
new file mode 100644
index 0000000..d2f545e
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/_core.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/_images.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/_images.cpython-314.pyc
new file mode 100644
index 0000000..a52ca38
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/_images.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/_widgets.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/_widgets.cpython-314.pyc
new file mode 100644
index 0000000..b795648
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/_widgets.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/colorchooser.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/colorchooser.cpython-314.pyc
new file mode 100644
index 0000000..1a24141
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/colorchooser.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/commondialog.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/commondialog.cpython-314.pyc
new file mode 100644
index 0000000..86dd2a6
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/commondialog.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/constants.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/constants.cpython-314.pyc
new file mode 100644
index 0000000..2169931
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/constants.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/dialog.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/dialog.cpython-314.pyc
new file mode 100644
index 0000000..3b3f09d
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/dialog.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/filedialog.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/filedialog.cpython-314.pyc
new file mode 100644
index 0000000..c776fec
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/filedialog.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/font.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/font.cpython-314.pyc
new file mode 100644
index 0000000..9ca2508
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/font.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/messagebox.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/messagebox.cpython-314.pyc
new file mode 100644
index 0000000..b569047
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/messagebox.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/scrolledtext.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/scrolledtext.cpython-314.pyc
new file mode 100644
index 0000000..feadff8
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/scrolledtext.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/simpledialog.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/simpledialog.cpython-314.pyc
new file mode 100644
index 0000000..08e2987
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/simpledialog.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/__pycache__/ttk.cpython-314.pyc b/bindings/python/bui/tksyntax/__pycache__/ttk.cpython-314.pyc
new file mode 100644
index 0000000..ae80adf
Binary files /dev/null and b/bindings/python/bui/tksyntax/__pycache__/ttk.cpython-314.pyc differ
diff --git a/bindings/python/bui/tksyntax/_core.py b/bindings/python/bui/tksyntax/_core.py
new file mode 100644
index 0000000..6e36c21
--- /dev/null
+++ b/bindings/python/bui/tksyntax/_core.py
@@ -0,0 +1,2543 @@
+"""tkinter's foundation on the BUI kit.
+
+The classes here mirror ``tkinter/__init__.py``: ``Variable`` and friends,
+``Event``, ``Misc`` (after, bind, focus, winfo ...), the ``Pack`` / ``Place``
+/ ``Grid`` geometry mixins, ``XView`` / ``YView``, ``BaseWidget`` /
+``Widget``, ``Wm``, ``Tk`` and ``Toplevel``.
+
+A widget *wraps* one kit node (``self._node``) rather than being one, so
+tkinter's names (``get``, ``set``, ``type``, ``children`` ...) never clash
+with the node API. Layout, drawing and input run in C; this module keeps
+what tkinter itself keeps in Tcl: options, variables, bindings, names.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import collections
+import enum
+import functools
+import itertools
+import re
+import sys
+import time
+import traceback
+from typing import Optional
+
+import buipy
+
+from bui import host
+from bui.components.core import (EV_CONFIGURE, EV_DOUBLE, EV_ENTER, EV_KEY, EV_LEAVE,
+ EV_MOTION, EV_PRESS, EV_RELEASE, EV_VIEW, EV_WHEEL)
+from .constants import * # noqa: F401,F403
+
+TkVersion = 8.6
+TclVersion = 8.6
+wantobjects = 1
+READABLE, WRITABLE, EXCEPTION = 2, 4, 8
+EV_KEYRELEASE = 20 # BK_EV_KEYRELEASE
+
+_PACK, _GRID, _PLACE = 1, 2, 3
+_AN, _AS, _AW, _AE = 1, 2, 4, 8 # kit anchor bits
+
+
+class TclError(Exception):
+ """Raised where Tk would raise (bad index, unknown variable value ...)."""
+
+
+# ==========================================================================
+# Values: colors, fonts, distances, booleans
+
+_NAMED_COLORS = {
+ "white": "#ffffff", "black": "#000000", "red": "#ff0000", "green": "#008000",
+ "blue": "#0000ff", "yellow": "#ffff00", "gray": "#bebebe", "grey": "#bebebe",
+ "orange": "#ffa500", "purple": "#a020f0", "cyan": "#00ffff", "magenta": "#ff00ff",
+ "lightgray": "#d3d3d3", "lightgrey": "#d3d3d3", "darkgray": "#a9a9a9",
+ "darkgrey": "#a9a9a9", "pink": "#ffc0cb", "brown": "#a52a2a", "navy": "#000080",
+ "gold": "#ffd700", "silver": "#c0c0c0", "lime": "#00ff00", "maroon": "#b03060",
+ "teal": "#008080", "olive": "#808000", "darkblue": "#00008b", "darkgreen": "#006400",
+ "darkred": "#8b0000", "lightblue": "#add8e6", "lightgreen": "#90ee90",
+ "lightyellow": "#ffffe0", "skyblue": "#87ceeb", "steelblue": "#4682b4",
+ "royalblue": "#4169e1", "dodgerblue": "#1e90ff", "tomato": "#ff6347",
+ "salmon": "#fa8072", "coral": "#ff7f50", "khaki": "#f0e68c", "violet": "#ee82ee",
+ "indigo": "#4b0082", "turquoise": "#40e0d0", "beige": "#f5f5dc", "ivory": "#fffff0",
+ "snow": "#fffafa", "whitesmoke": "#f5f5f5", "gainsboro": "#dcdcdc",
+ "dimgray": "#696969", "slategray": "#708090", "darkorange": "#ff8c00",
+ "crimson": "#dc143c", "chocolate": "#d2691e", "tan": "#d2b48c", "wheat": "#f5deb3",
+ "orchid": "#da70d6", "plum": "#dda0dd", "lavender": "#e6e6fa", "mintcream": "#f5fffa",
+ "seagreen": "#2e8b57", "forestgreen": "#228b22", "limegreen": "#32cd32",
+ "springgreen": "#00ff7f", "aquamarine": "#7fffd4", "deepskyblue": "#00bfff",
+ "midnightblue": "#191970", "firebrick": "#b22222", "hotpink": "#ff69b4",
+ "deeppink": "#ff1493", "goldenrod": "#daa520", "sienna": "#a0522d",
+ # Tk's system colors map onto Blender's theme
+ "systembuttonface": "#3d3d3d", "systemwindow": "#282828", "systemwindowtext": "#e6e6e6",
+ "systembuttontext": "#e6e6e6", "systemhighlight": "#4772b3",
+ "systemhighlighttext": "#ffffff", "systemdisabledtext": "#808080",
+}
+
+
+def color(value):
+ """A Tk color (``#rgb``, ``#rrggbb``, ``#rrrrggggbbbb``, a name, or an
+ RGB(A) tuple) as RGBA floats; None for "" / None."""
+ if value is None or value == "":
+ return None
+ if isinstance(value, (tuple, list)):
+ v = tuple(float(c) / (255.0 if max(value) > 1 else 1.0) for c in value)
+ return v + (1.0,) if len(v) == 3 else v
+ s = str(value).strip()
+ key = s.lower().replace(" ", "")
+ s = _NAMED_COLORS.get(key, s)
+ if not s.startswith("#"):
+ m = re.match(r"^(gr[ae]y)(\d+)$", key) # gray0 .. gray100
+ if m:
+ v = round(int(m.group(2)) * 2.55)
+ s = "#%02x%02x%02x" % (v, v, v)
+ else:
+ raise TclError('unknown color name "%s"' % value)
+ hexs = s[1:]
+ if len(hexs) in (3, 6, 9, 12):
+ n = len(hexs) // 3
+ vals = [int(hexs[i * n:(i + 1) * n], 16) / float(16 ** n - 1) for i in range(3)]
+ return tuple(vals) + (1.0,)
+ if len(hexs) == 8:
+ return tuple(int(hexs[i:i + 2], 16) / 255.0 for i in range(0, 8, 2))
+ raise TclError('invalid color name "%s"' % value)
+
+
+def _try_color(value):
+ try:
+ return color(value)
+ except TclError:
+ return None
+
+
+def _hex(rgba) -> str:
+ return "#%02x%02x%02x" % tuple(round(c * 255) for c in rgba[:3])
+
+
+_TK_DEFAULT_POINTS = 9.0 # TkDefaultFont on Windows: the kit's UI font size
+
+
+def _font_parts(font):
+ """(family, points, styles) of a Tk font spec: a tuple, a string
+ ("Arial 12 bold", "{Courier New} 10"), a Font object or a named font."""
+ if font is None or font == "":
+ return "", 0.0, ()
+ actual = getattr(font, "actual", None)
+ if callable(actual) and not isinstance(font, (str, tuple, list)):
+ a = actual()
+ styles = tuple(s for s in (a.get("weight"), a.get("slant")) if s not in ("normal", "roman"))
+ return a.get("family", ""), float(a.get("size", 0)), styles
+ if isinstance(font, str):
+ named = _named_fonts().get(font)
+ if named is not None:
+ return _font_parts(named)
+ m = re.match(r"^\s*\{([^}]*)\}\s*(.*)$", font)
+ if m:
+ parts = [m.group(1)] + m.group(2).split()
+ else:
+ parts = font.split()
+ else:
+ parts = list(font)
+ family = str(parts[0]) if parts else ""
+ size = 0.0
+ if len(parts) > 1:
+ try:
+ size = float(parts[1])
+ except (TypeError, ValueError):
+ size = 0.0
+ styles = tuple(str(p).lower() for p in parts[2:])
+ if len(parts) > 2 and isinstance(parts[2], (tuple, list)):
+ styles = tuple(str(p).lower() for p in parts[2])
+ return family, size, styles
+
+
+def _named_fonts():
+ from . import font as _font # late: font imports this module
+ return _font._named
+
+
+def _font_scale(font) -> float:
+ """Kit text scale for a Tk font (points; negative sizes are pixels)."""
+ _, size, _ = _font_parts(font)
+ if not size:
+ return 0.0
+ points = size if size > 0 else -size * 0.75
+ return max(0.5, points / _TK_DEFAULT_POINTS)
+
+
+def _font_bold(font) -> bool:
+ return "bold" in _font_parts(font)[2]
+
+
+def _pixels(value) -> float:
+ """Tk screen distance ("10", "2c", "1i", "5m", "12p") in pixels."""
+ if isinstance(value, (int, float)):
+ return float(value)
+ s = str(value).strip()
+ m = re.match(r"^(-?[\d.]+)\s*([cimp]?)$", s)
+ if not m:
+ raise TclError('bad screen distance "%s"' % value)
+ v, unit = float(m.group(1)), m.group(2)
+ dpi = 96.0
+ return v * {"": 1.0, "c": dpi / 2.54, "i": dpi, "m": dpi / 25.4, "p": dpi / 72.0}[unit]
+
+
+def getint(s):
+ try:
+ return int(s)
+ except (TypeError, ValueError):
+ try:
+ return int(str(s), 0)
+ except ValueError:
+ raise TclError('expected integer but got "%s"' % s) from None
+
+
+def getdouble(s):
+ try:
+ return float(s)
+ except (TypeError, ValueError):
+ raise TclError('expected floating-point number but got "%s"' % s) from None
+
+
+_TRUE = ("1", "true", "yes", "on", "t", "y")
+_FALSE = ("0", "false", "no", "off", "f", "n")
+
+
+def getboolean(s):
+ if isinstance(s, bool):
+ return s
+ if isinstance(s, (int, float)):
+ return bool(s)
+ v = str(s).strip().lower()
+ if v in _TRUE:
+ return True
+ if v in _FALSE:
+ return False
+ raise TclError('expected boolean value but got "%s"' % s)
+
+
+def _anchor_bits(anchor) -> int:
+ a = str(anchor or "center").lower()
+ if a == "center":
+ return 0
+ return (_AN if "n" in a else 0) | (_AS if "s" in a else 0) | (_AW if "w" in a else 0) | \
+ (_AE if "e" in a else 0)
+
+
+def _pads(v):
+ if isinstance(v, (tuple, list)):
+ return int(_pixels(v[0])), int(_pixels(v[1] if len(v) > 1 else v[0]))
+ if isinstance(v, str) and " " in v.strip():
+ return _pads(v.split())
+ p = int(_pixels(v or 0))
+ return p, p
+
+
+def _chars(n) -> int:
+ """Tk text widths are in average characters."""
+ return int(round(int(n) * buipy.kit_unit() * 0.42)) + round(0.8 * buipy.kit_unit())
+
+
+def _font_px() -> float:
+ return buipy.kit_unit() * 0.55
+
+
+def _text_width(text: str) -> float:
+ w = buipy.measure_text(text, _font_px()) if text else 0
+ return float(w) if w is not None else len(text) * _font_px() * 0.55
+
+
+def _wrap(text: str, width_px: float) -> str:
+ """Word-wrap `text` to `width_px` (Tk's wraplength / Message)."""
+ if width_px <= 0:
+ return text
+ out = []
+ for para in str(text).split("\n"):
+ line = ""
+ for word in para.split(" "):
+ cand = word if not line else line + " " + word
+ if line and _text_width(cand) > width_px:
+ out.append(line)
+ line = word
+ else:
+ line = cand
+ out.append(line)
+ return "\n".join(out)
+
+
+# ==========================================================================
+# Variables
+
+_var_counter = itertools.count()
+_variables: dict = {}
+
+
+class Variable:
+ """tkinter.Variable: a named value with read/write/unset traces."""
+
+ _default = ""
+
+ def __init__(self, master=None, value=None, name=None):
+ self._name = name or "PY_VAR%d" % next(_var_counter)
+ self._root = master
+ self._traces: dict = {}
+ old = _variables.get(self._name)
+ if value is not None:
+ self._value = value
+ elif old is not None:
+ self._value = old._value
+ else:
+ self._value = self._default
+ _variables[self._name] = self
+
+ def __str__(self):
+ return self._name
+
+ def __repr__(self):
+ return "<%s object %s>" % (type(self).__name__, self._name)
+
+ def __eq__(self, other):
+ return isinstance(other, Variable) and type(self) is type(other) and \
+ self._name == other._name
+
+ def __hash__(self):
+ return hash(self._name)
+
+ def _fire(self, mode):
+ for cbname, (modes, fn) in list(self._traces.items()):
+ if mode in modes and cbname in self._traces:
+ fn(self._name, "", mode)
+
+ def set(self, value):
+ """Set the variable to VALUE."""
+ self._value = value
+ self._fire("write")
+
+ initialize = set
+
+ def _raw(self): # read without firing read traces (widget sync)
+ return self._value
+
+ def get(self):
+ """Return value of variable."""
+ self._fire("read")
+ return self._value
+
+ def trace_add(self, mode, callback):
+ modes = (mode,) if isinstance(mode, str) else tuple(mode)
+ for m in modes:
+ if m not in ("array", "read", "write", "unset"):
+ raise TclError('bad operation "%s"' % m)
+ cbname = "%d%s" % (next(_var_counter), getattr(callback, "__name__", "cb"))
+ self._traces[cbname] = (modes, callback)
+ return cbname
+
+ def trace_remove(self, mode, cbname):
+ self._traces.pop(cbname, None)
+
+ def trace_info(self):
+ return [(modes, cbname) for cbname, (modes, _fn) in self._traces.items()]
+
+ _LETTERS = {"r": "read", "w": "write", "u": "unset", "a": "array"}
+
+ def trace_variable(self, mode, callback):
+ return self.trace_add(tuple(self._LETTERS[c] for c in mode), callback)
+
+ trace = trace_variable
+
+ def trace_vdelete(self, mode, cbname):
+ self.trace_remove(mode, cbname)
+
+ def trace_vinfo(self):
+ rev = {v: k for k, v in self._LETTERS.items()}
+ return [("".join(rev[m] for m in modes), cb) for modes, cb in self.trace_info()]
+
+ def __del__(self):
+ pass
+
+
+class StringVar(Variable):
+ _default = ""
+
+ def get(self):
+ v = super().get()
+ return v if isinstance(v, str) else str(v)
+
+
+class IntVar(Variable):
+ _default = 0
+
+ def get(self):
+ v = super().get()
+ try:
+ return int(v)
+ except (TypeError, ValueError):
+ try:
+ return int(getdouble(v))
+ except TclError:
+ raise TclError('expected integer but got "%s"' % v) from None
+
+
+class DoubleVar(Variable):
+ _default = 0.0
+
+ def get(self):
+ return getdouble(super().get())
+
+
+class BooleanVar(Variable):
+ _default = False
+
+ def set(self, value):
+ super().set(getboolean(value) if value != "" else value)
+
+ initialize = set
+
+ def get(self):
+ v = super().get()
+ try:
+ return getboolean(v)
+ except TclError:
+ raise ValueError("invalid literal for getboolean()") from None
+
+
+def _var_value(var):
+ return var._raw() if isinstance(var, Variable) else _variables[str(var)]._raw()
+
+
+# ==========================================================================
+# Events
+
+class EventType(enum.StrEnum):
+ KeyPress = '2'
+ Key = KeyPress
+ KeyRelease = '3'
+ ButtonPress = '4'
+ Button = ButtonPress
+ ButtonRelease = '5'
+ Motion = '6'
+ Enter = '7'
+ Leave = '8'
+ FocusIn = '9'
+ FocusOut = '10'
+ Keymap = '11'
+ Expose = '12'
+ GraphicsExpose = '13'
+ NoExpose = '14'
+ Visibility = '15'
+ Create = '16'
+ Destroy = '17'
+ Unmap = '18'
+ Map = '19'
+ MapRequest = '20'
+ Reparent = '21'
+ Configure = '22'
+ ConfigureRequest = '23'
+ Gravity = '24'
+ ResizeRequest = '25'
+ Circulate = '26'
+ CirculateRequest = '27'
+ Property = '28'
+ SelectionClear = '29'
+ SelectionRequest = '30'
+ Selection = '31'
+ Colormap = '32'
+ ClientMessage = '33'
+ Mapping = '34'
+ VirtualEvent = '35'
+ Activate = '36'
+ Deactivate = '37'
+ MouseWheel = '38'
+
+ def __str__(self):
+ return self.name
+
+
+class Event:
+ """Container for the properties of an event (tkinter.Event)."""
+
+ def __init__(self, **kw):
+ self.serial = 0
+ self.num = "??"
+ self.focus = False
+ self.height = self.width = "??"
+ self.keycode = "??"
+ self.state = 0
+ self.time = int(time.monotonic() * 1000) & 0x7fffffff
+ self.x = self.y = self.x_root = self.y_root = 0
+ self.char = ""
+ self.send_event = False
+ self.keysym = "??"
+ self.keysym_num = "??"
+ self.type = EventType.VirtualEvent
+ self.widget = None
+ self.delta = 0
+ self.__dict__.update(kw)
+
+ def __repr__(self):
+ attrs = {k: v for k, v in self.__dict__.items() if v != "??" and not k.startswith("_")}
+ attrs.pop("widget", None)
+ body = " ".join("%s=%r" % (k, v) for k, v in attrs.items()
+ if k not in ("serial", "time", "send_event", "focus"))
+ return "<%s event %s>" % (getattr(self.type, "name", self.type), body)
+
+
+# modifier bits (Tk's event.state)
+_SHIFT, _LOCK, _CONTROL = 0x1, 0x2, 0x4
+_ALT = 0x20000 if sys.platform == "win32" else 0x8
+_B1, _B2, _B3 = 0x100, 0x200, 0x400
+_MOD_BITS = {"shift": _SHIFT, "lock": _LOCK, "control": _CONTROL, "ctrl": _CONTROL,
+ "alt": _ALT, "meta": _ALT, "mod1": _ALT, "option": _ALT, "command": _CONTROL,
+ "b1": _B1, "button1": _B1, "b2": _B2, "button2": _B2, "b3": _B3, "button3": _B3}
+_COUNTS = {"double": 2, "triple": 3, "quadruple": 4}
+_TYPES = {"keypress": "KeyPress", "key": "KeyPress", "keyrelease": "KeyRelease",
+ "buttonpress": "ButtonPress", "button": "ButtonPress",
+ "buttonrelease": "ButtonRelease", "motion": "Motion", "enter": "Enter",
+ "leave": "Leave", "mousewheel": "MouseWheel", "configure": "Configure",
+ "focusin": "FocusIn", "focusout": "FocusOut", "destroy": "Destroy", "map": "Map",
+ "unmap": "Unmap", "expose": "Expose", "visibility": "Visibility",
+ "activate": "Activate", "deactivate": "Deactivate"}
+
+
+def _kit_mods_to_state(mods: int) -> int:
+ return ((_SHIFT if mods & 1 else 0) | (_CONTROL if mods & 2 else 0) |
+ (_ALT if mods & 4 else 0) | (_B1 if mods & 8 else 0))
+
+
[email protected]_cache(maxsize=512)
+def _parse_sequence(sequence: str):
+ """'<Control-Button-1>' -> (type, detail, modifier mask, click count).
+ Virtual events -> ('Virtual', '<<Name>>', 0, 1)."""
+ s = sequence.strip()
+ if s.startswith("<<") and s.endswith(">>"):
+ return ("Virtual", s, 0, 1)
+ if not s.startswith("<"): # "a": a key press
+ return ("KeyPress", s[-1:] if s else "", 0, 1)
+ parts = s.strip("<>").split("-")
+ etype, detail, mask, count = None, None, 0, 1
+ for i, p in enumerate(parts):
+ low = p.lower()
+ if detail is None and etype is None and low in _COUNTS:
+ count = _COUNTS[low]
+ elif etype is None and detail is None and low in _MOD_BITS and i < len(parts) - 1:
+ mask |= _MOD_BITS[low]
+ elif etype is None and low in _TYPES:
+ etype = _TYPES[low]
+ elif p == "" and i == len(parts) - 1: # "<Control-->" (minus key)
+ detail = "minus"
+ else:
+ detail = "-".join(parts[i:])
+ break
+ if etype is None:
+ etype = "ButtonPress" if detail and detail.isdigit() else "KeyPress"
+ if etype in ("ButtonPress", "ButtonRelease") and detail and not detail.isdigit():
+ raise TclError('bad event type or keysym "%s"' % detail)
+ return (etype, detail, mask, count)
+
+
+def _matches(pattern, ev) -> bool:
+ etype, detail, mask, count = pattern
+ if etype != ev.type.name:
+ return False
+ if (ev.state & mask) != mask or count > getattr(ev, "_count", 1):
+ return False
+ if detail is None:
+ return True
+ if etype in ("ButtonPress", "ButtonRelease"):
+ return str(ev.num) == detail
+ if ev.keysym == detail:
+ return True
+ return bool(mask & (_CONTROL | _ALT)) and ev.keysym.lower() == detail.lower()
+
+
+def _specificity(pattern):
+ etype, detail, mask, count = pattern
+ return (count, bin(mask).count("1"), detail is not None)
+
+
+class _BindTable:
+ """Bindings of one tag: sequence -> callbacks (Tk keeps one script per
+ sequence; ``add`` appends)."""
+
+ __slots__ = ("seqs",)
+
+ def __init__(self):
+ self.seqs: dict = {}
+
+ def bind(self, sequence, func, add):
+ _parse_sequence(sequence) # validate now (Tk raises at bind time)
+ funcs = self.seqs.setdefault(sequence, [])
+ if not add or add == "":
+ funcs.clear()
+ funcs.append(func)
+ return "%d%s" % (id(func), getattr(func, "__name__", ""))
+
+ def unbind(self, sequence, funcid=None):
+ funcs = self.seqs.get(sequence)
+ if funcs is None:
+ return
+ if funcid is None:
+ del self.seqs[sequence]
+ else:
+ funcs[:] = [f for f in funcs if "%d%s" % (id(f), getattr(f, "__name__", "")) != funcid]
+
+ def match(self, ev):
+ """Callbacks of the most specific sequence matching `ev` (Tk runs
+ one binding per tag)."""
+ best, best_key = None, None
+ for seq, funcs in self.seqs.items():
+ pat = _parse_sequence(seq)
+ if _matches(pat, ev):
+ key = _specificity(pat)
+ if best_key is None or key > best_key:
+ best, best_key = funcs, key
+ return best or ()
+
+ def virtual(self, name):
+ return self.seqs.get(name, ())
+
+
+_bindtables: dict = collections.defaultdict(_BindTable)
+_virtual_events: dict = {} # "<<Copy>>" -> [physical sequences]
+_class_tags_bound: set = set() # tags other than widget paths that have bindings
+
+
+def _dispatch(widget, ev):
+ """Run the bindings of every bindtag of `widget` (widget, class,
+ toplevel, all); "break" stops (Tk semantics)."""
+ for tag in widget.bindtags():
+ table = _bindtables.get(tag)
+ if table is None:
+ continue
+ funcs = table.virtual(ev._virtual) if getattr(ev, "_virtual", None) else table.match(ev)
+ for fn in list(funcs):
+ if _call(widget, fn, ev) == "break":
+ return "break"
+ if not getattr(ev, "_virtual", None):
+ for name, seqs in list(_virtual_events.items()):
+ if any(_matches(_parse_sequence(s), ev) for s in seqs):
+ widget.event_generate(name)
+ return None
+
+
+def _call(widget, fn, *args):
+ try:
+ return fn(*args)
+ except Exception:
+ root = widget._root() if widget is not None else _default_root
+ if root is not None:
+ root.report_callback_exception(*sys.exc_info())
+ else:
+ raise
+ return None
+
+
+# ==========================================================================
+# Misc: services shared by every widget and window
+
+
+_after_ids = itertools.count(1)
+_commands: dict = {}
+_option_db: list = []
+_selection = {"PRIMARY": None, "CLIPBOARD": None}
+
+_TK_CURSORS = {"": -1, "arrow": 0, "left_ptr": 0, "top_left_arrow": 0, "xterm": 3, "ibeam": 3,
+ "hand1": 5, "hand2": 5, "pointinghand": 5, "crosshair": 4, "cross": 4,
+ "tcross": 4, "sb_h_double_arrow": 1, "sb_v_double_arrow": 2,
+ "size_we": 1, "size_ns": 2, "fleur": 6, "size": 6, "sizing": 6,
+ "watch": 0, "wait": 0, "none": 7}
+
+
+class Misc:
+ """Methods shared by all widgets and windows (tkinter.Misc)."""
+
+ _last_child_ids = None
+ _name = ""
+ _w = ""
+
+ # -- identity -------------------------------------------------------------
+ def __str__(self):
+ return self._w
+
+ def _root(self):
+ w = self
+ while w.master is not None:
+ w = w.master
+ return w
+
+ def _toplevel_window(self):
+ w = self
+ while not getattr(w, "_is_window", False):
+ w = w.master
+ return w
+
+ def winfo_toplevel(self):
+ return self._toplevel_window()
+
+ def nametowidget(self, name):
+ name = str(name)
+ if not name.startswith("."):
+ w = self
+ else:
+ w = self._root()
+ name = name[1:]
+ for part in filter(None, name.split(".")):
+ w = w.children[part]
+ return w
+
+ _nametowidget = nametowidget
+
+ # -- timers -----------------------------------------------------------------
+ def after(self, ms, func=None, *args):
+ """Call FUNC with ARGS after MS milliseconds (sleep when no FUNC)."""
+ if func is None:
+ time.sleep(int(ms) / 1000.0)
+ return None
+ root = self._root()
+ name = "after#%d" % next(_after_ids)
+
+ def fire():
+ root._afters.pop(name, None)
+ _call(self, func, *args)
+ win = self._toplevel_window()._window
+ root._afters[name] = (win, win.after(max(0, int(ms)), fire), "timer")
+ return name
+
+ def after_idle(self, func, *args):
+ name = self.after(0, func, *args)
+ win, token, _ = self._root()._afters[name]
+ self._root()._afters[name] = (win, token, "idle")
+ return name
+
+ def after_cancel(self, id): # noqa: A002 - tkinter name
+ if not id:
+ raise ValueError("id must be a valid identifier returned from after or after_idle")
+ entry = self._root()._afters.pop(id, None)
+ if entry is not None:
+ entry[0].after_cancel(entry[1])
+
+ def after_info(self, id=None): # noqa: A002
+ afters = self._root()._afters
+ if id is None:
+ return tuple(afters)
+ if id not in afters:
+ raise TclError('event "%s" doesn\'t exist' % id)
+ return (None, afters[id][2])
+
+ # -- event loop ------------------------------------------------------------
+ def mainloop(self, n=0):
+ _show_windows()
+ host.run()
+
+ def quit(self):
+ host.quit()
+
+ def update(self):
+ _show_windows()
+ host.update()
+
+ def update_idletasks(self):
+ host.update()
+
+ def wait_variable(self, name="PY_VAR"):
+ var = name if isinstance(name, Variable) else _variables[str(name)]
+ done = []
+ cb = var.trace_add("write", lambda *a: done.append(1))
+ try:
+ _wait_until(lambda: done)
+ finally:
+ var.trace_remove("write", cb)
+
+ waitvar = wait_variable
+
+ def wait_window(self, window=None):
+ window = window or self
+ _wait_until(lambda: not window.winfo_exists())
+
+ def wait_visibility(self, window=None):
+ window = window or self
+ _wait_until(lambda: window.winfo_ismapped() or not window.winfo_exists())
+
+ # -- bindings ------------------------------------------------------------------
+ def _bind(self, tag, sequence, func, add):
+ if sequence is None:
+ return tuple(_bindtables[tag].seqs) if tag in _bindtables else ()
+ if func is None:
+ funcs = _bindtables[tag].seqs.get(sequence) if tag in _bindtables else None
+ return " ".join(getattr(f, "__name__", "?") for f in funcs) if funcs else ""
+ funcid = _bindtables[tag].bind(sequence, func, add)
+ if not tag.startswith("."):
+ _class_tags_bound.add(tag)
+ _events_changed(self._root(), tag)
+ return funcid
+
+ def bind(self, sequence=None, func=None, add=None):
+ """Bind FUNC to SEQUENCE on this widget ('<Button-1>', '<Key>' ...)."""
+ return self._bind(self._w, sequence, func, add)
+
+ def unbind(self, sequence, funcid=None):
+ if self._w in _bindtables:
+ _bindtables[self._w].unbind(sequence, funcid)
+
+ def bind_all(self, sequence=None, func=None, add=None):
+ return self._bind("all", sequence, func, add)
+
+ def unbind_all(self, sequence):
+ if "all" in _bindtables:
+ _bindtables["all"].unbind(sequence)
+
+ def bind_class(self, className, sequence=None, func=None, add=None):
+ return self._bind(className, sequence, func, add)
+
+ def unbind_class(self, className, sequence):
+ if className in _bindtables:
+ _bindtables[className].unbind(sequence)
+
+ def bindtags(self, tagList=None):
+ if tagList is None:
+ if self.__dict__.get("_tags") is not None:
+ return self._tags
+ top = self._toplevel_window()
+ if top is self:
+ return (self._w, self.winfo_class(), "all")
+ return (self._w, self.winfo_class(), top._w, "all")
+ self._tags = tuple(tagList)
+ _events_changed(self._root(), None)
+ return None
+
+ def event_add(self, virtual, *sequences):
+ _virtual_events.setdefault(virtual, [])
+ for s in sequences:
+ _parse_sequence(s)
+ if s not in _virtual_events[virtual]:
+ _virtual_events[virtual].append(s)
+ _events_changed(self._root(), None)
+
+ def event_delete(self, virtual, *sequences):
+ if not sequences:
+ _virtual_events.pop(virtual, None)
+ else:
+ _virtual_events[virtual] = [s for s in _virtual_events.get(virtual, ())
+ if s not in sequences]
+
+ def event_info(self, virtual=None):
+ if virtual is None:
+ return tuple(_virtual_events)
+ return tuple(_virtual_events.get(virtual, ()))
+
+ def event_generate(self, sequence, **kw):
+ """Generate an event: virtual ('<<Name>>') or physical ('<Button-1>')."""
+ etype, detail, mask, count = _parse_sequence(sequence)
+ if etype == "Virtual":
+ ev = Event(type=EventType.VirtualEvent, widget=self, _virtual=sequence, **kw)
+ else:
+ fields = dict(type=EventType[etype], widget=self, state=mask | kw.pop("state", 0),
+ _count=count)
+ if etype in ("ButtonPress", "ButtonRelease"):
+ fields["num"] = int(detail or 1)
+ elif etype in ("KeyPress", "KeyRelease"):
+ fields["keysym"] = detail or kw.get("keysym", "")
+ fields["char"] = detail if detail and len(detail) == 1 else ""
+ fields.update(kw)
+ ev = Event(**fields)
+ if etype in ("KeyPress", "KeyRelease"): # Tk sends keys to the focus widget
+ target = self._toplevel_window()._focus
+ if target is None:
+ return
+ ev.widget = target
+ _dispatch(target, ev)
+ return
+ _dispatch(self, ev)
+
+ # -- focus -----------------------------------------------------------------------
+ def focus_set(self):
+ """Direct keyboard input to this widget."""
+ top = self._toplevel_window()
+ old = top._focus
+ top._focus = self
+ node = getattr(self, "_node", None)
+ if node is not None and hasattr(self, "_focus_node"):
+ top._ctx.focus_node(self._focus_node())
+ if old is not self:
+ if old is not None and old.winfo_exists():
+ old.event_generate("<FocusOut>")
+ self.event_generate("<FocusIn>")
+
+ focus = focus_set
+
+ def focus_force(self):
+ self._toplevel_window()._window.wm("focus")
+ self.focus_set()
+
+ def focus_get(self):
+ for top in _windows():
+ if top._focus is not None and top._focus.winfo_exists():
+ return top._focus
+ return None
+
+ def focus_displayof(self):
+ return self._toplevel_window()._focus
+
+ def focus_lastfor(self):
+ top = self._toplevel_window()
+ return top._focus or top
+
+ def _focus_order(self):
+ top = self._toplevel_window()
+ return [w for w in top._descendants() if w.cget("takefocus") not in (0, "0", False) and
+ getattr(w, "_TAKEFOCUS", False) and w.winfo_ismapped()]
+
+ def tk_focusNext(self):
+ order = self._focus_order()
+ if not order:
+ return None
+ return order[(order.index(self) + 1) % len(order)] if self in order else order[0]
+
+ def tk_focusPrev(self):
+ order = self._focus_order()
+ if not order:
+ return None
+ return order[(order.index(self) - 1) % len(order)] if self in order else order[-1]
+
+ def tk_focusFollowsMouse(self):
+ pass # the kit routes keys to the field being edited (Blender)
+
+ # -- grabs (modal windows disable their siblings) --------------------------------------
+ def grab_set(self):
+ top = self._toplevel_window()
+ for w in _windows():
+ if w is not top:
+ w._window.wm("disabled", 1)
+ _grab["window"] = top
+ _grab["widget"] = self
+
+ grab_set_global = grab_set
+
+ def grab_release(self):
+ if _grab.get("widget") is self or _grab.get("window") is self._toplevel_window():
+ for w in _windows():
+ w._window.wm("disabled", 0)
+ _grab.clear()
+
+ def grab_current(self):
+ return _grab.get("widget")
+
+ def grab_status(self):
+ return "local" if _grab.get("widget") is self else None
+
+ # -- clipboard & selection -----------------------------------------------------------------
+ def clipboard_clear(self, **kw):
+ self._toplevel_window()._ctx.clipboard_set("")
+
+ def clipboard_append(self, string, **kw):
+ ctx = self._toplevel_window()._ctx
+ ctx.clipboard_set(ctx.clipboard_get() + str(string))
+
+ def clipboard_get(self, **kw):
+ text = self._toplevel_window()._ctx.clipboard_get()
+ if not text:
+ raise TclError("CLIPBOARD selection doesn't exist or form \"STRING\" not defined")
+ return text
+
+ def selection_own(self, **kw):
+ _selection[kw.get("selection", "PRIMARY")] = self
+
+ def selection_own_get(self, **kw):
+ owner = _selection.get(kw.get("selection", "PRIMARY"))
+ if owner is None:
+ raise TclError("selection isn't owned")
+ return owner
+
+ def selection_clear(self, **kw):
+ _selection[kw.get("selection", "PRIMARY")] = None
+
+ def selection_get(self, **kw):
+ sel = kw.get("selection", "PRIMARY")
+ if sel == "CLIPBOARD":
+ return self.clipboard_get()
+ owner = _selection.get(sel)
+ text = owner._selected_text() if owner is not None and hasattr(owner, "_selected_text") \
+ else None
+ if not text:
+ raise TclError("PRIMARY selection doesn't exist or form \"STRING\" not defined")
+ return text
+
+ def selection_handle(self, command, **kw):
+ self._selection_handler = command
+
+ # -- variables / commands / interpreter ------------------------------------------------------
+ def getvar(self, name="PY_VAR"):
+ try:
+ return _variables[str(name)]._raw()
+ except KeyError:
+ raise TclError("can't read \"%s\": no such variable" % name) from None
+
+ def setvar(self, name="PY_VAR", value="1"):
+ var = _variables.get(str(name))
+ if var is None:
+ var = StringVar(name=str(name))
+ var.set(value)
+
+ getint = staticmethod(getint)
+ getdouble = staticmethod(getdouble)
+
+ def getboolean(self, s):
+ return getboolean(s)
+
+ def register(self, func, subst=None, needcleanup=1):
+ name = "%d%s" % (id(func), getattr(func, "__name__", "cmd"))
+ _commands[name] = func
+ return name
+
+ _register = register
+
+ def deletecommand(self, name):
+ _commands.pop(name, None)
+
+ def info_patchlevel(self):
+ return _VersionInfo(8, 6, 13, "final", 0)
+
+ def image_names(self):
+ from ._images import image_names
+ return image_names()
+
+ def image_types(self):
+ return ("photo", "bitmap")
+
+ # -- option database (kept; the look is Blender's theme) -----------------------------------------
+ def option_add(self, pattern, value, priority=None):
+ _option_db.append((str(pattern), value))
+
+ def option_clear(self):
+ _option_db.clear()
+
+ def option_get(self, name, className):
+ for pattern, value in reversed(_option_db):
+ last = pattern.split(".")[-1].split("*")[-1]
+ if last in (name, className):
+ return value
+ return ""
+
+ def option_readfile(self, fileName, priority=None):
+ with open(fileName, encoding="utf-8") as fh:
+ for line in fh:
+ line = line.strip()
+ if line and not line.startswith(("!", "#")) and ":" in line:
+ pattern, _, value = line.partition(":")
+ self.option_add(pattern.strip(), value.strip())
+
+ # -- palette & misc (the theme is Blender's) ---------------------------------------------------
+ def tk_setPalette(self, *args, **kw):
+ pass
+
+ def tk_bisque(self):
+ pass
+
+ def tk_strictMotif(self, boolean=None):
+ return 0
+
+ def bell(self, displayof=0):
+ if sys.platform == "win32":
+ import ctypes
+ ctypes.windll.user32.MessageBeep(0)
+ else:
+ sys.stdout.write("\a")
+ sys.stdout.flush()
+
+ def send(self, interp, cmd, *args):
+ raise TclError('invalid command name "send"') # as on Windows Tk
+
+ # -- busy (Tk 8.7) --------------------------------------------------------------------------
+ def tk_busy_hold(self, **kw):
+ self._busy = True
+ if getattr(self, "_node", None) is not None:
+ self._node.set("cursor", 0)
+ self._node.set("enabled", False)
+
+ busy_hold = busy = tk_busy = tk_busy_hold
+
+ def tk_busy_forget(self):
+ self._busy = False
+ if getattr(self, "_node", None) is not None:
+ self._node.set("enabled", True)
+ self._node.set("cursor", -1)
+
+ busy_forget = tk_busy_forget
+
+ def tk_busy_status(self):
+ return bool(getattr(self, "_busy", False))
+
+ busy_status = tk_busy_status
+
+ def tk_busy_current(self, pattern=None):
+ return [w for w in self._root()._descendants() if getattr(w, "_busy", False)]
+
+ busy_current = tk_busy_current
+
+ def tk_busy_cget(self, option):
+ return "watch" if option.lstrip("-") == "cursor" else ""
+
+ busy_cget = tk_busy_cget
+
+ def tk_busy_configure(self, cnf=None, **kw):
+ return {}
+
+ tk_busy_config = busy_configure = busy_config = tk_busy_configure
+
+ # -- stacking -----------------------------------------------------------------------------
+ def tkraise(self, aboveThis=None):
+ """Raise this widget in the stacking order (place-managed siblings)."""
+ node = getattr(self, "_node", None)
+ if node is not None and node.parent is not None and node.geom_get("manager") == _PLACE:
+ node.parent.add(node)
+
+ lift = tkraise
+
+ def lower(self, belowThis=None):
+ node = getattr(self, "_node", None)
+ if node is not None and node.parent is not None and node.geom_get("manager") == _PLACE:
+ node.parent.add(node, 0)
+
+ # -- geometry info on containers (tkinter defines these on Misc) -------------------------------
+ def _container(self):
+ return self._node
+
+ def _managed_children(self, manager):
+ return [c for c in self.winfo_children() if c.winfo_manager() == manager]
+
+ def pack_propagate(self, flag=None):
+ if flag is None:
+ return not self._container().get("nopropagate")
+ self._container().set("nopropagate", not getboolean(flag))
+ self._size_changed()
+ return None
+
+ propagate = pack_propagate
+
+ def pack_slaves(self):
+ return self._managed_children("pack")
+
+ slaves = pack_slaves
+
+ def place_slaves(self):
+ return self._managed_children("place")
+
+ def grid_propagate(self, flag=None):
+ return self.pack_propagate(flag)
+
+ def grid_slaves(self, row=None, column=None):
+ out = []
+ for c in reversed(self._managed_children("grid")):
+ info = c._ginfo
+ r0, c0 = int(info.get("row", 0)), int(info.get("column", 0))
+ rs, cs = int(info.get("rowspan", 1)), int(info.get("columnspan", 1))
+ if (row is None or r0 <= int(row) < r0 + rs) and \
+ (column is None or c0 <= int(column) < c0 + cs):
+ out.append(c)
+ return out
+
+ def grid_size(self):
+ cols = rows = 0
+ for c in self._managed_children("grid"):
+ info = c._ginfo
+ cols = max(cols, int(info.get("column", 0)) + int(info.get("columnspan", 1)))
+ rows = max(rows, int(info.get("row", 0)) + int(info.get("rowspan", 1)))
+ return (cols, rows)
+
+ size = grid_size
+
+ def _grid_cells(self):
+ """Measured column/row edges from the gridded children."""
+ x0, y0 = self._container().rect[:2]
+ cols, rows = {}, {}
+ for c in self._managed_children("grid"):
+ info, r = c._ginfo, c._node.rect
+ ci, ri = int(info.get("column", 0)), int(info.get("row", 0))
+ cols.setdefault(ci, [r[0] - x0, r[0] - x0 + r[2]])
+ rows.setdefault(ri, [r[1] - y0, r[1] - y0 + r[3]])
+ cols[ci] = [min(cols[ci][0], r[0] - x0), max(cols[ci][1], r[0] - x0 + r[2])]
+ rows[ri] = [min(rows[ri][0], r[1] - y0), max(rows[ri][1], r[1] - y0 + r[3])]
+ return cols, rows
+
+ def grid_bbox(self, column=None, row=None, col2=None, row2=None):
+ cols, rows = self._grid_cells()
+ if not cols:
+ return None
+ c0 = min(cols) if column is None else int(column)
+ r0 = min(rows) if row is None else int(row)
+ c1 = (max(cols) if column is None else c0) if col2 is None else int(col2)
+ r1 = (max(rows) if row is None else r0) if row2 is None else int(row2)
+ xs = [cols[c] for c in cols if c0 <= c <= c1]
+ ys = [rows[r] for r in rows if r0 <= r <= r1]
+ if not xs or not ys:
+ return (0, 0, 0, 0)
+ x, y = min(a for a, _ in xs), min(a for a, _ in ys)
+ return (x, y, max(b for _, b in xs) - x, max(b for _, b in ys) - y)
+
+ bbox = grid_bbox
+
+ def grid_location(self, x, y):
+ cols, rows = self._grid_cells()
+
+ def find(edges, v):
+ for i in sorted(edges):
+ if v < edges[i][1]:
+ return i
+ return max(edges) + 1 if edges else 0
+ return (find(cols, int(x)) if int(x) >= 0 else -1,
+ find(rows, int(y)) if int(y) >= 0 else -1)
+
+ def grid_anchor(self, anchor=None):
+ if anchor is None:
+ return getattr(self, "_grid_anchor", "nw")
+ self._grid_anchor = anchor # the kit grid is anchored nw
+
+ anchor = grid_anchor
+
+ def grid_columnconfigure(self, index, cnf=None, **kw):
+ return self._grid_weight(1, index, cnf, kw)
+
+ columnconfigure = grid_columnconfigure
+
+ def grid_rowconfigure(self, index, cnf=None, **kw):
+ return self._grid_weight(0, index, cnf, kw)
+
+ rowconfigure = grid_rowconfigure
+
+ def _grid_weight(self, axis, index, cnf, kw):
+ if cnf:
+ kw = dict(cnf, **kw)
+ store = self.__dict__.setdefault("_grid_conf", {})
+ indices = index if isinstance(index, (tuple, list)) else (index,)
+ if not kw:
+ return dict(store.get((axis, int(indices[0]) if str(indices[0]).isdigit()
+ else indices[0]), {"weight": 0, "minsize": 0, "pad": 0,
+ "uniform": None}))
+ for i in indices:
+ if isinstance(i, BaseWidget):
+ info = i._ginfo
+ i = int(info.get("column" if axis else "row", 0))
+ conf = store.setdefault((axis, int(i)), {"weight": 0, "minsize": 0, "pad": 0,
+ "uniform": None})
+ conf.update(kw)
+ self._container().grid_weight(axis, int(i), float(conf["weight"]),
+ int(_pixels(conf["minsize"])))
+ return None
+
+ # -- window information ---------------------------------------------------------------
+ def _rect(self):
+ node = getattr(self, "_node", None)
+ return node.rect if node is not None else (0, 0, 0, 0)
+
+ def winfo_width(self):
+ return max(1, self._rect()[2])
+
+ def winfo_height(self):
+ return max(1, self._rect()[3])
+
+ def winfo_reqwidth(self):
+ return self._node.natural()[0]
+
+ def winfo_reqheight(self):
+ return self._node.natural()[1]
+
+ def winfo_x(self):
+ parent = self.master
+ px = parent._rect()[0] if parent is not None and not getattr(self, "_is_window", 0) else 0
+ return self._rect()[0] - px
+
+ def winfo_y(self):
+ parent = self.master
+ py = parent._rect()[1] if parent is not None and not getattr(self, "_is_window", 0) else 0
+ return self._rect()[1] - py
+
+ def winfo_rootx(self):
+ pos = self._toplevel_window()._window.wm_get("pos") or (0, 0)
+ return int(pos[0]) + self._rect()[0]
+
+ def winfo_rooty(self):
+ pos = self._toplevel_window()._window.wm_get("pos") or (0, 0)
+ return int(pos[1]) + self._rect()[1]
+
+ def winfo_geometry(self):
+ return "%dx%d+%d+%d" % (self.winfo_width(), self.winfo_height(), self.winfo_x(),
+ self.winfo_y())
+
+ def winfo_ismapped(self):
+ return 1 if self.winfo_exists() and self._rect()[2] > 0 and self._shown() else 0
+
+ def _shown(self):
+ node = getattr(self, "_node", None)
+ while node is not None:
+ if not node.get("visible"):
+ return False
+ node = node.parent
+ return True
+
+ winfo_viewable = winfo_ismapped
+
+ def winfo_exists(self):
+ return 0 if getattr(self, "_destroyed", False) else 1
+
+ def winfo_manager(self):
+ return getattr(self, "_ginfo", {}).get("manager", "")
+
+ def winfo_children(self):
+ return list(self.children.values())
+
+ def winfo_class(self):
+ return getattr(self, "_class", None) or type(self).__name__
+
+ def winfo_name(self):
+ return self._name
+
+ def winfo_parent(self):
+ return self.master._w if self.master is not None else ""
+
+ def winfo_pathname(self, id, displayof=0): # noqa: A002
+ for w in self._root()._descendants():
+ if w.winfo_id() == id:
+ return w._w
+ raise TclError('window id "%s" doesn\'t exist in this application' % id)
+
+ def winfo_id(self):
+ if getattr(self, "_is_window", False):
+ return int(self._window.handle or id(self))
+ return id(self._node)
+
+ def winfo_containing(self, rootX, rootY, displayof=0):
+ best = None
+ for w in [self._root()] + self._root()._descendants():
+ if not w.winfo_ismapped():
+ continue
+ x, y = w.winfo_rootx(), w.winfo_rooty()
+ if x <= rootX < x + w.winfo_width() and y <= rootY < y + w.winfo_height():
+ best = w # descendants come after their parents
+ return best
+
+ def _screen(self):
+ top = self._toplevel_window()
+ return top._window.wm_get("screen") or (1920, 1080)
+
+ def winfo_screenwidth(self):
+ return int(self._screen()[0])
+
+ def winfo_screenheight(self):
+ return int(self._screen()[1])
+
+ def winfo_screenmmwidth(self):
+ return int(self.winfo_screenwidth() * 25.4 / 96.0)
+
+ def winfo_screenmmheight(self):
+ return int(self.winfo_screenheight() * 25.4 / 96.0)
+
+ def winfo_vrootwidth(self):
+ return self.winfo_screenwidth()
+
+ def winfo_vrootheight(self):
+ return self.winfo_screenheight()
+
+ def winfo_vrootx(self):
+ return 0
+
+ winfo_vrooty = winfo_vrootx
+
+ def winfo_pointerxy(self):
+ p = self._toplevel_window()._window.wm_get("pointer") or (0, 0)
+ return (int(p[0]), int(p[1]))
+
+ def winfo_pointerx(self):
+ return self.winfo_pointerxy()[0]
+
+ def winfo_pointery(self):
+ return self.winfo_pointerxy()[1]
+
+ def winfo_rgb(self, color_):
+ c = color(color_)
+ return tuple(int(round(v * 65535)) for v in c[:3])
+
+ def winfo_fpixels(self, number):
+ return _pixels(number)
+
+ def winfo_pixels(self, number):
+ return int(round(_pixels(number)))
+
+ def winfo_depth(self):
+ return 24
+
+ winfo_screendepth = winfo_depth
+
+ def winfo_cells(self):
+ return 256
+
+ winfo_screencells = winfo_cells
+
+ def winfo_visual(self):
+ return "truecolor"
+
+ winfo_screenvisual = winfo_visual
+
+ def winfo_visualid(self):
+ return "0x21"
+
+ def winfo_visualsavailable(self, includeids=False):
+ return [("truecolor", 24)]
+
+ def winfo_colormapfull(self):
+ return 0
+
+ def winfo_screen(self):
+ return ":0"
+
+ def winfo_server(self):
+ return "BUI kit %s" % sys.platform
+
+ def winfo_interps(self, displayof=0):
+ return ()
+
+ _atoms: dict = {}
+
+ def winfo_atom(self, name, displayof=0):
+ return Misc._atoms.setdefault(name, len(Misc._atoms) + 1)
+
+ def winfo_atomname(self, id, displayof=0): # noqa: A002
+ for name, value in Misc._atoms.items():
+ if value == id:
+ return name
+ raise TclError('no atom exists with id "%s"' % id)
+
+ # -- tkinter internals some programs call ------------------------------------------------
+ def _descendants(self):
+ out = []
+ for c in self.children.values():
+ out.append(c)
+ out.extend(c._descendants())
+ return out
+
+ def _size_changed(self):
+ pass
+
+ def _grid_next_row(self):
+ rows = [int(c._ginfo.get("row", 0)) + int(c._ginfo.get("rowspan", 1))
+ for c in self.winfo_children() if c.winfo_manager() == "grid"]
+ return max(rows, default=0)
+
+ def keys(self):
+ return sorted(getattr(self, "_opts", {}))
+
+ def __repr__(self):
+ return "<%s.%s object %s>" % (self.__class__.__module__, self.__class__.__qualname__,
+ self._w)
+
+
+_VersionInfo = collections.namedtuple("_VersionInfoType",
+ "major minor micro releaselevel serial")
+_grab: dict = {}
+
+
+def _wait_until(cond):
+ _show_windows()
+ while not cond() and host._windows:
+ host.update()
+ time.sleep(0.004)
+
+
+# ==========================================================================
+# Geometry managers (tkinter.Pack / Place / Grid)
+
+
+def _gm_kw(cnf, kw):
+ kw = dict(cnf, **kw) if cnf else dict(kw)
+ return {k[:-1] if k in ("in_",) else k: v for k, v in kw.items()}
+
+
+class Pack:
+ """Tk's packer (runs in C: kit/intern/kit_frame.c)."""
+
+ def pack_configure(self, cnf={}, **kw): # noqa: B006 - tkinter signature
+ kw = _gm_kw(cnf, kw)
+ info = self._ginfo if self.winfo_manager() == "pack" else \
+ {"side": "top", "fill": "none", "expand": 0, "anchor": "center", "padx": 0,
+ "pady": 0, "ipadx": 0, "ipady": 0}
+ info = dict(info, **kw)
+ info.pop("before", None)
+ info.pop("after", None)
+ target = kw.get("in") or kw.get("before", None) and kw["before"].master or \
+ kw.get("after", None) and kw["after"].master or self._gm_parent()
+ info["in"] = target
+ self._manage(target, "pack", info)
+ px, py = _pads(info["padx"]), _pads(info["pady"])
+ self._node.geom(_PACK, side={"top": 0, "bottom": 1, "left": 2, "right": 3}[
+ str(info["side"])], fill={"none": 0, "x": 1, "y": 2, "both": 3}[
+ str(info["fill"] or "none")], expand=1 if getboolean(info["expand"]) else 0,
+ anchor=_anchor_bits(info["anchor"]), padx0=px[0], padx1=px[1], pady0=py[0],
+ pady1=py[1], ipadx=int(_pixels(info["ipadx"])), ipady=int(_pixels(info["ipady"])))
+ ref = kw.get("before") or kw.get("after")
+ if ref is not None:
+ parent = self._node.parent
+ sibs = parent.children
+ sibs.remove(self._node)
+ i = sibs.index(ref._node) + (1 if kw.get("after") is not None else 0)
+ parent.add(self._node, i)
+
+ pack = configure = config = pack_configure
+
+ def pack_forget(self):
+ if self.winfo_manager() == "pack":
+ self._unmanage()
+
+ forget = pack_forget
+
+ def pack_info(self):
+ if self.winfo_manager() != "pack":
+ raise TclError('window "%s" isn\'t packed' % self._w)
+ return {k: v for k, v in self._ginfo.items() if k != "manager"}
+
+ info = pack_info
+ propagate = Misc.pack_propagate
+ slaves = Misc.pack_slaves
+
+
+class Place:
+ """Tk's placer."""
+
+ def place_configure(self, cnf={}, **kw): # noqa: B006
+ kw = _gm_kw(cnf, kw)
+ info = dict(self._ginfo if self.winfo_manager() == "place" else
+ {"x": 0, "y": 0, "anchor": "nw", "bordermode": "inside"}, **kw)
+ target = kw.get("in") or self._gm_parent()
+ info["in"] = target
+ self._manage(target, "place", info)
+ params = {"reset_place": 1, "anchor": _anchor_bits(info.get("anchor", "nw"))}
+ for k in ("x", "y", "width", "height"):
+ if info.get(k) not in (None, ""):
+ params[k] = _pixels(info[k])
+ for k in ("relx", "rely", "relwidth", "relheight"):
+ if info.get(k) not in (None, ""):
+ params[k] = float(info[k])
+ self._node.geom(_PLACE, **params)
+
+ place = place_configure
+
+ def place_forget(self):
+ if self.winfo_manager() == "place":
+ self._unmanage()
+
+ forget = place_forget
+
+ def place_info(self):
+ return {k: v for k, v in self._ginfo.items() if k != "manager"} \
+ if self.winfo_manager() == "place" else {}
+
+ info = place_info
+ slaves = Misc.place_slaves
+
+
+class Grid:
+ """Tk's gridder."""
+
+ def grid_configure(self, cnf={}, **kw): # noqa: B006
+ kw = _gm_kw(cnf, kw)
+ info = dict(self._ginfo if self.winfo_manager() in ("grid", "grid_removed") else
+ {"row": None, "column": 0, "rowspan": 1, "columnspan": 1, "sticky": "",
+ "padx": 0, "pady": 0, "ipadx": 0, "ipady": 0}, **kw)
+ target = kw.get("in") or self._gm_parent()
+ if info.get("row") is None: # next free row (Tk)
+ info["row"] = target._grid_next_row()
+ info["in"] = target
+ self._manage(target, "grid", info)
+ px, py = _pads(info["padx"]), _pads(info["pady"])
+ self._node.geom(_GRID, row=int(info["row"]), column=int(info["column"]),
+ rowspan=int(info["rowspan"]), columnspan=int(info["columnspan"]),
+ sticky=_anchor_bits(info["sticky"]) if info["sticky"] else 0,
+ padx0=px[0], padx1=px[1], pady0=py[0], pady1=py[1],
+ ipadx=int(_pixels(info["ipadx"])), ipady=int(_pixels(info["ipady"])))
+
+ grid = grid_configure
+
+ def grid_forget(self):
+ if self.winfo_manager() in ("grid", "grid_removed"):
+ self._unmanage()
+
+ forget = grid_forget
+
+ def grid_remove(self):
+ """Unmap but remember the grid options (grid() restores them)."""
+ if self.winfo_manager() == "grid":
+ info = dict(self._ginfo)
+ self._unmanage()
+ self._ginfo = dict(info, manager="grid_removed")
+
+ def grid_info(self):
+ if self.winfo_manager() != "grid":
+ return {}
+ return {k: v for k, v in self._ginfo.items() if k != "manager"}
+
+ info = grid_info
+ location = Misc.grid_location
+ size = Misc.grid_size
+ bbox = Misc.grid_bbox
+ slaves = Misc.grid_slaves
+ propagate = Misc.grid_propagate
+ columnconfigure = Misc.grid_columnconfigure
+ rowconfigure = Misc.grid_rowconfigure
+ anchor = Misc.grid_anchor
+
+
+# ==========================================================================
+# Scrolling (tkinter.XView / YView over the kit's view protocol)
+
+
+class _View:
+ _AXIS = "y"
+
+ def _view(self, axis):
+ """(first, last) visible fractions along 'x' or 'y'."""
+ return (float(self._node.get(axis + "first")), float(self._node.get(axis + "last")))
+
+ def _view_set(self, axis, op, args):
+ node = self._node
+ if op == "moveto":
+ node.set(axis + "view", float(args[0]))
+ elif op == "scroll":
+ n, what = int(float(args[0])), str(args[1])
+ if what.startswith("page"):
+ n *= max(1, int(node.get(axis + "visible")) - 1)
+ node.set(axis + "scroll", float(n))
+ else:
+ raise TclError('bad option "%s": must be moveto or scroll' % op)
+ self._view_changed()
+
+ def _view_cmd(self, axis, args):
+ if not args:
+ return self._view(axis)
+ if isinstance(args[0], (int, float)) or str(args[0]).replace(".", "", 1).isdigit():
+ return self._view_set(axis, "moveto", args)
+ return self._view_set(axis, str(args[0]), args[1:])
+
+ def _view_changed(self):
+ """Tell x/yscrollcommand about the current view (Tk sends strings)."""
+ for axis in ("x", "y"):
+ cmd = self._opts.get(axis + "scrollcommand")
+ if cmd:
+ first, last = self._view(axis)
+ _call(self, _command(cmd), repr(first), repr(last))
+
+
+class XView(_View):
+ def xview(self, *args):
+ return self._view_cmd("x", args)
+
+ def xview_moveto(self, fraction):
+ self._view_set("x", "moveto", (fraction,))
+
+ def xview_scroll(self, number, what):
+ self._view_set("x", "scroll", (number, what))
+
+
+class YView(_View):
+ def yview(self, *args):
+ return self._view_cmd("y", args)
+
+ def yview_moveto(self, fraction):
+ self._view_set("y", "moveto", (fraction,))
+
+ def yview_scroll(self, number, what):
+ self._view_set("y", "scroll", (number, what))
+
+
+def _command(cmd):
+ """A widget command option: a callable or a name from register()."""
+ if callable(cmd):
+ return cmd
+ name = cmd[0] if isinstance(cmd, (tuple, list)) else str(cmd).split()[0]
+ return _commands.get(name, lambda *a: None)
+
+
+# ==========================================================================
+# Widgets
+
+
+class _Node(buipy.KitNode):
+ """The kit node of a widget; forwards kit events to it."""
+
+ def __init__(self, kind, widget):
+ super().__init__(kind)
+ self.widget = widget
+
+ def _on_event(self, kind, ref, a, b):
+ self.widget._on_node_event(kind, ref, a, b)
+
+
+_RAW_KINDS = (EV_PRESS, EV_RELEASE, EV_DOUBLE, EV_MOTION, EV_ENTER, EV_LEAVE, EV_KEY,
+ EV_WHEEL, EV_KEYRELEASE)
+_CHAR_FOR_KEYSYM = {"Return": "\r", "KP_Enter": "\r", "BackSpace": "\b", "Tab": "\t",
+ "Escape": "\x1b", "Delete": "\x7f", "space": " "}
+
+
+class BaseWidget(Misc):
+ """Internal base of widgets: names, options, the kit node."""
+
+ _KIND: Optional[str] = "frame" # kit node class (None: no node, e.g. Menu)
+ _DEFAULTS: dict = {} # cget() values of unset options
+ _TAKEFOCUS = False
+
+ def __init__(self, master=None, widgetName=None, cnf={}, kw={}, extra=()): # noqa: B006
+ kw = _gm_kw(cnf, kw)
+ if master is None:
+ master = _get_default_root()
+ self.master = master
+ self.children = {}
+ self._opts = {}
+ self._ginfo = {}
+ self._destroyed = False
+ self._class = kw.pop("class", None)
+ name = kw.pop("name", None)
+ if name is None:
+ base = "!" + type(self).__name__.lower()
+ counts = master.__dict__.setdefault("_last_child_ids", {})
+ counts[base] = counts.get(base, 0) + 1
+ name = base if counts[base] == 1 else "%s%d" % (base, counts[base])
+ self._name = str(name)
+ self._w = ("." if master._w == "." else master._w + ".") + self._name
+ old = master.children.get(self._name)
+ if old is not None:
+ old.destroy()
+ master.children[self._name] = self
+ self._node = _Node(self._KIND, self) if self._KIND else None
+ self._setup()
+ if self._node is not None:
+ parent = master._container_for(self)
+ if parent is not None:
+ parent.add(self._node)
+ if _needs_events(self):
+ self._node.set("events", True)
+ self.configure(**kw)
+
+ def _setup(self):
+ """Class-specific node setup before options apply."""
+
+ def _container_for(self, child):
+ """Kit node that receives `child`'s node (None: added later)."""
+ return self._node
+
+ def _gm_parent(self):
+ return self.master
+
+ # -- geometry management (shared by Pack / Place / Grid) ----------------------------------
+ def _manage(self, target, manager, info):
+ desired = target._container_for(self) if target is self.master else target._container()
+ if desired is not None and self._node.parent is not desired:
+ desired.add(self._node)
+ old = self._ginfo.get("in")
+ self._ginfo = dict(info, manager=manager)
+ target._size_changed()
+ if old is not None and old is not target:
+ old._size_changed()
+
+ def _unmanage(self):
+ target = self._ginfo.get("in") or self.master
+ self._ginfo = {}
+ self._node.geom(0)
+ target._size_changed()
+
+ # -- options --------------------------------------------------------------------------------
+ def configure(self, cnf=None, **kw):
+ """Configure resources of a widget (tkinter.Misc.configure)."""
+ kw = _gm_kw(cnf, kw)
+ if not kw:
+ if cnf is not None and isinstance(cnf, str):
+ return self._option_tuple(cnf)
+ keys = sorted(set(self._DEFAULTS) | set(self._opts))
+ return {k: self._option_tuple(k) for k in keys}
+ for k, v in kw.items():
+ k = _ALIASES.get(k, k)
+ self._opts[k] = v
+ self._apply(k, v)
+ return None
+
+ config = configure
+
+ def _option_tuple(self, key):
+ key = _ALIASES.get(key.lstrip("-"), key.lstrip("-"))
+ return (key, key, key.capitalize(), self._DEFAULTS.get(key, ""), self.cget(key))
+
+ def cget(self, key):
+ """Return the resource value for a KEY given as string."""
+ key = _ALIASES.get(key.lstrip("-"), key.lstrip("-"))
+ if key == "text" and self._opts.get("textvariable") not in (None, ""):
+ try: # Tk: -text shows the variable's value
+ return str(_var_value(self._opts["textvariable"]))
+ except KeyError:
+ pass
+ if key in self._opts:
+ return self._opts[key]
+ if key in self._DEFAULTS:
+ return self._DEFAULTS[key]
+ return ""
+
+ def __getitem__(self, key):
+ return self.cget(key)
+
+ def __setitem__(self, key, value):
+ self.configure({key: value})
+
+ def keys(self):
+ return sorted(set(self._DEFAULTS) | set(self._opts))
+
+ def _apply(self, key, value):
+ """Apply one option to the node. Options the Blender look has no use
+ for (relief, borderwidth, highlight*, activebackground ...) are kept
+ and returned by cget."""
+ node = self._node
+ if node is None:
+ return
+ if key == "state":
+ node.set("enabled", str(value) not in ("disabled",))
+ elif key == "font":
+ node.set("font_scale", _font_scale(value))
+ _set_quiet(node, "bold", _font_bold(value))
+ elif key == "cursor":
+ node.set("cursor", float(_TK_CURSORS.get(str(value), 0)))
+ elif key in ("bg", "fg") and value not in (None, ""):
+ c = color(value)
+ if key == "bg" and self._KIND in ("frame", "canvas"):
+ node.set("bg", c)
+ elif key == "fg":
+ _set_quiet(node, "text_color", c)
+
+ # -- events from the kit ------------------------------------------------------------------
+ def _on_node_event(self, kind, ref, a, b):
+ if kind in _RAW_KINDS:
+ ev = self._make_event(kind, ref, a, b)
+ self._raw_event(ev)
+ _dispatch(self, ev)
+ if kind == EV_WHEEL and sys.platform not in ("win32", "darwin"):
+ ev4 = self._make_event(EV_PRESS, "%d %d" % (0, 4 if a > 0 else 5), 0, 0)
+ _dispatch(self, ev4)
+ elif kind == EV_CONFIGURE:
+ first = not getattr(self, "_mapped", False)
+ self._mapped = True
+ x, y = self.winfo_x(), self.winfo_y()
+ if first:
+ _dispatch(self, Event(type=EventType.Map, widget=self))
+ _dispatch(self, Event(type=EventType.Configure, widget=self, width=int(a),
+ height=int(b), x=x, y=y))
+ self._configured(int(a), int(b))
+ elif kind == EV_VIEW and isinstance(self, _View):
+ self._view_changed()
+ else:
+ self._event(kind, ref, a, b)
+
+ def _make_event(self, kind, ref, a, b):
+ if kind in (EV_KEY, EV_KEYRELEASE):
+ char, _, keysym = (ref or "").partition("\t")
+ char = char or _CHAR_FOR_KEYSYM.get(keysym, "")
+ return Event(type=EventType.KeyPress if kind == EV_KEY else EventType.KeyRelease,
+ widget=self, char=char, keysym=keysym,
+ keysym_num=ord(char) if len(char) == 1 else 0,
+ keycode=ord(keysym.upper()) if len(keysym) == 1 else 0,
+ state=_kit_mods_to_state(int(a)), x=0, y=0)
+ mods, _, num = (ref or "0 1").partition(" ")
+ state = _kit_mods_to_state(int(mods or 0))
+ if kind == EV_WHEEL:
+ return Event(type=EventType.MouseWheel, widget=self, delta=int(a) * 120,
+ state=state)
+ etype = {EV_PRESS: EventType.ButtonPress, EV_DOUBLE: EventType.ButtonPress,
+ EV_RELEASE: EventType.ButtonRelease, EV_MOTION: EventType.Motion,
+ EV_ENTER: EventType.Enter, EV_LEAVE: EventType.Leave}[kind]
+ x, y = int(a), int(b)
+ rx, ry = self.winfo_rootx(), self.winfo_rooty()
+ return Event(type=etype, widget=self, x=x, y=y, x_root=rx + x, y_root=ry + y,
+ num=int(num or 1) if etype in (EventType.ButtonPress,
+ EventType.ButtonRelease) else "??",
+ state=state, _count=2 if kind == EV_DOUBLE else 1)
+
+ def _raw_event(self, ev):
+ """Widget hook before bindings run (canvas items, text tags)."""
+
+ def _event(self, kind, ref, a, b):
+ """Widget events (value changed, clicked ...)."""
+
+ def _configured(self, width, height):
+ """Size known/changed (canvas scroll region, wrapping ...)."""
+
+ # -- life cycle ----------------------------------------------------------------------------
+ def destroy(self):
+ """Destroy this and all descendants widgets."""
+ if self._destroyed:
+ return
+ for c in list(self.children.values()):
+ c.destroy()
+ _dispatch(self, Event(type=EventType.Destroy, widget=self))
+ self._destroyed = True
+ if self._node is not None and self._node.parent is not None:
+ self._node.parent.remove(self._node)
+ if self.master is not None and self.master.children.get(self._name) is self:
+ del self.master.children[self._name]
+ _bindtables.pop(self._w, None)
+ top = self._toplevel_window() if not getattr(self, "_is_window", False) else None
+ if top is not None and top._focus is self:
+ top._focus = None
+
+
+class Widget(BaseWidget, Pack, Place, Grid):
+ """Internal class: a widget that can be managed by pack, place or grid."""
+
+
+_ALIASES = {"background": "bg", "foreground": "fg", "borderwidth": "bd",
+ "from_": "from", "class_": "class", "in_": "in"}
+
+
+def _set_quiet(node, key, value):
+ """Set a property the node's class may not support."""
+ try:
+ node.set(key, value)
+ except (KeyError, ValueError, TypeError):
+ pass
+
+
+def _needs_events(widget) -> bool:
+ """Raw events are forwarded only to widgets with bindings in their tags
+ (keeps hover/motion in C for everything else)."""
+ if getattr(widget, "_ALWAYS_EVENTS", False):
+ return True
+ tags = widget.bindtags()
+ return any(t in _bindtables and _bindtables[t].seqs for t in tags) or \
+ bool(_virtual_events)
+
+
+def _events_changed(root, tag):
+ """A binding was added: switch on raw events where it can now fire."""
+ if root is None:
+ return
+ for w in [root] + root._descendants():
+ node = getattr(w, "_node", None)
+ if node is not None and (tag is None or tag in w.bindtags()) and _needs_events(w):
+ node.set("events", True)
+
+
+# ==========================================================================
+# Windows (tkinter.Wm, Tk, Toplevel)
+
+
+_STATE_CODES = {"normal": 0, "iconic": 1, "withdrawn": 2, "zoomed": 3}
+
+
+class Wm:
+ """Window-manager methods (tkinter.Wm); short names alias wm_*."""
+
+ def wm_aspect(self, minNumer=None, minDenom=None, maxNumer=None, maxDenom=None):
+ if minNumer is None:
+ return self._wm_store.get("aspect")
+ self._wm_store["aspect"] = (minNumer, minDenom, maxNumer, maxDenom)
+
+ aspect = wm_aspect
+
+ def wm_attributes(self, *args, return_python_dict=False, **kw):
+ """'-topmost', '-alpha', '-fullscreen', '-disabled', '-toolwindow' ..."""
+ attrs = self._wm_store.setdefault("attributes", {"-alpha": 1.0, "-topmost": 0,
+ "-fullscreen": 0, "-disabled": 0,
+ "-toolwindow": 0,
+ "-transparentcolor": ""})
+ for k, v in kw.items():
+ args += ("-" + k, v)
+ if not args:
+ return dict(attrs) if return_python_dict else \
+ tuple(itertools.chain.from_iterable(attrs.items()))
+ if len(args) == 1:
+ key = args[0] if str(args[0]).startswith("-") else "-" + str(args[0])
+ return attrs.get(key, "")
+ for key, value in zip(args[0::2], args[1::2]):
+ key = key if str(key).startswith("-") else "-" + str(key)
+ attrs[key] = value
+ if key == "-topmost":
+ self._window.wm("topmost", 1 if getboolean(value) else 0)
+ elif key == "-alpha":
+ self._window.wm("alpha", float(value))
+ elif key == "-fullscreen":
+ full = getboolean(value)
+ self._window.wm("override", 1 if full else 0)
+ self._window.wm("state", 3 if full else 0)
+ elif key == "-disabled":
+ self._window.wm("disabled", 1 if getboolean(value) else 0)
+ return None
+
+ attributes = wm_attributes
+
+ def wm_client(self, name=None):
+ return self._wm_get_set("client", name)
+
+ client = wm_client
+
+ def wm_colormapwindows(self, *wlist):
+ return self._wm_get_set("colormapwindows", list(wlist) or None) or []
+
+ colormapwindows = wm_colormapwindows
+
+ def wm_command(self, value=None):
+ return self._wm_get_set("command", value)
+
+ command = wm_command
+
+ def wm_deiconify(self):
+ self._withdrawn = False
+ self._show()
+ self._window.show()
+ self._window.wm("state", 0)
+
+ deiconify = wm_deiconify
+
+ def wm_focusmodel(self, model=None):
+ return self._wm_get_set("focusmodel", model) or "passive"
+
+ focusmodel = wm_focusmodel
+
+ def wm_forget(self, window):
+ pass # windows can't be turned into frames
+
+ forget = wm_forget
+
+ def wm_frame(self):
+ return hex(self.winfo_id())
+
+ frame = wm_frame
+
+ def wm_geometry(self, newGeometry=None):
+ """'WxH+X+Y' (any part optional); without an argument, the current."""
+ if newGeometry is None:
+ w, h = self._window.size
+ pos = self._window.wm_get("pos") or (0, 0)
+ return "%dx%d+%d+%d" % (w, h, pos[0], pos[1])
+ m = re.match(r"^\s*(?:(\d+)x(\d+))?\s*(?:([+-]-?\d+)([+-]-?\d+))?\s*$",
+ str(newGeometry))
+ if not m:
+ raise TclError('bad geometry specifier "%s"' % newGeometry)
+ if newGeometry == "":
+ self._geometry = None
+ return None
+ if m.group(1):
+ self._geometry = (int(m.group(1)), int(m.group(2)))
+ self._window.set_size(*self._geometry)
+ if m.group(3):
+ x, y = int(m.group(3)), int(m.group(4))
+ if m.group(3).startswith("-"):
+ x = self.winfo_screenwidth() - self._window.size[0] + x
+ if m.group(4).startswith("-"):
+ y = self.winfo_screenheight() - self._window.size[1] + y
+ self._window.wm("pos", x, y)
+ return None
+
+ geometry = wm_geometry
+
+ def wm_grid(self, baseWidth=None, baseHeight=None, widthInc=None, heightInc=None):
+ return self._wm_get_set("grid", baseWidth and (baseWidth, baseHeight, widthInc,
+ heightInc))
+
+ grid = wm_grid
+
+ def wm_group(self, pathName=None):
+ return self._wm_get_set("group", pathName)
+
+ group = wm_group
+
+ def wm_iconbitmap(self, bitmap=None, default=None):
+ return self._wm_get_set("iconbitmap", bitmap or default)
+
+ iconbitmap = wm_iconbitmap
+
+ def wm_iconify(self):
+ self._show()
+ self._window.wm("state", 1)
+
+ iconify = wm_iconify
+
+ def wm_iconmask(self, bitmap=None):
+ return self._wm_get_set("iconmask", bitmap)
+
+ iconmask = wm_iconmask
+
+ def wm_iconname(self, newName=None):
+ return self._wm_get_set("iconname", newName) or ""
+
+ iconname = wm_iconname
+
+ def wm_iconphoto(self, default=False, *args):
+ self._wm_store["iconphoto"] = args
+
+ iconphoto = wm_iconphoto
+
+ def wm_iconposition(self, x=None, y=None):
+ return self._wm_get_set("iconposition", x is not None and (x, y) or None)
+
+ iconposition = wm_iconposition
+
+ def wm_iconwindow(self, pathName=None):
+ return self._wm_get_set("iconwindow", pathName)
+
+ iconwindow = wm_iconwindow
+
+ def wm_manage(self, widget):
+ pass
+
+ manage = wm_manage
+
+ def wm_maxsize(self, width=None, height=None):
+ if width is None:
+ return self._wm_store.get("maxsize", (self.winfo_screenwidth(),
+ self.winfo_screenheight()))
+ self._wm_store["maxsize"] = (int(width), int(height))
+ self._window.wm("maxsize", int(width), int(height))
+
+ maxsize = wm_maxsize
+
+ def wm_minsize(self, width=None, height=None):
+ if width is None:
+ return self._wm_store.get("minsize", (1, 1))
+ self._wm_store["minsize"] = (int(width), int(height))
+ self._window.wm("minsize", int(width), int(height))
+
+ minsize = wm_minsize
+
+ def wm_overrideredirect(self, boolean=None):
+ if boolean is None:
+ return self._wm_store.get("override", False)
+ self._wm_store["override"] = getboolean(boolean)
+ self._window.wm("override", 1 if self._wm_store["override"] else 0)
+
+ overrideredirect = wm_overrideredirect
+
+ def wm_positionfrom(self, who=None):
+ return self._wm_get_set("positionfrom", who) or ""
+
+ positionfrom = wm_positionfrom
+
+ def wm_protocol(self, name=None, func=None):
+ if name is None:
+ return tuple(self._protocols)
+ if func is None:
+ return self._protocols.get(name, "")
+ self._protocols[name] = func
+ return None
+
+ protocol = wm_protocol
+
+ def wm_resizable(self, width=None, height=None):
+ if width is None:
+ return self._wm_store.get("resizable", (True, True))
+ if height is None:
+ height = width
+ self._wm_store["resizable"] = (getboolean(width), getboolean(height))
+ self._window.wm("resizable", 1 if getboolean(width) else 0,
+ 1 if getboolean(height) else 0)
+
+ resizable = wm_resizable
+
+ def wm_sizefrom(self, who=None):
+ return self._wm_get_set("sizefrom", who) or ""
+
+ sizefrom = wm_sizefrom
+
+ def wm_state(self, newstate=None):
+ if newstate is None:
+ if not self._shown_window:
+ return "withdrawn"
+ code = (self._window.wm_get("state") or (0, 0))[0]
+ return {v: k for k, v in _STATE_CODES.items()}[int(code)]
+ if newstate != "withdrawn":
+ self._show()
+ self._window.wm("state", _STATE_CODES[str(newstate)])
+
+ state = wm_state
+
+ def wm_title(self, string=None):
+ if string is None:
+ return self._title
+ self._title = str(string)
+ self._window.title(self._title)
+
+ title = wm_title
+
+ def wm_transient(self, master=None):
+ if master is None:
+ return self._wm_store.get("transient", "")
+ self._wm_store["transient"] = master
+ if self._wm_store.get("_placed") is None: # centre over the master once shown
+ self._wm_store["_placed"] = False
+
+ transient = wm_transient
+
+ def wm_withdraw(self):
+ self._window.wm("state", 2)
+ self._withdrawn = True
+
+ withdraw = wm_withdraw
+
+ def _wm_get_set(self, key, value):
+ if value is None:
+ return self._wm_store.get(key)
+ self._wm_store[key] = value
+ return None
+
+
+class _WindowHost:
+ """A top-level window: kit context + host window (Tk and Toplevel)."""
+
+ _is_window = True
+
+ def _init_window(self, class_name):
+ self._focus = None
+ self._afters = {}
+ self._protocols = {}
+ self._wm_store = {}
+ self._title = class_name.lower() if class_name else "tk"
+ self._geometry = None
+ self._shown_window = False
+ self._withdrawn = False
+ self._menubar = None
+ self._ctx = buipy.KitContext(self._node)
+ self._window = host.Window(self._ctx, self._title, (200, 200))
+ self._window.on_close = self._on_close_button
+ _window_list.append(self)
+
+ def _on_close_button(self):
+ handler = self._protocols.get("WM_DELETE_WINDOW")
+ if handler:
+ _call(self, handler)
+ return False # the handler decides (it calls destroy())
+ self.destroy()
+ return False
+
+ def _show(self):
+ if self._shown_window or self._destroyed:
+ return
+ self._shown_window = True
+ if self._geometry is None: # Tk: the window fits its content (+ menu bar)
+ w, h = self._node.natural()
+ if self._menubar is not None and self._menubar._bar is not None:
+ bw, bh = self._menubar._bar.natural()
+ w, h = max(w, bw), h + bh
+ self._window.set_size(max(1, w), max(1, h))
+ master = self._wm_store.get("transient")
+ if master and self._wm_store.get("_placed") is False:
+ self._wm_store["_placed"] = True
+ mw, mh = master._window.size
+ w, h = self._window.size
+ self._window.wm("pos", master.winfo_rootx() + (mw - w) // 2,
+ master.winfo_rooty() + (mh - h) // 2)
+ if not self._withdrawn:
+ self._window.show()
+
+ def _set_menu(self, menu):
+ self._menubar = menu
+ if menu is None:
+ self._ctx.set_header(None)
+ else:
+ self._ctx.set_header(menu._bar_node())
+
+ def _close_window(self):
+ if self in _window_list:
+ _window_list.remove(self)
+ for name, (win, token, _) in list(self._afters.items()) if self is self._root() else ():
+ win.after_cancel(token)
+ self._window.close()
+
+ def report_callback_exception(self, exc, val, tb):
+ """Report callback exception on sys.stderr (tkinter's default)."""
+ sys.stderr.write("Exception in Tkinter callback\n")
+ traceback.print_exception(exc, val, tb)
+
+
+_window_list: list = []
+
+
+def _windows():
+ return [w for w in _window_list if not w._destroyed]
+
+
+def _show_windows():
+ for w in _windows():
+ w._show()
+
+
+class _TkApp:
+ """``root.tk``: the few Tcl commands programs commonly call directly."""
+
+ def __init__(self, root):
+ self._root = root
+
+ def call(self, *args):
+ args = tuple(str(a) for a in (args[0] if len(args) == 1 and
+ isinstance(args[0], (tuple, list)) else args))
+ if args[:2] == ("tk", "scaling"):
+ return buipy.kit_scale() * 1.333 if len(args) == 2 else None
+ if args[:2] == ("info", "patchlevel"):
+ return "8.6.13"
+ if args[:1] == ("wm",) and len(args) >= 3:
+ w = self._root.nametowidget(args[2])
+ return getattr(w, "wm_" + args[1])(*args[3:])
+ if args[:2] == ("tk", "windowingsystem"):
+ return {"win32": "win32", "darwin": "aqua"}.get(sys.platform, "x11")
+ if args[:1] == ("set",) and len(args) >= 2:
+ if len(args) == 2:
+ return self._root.getvar(args[1])
+ self._root.setvar(args[1], args[2])
+ return args[2]
+ raise TclError('invalid command name "%s"' % args[0])
+
+ def eval(self, script):
+ return self.call(*script.split())
+
+ def splitlist(self, value):
+ return tuple(value) if isinstance(value, (tuple, list)) else tuple(str(value).split())
+
+ split = splitlist
+
+ def getboolean(self, s):
+ return getboolean(s)
+
+ def getint(self, s):
+ return getint(s)
+
+ def getdouble(self, s):
+ return getdouble(s)
+
+ def globalgetvar(self, name):
+ return self._root.getvar(name)
+
+ getvar = globalgetvar
+
+ def globalsetvar(self, name, value):
+ self._root.setvar(name, value)
+
+ setvar = globalsetvar
+
+ def mainloop(self, n=0):
+ self._root.mainloop(n)
+
+ def dooneevent(self, flags=0):
+ host.update()
+ return 1
+
+ def createcommand(self, name, func):
+ _commands[name] = func
+
+ def deletecommand(self, name):
+ _commands.pop(name, None)
+
+ def wantobjects(self, *a):
+ return 1
+
+ def willdispatch(self):
+ pass
+
+ def interpaddr(self):
+ return id(self)
+
+
+_ROOT_BG = (0.188, 0.188, 0.188, 1.0) # Blender's editor background (#303030)
+
+
+class Tk(_WindowHost, Misc, Wm):
+ """Toplevel widget of Tk which represents mostly the main window of an
+ application (a native window on Windows, Blender-styled)."""
+
+ _w = "."
+ _name = "."
+
+ def __init__(self, screenName=None, baseName=None, className="Tk", useTk=True, sync=False,
+ use=None):
+ global _default_root
+ self.master = None
+ self.children = {}
+ self._destroyed = False
+ self._opts = {}
+ self._className = className
+ self._node = _Node("frame", self)
+ self._node.set("bg", _ROOT_BG)
+ self.tk = _TkApp(self)
+ self._init_window(className)
+ if baseName is None: # tkinter titles the window after the script
+ import os
+ baseName = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0] or "tk"
+ self._title = baseName if className == "Tk" else className.lower()
+ self._window.title(self._title)
+ if _support_default_root and _default_root is None:
+ _default_root = self
+
+ def winfo_class(self):
+ return self._className
+
+ def _container_for(self, child):
+ return self._node
+
+ def _gm_parent(self):
+ return self
+
+ def configure(self, cnf=None, **kw):
+ kw = _gm_kw(cnf, kw)
+ if not kw:
+ return {k: (k, k, k.capitalize(), "", v) for k, v in self._opts.items()}
+ for k, v in kw.items():
+ k = _ALIASES.get(k, k)
+ self._opts[k] = v
+ if k == "menu":
+ self._set_menu(v)
+ elif k == "bg":
+ self._node.set("bg", color(v))
+ elif k in ("width", "height"):
+ self._node.geom(0, **{"req" + k: int(_pixels(v))})
+ elif k == "cursor":
+ self._node.set("cursor", float(_TK_CURSORS.get(str(v), 0)))
+ return None
+
+ config = configure
+
+ def cget(self, key):
+ return self._opts.get(_ALIASES.get(key.lstrip("-"), key.lstrip("-")), "")
+
+ __getitem__ = cget
+
+ def __setitem__(self, key, value):
+ self.configure({key: value})
+
+ def _on_node_event(self, kind, ref, a, b):
+ BaseWidget._on_node_event(self, kind, ref, a, b)
+
+ _make_event = BaseWidget._make_event
+ _raw_event = BaseWidget._raw_event
+ _configured = BaseWidget._configured
+ _event = BaseWidget._event
+
+ def destroy(self):
+ """Destroy this and all descendants widgets (ends mainloop)."""
+ global _default_root
+ if self._destroyed:
+ return
+ for c in list(self.children.values()):
+ c.destroy()
+ _dispatch(self, Event(type=EventType.Destroy, widget=self))
+ self._destroyed = True
+ for w in _windows():
+ if w is not self and w._root() is self:
+ w.destroy()
+ self._close_window()
+ if _default_root is self:
+ _default_root = None
+ if not _windows():
+ host.quit()
+
+ def readprofile(self, baseName, className):
+ pass
+
+ def loadtk(self):
+ pass
+
+ def __getattr__(self, attr):
+ """Delegate unknown attributes to the interpreter (as tkinter does)."""
+ if attr.startswith("__") or "tk" not in self.__dict__:
+ raise AttributeError(attr)
+ return getattr(self.__dict__["tk"], attr)
+
+
+class Toplevel(_WindowHost, BaseWidget, Wm):
+ """Toplevel widget, e.g. for dialogs (a second native window)."""
+
+ _KIND = "frame"
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ kw = _gm_kw(cnf, kw)
+ menu = kw.pop("menu", None)
+ BaseWidget.__init__(self, master, "toplevel", {}, {})
+ self._node.set("bg", _ROOT_BG)
+ self._init_window("Toplevel")
+ self._window.title(self._root().title())
+ self._title = self._root().title()
+ if menu is not None:
+ self._set_menu(menu)
+ self.configure(**kw)
+ self._window.after(0, self._show) # Tk maps new toplevels when idle
+
+ def _container_for(self, child):
+ return self._node
+
+ def _gm_parent(self):
+ return self
+
+ def _apply(self, key, value):
+ if key in ("width", "height"):
+ self._node.geom(0, **{"req" + key: int(_pixels(value))})
+ elif key == "menu":
+ self._set_menu(value)
+ else:
+ super()._apply(key, value)
+
+ def destroy(self):
+ if self._destroyed:
+ return
+ BaseWidget.destroy(self)
+ self._close_window()
+ if _grab.get("window") is self:
+ self.grab_release()
+
+
+# ==========================================================================
+# Default root
+
+_support_default_root = True
+_default_root: Optional[Tk] = None
+
+
+def NoDefaultRoot(): # noqa: N802
+ global _support_default_root, _default_root
+ _support_default_root = False
+ _default_root = None
+
+
+def _get_default_root(what=None):
+ global _default_root
+ if not _support_default_root:
+ raise RuntimeError("No master specified and tkinter is configured to not support "
+ "default root")
+ if _default_root is None:
+ if what:
+ raise RuntimeError("Too early to %s: no default root window" % what)
+ _default_root = Tk()
+ return _default_root
+
+
+def _get_temp_root():
+ return _default_root or Tk()
+
+
+def mainloop(n=0):
+ """Run the main loop of Tcl."""
+ _get_default_root("run the main loop").mainloop(n)
+
+
+class CallWrapper:
+ """Internal class: calls a function with exception reporting."""
+
+ def __init__(self, func, subst, widget):
+ self.func, self.subst, self.widget = func, subst, widget
+
+ def __call__(self, *args):
+ if self.subst:
+ args = self.subst(*args)
+ return _call(self.widget, self.func, *args)
+
+
+class _setit:
+ """Internal class: sets a variable to a value (OptionMenu commands)."""
+
+ def __init__(self, var, value, callback=None):
+ self.__value = value
+ self.__var = var
+ self.__callback = callback
+
+ def __call__(self, *args):
+ self.__var.set(self.__value)
+ if self.__callback is not None:
+ self.__callback(self.__value, *args)
diff --git a/bindings/python/bui/tksyntax/_images.py b/bindings/python/bui/tksyntax/_images.py
new file mode 100644
index 0000000..29ee288
--- /dev/null
+++ b/bindings/python/bui/tksyntax/_images.py
@@ -0,0 +1,498 @@
+"""tkinter images: Image, PhotoImage, BitmapImage.
+
+Pixels are RGBA bytes handed to the kit (labels, buttons, canvas items).
+PNG and PPM/PGM are decoded and encoded here (stdlib zlib); GIF goes
+through the real Tk when present.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import base64
+import itertools
+import re
+import struct
+import weakref
+import zlib
+
+from bui import _realtk
+from ._core import TclError, color
+
+_image_ids = itertools.count(1)
+_images: "weakref.WeakValueDictionary[str, Image]" = weakref.WeakValueDictionary()
+
+
+def image_names():
+ return tuple(_images)
+
+
+def image_types():
+ return ("photo", "bitmap")
+
+
+class Image:
+ """Base class for images (tkinter.Image)."""
+
+ _TYPE = "image"
+
+ def __init__(self, imgtype, name=None, cnf={}, master=None, **kw): # noqa: B006
+ self.name = name or "pyimage%d" % next(_image_ids)
+ self._opts = {}
+ self._w = self._h = 0
+ self._px = bytearray()
+ self._users: "weakref.WeakSet" = weakref.WeakSet()
+ _images[self.name] = self
+ kw = dict(cnf, **kw) if cnf else kw
+ self.configure(**kw)
+
+ def __str__(self):
+ return self.name
+
+ def __del__(self):
+ pass
+
+ def __setitem__(self, key, value):
+ self.configure(**{key: value})
+
+ def __getitem__(self, key):
+ return self.cget(key)
+
+ def configure(self, **kw):
+ for k, v in kw.items():
+ self._opts[k] = v
+ self._configured(kw)
+
+ config = configure
+
+ def cget(self, key):
+ return self._opts.get(key.lstrip("-"), "")
+
+ def height(self):
+ return self._h
+
+ def width(self):
+ return self._w
+
+ def type(self):
+ return self._TYPE
+
+ def _configured(self, kw):
+ pass
+
+ # -- kit side -----------------------------------------------------------------
+ def rgba(self) -> bytes:
+ return bytes(self._px)
+
+ def _attach(self, user):
+ """`user._image_changed()` runs when the pixels change."""
+ self._users.add(user)
+
+ def _changed(self):
+ for u in list(self._users):
+ u._image_changed(self)
+
+
+class PhotoImage(Image):
+ """Widget which can display images in PGM, PPM, GIF and PNG format."""
+
+ _TYPE = "photo"
+
+ def __init__(self, name=None, cnf={}, master=None, **kw): # noqa: B006
+ super().__init__("photo", name, cnf, master, **kw)
+
+ def _configured(self, kw):
+ if "width" in kw or "height" in kw:
+ w = int(kw.get("width", self._w) or 0)
+ h = int(kw.get("height", self._h) or 0)
+ self._resize(w, h)
+ if kw.get("file") is not None:
+ with open(kw["file"], "rb") as fh:
+ self._load(fh.read(), kw.get("format"))
+ elif kw.get("data") is not None:
+ data = kw["data"]
+ raw = data.encode("latin-1") if isinstance(data, str) else bytes(data)
+ if not raw[:2].startswith(b"P") and not raw.startswith(b"\x89PNG") \
+ and not raw.startswith(b"GIF"):
+ try:
+ raw = base64.b64decode(raw, validate=False)
+ except ValueError:
+ pass
+ self._load(raw, kw.get("format"))
+ if kw:
+ self._changed()
+
+ def _resize(self, w, h):
+ old, ow, oh = self._px, self._w, self._h
+ self._w, self._h = max(0, w), max(0, h)
+ self._px = bytearray(self._w * self._h * 4)
+ for y in range(min(oh, self._h)):
+ n = min(ow, self._w) * 4
+ self._px[y * self._w * 4:y * self._w * 4 + n] = old[y * ow * 4:y * ow * 4 + n]
+
+ # -- decoding ------------------------------------------------------------------
+ def _load(self, raw: bytes, fmt=None):
+ if raw[:2] in (b"P2", b"P3", b"P5", b"P6"):
+ w, h, px = _decode_pnm(raw)
+ elif raw.startswith(b"\x89PNG"):
+ w, h, px = _decode_png(raw)
+ else:
+ w, h, px = _decode_with_tk(raw)
+ if not self._opts.get("width"):
+ self._w = w
+ if not self._opts.get("height"):
+ self._h = h
+ if (self._w, self._h) == (w, h):
+ self._px = bytearray(px)
+ else: # fixed-size image: copy what fits
+ self._px = bytearray(self._w * self._h * 4)
+ self._paste(px, w, h, 0, 0)
+
+ def _paste(self, px, w, h, x0, y0):
+ for y in range(h):
+ ty = y0 + y
+ if 0 <= ty < self._h:
+ xa, xb = max(0, x0), min(self._w, x0 + w)
+ if xb > xa:
+ sa = (y * w + (xa - x0)) * 4
+ self._px[(ty * self._w + xa) * 4:(ty * self._w + xb) * 4] = \
+ px[sa:sa + (xb - xa) * 4]
+
+ # -- pixels ---------------------------------------------------------------------
+ def blank(self):
+ """Display a transparent image."""
+ self._px = bytearray(self._w * self._h * 4)
+ self._changed()
+
+ def get(self, x, y):
+ """Return the color (red, green, blue) of the pixel at X,Y."""
+ x, y = int(x), int(y)
+ if not (0 <= x < self._w and 0 <= y < self._h):
+ raise TclError('photo get: coordinates out of range')
+ i = 4 * (y * self._w + x)
+ return tuple(self._px[i:i + 3])
+
+ def put(self, data, to=None):
+ """Put row formatted colors to image starting from position TO,
+ e.g. image.put("{red green} {blue yellow}", to=(4,6))."""
+ x0, y0 = (to or (0, 0))[:2]
+ if isinstance(data, str):
+ rows = re.findall(r"\{([^}]*)\}", data) or [data]
+ rows = [r.split() for r in rows]
+ else:
+ rows = [r.split() if isinstance(r, str) else list(r) for r in data]
+ if rows and not isinstance(rows[0], list):
+ rows = [rows]
+ if to is not None and len(to) == 4: # fill a rectangle with the pattern
+ x1, y1 = to[2], to[3]
+ for y in range(y0, y1):
+ for x in range(x0, x1):
+ row = rows[(y - y0) % len(rows)]
+ self._put_pixel(x, y, row[(x - x0) % len(row)])
+ else:
+ for dy, row in enumerate(rows):
+ for dx, c in enumerate(row):
+ self._put_pixel(x0 + dx, y0 + dy, c)
+ self._changed()
+
+ def _put_pixel(self, x, y, c):
+ if x >= self._w or y >= self._h: # Tk grows unsized images
+ if not self._opts.get("width") and not self._opts.get("height"):
+ self._resize(max(self._w, x + 1), max(self._h, y + 1))
+ else:
+ return
+ if x < 0 or y < 0:
+ return
+ rgba = color(c)
+ i = 4 * (y * self._w + x)
+ self._px[i:i + 4] = bytes(int(round(v * 255)) for v in rgba)
+
+ def transparency_get(self, x, y):
+ """Return True if the pixel at x,y is transparent."""
+ return self._px[4 * (int(y) * self._w + int(x)) + 3] == 0
+
+ def transparency_set(self, x, y, boolean):
+ """Set the transparency of the pixel at x,y."""
+ self._px[4 * (int(y) * self._w + int(x)) + 3] = 0 if boolean else 255
+ self._changed()
+
+ # -- copies ------------------------------------------------------------------------
+ def _region(self, from_coords):
+ if not from_coords:
+ return 0, 0, self._w, self._h
+ c = list(from_coords)
+ x0, y0 = int(c[0]), int(c[1])
+ x1, y1 = (int(c[2]), int(c[3])) if len(c) >= 4 else (self._w, self._h)
+ return x0, y0, x1, y1
+
+ def _sample(self, sx, sy, zx=1, zy=1, from_coords=None):
+ x0, y0, x1, y1 = self._region(from_coords)
+ w = max(1, ((x1 - x0) * zx + sx - 1) // sx)
+ h = max(1, ((y1 - y0) * zy + sy - 1) // sy)
+ out = PhotoImage(width=w, height=h)
+ for y in range(h):
+ syy = y0 + (y * sy) // zy
+ for x in range(w):
+ sxx = x0 + (x * sx) // zx
+ si, di = 4 * (syy * self._w + sxx), 4 * (y * w + x)
+ out._px[di:di + 4] = self._px[si:si + 4]
+ out._opts.pop("width", None)
+ out._opts.pop("height", None)
+ return out
+
+ def copy(self, *, from_coords=None, zoom=None, subsample=None):
+ """Return a new PhotoImage with the same image as this widget."""
+ z = _pair(zoom) if zoom else (1, 1)
+ s = _pair(subsample) if subsample else (1, 1)
+ return self._sample(s[0], s[1], z[0], z[1], from_coords)
+
+ def zoom(self, x, y="", *, from_coords=None):
+ """Return a new PhotoImage with the same image as this widget but
+ zoom it with a factor of X in the X direction and Y in the Y direction."""
+ return self._sample(1, 1, int(x), int(y or x), from_coords)
+
+ def subsample(self, x, y="", *, from_coords=None):
+ """Return a new PhotoImage based on the same image as this widget
+ but use only every Xth or Yth pixel."""
+ return self._sample(int(x), int(y or x), 1, 1, from_coords)
+
+ def copy_replace(self, sourceImage, *, from_coords=None, to=None, shrink=False, zoom=None,
+ subsample=None, compositingrule=None):
+ """Copy a region from the source image into this image."""
+ src = sourceImage if isinstance(sourceImage, PhotoImage) else _images[str(sourceImage)]
+ part = src.copy(from_coords=from_coords, zoom=zoom, subsample=subsample)
+ tx, ty = (to or (0, 0))[:2]
+ if shrink:
+ self._resize(tx + part._w, ty + part._h)
+ elif tx + part._w > self._w or ty + part._h > self._h:
+ if not self._opts.get("width") and not self._opts.get("height"):
+ self._resize(max(self._w, tx + part._w), max(self._h, ty + part._h))
+ self._paste(part._px, part._w, part._h, tx, ty)
+ self._changed()
+
+ # -- files -------------------------------------------------------------------------------
+ def read(self, filename, format=None, *, from_coords=None, to=None, shrink=False):
+ """Reads image data from the file named FILENAME into the image."""
+ src = PhotoImage(file=filename, format=format)
+ self.copy_replace(src, from_coords=from_coords, to=to, shrink=shrink)
+
+ def data(self, format=None, *, from_coords=None, background=None, grayscale=False):
+ """Return image data: rows of colors, or (format='png'/'ppm') encoded."""
+ img = self.copy(from_coords=from_coords) if from_coords else self
+ if format is None:
+ return tuple(" ".join("#%02x%02x%02x" % tuple(img._px[4 * (y * img._w + x):
+ 4 * (y * img._w + x) + 3])
+ for x in range(img._w)) for y in range(img._h))
+ return base64.b64encode(img._encode(str(format).split()[0].lower(), background,
+ grayscale)).decode("ascii")
+
+ def write(self, filename, format=None, from_coords=None, *, background=None,
+ grayscale=False):
+ """Write image to file FILENAME in FORMAT (png, ppm, pgm)."""
+ img = self.copy(from_coords=from_coords) if from_coords else self
+ fmt = (format or str(filename).rsplit(".", 1)[-1]).split()[0].lower()
+ with open(filename, "wb") as fh:
+ fh.write(img._encode(fmt, background, grayscale))
+
+ def _encode(self, fmt, background=None, grayscale=False):
+ px = self._px
+ if background is not None or grayscale or fmt in ("ppm", "pgm", "pnm"):
+ bg = color(background) if background else (0, 0, 0, 1)
+ flat = bytearray()
+ for i in range(0, len(px), 4):
+ a = px[i + 3] / 255.0
+ rgb = [px[i + k] * a + bg[k] * 255 * (1 - a) for k in range(3)]
+ if grayscale:
+ rgb = [0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]] * 3
+ flat.extend(int(round(v)) for v in rgb)
+ flat.append(255)
+ px = flat
+ if fmt in ("ppm", "pnm"):
+ rgb = bytes(b for i, b in enumerate(px) if i % 4 != 3)
+ return b"P6\n%d %d\n255\n" % (self._w, self._h) + rgb
+ if fmt == "pgm":
+ return b"P5\n%d %d\n255\n" % (self._w, self._h) + bytes(px[0::4])
+ if fmt == "png":
+ return _encode_png(self._w, self._h, bytes(px))
+ raise TclError('image format "%s" is not supported' % fmt)
+
+
+class BitmapImage(Image):
+ """Widget which can display images in XBM format."""
+
+ _TYPE = "bitmap"
+
+ def __init__(self, name=None, cnf={}, master=None, **kw): # noqa: B006
+ super().__init__("bitmap", name, cnf, master, **kw)
+
+ def _configured(self, kw):
+ data = self._opts.get("data")
+ if self._opts.get("file"):
+ with open(self._opts["file"], encoding="latin-1") as fh:
+ data = fh.read()
+ if not data:
+ return
+ w, h, bits = _decode_xbm(data)
+ mask = None
+ maskdata = self._opts.get("maskdata")
+ if self._opts.get("maskfile"):
+ with open(self._opts["maskfile"], encoding="latin-1") as fh:
+ maskdata = fh.read()
+ if maskdata:
+ mask = _decode_xbm(maskdata)[2]
+ fg = color(self._opts.get("foreground", "black"))
+ bg = color(self._opts.get("background")) if self._opts.get("background") else None
+ self._w, self._h = w, h
+ px = bytearray(w * h * 4)
+ for i, on in enumerate(bits):
+ c = fg if on else bg
+ if mask is not None and not mask[i]:
+ c = None
+ if c is not None:
+ px[4 * i:4 * i + 4] = bytes(int(round(v * 255)) for v in c)
+ self._px = px
+ self._changed()
+
+
+# ==========================================================================
+# Codecs
+
+
+def _pair(v):
+ if isinstance(v, (tuple, list)):
+ return int(v[0]), int(v[1] if len(v) > 1 else v[0])
+ return int(v), int(v)
+
+
+def _decode_pnm(raw: bytes):
+ magic = raw[:2]
+ tokens, pos = [], 2
+ while len(tokens) < 3:
+ while raw[pos:pos + 1].isspace():
+ pos += 1
+ if raw[pos:pos + 1] == b"#":
+ pos = raw.index(b"\n", pos) + 1
+ continue
+ end = pos
+ while end < len(raw) and not raw[end:end + 1].isspace():
+ end += 1
+ tokens.append(int(raw[pos:end]))
+ pos = end
+ w, h, maxv = tokens
+ pos += 1
+ ch = 3 if magic in (b"P3", b"P6") else 1
+ vals = [int(v) for v in raw[pos:].split()] if magic in (b"P2", b"P3") else \
+ list(raw[pos:pos + w * h * ch])
+ px = bytearray(w * h * 4)
+ for i in range(w * h):
+ r, g, b = vals[3 * i:3 * i + 3] if ch == 3 else (vals[i],) * 3
+ px[4 * i:4 * i + 4] = bytes((r * 255 // maxv, g * 255 // maxv, b * 255 // maxv, 255))
+ return w, h, px
+
+
+def _paeth(a, b, c):
+ p = a + b - c
+ pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
+ return a if pa <= pb and pa <= pc else (b if pb <= pc else c)
+
+
+def _decode_png(raw: bytes):
+ pos, idat, palette, trns = 8, bytearray(), None, None
+ w = h = depth = ctype = interlace = 0
+ while pos < len(raw):
+ length, kind = struct.unpack(">I4s", raw[pos:pos + 8])
+ chunk = raw[pos + 8:pos + 8 + length]
+ pos += 12 + length
+ if kind == b"IHDR":
+ w, h, depth, ctype, _, _, interlace = struct.unpack(">IIBBBBB", chunk)
+ elif kind == b"PLTE":
+ palette = chunk
+ elif kind == b"tRNS":
+ trns = chunk
+ elif kind == b"IDAT":
+ idat += chunk
+ elif kind == b"IEND":
+ break
+ if interlace or depth not in (1, 2, 4, 8):
+ return _decode_with_tk(raw)
+ channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[ctype]
+ bpp = max(1, channels * depth // 8)
+ stride = (w * channels * depth + 7) // 8
+ data = zlib.decompress(bytes(idat))
+ rows, prev = [], bytearray(stride)
+ i = 0
+ for _ in range(h):
+ ftype, line = data[i], bytearray(data[i + 1:i + 1 + stride])
+ i += 1 + stride
+ for x in range(stride):
+ a = line[x - bpp] if x >= bpp else 0
+ b, c = prev[x], prev[x - bpp] if x >= bpp else 0
+ line[x] = (line[x] + (0, a, b, (a + b) // 2, _paeth(a, b, c))[ftype]) & 0xFF
+ rows.append(line)
+ prev = line
+ px = bytearray(w * h * 4)
+ for y, line in enumerate(rows):
+ if depth < 8: # unpack sub-byte samples
+ per = 8 // depth
+ vals = [(line[k // per] >> (8 - depth * (k % per + 1))) & ((1 << depth) - 1)
+ for k in range(w)]
+ else:
+ vals = line
+ for x in range(w):
+ o = 4 * (y * w + x)
+ if ctype == 3:
+ k = vals[x]
+ px[o:o + 3] = palette[3 * k:3 * k + 3]
+ px[o + 3] = trns[k] if trns and k < len(trns) else 255
+ elif ctype == 0:
+ v = vals[x] * 255 // ((1 << depth) - 1)
+ px[o:o + 4] = bytes((v, v, v, 255))
+ elif ctype == 4:
+ px[o:o + 4] = bytes((vals[2 * x], vals[2 * x], vals[2 * x], vals[2 * x + 1]))
+ elif ctype == 2:
+ px[o:o + 4] = bytes(vals[3 * x:3 * x + 3]) + b"\xff"
+ else:
+ px[o:o + 4] = vals[4 * x:4 * x + 4]
+ return w, h, px
+
+
+def _encode_png(w, h, rgba: bytes) -> bytes:
+ def chunk(kind, body):
+ return struct.pack(">I", len(body)) + kind + body + \
+ struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF)
+ raw = b"".join(b"\x00" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h))
+ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b""))
+
+
+def _decode_with_tk(raw: bytes):
+ """GIF (and anything else Tk reads) through the real Tk."""
+ from bui import host
+ tk = _realtk.module()
+ host._tk() # the hidden real Tk root
+ try:
+ img = tk.PhotoImage(master=host._tk(), data=base64.b64encode(raw).decode())
+ except tk.TclError as e:
+ raise TclError(str(e)) from None
+ w, h = img.width(), img.height()
+ px = bytearray(w * h * 4)
+ for y in range(h):
+ for x in range(w):
+ r, g, b = img.get(x, y)
+ a = 0 if img.transparency_get(x, y) else 255
+ px[4 * (y * w + x):4 * (y * w + x) + 4] = bytes((r, g, b, a))
+ return w, h, px
+
+
+def _decode_xbm(text: str):
+ w = int(re.search(r"_width\s+(\d+)", text).group(1))
+ h = int(re.search(r"_height\s+(\d+)", text).group(1))
+ body = text[text.index("{") + 1:text.rindex("}")]
+ data = [int(v, 16) for v in re.findall(r"0x[0-9a-fA-F]+", body)]
+ per_row = (w + 7) // 8
+ bits = []
+ for y in range(h):
+ for x in range(w):
+ byte = data[y * per_row + x // 8] if y * per_row + x // 8 < len(data) else 0
+ bits.append((byte >> (x % 8)) & 1)
+ return w, h, bits
diff --git a/bindings/python/bui/tksyntax/_widgets.py b/bindings/python/bui/tksyntax/_widgets.py
new file mode 100644
index 0000000..3959dce
--- /dev/null
+++ b/bindings/python/bui/tksyntax/_widgets.py
@@ -0,0 +1,3445 @@
+"""tkinter's classic widgets on the BUI kit (Blender look, tkinter API).
+
+Label, Message, Button, Checkbutton, Radiobutton, Scale, Spinbox, Entry,
+Listbox, Frame, LabelFrame, Scrollbar, Canvas, Text, Menu, Menubutton,
+OptionMenu, PanedWindow.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import math
+import re
+
+import buipy
+
+from bui.components.core import EV_CHANGE, EV_CLICK, EV_MOTION, EV_PRESS, EV_SCROLL, EV_SUBMIT
+from bui.components.menus import MenuItem
+
+from ._core import (BaseWidget, Event, EventType, IntVar, StringVar, TclError, Variable, Widget,
+ XView, YView, _BindTable, _call, _chars, _command, _commands,
+ _font_scale, _get_default_root, _pads, _pixels, _setit, _set_quiet,
+ _text_width, _try_color, _var_value, _wrap, color, getboolean)
+from ._images import Image, _images
+
+_TEXT_FG = (0.9, 0.9, 0.9, 1.0) # Blender's text color: default ink on dark canvases
+
+
+def _image_of(value):
+ if value in (None, ""):
+ return None
+ if isinstance(value, Image):
+ return value
+ img = _images.get(str(value))
+ if img is None:
+ raise TclError('image "%s" doesn\'t exist' % value)
+ return img
+
+
+_BITMAP_ICONS = {"error": "ERROR", "info": "INFO", "question": "QUESTION",
+ "warning": "ERROR", "hourglass": "TIME", "questhead": "QUESTION"}
+
+
+# ==========================================================================
+# Shared option groups
+
+
+class _TextOptions:
+ """text / textvariable / anchor / justify / wraplength / image / bitmap /
+ width / height for text-showing widgets."""
+
+ _TEXT_PROP = "text" # kit property that shows the text
+ _SIZE_IN_CHARS = True # width in characters (pixels when showing an image)
+
+ def _text_option(self, key, value) -> bool:
+ if key in ("text", "wraplength"):
+ self._show_text()
+ elif key == "textvariable":
+ var = value if isinstance(value, Variable) else None
+ if var is not None:
+ var.trace_add("write", lambda *a: self.winfo_exists() and self._show_text())
+ self._show_text()
+ elif key in ("anchor", "justify"):
+ a = str(self._opts.get("anchor", "")) if "anchor" in self._opts else ""
+ j = str(self._opts.get("justify", ""))
+ align = "left" if "w" in a else "right" if "e" in a else \
+ {"left": "left", "right": "right"}.get(j, "center")
+ _set_quiet(self._node, "text_align", align)
+ elif key == "image":
+ self._show_image(_image_of(value))
+ elif key == "bitmap":
+ icon = _BITMAP_ICONS.get(str(value).lstrip("@"))
+ if icon:
+ _set_quiet(self._node, "icon", icon)
+ elif isinstance(value, Image):
+ self._show_image(value)
+ elif key in ("width", "height"):
+ self._apply_size()
+ else:
+ return False
+ return True
+
+ def _current_text(self):
+ var = self._opts.get("textvariable")
+ if var not in (None, ""):
+ try:
+ return str(_var_value(var))
+ except KeyError:
+ return ""
+ return str(self._opts.get("text", ""))
+
+ def _show_text(self):
+ text = self._current_text()
+ wl = self._opts.get("wraplength")
+ if wl:
+ text = _wrap(text, _pixels(wl))
+ self._node.set(self._TEXT_PROP, text)
+
+ def _show_image(self, img):
+ if img is None:
+ self._node.set_image()
+ else:
+ img._attach(self)
+ self._image_changed(img)
+ self._apply_size()
+
+ def _image_changed(self, img):
+ if self.winfo_exists():
+ self._node.set_image(img.width(), img.height(), img.rgba())
+
+ def _apply_size(self):
+ img = self._opts.get("image")
+ w, h = self._opts.get("width"), self._opts.get("height")
+ params = {}
+ if w not in (None, "", 0, "0"):
+ params["reqwidth"] = int(_pixels(w)) if (img or not self._SIZE_IN_CHARS) else \
+ _chars(int(w))
+ else:
+ params["reqwidth"] = 0
+ if h not in (None, "", 0, "0"):
+ unit = buipy.kit_unit()
+ params["reqheight"] = int(_pixels(h)) if (img or not self._SIZE_IN_CHARS) else \
+ max(unit, int(int(h) * unit * 0.8 + unit * 0.4))
+ else:
+ params["reqheight"] = 0
+ self._node.geom(int(self._node.geom_get("manager")), **params)
+
+
+class _Validation:
+ """Entry/Spinbox validate + validatecommand (+ invalidcommand)."""
+
+ def _validate(self, reason, new, old, action=-1, index=-1, change=""):
+ mode = str(self._opts.get("validate", "none"))
+ if mode == "none" or not self._opts.get("validatecommand"):
+ return True
+ wanted = {"key": ("key",), "focus": ("focusin", "focusout"), "focusin": ("focusin",),
+ "focusout": ("focusout",), "all": ("key", "focusin", "focusout", "forced")}
+ if mode != "all" and reason not in wanted.get(mode, ()):
+ return True
+ subst = {"%d": str(action), "%i": str(index), "%P": new, "%s": old, "%S": change,
+ "%v": mode, "%V": reason, "%W": self._w}
+ ok = self._run_vcmd(self._opts["validatecommand"], subst)
+ if not ok:
+ inv = self._opts.get("invalidcommand")
+ if inv:
+ self._run_vcmd(inv, subst)
+ return ok
+
+ @staticmethod
+ def _run_vcmd(cmd, subst):
+ if isinstance(cmd, (tuple, list)):
+ fn = _commands.get(str(cmd[0])) or (cmd[0] if callable(cmd[0]) else None)
+ args = [subst.get(str(a), a) for a in cmd[1:]]
+ elif callable(cmd):
+ fn, args = cmd, []
+ else:
+ parts = str(cmd).split()
+ fn, args = _commands.get(parts[0]), [subst.get(a, a) for a in parts[1:]]
+ if fn is None:
+ return True
+ r = fn(*args)
+ return r is None or getboolean(r)
+
+
+def _diff(old: str, new: str):
+ """(index, removed, inserted) of a single edit."""
+ a = 0
+ while a < min(len(old), len(new)) and old[a] == new[a]:
+ a += 1
+ b = 0
+ while b < min(len(old), len(new)) - a and old[-1 - b] == new[-1 - b]:
+ b += 1
+ return a, old[a:len(old) - b], new[a:len(new) - b]
+
+
+# ==========================================================================
+# Labels and buttons
+
+
+class Label(_TextOptions, Widget):
+ """Label widget which can display text and bitmaps."""
+
+ _KIND = "label"
+ _DEFAULTS = {"text": "", "anchor": "center", "justify": "center", "state": "normal",
+ "relief": "flat", "bd": 2, "padx": 1, "pady": 1, "width": 0, "height": 0,
+ "wraplength": 0, "compound": "none"}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "label", cnf, kw)
+
+ def _setup(self):
+ self._node.set("text_align", "center")
+
+ def _apply(self, key, value):
+ if not self._text_option(key, value):
+ super()._apply(key, value)
+
+
+class Message(Label):
+ """Message widget: a label that wraps its text to `width` / `aspect`."""
+
+ _DEFAULTS = dict(Label._DEFAULTS, aspect=150, width=0, justify="left")
+ _SIZE_IN_CHARS = False
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "message", cnf, kw)
+
+ def _setup(self):
+ self._node.set("text_align", "left")
+
+ def _apply(self, key, value):
+ if key in ("width", "aspect"): # re-wrap whatever order options come in
+ self._show_text()
+ else:
+ super()._apply(key, value)
+
+ def _show_text(self):
+ text = self._current_text()
+ width = _pixels(self._opts["width"]) if self._opts.get("width") else 0
+ if not width: # aspect = 100 * width / height
+ aspect = float(self._opts.get("aspect", 150)) / 100.0
+ line_h = buipy.kit_unit() * 0.8
+ width = max(40.0, math.sqrt(max(1.0, _text_width(text)) * line_h * aspect))
+ self._node.set("text", _wrap(text, width))
+
+ def _apply_size(self):
+ pass
+
+
+class Button(_TextOptions, Widget):
+ """Button widget."""
+
+ _KIND = "button"
+ _TAKEFOCUS = True
+ _DEFAULTS = {"text": "", "state": "normal", "default": "disabled", "relief": "raised",
+ "bd": 2, "width": 0, "height": 0, "command": "", "compound": "none"}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "button", cnf, kw)
+
+ def _apply(self, key, value):
+ if not self._text_option(key, value):
+ super()._apply(key, value)
+
+ def invoke(self):
+ """Invoke the command associated with the button."""
+ if str(self._opts.get("state", "normal")) == "disabled":
+ return ""
+ cmd = self._opts.get("command")
+ return _command(cmd)() if cmd else ""
+
+ def flash(self):
+ """Flash the button (Blender buttons highlight on hover instead)."""
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CLICK:
+ _call(self, self.invoke)
+
+
+class _Choice(_TextOptions):
+ """Checkbutton / Radiobutton: text on the kit's 'label', optional
+ toggle-button look (indicatoron=0)."""
+
+ _TEXT_PROP = "label"
+ _TAKEFOCUS = True
+
+ def __init__(self, master, name, cnf, kw):
+ kw = dict(cnf, **kw) if cnf else dict(kw)
+ if str(kw.get("indicatoron", 1)) in ("0", "False", "false"):
+ self._KIND = "toggle" # Blender's toggle button
+ self._TEXT_PROP = "text"
+ Widget.__init__(self, master, name, {}, kw)
+
+ def _apply(self, key, value):
+ if key == "variable":
+ if isinstance(value, Variable):
+ value.trace_add("write", lambda *a: self.winfo_exists() and self._sync())
+ self._sync()
+ elif key in ("onvalue", "offvalue", "value"):
+ self._sync()
+ elif not self._text_option(key, value):
+ super()._apply(key, value)
+
+ def _var(self):
+ var = self._opts.get("variable")
+ if isinstance(var, str):
+ from ._core import _variables
+ var = _variables.get(var) or StringVar(name=var)
+ self._opts["variable"] = var
+ return var
+
+ def flash(self):
+ pass
+
+
+class Checkbutton(_Choice, Widget):
+ """Checkbutton widget which is either in on- or off-state."""
+
+ _KIND = "checkbox"
+ _DEFAULTS = {"text": "", "onvalue": 1, "offvalue": 0, "state": "normal",
+ "indicatoron": 1, "command": ""}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ kw = dict(cnf, **kw) if cnf else dict(kw)
+ _Choice.__init__(self, master, "checkbutton", {}, kw)
+ if "variable" not in self._opts: # Tk gives every checkbutton a variable
+ self.configure(variable=IntVar(name=self._w))
+
+ def _sync(self):
+ var = self._var()
+ if var is None:
+ return
+ on = self.cget("onvalue")
+ try:
+ value = var._raw()
+ except AttributeError:
+ return
+ self._node.set("value", 1.0 if str(value) == str(on) or
+ (value is True and str(on) == "1") else 0.0)
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ on = self._node.get("value") != 0
+ var = self._var()
+ if var is not None:
+ var.set(self.cget("onvalue") if on else self.cget("offvalue"))
+ cmd = self._opts.get("command")
+ if cmd:
+ _call(self, _command(cmd))
+
+ def select(self):
+ """Put the button in on-state."""
+ self._var().set(self.cget("onvalue"))
+
+ def deselect(self):
+ """Put the button in off-state."""
+ self._var().set(self.cget("offvalue"))
+
+ def toggle(self):
+ """Toggle the button."""
+ on = self._node.get("value") != 0
+ self._var().set(self.cget("offvalue") if on else self.cget("onvalue"))
+
+ def invoke(self):
+ """Toggle the button and invoke a command if given as resource."""
+ if str(self._opts.get("state", "normal")) == "disabled":
+ return ""
+ self.toggle()
+ cmd = self._opts.get("command")
+ return _command(cmd)() if cmd else ""
+
+
+_selected_button = None
+
+
+def _radio_default_var():
+ global _selected_button
+ if _selected_button is None:
+ _selected_button = StringVar(name="selectedButton")
+ return _selected_button
+
+
+class Radiobutton(_Choice, Widget):
+ """Radiobutton widget which shows only one of several buttons in on-state."""
+
+ _KIND = "radio"
+ _DEFAULTS = {"text": "", "state": "normal", "indicatoron": 1, "command": ""}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ kw = dict(cnf, **kw) if cnf else dict(kw)
+ _Choice.__init__(self, master, "radiobutton", {}, kw)
+ if "variable" not in self._opts: # Tk: one global variable for all
+ self.configure(variable=_radio_default_var())
+ if "value" not in self._opts: # Tk: the value defaults to the name
+ self.configure(value=self._name)
+
+ def _sync(self):
+ var = self._var()
+ if var is None or "value" not in self._opts:
+ return
+ self._node.set("value", 1.0 if str(var._raw()) == str(self._opts["value"]) else 0.0)
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ if self._node.get("value") == 0: # a radio can't be switched off by a click
+ self._sync()
+ return
+ self._var().set(self._opts.get("value"))
+ cmd = self._opts.get("command")
+ if cmd:
+ _call(self, _command(cmd))
+
+ def select(self):
+ """Put the button in on-state."""
+ self._var().set(self._opts.get("value"))
+
+ def deselect(self):
+ """Put the button in off-state."""
+ if str(self._var()._raw()) == str(self._opts.get("value")):
+ self._var().set("")
+
+ def invoke(self):
+ """Select the button and invoke a command if given as resource."""
+ if str(self._opts.get("state", "normal")) == "disabled":
+ return ""
+ self.select()
+ cmd = self._opts.get("command")
+ return _command(cmd)() if cmd else ""
+
+
+# ==========================================================================
+# Value widgets
+
+
+def _resolution_precision(res) -> int:
+ r = float(res)
+ if r <= 0:
+ return 2
+ if r >= 1 and r == int(r):
+ return 0
+ return max(1, min(6, len(("%.6f" % r).rstrip("0").split(".")[1])))
+
+
+class Scale(Widget):
+ """Scale widget which can display a numerical scale (a Blender slider)."""
+
+ _KIND = "slider"
+ _TAKEFOCUS = True
+ _DEFAULTS = {"from": 0, "to": 100, "resolution": 1, "orient": "vertical", "length": 100,
+ "showvalue": 1, "digits": 0, "tickinterval": 0, "bigincrement": 0,
+ "state": "normal", "label": "", "command": ""}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "scale", cnf, kw)
+
+ def _setup(self):
+ n = self._node
+ n.set("min", 0.0)
+ n.set("max", 100.0)
+ n.set("step", 1.0)
+ n.set("integer", True)
+ n.set("precision", 0)
+
+ def _apply(self, key, value):
+ n = self._node
+ if key in ("from", "to"):
+ lo, hi = float(self.cget("from")), float(self.cget("to"))
+ n.set("min", min(lo, hi))
+ n.set("max", max(lo, hi))
+ n.set("value", min(max(n.get("value"), min(lo, hi)), max(lo, hi)))
+ elif key == "resolution":
+ r = float(value)
+ n.set("step", r if r > 0 else 0.01)
+ n.set("integer", r >= 1 and r == int(r))
+ n.set("precision", _resolution_precision(r))
+ elif key == "label":
+ n.set("label", str(value))
+ elif key == "variable":
+ var = value
+ if isinstance(var, Variable):
+ var.trace_add("write", lambda *a: self.winfo_exists() and self._from_var())
+ self._from_var()
+ elif key == "length":
+ if str(self.cget("orient")).startswith("h"):
+ n.geom(int(n.geom_get("manager")), reqwidth=int(_pixels(value)))
+ elif key == "orient" and "length" in self._opts:
+ self._apply("length", self._opts["length"])
+ else:
+ super()._apply(key, value)
+
+ def _from_var(self):
+ var = self._opts.get("variable")
+ if var not in (None, ""):
+ try:
+ self._node.set("value", float(_var_value(var)))
+ except (TypeError, ValueError):
+ pass
+
+ def _format(self, v):
+ prec = _resolution_precision(self.cget("resolution"))
+ return str(int(round(v))) if prec == 0 else "%.*f" % (prec, v)
+
+ def get(self):
+ """Get the current value as integer or float."""
+ v = self._node.get("value")
+ return int(round(v)) if self._node.get("integer") else round(v, 6)
+
+ def set(self, value):
+ """Set the value to VALUE (runs the command, like Tk)."""
+ self._node.set("set_value", float(value))
+
+ def coords(self, value=None):
+ """Coordinates of the point on the trough corresponding to VALUE."""
+ v = self._node.get("value") if value is None else float(value)
+ lo, hi = self._node.get("min"), self._node.get("max")
+ frac = 0.0 if hi == lo else (v - lo) / (hi - lo)
+ w, h = self.winfo_width(), self.winfo_height()
+ return (int(frac * w), h // 2)
+
+ def identify(self, x, y):
+ """'slider', 'trough1' or 'trough2' at X, Y."""
+ sx = self.coords()[0]
+ if abs(int(x) - sx) <= 4:
+ return "slider"
+ return "trough1" if int(x) < sx else "trough2"
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ v = self.get()
+ var = self._opts.get("variable")
+ if var not in (None, ""):
+ (var if isinstance(var, Variable) else Variable(name=str(var))).set(v)
+ if self._opts.get("command") and not getattr(self, "_cmd_pending", False):
+ self._cmd_pending = True # Tk runs -command when idle (once per burst)
+ self.after_idle(self._run_command)
+
+ def _run_command(self):
+ self._cmd_pending = False
+ cmd = self._opts.get("command")
+ if cmd and self.winfo_exists():
+ _call(self, _command(cmd), self._format(self.get()))
+
+
+class Entry(_Validation, Widget, XView):
+ """Entry widget which allows displaying simple text."""
+
+ _KIND = "text"
+ _TAKEFOCUS = True
+ _DEFAULTS = {"state": "normal", "show": "", "width": 20, "validate": "none",
+ "justify": "left", "exportselection": 1}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "entry", cnf, kw)
+
+ def _setup(self):
+ self._node.set("live", True) # Tk entries change per keystroke
+ self._last = ""
+ self._cursor = 0
+ self._anchor = 0
+ self._sel = None
+ self._node.geom(0, reqwidth=_chars(20))
+
+ def _focus_node(self):
+ return self._node
+
+ def _apply(self, key, value):
+ n = self._node
+ if key == "textvariable":
+ if isinstance(value, Variable):
+ value.trace_add("write", lambda *a: self.winfo_exists() and self._from_var())
+ self._from_var()
+ elif key == "show":
+ n.set("mask", str(value)[:1] if value else "")
+ elif key == "width":
+ n.geom(int(n.geom_get("manager")), reqwidth=_chars(int(value or 20)))
+ elif key == "state":
+ n.set("enabled", str(value) == "normal")
+ elif key in ("placeholder",):
+ n.set("placeholder", str(value))
+ elif key == "validate":
+ if str(value) in ("focus", "focusout", "all"):
+ n.set("events", True) # Return / Tab end the edit: SUBMIT
+ else:
+ super()._apply(key, value)
+
+ def _from_var(self):
+ var = self._opts.get("textvariable")
+ if var in (None, ""):
+ return
+ text = str(_var_value(var))
+ if text != self._node.get_str("value"):
+ self._last = text
+ self._node.set("value", text)
+
+ def _set_text(self, text, reason="forced"):
+ old = self.get()
+ if text == old:
+ return
+ idx, removed, inserted = _diff(old, text)
+ if not self._validate(reason, text, old, 1 if inserted else 0, idx, inserted or removed):
+ return
+ self._last = text
+ self._node.set("value", text)
+ self._to_var(text)
+
+ def _to_var(self, text):
+ var = self._opts.get("textvariable")
+ if var not in (None, "") and str(_var_value(var)) != text:
+ (var if isinstance(var, Variable) else StringVar(name=str(var))).set(text)
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ new = self._node.get_str("value")
+ old = self._last
+ idx, removed, inserted = _diff(old, new)
+ if not self._validate("key", new, old, 1 if inserted else 0, idx,
+ inserted or removed):
+ self._node.set("value", old) # rejected: the field shows the old text
+ return
+ self._last = new
+ self._cursor = idx + len(inserted)
+ self._to_var(new)
+ elif kind == EV_SUBMIT:
+ self._validate("focusout", self.get(), self.get())
+
+ # -- tkinter API ---------------------------------------------------------------
+ def get(self):
+ """Return the text."""
+ return self._node.get_str("value")
+
+ def index(self, index):
+ """Return position of cursor."""
+ s = self.get()
+ if isinstance(index, int):
+ return max(0, min(len(s), index))
+ index = str(index)
+ if index == "end":
+ return len(s)
+ if index == "insert":
+ return min(self._cursor, len(s))
+ if index == "anchor":
+ return min(self._anchor, len(s))
+ if index in ("sel.first", "sel.last"):
+ if not self._sel:
+ raise TclError("selection isn't in widget %s" % self._w)
+ return self._sel[0 if index == "sel.first" else 1]
+ if index.startswith("@"):
+ x = int(index[1:])
+ pad = buipy.kit_unit() * 0.4
+ for i in range(len(s) + 1):
+ if _text_width(s[:i]) + pad >= x:
+ return i
+ return len(s)
+ try:
+ return max(0, min(len(s), int(index)))
+ except ValueError:
+ raise TclError('bad entry index "%s"' % index) from None
+
+ def insert(self, index, string):
+ """Insert STRING at INDEX."""
+ s = self.get()
+ i = self.index(index)
+ self._set_text(s[:i] + str(string) + s[i:], "key") # Tk validates edits as keys
+ self._cursor = i + len(str(string))
+
+ def delete(self, first, last=None):
+ """Delete text from FIRST to LAST (not included)."""
+ s = self.get()
+ a = self.index(first)
+ b = a + 1 if last is None else self.index(last)
+ if b > a:
+ self._set_text(s[:a] + s[b:], "key")
+ self._cursor = a
+
+ def icursor(self, index):
+ """Insert cursor at INDEX."""
+ self._cursor = self.index(index)
+
+ def bbox(self, index):
+ """Return a tuple of (x,y,width,height) of the character at INDEX."""
+ i = self.index(index)
+ s = self.get()
+ pad = int(buipy.kit_unit() * 0.4)
+ x = pad + int(_text_width(s[:i]))
+ return (x, 2, max(1, int(_text_width(s[i:i + 1] or " "))), self.winfo_height() - 4)
+
+ def scan_mark(self, x):
+ self._scan = int(x)
+
+ def scan_dragto(self, x):
+ pass # the kit scrolls the field to keep the cursor visible
+
+ def selection_adjust(self, index):
+ i = self.index(index)
+ a, b = self._sel or (i, i)
+ self._sel = (min(a, i), max(b, i))
+
+ select_adjust = selection_adjust
+
+ def selection_clear(self):
+ self._sel = None
+
+ select_clear = selection_clear
+
+ def selection_from(self, index):
+ self._anchor = self.index(index)
+
+ select_from = selection_from
+
+ def selection_present(self):
+ return bool(self._sel and self._sel[1] > self._sel[0])
+
+ select_present = selection_present
+
+ def selection_range(self, start, end):
+ a, b = self.index(start), self.index(end)
+ self._sel = (min(a, b), max(a, b)) if b != a else None
+
+ select_range = selection_range
+
+ def selection_to(self, index):
+ i = self.index(index)
+ self._sel = (min(self._anchor, i), max(self._anchor, i))
+
+ select_to = selection_to
+
+ def _selected_text(self):
+ return self.get()[self._sel[0]:self._sel[1]] if self.selection_present() else ""
+
+ def _view(self, axis):
+ return (0.0, 1.0) # the field scrolls itself around the cursor
+
+ def _view_set(self, axis, op, args):
+ pass
+
+
+class Spinbox(_Validation, Widget, XView):
+ """Spinbox widget: a Blender number field (or an enum dropdown with values=)."""
+
+ _TAKEFOCUS = True
+ _DEFAULTS = {"from": 0.0, "to": 0.0, "increment": 1.0, "state": "normal", "width": 20,
+ "wrap": 0, "format": "", "validate": "none", "command": ""}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ kw = dict(cnf, **kw) if cnf else dict(kw)
+ self._KIND = "dropdown" if kw.get("values") not in (None, "", ()) else "number"
+ Widget.__init__(self, master, "spinbox", {}, kw)
+
+ def _setup(self):
+ n = self._node
+ self._values = []
+ self._last = ""
+ if self._KIND == "number":
+ n.set("integer", True)
+ n.set("precision", 0)
+ n.set("min", 0.0)
+ n.set("max", 0.0)
+ n.set("step", 1.0)
+
+ def _focus_node(self):
+ return self._node
+
+ def _apply(self, key, value):
+ n = self._node
+ if key == "values":
+ vals = list(value) if not isinstance(value, str) else value.split()
+ self._values = [str(v) for v in vals]
+ if self._KIND == "dropdown":
+ n.set("items", self._values)
+ elif key in ("from", "to") and self._KIND == "number":
+ lo, hi = float(self.cget("from")), float(self.cget("to"))
+ n.set("min", min(lo, hi))
+ n.set("max", max(lo, hi))
+ if not lo <= n.get("value") <= hi and lo <= hi:
+ n.set("value", lo)
+ elif key == "increment" and self._KIND == "number":
+ inc = float(value)
+ n.set("step", inc)
+ self._set_precision()
+ elif key == "format":
+ self._set_precision()
+ elif key == "textvariable":
+ if isinstance(value, Variable):
+ value.trace_add("write", lambda *a: self.winfo_exists() and self._from_var())
+ self._from_var()
+ elif key == "width":
+ n.geom(int(n.geom_get("manager")), reqwidth=_chars(int(value or 20)))
+ elif key == "state":
+ n.set("enabled", str(value) == "normal")
+ else:
+ super()._apply(key, value)
+
+ def _set_precision(self):
+ fmt = str(self._opts.get("format", ""))
+ m = re.search(r"\.(\d+)f", fmt)
+ if m:
+ prec = int(m.group(1))
+ else:
+ prec = _resolution_precision(self.cget("increment"))
+ self._node.set("precision", prec)
+ self._node.set("integer", prec == 0)
+
+ def _from_var(self):
+ var = self._opts.get("textvariable")
+ if var not in (None, ""):
+ self._show(str(_var_value(var)))
+
+ def _show(self, text):
+ n = self._node
+ if self._KIND == "dropdown":
+ if text in self._values:
+ n.set("value", float(self._values.index(text)))
+ else:
+ try:
+ n.set("value", float(text))
+ except (TypeError, ValueError):
+ pass
+ self._last = self.get()
+
+ def get(self):
+ """Return the text."""
+ n = self._node
+ if self._KIND == "dropdown":
+ i = int(n.get("value"))
+ return self._values[i] if 0 <= i < len(self._values) else ""
+ v = n.get("value")
+ fmt = self._opts.get("format")
+ if fmt:
+ try:
+ return str(fmt) % v
+ except (TypeError, ValueError):
+ pass
+ return str(int(round(v))) if n.get("integer") else repr(round(v, 6))
+
+ def _set_text(self, text, reason="forced"):
+ old = self.get()
+ if not self._validate(reason, text, old):
+ return
+ self._show(text)
+ self._after_change()
+
+ def _after_change(self):
+ var = self._opts.get("textvariable")
+ if var not in (None, ""):
+ (var if isinstance(var, Variable) else StringVar(name=str(var))).set(self.get())
+
+ def insert(self, index, s):
+ cur = self.get()
+ i = self.index(index)
+ self._set_text(cur[:i] + str(s) + cur[i:])
+
+ def delete(self, first, last=None):
+ cur = self.get()
+ a = self.index(first)
+ b = a + 1 if last is None else self.index(last)
+ self._set_text(cur[:a] + cur[b:])
+
+ def index(self, index):
+ s = self.get()
+ if str(index) == "end":
+ return len(s)
+ if str(index) in ("insert", "anchor"):
+ return len(s)
+ return max(0, min(len(s), int(index)))
+
+ def icursor(self, index):
+ pass
+
+ def bbox(self, index):
+ return (0, 0, self.winfo_width(), self.winfo_height())
+
+ def identify(self, x, y):
+ """'entry', 'buttonup' or 'buttondown' at X, Y."""
+ w = self.winfo_width()
+ arrow = min(w // 3, int(self.winfo_height() * 0.7))
+ if int(x) < arrow:
+ return "buttondown"
+ if int(x) >= w - arrow:
+ return "buttonup"
+ return "entry"
+
+ def invoke(self, element):
+ """Press 'buttonup' or 'buttondown'."""
+ n = self._node
+ if self._KIND == "dropdown":
+ i = int(n.get("value")) + (1 if element == "buttonup" else -1)
+ if self.cget("wrap") not in (0, "0", False):
+ i %= max(1, len(self._values))
+ n.set("set_value", float(max(0, min(len(self._values) - 1, i))))
+ else:
+ step = float(self.cget("increment")) * (1 if element == "buttonup" else -1)
+ n.set("set_value", n.get("value") + step)
+ return ""
+
+ def scan(self, *args):
+ return ""
+
+ def scan_mark(self, x):
+ pass
+
+ def scan_dragto(self, x):
+ pass
+
+ def selection(self, *args):
+ return ""
+
+ def selection_adjust(self, index):
+ pass
+
+ def selection_clear(self):
+ pass
+
+ def selection_element(self, element=None):
+ return "none"
+
+ def selection_from(self, index):
+ pass
+
+ def selection_present(self):
+ return False
+
+ def selection_range(self, start, end):
+ pass
+
+ def selection_to(self, index):
+ pass
+
+ select_adjust, select_clear, select_from = selection_adjust, selection_clear, selection_from
+ select_present, select_range, select_to = selection_present, selection_range, selection_to
+
+ def _view(self, axis):
+ return (0.0, 1.0)
+
+ def _view_set(self, axis, op, args):
+ pass
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ new, old = self.get(), self._last
+ if not self._validate("key", new, old):
+ self._show(old)
+ return
+ self._last = new
+ self._after_change()
+ cmd = self._opts.get("command")
+ if cmd:
+ _call(self, _command(cmd))
+
+
+# ==========================================================================
+# Listbox
+
+
+_SELMODES = {"browse": 3, "single": 3, "multiple": 1, "extended": 2}
+
+
+class Listbox(Widget, XView, YView):
+ """Listbox widget which can display a list of strings."""
+
+ _KIND = "list"
+ _TAKEFOCUS = True
+ _DEFAULTS = {"selectmode": "browse", "height": 10, "width": 20, "activestyle": "dotbox",
+ "state": "normal", "exportselection": 1}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "listbox", cnf, kw)
+
+ def _setup(self):
+ n = self._node
+ self._items = []
+ self._item_opts = {}
+ self._anchor = 0
+ self._last_sel = ()
+ n.set("rows", 10)
+ n.set("selmode", 3)
+ n.geom(0, reqwidth=_chars(20))
+
+ def _apply(self, key, value):
+ n = self._node
+ if key == "height":
+ n.set("rows", int(value) or 10)
+ elif key == "width":
+ n.geom(int(n.geom_get("manager")), reqwidth=_chars(int(value or 20)))
+ elif key == "selectmode":
+ n.set("selmode", float(_SELMODES.get(str(value), 3)))
+ elif key == "listvariable":
+ if isinstance(value, Variable):
+ value.trace_add("write", lambda *a: self.winfo_exists() and self._from_var())
+ self._from_var()
+ elif key in ("xscrollcommand", "yscrollcommand"):
+ n.set("noscrollbar", bool(value) or bool(self._opts.get(
+ "yscrollcommand" if key[0] == "x" else "xscrollcommand")))
+ n.set("viewevents", True)
+ elif key == "state":
+ n.set("enabled", str(value) != "disabled")
+ else:
+ super()._apply(key, value)
+
+ def _from_var(self):
+ var = self._opts.get("listvariable")
+ if var in (None, ""):
+ return
+ value = _var_value(var)
+ if isinstance(value, str):
+ value = re.findall(r"\{([^}]*)\}|(\S+)", value)
+ value = [a or b for a, b in value]
+ self._set_items([str(v) for v in value], sync_var=False)
+
+ def _set_items(self, items, sync_var=True):
+ marked = set(self.curselection())
+ self._items = items
+ self._node.set("items", items)
+ self._node.set("clearmarks", 1)
+ for i in marked:
+ if i < len(items):
+ self._node.set("mark%d" % i, 1)
+ if sync_var:
+ var = self._opts.get("listvariable")
+ if isinstance(var, Variable):
+ var._value = tuple(items)
+ var._fire("write")
+
+ def _index(self, index, end_is_size=True):
+ if isinstance(index, int):
+ return index
+ s = str(index)
+ if s == "end":
+ return len(self._items) if end_is_size else max(0, len(self._items) - 1)
+ if s == "active":
+ return int(self._node.get("value"))
+ if s == "anchor":
+ return self._anchor
+ if s.startswith("@"):
+ _, _, y = s[1:].partition(",")
+ return self.nearest(int(y))
+ try:
+ return int(s)
+ except ValueError:
+ raise TclError('bad listbox index "%s": must be active, anchor, end, @x,y, '
+ 'or a number' % index) from None
+
+ def _range(self, first, last):
+ a = self._index(first, False)
+ b = a if last is None else self._index(last, False)
+ return a, b
+
+ # -- items -------------------------------------------------------------------------
+ def insert(self, index, *elements):
+ """Insert ELEMENTS at INDEX."""
+ i = min(self._index(index), len(self._items))
+ marked = self.curselection()
+ items = self._items[:i] + [str(e) for e in elements] + self._items[i:]
+ self._set_items(items)
+ self._node.set("clearmarks", 1)
+ for m in marked:
+ self._node.set("mark%d" % (m + len(elements) if m >= i else m), 1)
+
+ def delete(self, first, last=None):
+ """Delete items from FIRST to LAST (included)."""
+ a, b = self._range(first, last)
+ if b < a or not self._items:
+ return
+ marked = self.curselection()
+ items = self._items[:a] + self._items[b + 1:]
+ self._set_items(items)
+ self._node.set("clearmarks", 1)
+ for m in marked:
+ if m < a:
+ self._node.set("mark%d" % m, 1)
+ elif m > b:
+ self._node.set("mark%d" % (m - (b - a + 1)), 1)
+
+ def get(self, first, last=None):
+ """Get list of items from FIRST to LAST (included)."""
+ a, b = self._range(first, last)
+ if last is None:
+ return self._items[a] if 0 <= a < len(self._items) else ""
+ return tuple(self._items[a:b + 1])
+
+ def size(self):
+ """Return the number of elements in the listbox."""
+ return len(self._items)
+
+ def index(self, index):
+ """Return index of item identified with INDEX."""
+ i = self._index(index)
+ return None if i is None else i
+
+ def itemconfigure(self, index, cnf=None, **kw):
+ i = self._index(index, False)
+ if not kw and not cnf:
+ opts = self._item_opts.get(i, {})
+ return {k: (k, "", "", "", v) for k, v in opts.items()}
+ self._item_opts.setdefault(i, {}).update(dict(cnf or {}, **kw))
+ return None
+
+ itemconfig = itemconfigure
+
+ def itemcget(self, index, option):
+ return self._item_opts.get(self._index(index, False), {}).get(option.lstrip("-"), "")
+
+ # -- selection ------------------------------------------------------------------------
+ def curselection(self):
+ """Return the indices of currently selected item."""
+ n = self._node
+ return tuple(i for i in range(len(self._items)) if n.get("mark%d" % i))
+
+ def selection_set(self, first, last=None):
+ """Set the selection from FIRST to LAST (included) without changing
+ the currently selected elements."""
+ a, b = self._range(first, last)
+ for i in range(max(0, a), min(len(self._items), b + 1)):
+ self._node.set("mark%d" % i, 1)
+ self._last_sel = self.curselection()
+
+ select_set = selection_set
+
+ def selection_clear(self, first, last=None):
+ """Clear the selection from FIRST to LAST (included)."""
+ a, b = self._range(first, last)
+ for i in range(max(0, a), min(len(self._items), b + 1)):
+ self._node.set("mark%d" % i, 0)
+ self._last_sel = self.curselection()
+
+ select_clear = selection_clear
+
+ def selection_includes(self, index):
+ """Return True if INDEX is part of the selection."""
+ return bool(self._node.get("mark%d" % self._index(index, False)))
+
+ select_includes = selection_includes
+
+ def selection_anchor(self, index):
+ """Set the fixed end of the selection to INDEX."""
+ self._anchor = self._index(index, False)
+
+ select_anchor = selection_anchor
+
+ def activate(self, index):
+ """Activate item identified by INDEX."""
+ self._node.set("value", float(max(0, min(len(self._items) - 1, self._index(index,
+ False)))))
+
+ def _selected_text(self):
+ return "\n".join(self._items[i] for i in self.curselection())
+
+ # -- geometry ---------------------------------------------------------------------------
+ def _row_h(self):
+ return buipy.kit_unit()
+
+ def _first_row(self):
+ return int(round(self._node.get("yfirst") * max(1, len(self._items))))
+
+ def nearest(self, y):
+ """Get index of item which is nearest to y coordinate Y."""
+ if not self._items:
+ return -1
+ pad = round(0.15 * buipy.kit_unit())
+ return max(0, min(len(self._items) - 1, self._first_row() +
+ (int(y) - pad) // self._row_h()))
+
+ def bbox(self, index):
+ """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which
+ encloses the item identified by the given index."""
+ i = self._index(index, False)
+ first = self._first_row()
+ vis = int(self._node.get("yvisible"))
+ if not first <= i < first + vis:
+ return None
+ pad = round(0.15 * buipy.kit_unit())
+ return (pad, pad + (i - first) * self._row_h(), self.winfo_width() - 2 * pad,
+ self._row_h())
+
+ def see(self, index):
+ """Scroll such that INDEX is visible."""
+ i = self._index(index, False)
+ total = max(1, len(self._items))
+ first = self._first_row()
+ vis = max(1, int(self._node.get("yvisible")))
+ if i < first:
+ self._node.set("yview", i / total)
+ elif i >= first + vis:
+ self._node.set("yview", (i - vis + 1) / total)
+ self._view_changed()
+
+ def scan_mark(self, x, y):
+ self._scan = (int(y), self._first_row())
+
+ def scan_dragto(self, x, y):
+ y0, first = getattr(self, "_scan", (int(y), self._first_row()))
+ self._node.set("yview", (first - (int(y) - y0) * 10 // self._row_h()) /
+ max(1, len(self._items)))
+ self._view_changed()
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ sel = self.curselection()
+ if sel != self._last_sel:
+ self._last_sel = sel
+ self.event_generate("<<ListboxSelect>>")
+ if self.cget("exportselection") not in (0, "0", False) and sel:
+ self.selection_own()
+
+
+# ==========================================================================
+# Frames
+
+
+class Frame(Widget):
+ """Frame widget which may contain other widgets and can have a 3D border."""
+
+ _KIND = "frame"
+ _DEFAULTS = {"width": 0, "height": 0, "relief": "flat", "bd": 0, "padx": 0, "pady": 0}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "frame", cnf, kw)
+
+ def _apply(self, key, value):
+ if key in ("width", "height"):
+ self._size_changed()
+ elif key in ("padx", "pady", "padding"):
+ pads = _pads(value)
+ self._node.set("padding", int(max(pads)))
+ else:
+ super()._apply(key, value)
+
+ def _size_changed(self):
+ """Tk: width/height apply when the frame doesn't propagate its
+ children's size (pack_propagate(False)) or has no managed children."""
+ managed = any(c.winfo_manager() in ("pack", "grid", "place")
+ for c in self.winfo_children())
+ own = not managed or bool(self._node.get("nopropagate"))
+ w, h = self._opts.get("width", 0), self._opts.get("height", 0)
+ self._node.geom(int(self._node.geom_get("manager")),
+ reqwidth=int(_pixels(w or 0)) if own else 0,
+ reqheight=int(_pixels(h or 0)) if own else 0)
+
+
+class LabelFrame(Frame):
+ """Labelframe widget: a Blender panel box with its title."""
+
+ _DEFAULTS = dict(Frame._DEFAULTS, text="", labelanchor="nw")
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "labelframe", cnf, kw)
+
+ def _setup(self):
+ self._node.set("padding", round(0.3 * buipy.kit_unit()))
+
+ def _apply(self, key, value):
+ if key == "text":
+ self._node.set("text", str(value))
+ elif key == "labelwidget" and value is not None:
+ self._node.set("text", str(value.cget("text")))
+ else:
+ super()._apply(key, value)
+
+
+# ==========================================================================
+# Scrollbar
+
+
+class Scrollbar(Widget):
+ """Scrollbar widget which displays a slider at a certain position."""
+
+ _KIND = "scrollbar"
+ _DEFAULTS = {"orient": "vertical", "width": 0, "jump": 0, "command": ""}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "scrollbar", cnf, kw)
+
+ def _apply(self, key, value):
+ if key == "orient":
+ self._node.set("vertical", not str(value).startswith("h"))
+ elif key == "width" and value:
+ vert = not str(self.cget("orient")).startswith("h")
+ self._node.geom(int(self._node.geom_get("manager")),
+ **{"reqwidth" if vert else "reqheight": int(_pixels(value))})
+ else:
+ super()._apply(key, value)
+
+ def set(self, first, last):
+ """Set the fractional values of the slider position (upper and lower
+ ends as value between 0 and 1)."""
+ self._node.set("first", float(first))
+ self._node.set("last", float(last))
+
+ def get(self):
+ """Return the current fractional values (upper and lower end) of the
+ slider position."""
+ return (round(self._node.get("first"), 6), round(self._node.get("last"), 6))
+
+ def activate(self, index=None):
+ if index is None:
+ return getattr(self, "_active", None)
+ self._active = index
+ return None
+
+ def _length(self):
+ return self.winfo_height() if self._node.get("vertical") else self.winfo_width()
+
+ def delta(self, deltax, deltay):
+ """Return the fractional change of the scrollbar setting if it
+ would be moved by DELTAX or DELTAY pixels."""
+ d = deltay if self._node.get("vertical") else deltax
+ return float(d) / max(1, self._length())
+
+ def fraction(self, x, y):
+ """Return the fractional value which corresponds to a slider
+ position of X,Y."""
+ v = y if self._node.get("vertical") else x
+ return max(0.0, min(1.0, float(v) / max(1, self._length())))
+
+ def identify(self, x, y):
+ """Return the element under position X,Y as one of
+ "arrow1","slider","arrow2" or ""."""
+ f = self.fraction(x, y)
+ first, last = self.get()
+ if f < first:
+ return "trough1"
+ if f > last:
+ return "trough2"
+ return "slider"
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_SCROLL:
+ cmd = self._opts.get("command")
+ if not cmd:
+ return
+ fn = _command(cmd)
+ if int(a) == 0:
+ _call(self, fn, "moveto", repr(float(b)))
+ else:
+ _call(self, fn, "scroll", str(int(b)), "units" if int(a) == 1 else "pages")
+
+
+# ==========================================================================
+# Canvas
+
+
+_CANVAS_KIT = {"rectangle": 0, "oval": 1, "line": 2, "polygon": 3, "text": 4, "arc": 5,
+ "image": 6, "bitmap": 6}
+_SUB = 1 << 24 # kit ids of an item's parts (line arrows)
+
+
+class _Item:
+ __slots__ = ("id", "type", "coords", "tags", "opts")
+
+ def __init__(self, iid, kind, coords, tags, opts):
+ self.id, self.type, self.coords, self.tags, self.opts = iid, kind, coords, tags, opts
+
+
+def _flat(coords):
+ out = []
+ for c in coords:
+ if isinstance(c, (tuple, list)):
+ out.extend(_flat(c))
+ else:
+ out.append(float(_pixels(c)))
+ return out
+
+
+def _spline(pts, steps):
+ """Tk's smoothed line: quadratic B-spline through segment midpoints."""
+ if len(pts) < 6:
+ return pts
+ xy = list(zip(pts[0::2], pts[1::2]))
+ out = [xy[0]]
+ for i in range(1, len(xy) - 1):
+ p0 = xy[0] if i == 1 else ((xy[i - 1][0] + xy[i][0]) / 2, (xy[i - 1][1] + xy[i][1]) / 2)
+ p2 = xy[-1] if i == len(xy) - 2 else ((xy[i][0] + xy[i + 1][0]) / 2,
+ (xy[i][1] + xy[i + 1][1]) / 2)
+ p1 = xy[i]
+ for k in range(1, steps + 1):
+ t = k / steps
+ out.append(((1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * p1[0] + t * t * p2[0],
+ (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * p1[1] + t * t * p2[1]))
+ return [v for p in out for v in p]
+
+
+def _seg_dist(px, py, x1, y1, x2, y2):
+ dx, dy = x2 - x1, y2 - y1
+ t = 0.0 if dx == dy == 0 else max(0.0, min(1.0, ((px - x1) * dx + (py - y1) * dy) /
+ (dx * dx + dy * dy)))
+ return math.hypot(px - (x1 + t * dx), py - (y1 + t * dy))
+
+
+def _point_in_poly(x, y, pts):
+ inside = False
+ n = len(pts) // 2
+ for i in range(n):
+ x1, y1 = pts[2 * i], pts[2 * i + 1]
+ x2, y2 = pts[2 * ((i + 1) % n)], pts[2 * ((i + 1) % n) + 1]
+ if (y1 > y) != (y2 > y) and x < (x2 - x1) * (y - y1) / ((y2 - y1) or 1e-9) + x1:
+ inside = not inside
+ return inside
+
+
+class Canvas(Widget, XView, YView):
+ """Canvas widget to display graphical elements like lines or text."""
+
+ _KIND = "canvas"
+ _TAKEFOCUS = True
+ _DEFAULTS = {"width": 378, "height": 265, "bg": "#282828", "confine": 1,
+ "closeenough": 1.0, "scrollregion": "", "xscrollincrement": 0,
+ "yscrollincrement": 0, "state": "normal"}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "canvas", cnf, kw)
+
+ def _setup(self):
+ self._items: dict = {}
+ self._order: list = []
+ self._next = 1
+ self._item_binds: dict = {}
+ self._current = None
+ self._focus_item = None
+ self._sel = None
+ self._node.set("bg", color("#282828"))
+ self._node.geom(0, reqwidth=378, reqheight=265)
+
+ def _apply(self, key, value):
+ n = self._node
+ if key in ("width", "height"):
+ n.geom(int(n.geom_get("manager")), **{"req" + key: int(_pixels(value))})
+ elif key in ("scrollregion", "xscrollcommand", "yscrollcommand"):
+ n.set("events", True) # <Configure> keeps the scrollbars right
+ if key == "scrollregion":
+ self._confine()
+ self._view_changed()
+ elif key == "state":
+ n.set("enabled", str(value) != "disabled")
+ else:
+ super()._apply(key, value)
+
+ # -- item storage -------------------------------------------------------------------------
+ def _create(self, kind, args, kw):
+ coords = _flat(args)
+ kw = dict(kw)
+ if args and isinstance(args[-1], dict):
+ kw = dict(args[-1], **kw)
+ coords = _flat(args[:-1])
+ tags = kw.pop("tags", ())
+ tags = list(tags.split() if isinstance(tags, str) else tags)
+ iid = self._next
+ self._next += 1
+ item = _Item(iid, kind, coords, tags, kw)
+ self._items[iid] = item
+ self._order.append(iid)
+ self._push(item)
+ return iid
+
+ def _ink(self, item, key, default):
+ v = item.opts.get(key, default)
+ return None if v in ("", None) else _try_color(v)
+
+ def _push(self, item):
+ """Send one item to the kit display list."""
+ o, kind = item.opts, item.type
+ if kind == "window":
+ return self._place_window(item)
+ hidden = o.get("state", "") == "hidden"
+ coords = item.coords
+ common = dict(width=float(o.get("width", 1) or 1), hidden=hidden)
+ if kind in ("rectangle", "oval", "arc"):
+ fill = self._ink(item, "fill", "")
+ outline = self._ink(item, "outline", "#e6e6e6")
+ if kind == "arc" and str(o.get("style", "pieslice")) == "arc":
+ fill = None
+ self._node.canvas_set(item.id, _CANVAS_KIT[kind], coords, fill=fill, outline=outline,
+ start=float(o.get("start", 0)), extent=float(o.get("extent", 90)),
+ **common)
+ elif kind in ("line", "polygon"):
+ pts = coords
+ if getboolean(o.get("smooth", False)) and o.get("smooth") not in ("", 0):
+ pts = _spline(coords, int(o.get("splinesteps", 12)))
+ ink = self._ink(item, "fill", "#e6e6e6")
+ if kind == "line":
+ self._node.canvas_set(item.id, 2, pts, outline=ink, **common)
+ self._push_arrows(item, pts, ink, hidden)
+ else:
+ self._node.canvas_set(item.id, 3, pts, fill=ink,
+ outline=self._ink(item, "outline", ""), **common)
+ elif kind == "text":
+ text = str(o.get("text", ""))
+ if o.get("width"):
+ text = _wrap(text, _pixels(o["width"]))
+ scale = _font_scale(o.get("font")) or 1.0
+ self._node.canvas_set(item.id, 4, coords[:2], fill=self._ink(item, "fill", "#e6e6e6"),
+ text=text, anchor=_kit_anchor(o.get("anchor", "center")),
+ size=_font_px_kit(scale), hidden=hidden)
+ elif kind in ("image", "bitmap"):
+ img = _image_of(o.get("image")) if kind == "image" else self._bitmap(o)
+ if img is None:
+ self._node.canvas_delete(item.id)
+ return None
+ img._attach(self)
+ self._node.canvas_set(item.id, 6, coords[:2], anchor=_kit_anchor(o.get("anchor",
+ "center")),
+ image=(img.width(), img.height(), img.rgba()), hidden=hidden)
+ return None
+
+ def _bitmap(self, o):
+ bm = o.get("bitmap")
+ if isinstance(bm, Image):
+ return bm
+ return None
+
+ def _push_arrows(self, item, pts, ink, hidden):
+ arrow = str(item.opts.get("arrow", "none"))
+ shape = item.opts.get("arrowshape", (8, 10, 3))
+ a, b, c = (float(v) for v in (shape.split() if isinstance(shape, str) else shape))
+ width = float(item.opts.get("width", 1) or 1)
+ for k, (tip, base) in enumerate(((pts[0:2], pts[2:4]), (pts[-2:], pts[-4:-2]))):
+ kid = item.id + _SUB * (k + 1)
+ if arrow in (("first", "last")[k], "both") and len(pts) >= 4:
+ dx, dy = tip[0] - base[0], tip[1] - base[1]
+ d = math.hypot(dx, dy) or 1.0
+ ux, uy = dx / d, dy / d
+ bx, by = tip[0] - ux * b, tip[1] - uy * b
+ wing = c + width / 2
+ poly = [tip[0], tip[1], bx - uy * wing, by + ux * wing,
+ tip[0] - ux * a, tip[1] - uy * a, bx + uy * wing, by - ux * wing]
+ self._node.canvas_set(kid, 3, poly, fill=ink, hidden=hidden)
+ else:
+ self._node.canvas_delete(kid)
+
+ def _place_window(self, item):
+ w = item.opts.get("window")
+ if w in (None, ""):
+ return None
+ w = w if isinstance(w, BaseWidget) else self.nametowidget(w)
+ if w._node.parent is not self._node:
+ self._node.add(w._node)
+ params = {"reset_place": 1, "x": item.coords[0], "y": item.coords[1],
+ "anchor": _kit_anchor(item.opts.get("anchor", "center"))}
+ for k in ("width", "height"):
+ if item.opts.get(k):
+ params[k] = float(_pixels(item.opts[k]))
+ w._node.geom(3, **params)
+ w._ginfo = {"manager": "canvas", "in": self}
+ if item.opts.get("state") == "hidden":
+ w._node.set("visible", False)
+ return None
+
+ def _image_changed(self, img):
+ for item in self._items.values():
+ if item.opts.get("image") is img or str(item.opts.get("image")) == str(img):
+ self._push(item)
+
+ # -- creation ------------------------------------------------------------------------
+ def create_arc(self, *args, **kw):
+ """Create arc shaped region with coordinates x1,y1,x2,y2."""
+ return self._create("arc", args, kw)
+
+ def create_bitmap(self, *args, **kw):
+ """Create bitmap with coordinates x1,y1."""
+ return self._create("bitmap", args, kw)
+
+ def create_image(self, *args, **kw):
+ """Create image item with coordinates x1,y1."""
+ return self._create("image", args, kw)
+
+ def create_line(self, *args, **kw):
+ """Create line with coordinates x1,y1,...,xn,yn."""
+ return self._create("line", args, kw)
+
+ def create_oval(self, *args, **kw):
+ """Create oval with coordinates x1,y1,x2,y2."""
+ return self._create("oval", args, kw)
+
+ def create_polygon(self, *args, **kw):
+ """Create polygon with coordinates x1,y1,...,xn,yn."""
+ return self._create("polygon", args, kw)
+
+ def create_rectangle(self, *args, **kw):
+ """Create rectangle with coordinates x1,y1,x2,y2."""
+ return self._create("rectangle", args, kw)
+
+ def create_text(self, *args, **kw):
+ """Create text with coordinates x1,y1."""
+ return self._create("text", args, kw)
+
+ def create_window(self, *args, **kw):
+ """Create window with coordinates x1,y1,x2,y2."""
+ return self._create("window", args, kw)
+
+ # -- tags and searches ----------------------------------------------------------------------
+ def _ids(self, tag_or_id):
+ """Item ids for an id, a tag or a tag expression ("a&&!b", "a||b")."""
+ if isinstance(tag_or_id, int) or (isinstance(tag_or_id, str) and tag_or_id.isdigit()):
+ i = int(tag_or_id)
+ return [i] if i in self._items else []
+ t = str(tag_or_id)
+ if t == "all":
+ return list(self._order)
+ if t == "current":
+ return [self._current] if self._current in self._items else []
+ if any(op in t for op in ("&&", "||", "^", "!")):
+ return [i for i in self._order if self._tag_expr(self._items[i], t)]
+ return [i for i in self._order if t in self._items[i].tags]
+
+ def _tag_expr(self, item, expr):
+ tags = set(item.tags) | {"all"}
+ for alt in expr.split("||"):
+ ok = True
+ for term in alt.split("&&"):
+ term = term.strip().strip("()")
+ neg = term.startswith("!")
+ if (term.lstrip("!").strip() in tags) == neg:
+ ok = False
+ break
+ if ok:
+ return True
+ return False
+
+ def addtag(self, *args):
+ """Internal function: addtag(newtag, 'withtag', tag) etc."""
+ newtag, spec = args[0], args[1:]
+ for i in self.find(*spec):
+ if newtag not in self._items[i].tags:
+ self._items[i].tags.append(newtag)
+
+ def addtag_above(self, newtag, tagOrId):
+ self.addtag(newtag, "above", tagOrId)
+
+ def addtag_all(self, newtag):
+ self.addtag(newtag, "all")
+
+ def addtag_below(self, newtag, tagOrId):
+ self.addtag(newtag, "below", tagOrId)
+
+ def addtag_closest(self, newtag, x, y, halo=None, start=None):
+ self.addtag(newtag, "closest", x, y, halo, start)
+
+ def addtag_enclosed(self, newtag, x1, y1, x2, y2):
+ self.addtag(newtag, "enclosed", x1, y1, x2, y2)
+
+ def addtag_overlapping(self, newtag, x1, y1, x2, y2):
+ self.addtag(newtag, "overlapping", x1, y1, x2, y2)
+
+ def addtag_withtag(self, newtag, tagOrId):
+ self.addtag(newtag, "withtag", tagOrId)
+
+ def dtag(self, *args):
+ """Delete tag or id given as last arguments in ARGS from items
+ identified by first argument in ARGS."""
+ target = args[0]
+ tag = args[1] if len(args) > 1 else target
+ for i in self._ids(target):
+ if tag in self._items[i].tags:
+ self._items[i].tags.remove(tag)
+
+ def find(self, *args):
+ """Internal function: find('withtag', tag) etc."""
+ kind, rest = args[0], args[1:]
+ if kind == "above":
+ ids = self._ids(rest[0])
+ if not ids:
+ return ()
+ k = self._order.index(ids[-1])
+ return tuple(self._order[k + 1:k + 2])
+ if kind == "below":
+ ids = self._ids(rest[0])
+ if not ids:
+ return ()
+ k = self._order.index(ids[0])
+ return tuple(self._order[k - 1:k]) if k > 0 else ()
+ if kind == "all":
+ return tuple(self._order)
+ if kind == "withtag":
+ return tuple(self._ids(rest[0]))
+ if kind == "closest":
+ return self.find_closest(*rest)
+ if kind == "enclosed":
+ return self.find_enclosed(*rest)
+ if kind == "overlapping":
+ return self.find_overlapping(*rest)
+ raise TclError('bad search command "%s"' % kind)
+
+ def find_above(self, tagOrId):
+ return self.find("above", tagOrId)
+
+ def find_all(self):
+ return tuple(self._order)
+
+ def find_below(self, tagOrId):
+ return self.find("below", tagOrId)
+
+ def find_withtag(self, tagOrId):
+ return tuple(self._ids(tagOrId))
+
+ def find_enclosed(self, x1, y1, x2, y2):
+ out = []
+ for i in self._order:
+ bb = self._item_bbox(self._items[i])
+ if bb and bb[0] >= x1 and bb[1] >= y1 and bb[2] <= x2 and bb[3] <= y2:
+ out.append(i)
+ return tuple(out)
+
+ def find_overlapping(self, x1, y1, x2, y2):
+ out = []
+ for i in self._order:
+ bb = self._item_bbox(self._items[i])
+ if bb and bb[0] <= x2 and bb[2] >= x1 and bb[1] <= y2 and bb[3] >= y1:
+ out.append(i)
+ return tuple(out)
+
+ def find_closest(self, x, y, halo=None, start=None):
+ x, y = float(x), float(y)
+ best, best_d = None, None
+ for i in reversed(self._order):
+ item = self._items[i]
+ if item.opts.get("state") == "hidden":
+ continue
+ d = self._distance(item, x, y)
+ if best_d is None or d < best_d:
+ best, best_d = i, d
+ if d <= float(halo or 0):
+ return (i,)
+ return (best,) if best is not None else ()
+
+ def gettags(self, tagOrId):
+ ids = self._ids(tagOrId)
+ return tuple(self._items[ids[0]].tags) if ids else ()
+
+ def type(self, tagOrId):
+ ids = self._ids(tagOrId)
+ return self._items[ids[0]].type if ids else None
+
+ # -- geometry of items --------------------------------------------------------------------
+ def _item_bbox(self, item):
+ c = item.coords
+ if item.type in ("text", "image", "bitmap", "window") and len(c) >= 2:
+ w, h = self._item_size(item)
+ ax, ay = _anchor_offset(item.opts.get("anchor", "center"), w, h)
+ x0, y0 = c[0] - ax, c[1] - ay
+ return (x0, y0, x0 + w, y0 + h)
+ if len(c) < 2:
+ return None
+ xs, ys = c[0::2], c[1::2]
+ pad = float(item.opts.get("width", 1) or 1) / 2
+ return (min(xs) - pad, min(ys) - pad, max(xs) + pad, max(ys) + pad)
+
+ def _item_size(self, item):
+ o = item.opts
+ if item.type == "text":
+ text = str(o.get("text", ""))
+ if o.get("width"):
+ text = _wrap(text, _pixels(o["width"]))
+ lines = text.split("\n")
+ scale = _font_scale(o.get("font")) or 1.0
+ w = max(_text_width(line) for line in lines) * scale
+ return w, len(lines) * buipy.kit_unit() * 0.8 * scale
+ if item.type in ("image", "bitmap"):
+ img = _image_of(o.get("image")) if item.type == "image" else self._bitmap(o)
+ return (img.width(), img.height()) if img else (0, 0)
+ w = o.get("window")
+ if w:
+ w = w if isinstance(w, BaseWidget) else self.nametowidget(w)
+ return (float(_pixels(o["width"])) if o.get("width") else w.winfo_reqwidth(),
+ float(_pixels(o["height"])) if o.get("height") else w.winfo_reqheight())
+ return 0, 0
+
+ def _distance(self, item, x, y):
+ c, t = item.coords, item.type
+ width = float(item.opts.get("width", 1) or 1)
+ if t == "line" and len(c) >= 4:
+ return max(0.0, min(_seg_dist(x, y, c[i], c[i + 1], c[i + 2], c[i + 3])
+ for i in range(0, len(c) - 3, 2)) - width / 2)
+ if t == "polygon" and len(c) >= 6:
+ if _point_in_poly(x, y, c):
+ return 0.0
+ n = len(c) // 2
+ return min(_seg_dist(x, y, c[2 * i], c[2 * i + 1], c[2 * ((i + 1) % n)],
+ c[2 * ((i + 1) % n) + 1]) for i in range(n))
+ if t == "oval" and len(c) >= 4:
+ cx, cy = (c[0] + c[2]) / 2, (c[1] + c[3]) / 2
+ rx, ry = abs(c[2] - c[0]) / 2 or 1, abs(c[3] - c[1]) / 2 or 1
+ r = math.hypot((x - cx) / rx, (y - cy) / ry)
+ filled = item.opts.get("fill") not in (None, "")
+ if r <= 1 and filled:
+ return 0.0
+ return abs(r - 1) * min(rx, ry)
+ bb = self._item_bbox(item)
+ if not bb:
+ return 1e9
+ dx = max(bb[0] - x, 0, x - bb[2])
+ dy = max(bb[1] - y, 0, y - bb[3])
+ if t == "rectangle" and dx == 0 and dy == 0 and item.opts.get("fill") in (None, ""):
+ return max(0.0, min(x - bb[0], bb[2] - x, y - bb[1], bb[3] - y) - width / 2)
+ return math.hypot(dx, dy)
+
+ def bbox(self, *args):
+ """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which
+ encloses all items with tags specified as arguments."""
+ boxes = [self._item_bbox(self._items[i]) for t in (args or ("all",))
+ for i in self._ids(t)]
+ boxes = [b for b in boxes if b]
+ if not boxes:
+ return None
+ return (int(math.floor(min(b[0] for b in boxes))), int(math.floor(min(b[1] for b in
+ boxes))),
+ int(math.ceil(max(b[2] for b in boxes))), int(math.ceil(max(b[3] for b in
+ boxes))))
+
+ def coords(self, tagOrId, *args):
+ """Return a list of coordinates for the item given in ARGS."""
+ ids = self._ids(tagOrId)
+ if not ids:
+ return []
+ if not args:
+ return [float(v) for v in self._items[ids[0]].coords]
+ flat = _flat(args)
+ for i in ids[:1]:
+ self._items[i].coords = flat
+ self._push(self._items[i])
+ return None
+
+ def move(self, tagOrId, xAmount, yAmount):
+ """Move an item TAGORID given in ARGS."""
+ dx, dy = float(_pixels(xAmount)), float(_pixels(yAmount))
+ for i in self._ids(tagOrId):
+ item = self._items[i]
+ item.coords = [v + (dx if k % 2 == 0 else dy) for k, v in enumerate(item.coords)]
+ self._push(item)
+
+ def moveto(self, tagOrId, x="", y=""):
+ """Move the items given by TAGORID so the top-left of their bbox is at X, Y."""
+ bb = self.bbox(tagOrId)
+ if bb is None:
+ return
+ dx = float(x) - bb[0] if x != "" else 0
+ dy = float(y) - bb[1] if y != "" else 0
+ self.move(tagOrId, dx, dy)
+
+ def scale(self, tagOrId, xOrigin, yOrigin, xScale, yScale):
+ """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
+ ox, oy, sx, sy = float(xOrigin), float(yOrigin), float(xScale), float(yScale)
+ for i in self._ids(tagOrId):
+ item = self._items[i]
+ item.coords = [ox + (v - ox) * sx if k % 2 == 0 else oy + (v - oy) * sy
+ for k, v in enumerate(item.coords)]
+ self._push(item)
+
+ def delete(self, *args):
+ """Delete items identified by all tag or ids contained in ARGS."""
+ for t in args:
+ for i in self._ids(t):
+ item = self._items.pop(i)
+ self._order.remove(i)
+ if item.type == "window" and item.opts.get("window"):
+ w = item.opts["window"]
+ w = w if isinstance(w, BaseWidget) else self.nametowidget(w)
+ w._node.geom(0)
+ w._ginfo = {}
+ else:
+ self._node.canvas_delete(i)
+ self._node.canvas_delete(i + _SUB)
+ self._node.canvas_delete(i + 2 * _SUB)
+
+ def itemconfigure(self, tagOrId, cnf=None, **kw):
+ """Configure resources of an item TAGORID."""
+ kw = dict(cnf, **kw) if cnf else kw
+ ids = self._ids(tagOrId)
+ if not kw:
+ if not ids:
+ return {}
+ return {k: (k, "", "", "", v) for k, v in self._items[ids[0]].opts.items()}
+ for i in ids:
+ item = self._items[i]
+ if "tags" in kw:
+ t = kw.pop("tags")
+ item.tags = list(t.split() if isinstance(t, str) else t)
+ item.opts.update(kw)
+ self._push(item)
+ return None
+
+ itemconfig = itemconfigure
+
+ def itemcget(self, tagOrId, option):
+ """Return the resource value for an OPTION for item TAGORID."""
+ ids = self._ids(tagOrId)
+ if not ids:
+ return ""
+ item = self._items[ids[0]]
+ option = option.lstrip("-")
+ if option == "tags":
+ return " ".join(item.tags)
+ return item.opts.get(option, "")
+
+ def tag_raise(self, *args):
+ """Raise an item TAGORID given in ARGS (optional above another item)."""
+ tag, above = args[0], (args[1] if len(args) > 1 else None)
+ ids = self._ids(tag)
+ if not ids:
+ return
+ for i in ids:
+ self._order.remove(i)
+ pos = len(self._order) if above is None else \
+ self._order.index(self._ids(above)[-1]) + 1
+ self._order[pos:pos] = ids
+ self._resync_order()
+
+ lift = tkraise = tag_raise
+
+ def tag_lower(self, *args):
+ """Lower an item TAGORID given in ARGS (optional below another item)."""
+ tag, below = args[0], (args[1] if len(args) > 1 else None)
+ ids = self._ids(tag)
+ if not ids:
+ return
+ for i in ids:
+ self._order.remove(i)
+ pos = 0 if below is None else self._order.index(self._ids(below)[0])
+ self._order[pos:pos] = ids
+ self._resync_order()
+
+ lower = tag_lower
+
+ def _resync_order(self):
+ for i in self._order: # kit draw order = raise order
+ self._node.canvas_raise(i, True)
+ for k in (1, 2):
+ self._node.canvas_raise(i + k * _SUB, True)
+
+ # -- text items ---------------------------------------------------------------------------
+ def _text_index(self, item, index):
+ text = str(item.opts.get("text", ""))
+ s = str(index)
+ if s == "end":
+ return len(text)
+ if s == "insert":
+ return int(item.opts.get("_icursor", len(text)))
+ if s in ("sel.first", "sel.last"):
+ if not self._sel or self._sel[0] != item.id:
+ raise TclError("selection isn't in item")
+ return self._sel[1 if s == "sel.first" else 2]
+ if s.startswith("@"):
+ x = float(s[1:].split(",")[0])
+ bb = self._item_bbox(item)
+ for k in range(len(text) + 1):
+ if bb[0] + _text_width(text[:k]) >= x:
+ return k
+ return len(text)
+ return max(0, min(len(text), int(s)))
+
+ def dchars(self, tagOrId, first, last=None):
+ """Delete characters of text items identified by tag or id in ARGS."""
+ for i in self._ids(tagOrId):
+ item = self._items[i]
+ if item.type != "text":
+ continue
+ a = self._text_index(item, first)
+ b = a if last is None else self._text_index(item, last)
+ t = str(item.opts.get("text", ""))
+ item.opts["text"] = t[:a] + t[b + 1:]
+ self._push(item)
+
+ def insert(self, tagOrId, beforeThis, string):
+ """Insert STRING in item TAGORID at position BEFORETHIS."""
+ for i in self._ids(tagOrId):
+ item = self._items[i]
+ if item.type != "text":
+ continue
+ k = self._text_index(item, beforeThis)
+ t = str(item.opts.get("text", ""))
+ item.opts["text"] = t[:k] + str(string) + t[k:]
+ item.opts["_icursor"] = k + len(str(string))
+ self._push(item)
+
+ def icursor(self, tagOrId, index):
+ for i in self._ids(tagOrId):
+ item = self._items[i]
+ if item.type == "text":
+ item.opts["_icursor"] = self._text_index(item, index)
+
+ def index(self, tagOrId, index):
+ ids = self._ids(tagOrId)
+ if not ids:
+ raise TclError("can't find an indexable item \"%s\"" % tagOrId)
+ return self._text_index(self._items[ids[0]], index)
+
+ def focus(self, tagOrId=None):
+ if tagOrId is None:
+ return self._focus_item or ""
+ ids = self._ids(tagOrId)
+ self._focus_item = ids[0] if ids else None
+ return None
+
+ def select_from(self, tagOrId, index):
+ ids = self._ids(tagOrId)
+ if ids:
+ k = self._text_index(self._items[ids[0]], index)
+ self._sel = (ids[0], k, k)
+
+ def select_to(self, tagOrId, index):
+ ids = self._ids(tagOrId)
+ if ids and self._sel:
+ k = self._text_index(self._items[ids[0]], index)
+ self._sel = (ids[0], min(self._sel[1], k), max(self._sel[1], k))
+
+ select_adjust = select_to
+
+ def select_clear(self):
+ self._sel = None
+
+ def select_item(self):
+ return self._sel[0] if self._sel else None
+
+ def _selected_text(self):
+ if not self._sel or self._sel[0] not in self._items:
+ return ""
+ return str(self._items[self._sel[0]].opts.get("text", ""))[self._sel[1]:self._sel[2] + 1]
+
+ # -- view ------------------------------------------------------------------------------
+ def _region(self):
+ sr = self._opts.get("scrollregion")
+ if sr:
+ vals = [float(_pixels(v)) for v in (sr.split() if isinstance(sr, str) else sr)]
+ return tuple(vals[:4])
+ w, h = self.winfo_width(), self.winfo_height()
+ bb = self.bbox("all") or (0, 0, w, h)
+ return (min(0, bb[0]), min(0, bb[1]), max(w, bb[2]), max(h, bb[3]))
+
+ def _view(self, axis):
+ x0, y0, x1, y1 = self._region()
+ k = 0 if axis == "x" else 1
+ lo, hi = (x0, x1) if k == 0 else (y0, y1)
+ size = self.winfo_width() if k == 0 else self.winfo_height()
+ off = self._node.get("scroll_x" if k == 0 else "scroll")
+ span = max(1.0, hi - lo)
+ return (max(0.0, min(1.0, (off - lo) / span)),
+ max(0.0, min(1.0, (off + size - lo) / span)))
+
+ def _view_set(self, axis, op, args):
+ x0, y0, x1, y1 = self._region()
+ k = 0 if axis == "x" else 1
+ lo, hi = (x0, x1) if k == 0 else (y0, y1)
+ size = self.winfo_width() if k == 0 else self.winfo_height()
+ key = "scroll_x" if k == 0 else "scroll"
+ off = self._node.get(key)
+ if op == "moveto":
+ off = lo + float(args[0]) * (hi - lo)
+ elif op == "scroll":
+ n, what = int(float(args[0])), str(args[1])
+ inc = float(_pixels(self._opts.get(axis + "scrollincrement", 0) or 0)) or size / 10
+ off += n * (size * 0.9 if what.startswith("page") else inc)
+ else:
+ raise TclError('bad option "%s"' % op)
+ self._node.set(key, float(self._confined(off, lo, hi, size)))
+ self._view_changed()
+
+ @staticmethod
+ def _confined(off, lo, hi, size):
+ return max(lo, min(off, hi - size)) if hi - lo > size else lo
+
+ def _confine(self):
+ if self.cget("confine") in (0, "0", False):
+ return
+ x0, y0, x1, y1 = self._region()
+ self._node.set("scroll_x", float(self._confined(self._node.get("scroll_x"), x0, x1,
+ self.winfo_width())))
+ self._node.set("scroll", float(self._confined(self._node.get("scroll"), y0, y1,
+ self.winfo_height())))
+
+ def _configured(self, width, height):
+ self._confine()
+ self._view_changed()
+
+ def canvasx(self, screenx, gridspacing=None):
+ """Return the canvas x coordinate of pixel position SCREENX rounded
+ to nearest multiple of GRIDSPACING units."""
+ v = float(screenx) + self._node.get("scroll_x")
+ return round(v / float(gridspacing)) * float(gridspacing) if gridspacing else v
+
+ def canvasy(self, screeny, gridspacing=None):
+ v = float(screeny) + self._node.get("scroll")
+ return round(v / float(gridspacing)) * float(gridspacing) if gridspacing else v
+
+ def scan_mark(self, x, y):
+ self._scan = (int(x), int(y), self._node.get("scroll_x"), self._node.get("scroll"))
+
+ def scan_dragto(self, x, y, gain=10):
+ mx, my, sx, sy = getattr(self, "_scan", (int(x), int(y), 0, 0))
+ x0, y0, x1, y1 = self._region()
+ self._node.set("scroll_x", float(self._confined(sx - (int(x) - mx) * gain, x0, x1,
+ self.winfo_width())))
+ self._node.set("scroll", float(self._confined(sy - (int(y) - my) * gain, y0, y1,
+ self.winfo_height())))
+ self._view_changed()
+
+ def postscript(self, cnf={}, **kw): # noqa: B006
+ """Return PostScript of the canvas (or write it to file=)."""
+ kw = dict(cnf, **kw) if cnf else kw
+ w, h = self.winfo_width(), self.winfo_height()
+ ps = "%%!PS-Adobe-3.0 EPSF-3.0\n%%%%BoundingBox: 0 0 %d %d\n%%%%EndComments\n" \
+ "showpage\n%%%%EOF\n" % (w, h)
+ if kw.get("file"):
+ with open(kw["file"], "w", encoding="ascii") as fh:
+ fh.write(ps)
+ return ""
+ return ps
+
+ # -- item bindings -----------------------------------------------------------------------
+ def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
+ """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC."""
+ key = str(tagOrId)
+ table = self._item_binds.setdefault(key, _BindTable())
+ if sequence is None:
+ return tuple(table.seqs)
+ if func is None:
+ return table.seqs.get(sequence, "")
+ self._node.set("events", True)
+ return table.bind(sequence, func, add)
+
+ def tag_unbind(self, tagOrId, sequence, funcid=None):
+ table = self._item_binds.get(str(tagOrId))
+ if table is not None:
+ table.unbind(sequence, funcid)
+
+ def _item_at(self, x, y):
+ halo = float(self.cget("closeenough") or 1.0)
+ cx, cy = self.canvasx(x), self.canvasy(y)
+ for i in reversed(self._order):
+ item = self._items[i]
+ if item.opts.get("state") in ("hidden", "disabled") or item.type == "window":
+ continue
+ if self._distance(item, cx, cy) <= halo:
+ return i
+ return None
+
+ def _fire_item(self, iid, ev):
+ if iid not in self._items:
+ return
+ item = self._items[iid]
+ for key in ["all"] + item.tags + [str(iid)]:
+ table = self._item_binds.get(key)
+ if table is None:
+ continue
+ for fn in list(table.match(ev)):
+ _call(self, fn, ev)
+
+ def _raw_event(self, ev):
+ if not self._item_binds:
+ return
+ t = ev.type
+ if t in (EventType.Motion, EventType.Enter, EventType.Leave, EventType.ButtonPress):
+ new = None if t == EventType.Leave else self._item_at(ev.x, ev.y)
+ if new != self._current:
+ old, self._current = self._current, new
+ if old is not None:
+ self._fire_item(old, Event(type=EventType.Leave, widget=self, x=ev.x,
+ y=ev.y, state=ev.state))
+ if new is not None:
+ self._fire_item(new, Event(type=EventType.Enter, widget=self, x=ev.x,
+ y=ev.y, state=ev.state))
+ if t in (EventType.ButtonPress, EventType.ButtonRelease, EventType.Motion,
+ EventType.MouseWheel):
+ if self._current is not None:
+ self._fire_item(self._current, ev)
+ elif t in (EventType.KeyPress, EventType.KeyRelease) and self._focus_item is not None:
+ self._fire_item(self._focus_item, ev)
+
+
+def _kit_anchor(anchor):
+ a = str(anchor or "center").lower()
+ if a == "center":
+ return 0
+ return (1 if "n" in a else 0) | (2 if "s" in a else 0) | (4 if "w" in a else 0) | \
+ (8 if "e" in a else 0)
+
+
+def _anchor_offset(anchor, w, h):
+ a = str(anchor or "center").lower()
+ ax = 0 if "w" in a else w if "e" in a else w / 2
+ ay = 0 if "n" in a else h if "s" in a else h / 2
+ if a == "center":
+ ax, ay = w / 2, h / 2
+ return ax, ay
+
+
+def _font_px_kit(scale):
+ return buipy.kit_unit() * 0.55 * scale
+
+
+# ==========================================================================
+# Text
+
+
+_TAG_COLOR_KEYS = ("foreground", "fg", "background", "bg")
+
+
+class Text(Widget, XView, YView):
+ """Text widget which can display text in various forms (Blender text area)."""
+
+ _KIND = "textarea"
+ _TAKEFOCUS = True
+ _DEFAULTS = {"width": 80, "height": 24, "wrap": "char", "state": "normal", "undo": 0,
+ "maxundo": 0, "autoseparators": 1, "tabs": "", "spacing1": 0}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "text", cnf, kw)
+
+ def _setup(self):
+ self._tags: dict = {} # name -> {"ranges": [[a, b]], "opts": {}}
+ self._tag_order: list = [] # priority, lowest first
+ self._marks: dict = {} # name -> [offset, gravity]
+ self._undo: list = []
+ self._redo: list = []
+ self._last = ""
+ self._modified = False
+ self._peers: list = []
+ self._tag_binds: dict = {}
+ self._hover_tags = ()
+ self._embedded: dict = {}
+ self._node.set("rows", 24)
+ self._node.geom(0, reqwidth=_chars(80))
+ self._node.set("viewevents", True)
+
+ def _focus_node(self):
+ return self._node
+
+ def _apply(self, key, value):
+ n = self._node
+ if key == "height":
+ n.set("rows", int(value) or 1)
+ elif key == "width":
+ n.geom(int(n.geom_get("manager")), reqwidth=_chars(int(value or 80)))
+ elif key == "state":
+ n.set("enabled", str(value) != "disabled")
+ elif key in ("xscrollcommand", "yscrollcommand"):
+ n.set("noscrollbar", True)
+ else:
+ super()._apply(key, value)
+
+ # -- text & indices ---------------------------------------------------------------------
+ def _text(self):
+ return self._node.get_str("value")
+
+ def _byte(self, off):
+ return len(self._text()[:off].encode("utf-8"))
+
+ def _char(self, byte_off):
+ return len(self._text().encode("utf-8")[:byte_off].decode("utf-8", "ignore"))
+
+ def _line_col(self, off):
+ t = self._text()
+ before = t[:off]
+ return before.count("\n") + 1, off - (before.rfind("\n") + 1)
+
+ def _line_start(self, line):
+ lines = self._text().split("\n")
+ line = max(1, min(len(lines), line))
+ return sum(len(lines[k]) + 1 for k in range(line - 1)), lines[line - 1]
+
+ _MOD = re.compile(r"\s*([+-])\s*(\d+)\s*(?:(?:display|any)\s*)?([a-z]*)"
+ r"|\s*(linestart|lineend|wordstart|wordend)", re.I)
+
+ def _off(self, index):
+ """Tk text index -> character offset in [0, len] (the trailing
+ newline Tk keeps is 'end')."""
+ if isinstance(index, (int, float)) and not isinstance(index, bool):
+ index = repr(float(index)) if isinstance(index, float) else "%d.0" % index
+ s = str(index).strip()
+ t = self._text()
+ m = re.match(r"^(\d+)\.(\d+|end)|^(end)|^(insert|current|anchor)|^@(-?\d+),(-?\d+)|"
+ r"^([^\s+-]+)\.(first|last)|^([^\s+-]+)", s)
+ if not m:
+ raise TclError('bad text index "%s"' % index)
+ if m.group(1):
+ start, line = self._line_start(int(m.group(1)))
+ if int(m.group(1)) > t.count("\n") + 1:
+ off = len(t)
+ else:
+ off = start + (len(line) if m.group(2) == "end" else min(int(m.group(2)),
+ len(line)))
+ elif m.group(3):
+ off = len(t)
+ elif m.group(4):
+ name = m.group(4)
+ if name == "insert":
+ off = self._char(self._node.ta_caret())
+ elif name == "current":
+ off = getattr(self, "_current_off", 0)
+ else:
+ off = self._marks.get("anchor", [0])[0]
+ elif m.group(5) is not None:
+ x, y = int(m.group(5)), int(m.group(6))
+ r = self._node.rect
+ off = self._char(self._node.ta_index_at(r[0] + x, r[1] + y))
+ elif m.group(7):
+ tag, which = m.group(7), m.group(8)
+ ranges = self._ranges(tag)
+ if not ranges:
+ raise TclError('text doesn\'t contain any characters tagged with "%s"' % tag)
+ off = ranges[0][0] if which == "first" else ranges[-1][1]
+ else:
+ name = m.group(9)
+ if name not in self._marks:
+ raise TclError('bad text index "%s"' % index)
+ off = self._marks[name][0]
+ rest = s[m.end():]
+ while rest.strip():
+ mm = self._MOD.match(rest)
+ if not mm:
+ raise TclError('bad text index "%s"' % index)
+ rest = rest[mm.end():]
+ if mm.group(4):
+ off = self._modify(off, mm.group(4).lower())
+ continue
+ n = int(mm.group(2)) * (1 if mm.group(1) == "+" else -1)
+ unit = (mm.group(3) or "c").lower()
+ if unit.startswith("l"):
+ line, col = self._line_col(off)
+ start, text = self._line_start(line + n)
+ off = start + min(col, len(text))
+ else:
+ off += n
+ off = max(0, min(len(t), off))
+ return max(0, min(len(t), off))
+
+ def _modify(self, off, what):
+ t = self._text()
+ if what == "linestart":
+ return t.rfind("\n", 0, off) + 1
+ if what == "lineend":
+ e = t.find("\n", off)
+ return len(t) if e < 0 else e
+ word = re.compile(r"\w")
+ if what == "wordstart":
+ while off > 0 and word.match(t[off - 1:off]):
+ off -= 1
+ return off
+ while off < len(t) and word.match(t[off:off + 1]):
+ off += 1
+ return off
+
+ def index(self, index):
+ """Return the index in the form line.char for INDEX."""
+ if str(index).strip() == "end":
+ return "%d.0" % (self._text().count("\n") + 2)
+ return "%d.%d" % self._line_col(self._off(index))
+
+ def compare(self, index1, op, index2):
+ """Return whether between index INDEX1 and index INDEX2 the
+ relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
+ a, b = self._off(index1), self._off(index2)
+ if str(index1).strip() == "end":
+ a += 1
+ if str(index2).strip() == "end":
+ b += 1
+ return {"<": a < b, "<=": a <= b, "==": a == b, ">=": a >= b, ">": a > b,
+ "!=": a != b}[op]
+
+ def count(self, index1, index2, *options, return_ints=False):
+ """Counts the number of relevant things between the two indices."""
+ a, b = self._off(index1), self._off(index2)
+ t = self._text()
+ out = []
+ for opt in (options or ("indices",)):
+ opt = opt.lstrip("-")
+ if opt in ("chars", "indices", "displaychars", "displayindices"):
+ out.append(b - a)
+ elif opt in ("lines", "displaylines"):
+ out.append(t[min(a, b):max(a, b)].count("\n") * (1 if b >= a else -1))
+ elif opt == "xpixels":
+ out.append(int(_text_width(t[a:b])))
+ elif opt == "ypixels":
+ out.append(t[min(a, b):max(a, b)].count("\n") * int(buipy.kit_unit() * 0.8))
+ elif opt == "update":
+ continue
+ if return_ints or len(out) > 1:
+ return tuple(out) if len(out) > 1 else out[0]
+ return (out[0],) if out and out[0] else None
+
+ # -- editing ------------------------------------------------------------------------
+ def _snapshot(self):
+ if self._undo_enabled():
+ self._undo.append(self._text())
+ self._redo.clear()
+
+ def _undo_enabled(self):
+ return self.cget("undo") not in (0, "0", False, "false")
+
+ def _edited(self, off, removed, inserted):
+ """Keep tag ranges and marks attached to their text (Tk gravity)."""
+ n_ins, n_rem = len(inserted), len(removed)
+ for tag in self._tags.values():
+ new = []
+ for a, b in tag["ranges"]:
+ if n_rem:
+ e = off + n_rem
+ a = a - n_rem if a >= e else (off if a > off else a)
+ b = b - n_rem if b >= e else (off if b > off else b)
+ if n_ins:
+ a = a + n_ins if a >= off else a
+ b = b + n_ins if b > off else b
+ if b > a:
+ new.append([a, b])
+ tag["ranges"] = new
+ for name, mark in self._marks.items():
+ pos, gravity = mark
+ if n_rem:
+ e = off + n_rem
+ pos = pos - n_rem if pos >= e else (off if pos > off else pos)
+ if n_ins and (pos > off or (pos == off and gravity == "right")):
+ pos += n_ins
+ mark[0] = pos
+ self._last = self._text()
+ self._set_modified(True)
+ for peer in self._peers:
+ if peer.winfo_exists() and peer._text() != self._last:
+ peer._node.set("value", self._last)
+ peer._last = self._last
+
+ def insert(self, index, chars, *args):
+ """Insert CHARS before the characters at INDEX. An additional tag can
+ be given in ARGS. Additional CHARS and tags can follow in ARGS."""
+ if str(self.cget("state")) == "disabled":
+ return
+ self._snapshot()
+ off = self._off(index)
+ pairs = [(chars, args[0] if args else None)] + \
+ [(args[k], args[k + 1] if k + 1 < len(args) else None)
+ for k in range(1, len(args), 2)]
+ for text, tags in pairs:
+ text = str(text)
+ if not text:
+ continue
+ self._insert_chars(off, text)
+ if tags not in (None, ""):
+ names = tags.split() if isinstance(tags, str) else tags
+ for name in names:
+ self._tag(name)["ranges"].append([off, off + len(text)])
+ off += len(text)
+ self._push_tags()
+
+ def _insert_chars(self, off, text):
+ before = self._text()
+ self._node.ta_insert(self._byte(off), text)
+ if self._text() != before:
+ self._edited(off, "", text)
+
+ def delete(self, index1, index2=None):
+ """Delete the characters between INDEX1 and INDEX2 (not included)."""
+ if str(self.cget("state")) == "disabled":
+ return
+ a = self._off(index1)
+ b = a + 1 if index2 is None else self._off(index2)
+ if b <= a:
+ return
+ self._snapshot()
+ removed = self._text()[a:b]
+ self._node.ta_delete(self._byte(a), self._byte(b))
+ self._edited(a, removed, "")
+ self._push_tags()
+
+ def get(self, index1, index2=None):
+ """Return the text from INDEX1 to INDEX2 (not included)."""
+ t = self._text() + "\n"
+ a = self._off(index1)
+ if index2 is None:
+ return t[a:a + 1] if str(index1).strip() != "end" else ""
+ b = self._off(index2) + (1 if str(index2).strip() == "end" else 0)
+ return t[a:b]
+
+ def replace(self, index1, index2, chars, *args):
+ """Replaces the range of characters between index1 and index2 with
+ the given characters and tags specified by args."""
+ a = self.index(index1)
+ self.delete(index1, index2)
+ self.insert(a, chars, *args)
+
+ def see(self, index):
+ """Scroll such that the character at INDEX is visible."""
+ self._node.ta_see(self._byte(self._off(index)))
+ self._view_changed()
+
+ yview_pickplace = see
+
+ def dlineinfo(self, index):
+ """(x, y, width, height, baseline) of the display line holding INDEX."""
+ line, _ = self._line_col(self._off(index))
+ first = int(round(self._node.get("yfirst") * max(1, self._text().count("\n") + 1))) + 1
+ lh = int(buipy.kit_unit() * 0.8)
+ if not first <= line < first + int(self._node.get("yvisible")):
+ return None
+ _, text = self._line_start(line)
+ pad = int(buipy.kit_unit() * 0.4)
+ y = (line - first) * lh + pad // 2
+ return (pad, y, int(_text_width(text)), lh, int(lh * 0.75))
+
+ def bbox(self, index):
+ """(x, y, width, height) of the character at INDEX."""
+ off = self._off(index)
+ info = self.dlineinfo(index)
+ if info is None:
+ return None
+ line, col = self._line_col(off)
+ _, text = self._line_start(line)
+ return (info[0] + int(_text_width(text[:col])), info[1],
+ max(1, int(_text_width(text[col:col + 1] or " "))), info[3])
+
+ def search(self, pattern, index, stopindex=None, forwards=None, backwards=None,
+ exact=None, regexp=None, nocase=None, count=None, elide=None, *, nolinestop=None,
+ strictlimits=None):
+ """Search PATTERN beginning from INDEX until STOPINDEX. Return the
+ index of the first character of a match or an empty string."""
+ t = self._text()
+ start = self._off(index)
+ stop = self._off(stopindex) if stopindex else None
+ flags = (re.IGNORECASE if nocase else 0) | (re.DOTALL if nolinestop else 0)
+ rx = re.compile(pattern if regexp else re.escape(pattern), flags)
+ if backwards:
+ limit = stop if stop is not None else 0
+ m = None
+ for cand in rx.finditer(t, limit, start):
+ m = cand
+ if m is None and stop is None:
+ for cand in rx.finditer(t, start):
+ m = cand
+ else:
+ end = stop if stop is not None else len(t)
+ m = rx.search(t, start, end) if end >= start else None
+ if m is None and stop is None:
+ m = rx.search(t, 0, start)
+ if m is None:
+ return ""
+ if count is not None:
+ count.set(len(m.group(0)))
+ return self.index("1.0 + %d chars" % m.start())
+
+ def dump(self, index1, index2=None, command=None, **kw):
+ """Return (key, value, index) triples of text, tags and marks."""
+ a = self._off(index1)
+ b = a + 1 if index2 is None else self._off(index2)
+ want_all = kw.get("all") or not any(kw.get(k) for k in ("text", "tag", "mark",
+ "image", "window"))
+ out = []
+ if want_all or kw.get("mark"):
+ for name, (pos, _g) in self._marks.items():
+ if a <= pos <= b:
+ out.append(("mark", name, self.index("1.0+%dc" % pos)))
+ if want_all or kw.get("tag"):
+ for name, tag in self._tags.items():
+ for ra, rb in tag["ranges"]:
+ if a <= ra < b:
+ out.append(("tagon", name, self.index("1.0+%dc" % ra)))
+ if a < rb <= b:
+ out.append(("tagoff", name, self.index("1.0+%dc" % rb)))
+ if want_all or kw.get("text"):
+ text = self._text()[a:b]
+ pos = a
+ for line in text.split("\n"):
+ chunk = line + ("\n" if pos + len(line) < b else "")
+ if chunk:
+ out.append(("text", chunk, self.index("1.0+%dc" % pos)))
+ pos += len(line) + 1
+ out.sort(key=lambda e: self._off(e[2]))
+ if command is not None:
+ for e in out:
+ command(*e)
+ return None
+ return out
+
+ # -- undo -------------------------------------------------------------------------------
+ def edit(self, *args):
+ """Internal method: edit('undo'), edit('modified', flag) ..."""
+ return getattr(self, "edit_" + args[0])(*args[1:])
+
+ def edit_modified(self, arg=None):
+ """Get or set the modified flag (changes fire <<Modified>>)."""
+ if arg is None:
+ return self._modified
+ self._modified = getboolean(arg)
+ self.event_generate("<<Modified>>")
+ return None
+
+ def _set_modified(self, flag):
+ if flag and not self._modified:
+ self._modified = True
+ self.event_generate("<<Modified>>")
+
+ def edit_redo(self):
+ """Redo the last undone edit."""
+ if not self._undo_enabled():
+ return "" # Tk: a no-op while -undo is off
+ if not self._redo:
+ raise TclError("nothing to redo")
+ self._undo.append(self._text())
+ self._set_all(self._redo.pop())
+
+ def edit_reset(self):
+ """Clears the undo and redo stacks."""
+ self._undo.clear()
+ self._redo.clear()
+
+ def edit_separator(self):
+ """Inserts a separator (boundary) on the undo stack."""
+ self._snapshot()
+
+ def edit_undo(self):
+ """Undoes the last edit action."""
+ if not self._undo_enabled():
+ return "" # Tk: a no-op while -undo is off
+ if not self._undo:
+ raise TclError("nothing to undo")
+ self._redo.append(self._text())
+ self._set_all(self._undo.pop())
+
+ def _set_all(self, text):
+ old = self._text()
+ self._node.set("value", text)
+ idx, removed, inserted = _diff(old, text)
+ self._edited(idx, removed, inserted)
+ self._push_tags()
+
+ # -- marks -----------------------------------------------------------------------------
+ def mark_set(self, markName, index):
+ """Set mark MARKNAME before the character at INDEX."""
+ off = self._off(index)
+ if markName == "insert":
+ self._node.ta_caret(self._byte(off))
+ elif markName == "current":
+ self._current_off = off
+ else:
+ self._marks.setdefault(markName, [off, "right"])[0] = off
+
+ def mark_unset(self, *markNames):
+ """Delete all marks in MARKNAMES."""
+ for name in markNames:
+ self._marks.pop(name, None)
+
+ def mark_names(self):
+ """Return all mark names."""
+ return ("insert", "current") + tuple(self._marks)
+
+ def mark_gravity(self, markName, direction=None):
+ """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT)."""
+ if markName not in self._marks:
+ return "right"
+ if direction is None:
+ return self._marks[markName][1]
+ self._marks[markName][1] = str(direction)
+ return None
+
+ def mark_next(self, index):
+ """Return the name of the next mark after INDEX."""
+ off = self._off(index)
+ after = sorted((pos, name) for name, (pos, _) in self._marks.items() if pos >= off)
+ return after[0][1] if after else ""
+
+ def mark_previous(self, index):
+ """Return the name of the previous mark before INDEX."""
+ off = self._off(index)
+ before = sorted((pos, name) for name, (pos, _) in self._marks.items() if pos < off)
+ return before[-1][1] if before else ""
+
+ # -- tags ---------------------------------------------------------------------------------
+ def _tag(self, name):
+ if name not in self._tags:
+ self._tags[name] = {"ranges": [], "opts": {}}
+ self._tag_order.append(name)
+ return self._tags[name]
+
+ def _ranges(self, name):
+ if name == "sel":
+ sel = self._node.ta_selection()
+ if not sel or sel[0] == sel[1]:
+ return []
+ return [[self._char(sel[0]), self._char(sel[1])]]
+ return sorted(self._tags.get(name, {"ranges": []})["ranges"])
+
+ def tag_add(self, tagName, index1, *args):
+ """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS."""
+ idx = (index1,) + args
+ for k in range(0, len(idx), 2):
+ a = self._off(idx[k])
+ b = a + 1 if k + 1 >= len(idx) else self._off(idx[k + 1])
+ if b <= a:
+ continue
+ if tagName == "sel":
+ self._node.ta_selection(self._byte(a), self._byte(b))
+ continue
+ ranges = self._tag(tagName)["ranges"]
+ ranges.append([a, b])
+ ranges.sort()
+ merged = [ranges[0]]
+ for r in ranges[1:]:
+ if r[0] <= merged[-1][1]:
+ merged[-1][1] = max(merged[-1][1], r[1])
+ else:
+ merged.append(r)
+ self._tags[tagName]["ranges"] = merged
+ self._push_tags()
+
+ def tag_remove(self, tagName, index1, index2=None):
+ """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
+ a = self._off(index1)
+ b = a + 1 if index2 is None else self._off(index2)
+ if tagName == "sel":
+ self._node.ta_selection(-1, -1)
+ return
+ tag = self._tags.get(tagName)
+ if tag:
+ out = []
+ for ra, rb in tag["ranges"]:
+ if rb <= a or ra >= b:
+ out.append([ra, rb])
+ else:
+ if ra < a:
+ out.append([ra, a])
+ if rb > b:
+ out.append([b, rb])
+ tag["ranges"] = out
+ self._push_tags()
+
+ def tag_delete(self, *tagNames):
+ """Delete all tags in TAGNAMES."""
+ for n in tagNames:
+ self._tags.pop(n, None)
+ if n in self._tag_order:
+ self._tag_order.remove(n)
+ self._push_tags()
+
+ def tag_configure(self, tagName, cnf=None, **kw):
+ """Configure a tag TAGNAME."""
+ kw = dict(cnf, **kw) if cnf else kw
+ tag = self._tag(tagName)
+ if not kw:
+ return {k: (k, "", "", "", v) for k, v in tag["opts"].items()}
+ tag["opts"].update(kw)
+ self._push_tags()
+ return None
+
+ tag_config = tag_configure
+
+ def tag_cget(self, tagName, option):
+ """Return the value of OPTION for tag TAGNAME."""
+ return self._tags.get(tagName, {"opts": {}})["opts"].get(option.lstrip("-"), "")
+
+ def tag_names(self, index=None):
+ """Return a list of all tag names (at INDEX)."""
+ if index is None:
+ return tuple(["sel"] + [n for n in self._tag_order])
+ off = self._off(index)
+ return tuple(n for n in ["sel"] + self._tag_order
+ if any(a <= off < b for a, b in self._ranges(n)))
+
+ def tag_ranges(self, tagName):
+ """Return a list of start and end index for the ranges of TAGNAME."""
+ out = []
+ for a, b in self._ranges(tagName):
+ out.extend([self.index("1.0+%dc" % a), self.index("1.0+%dc" % b)])
+ return tuple(out)
+
+ def tag_nextrange(self, tagName, index1, index2=None):
+ """First range of TAGNAME starting in [INDEX1, INDEX2)."""
+ a = self._off(index1)
+ b = len(self._text()) if index2 is None else self._off(index2)
+ for ra, rb in self._ranges(tagName):
+ if a <= ra < b or (ra < a < rb and False):
+ return (self.index("1.0+%dc" % ra), self.index("1.0+%dc" % rb))
+ return ()
+
+ def tag_prevrange(self, tagName, index1, index2=None):
+ """Last range of TAGNAME starting before INDEX1 (and at/after INDEX2)."""
+ a = self._off(index1)
+ b = 0 if index2 is None else self._off(index2)
+ for ra, rb in reversed(self._ranges(tagName)):
+ if b <= ra < a:
+ return (self.index("1.0+%dc" % ra), self.index("1.0+%dc" % rb))
+ return ()
+
+ def tag_raise(self, tagName, aboveThis=None):
+ """Change the priority of tag TAGNAME such that it is higher than
+ the priority of ABOVETHIS."""
+ self._tag(tagName)
+ self._tag_order.remove(tagName)
+ pos = len(self._tag_order) if aboveThis is None else \
+ self._tag_order.index(aboveThis) + 1
+ self._tag_order.insert(pos, tagName)
+ self._push_tags()
+
+ def tag_lower(self, tagName, belowThis=None):
+ """Change the priority of tag TAGNAME such that it is lower than
+ the priority of BELOWTHIS."""
+ self._tag(tagName)
+ self._tag_order.remove(tagName)
+ pos = 0 if belowThis is None else self._tag_order.index(belowThis)
+ self._tag_order.insert(pos, tagName)
+ self._push_tags()
+
+ def tag_bind(self, tagName, sequence, func, add=None):
+ """Bind to all characters with TAGNAME at event SEQUENCE a call to FUNC."""
+ table = self._tag_binds.setdefault(tagName, _BindTable())
+ self._node.set("events", True)
+ return table.bind(sequence, func, add)
+
+ def tag_unbind(self, tagName, sequence, funcid=None):
+ """Unbind for all characters with TAGNAME for event SEQUENCE."""
+ table = self._tag_binds.get(tagName)
+ if table is not None:
+ table.unbind(sequence, funcid)
+
+ def _push_tags(self):
+ spans = []
+ for name in self._tag_order: # later = higher priority (drawn last)
+ o = self._tags[name]["opts"]
+ fg = _try_color(o.get("foreground", o.get("fg")))
+ bg = _try_color(o.get("background", o.get("bg")))
+ if fg is None and bg is None:
+ continue
+ for a, b in self._tags[name]["ranges"]:
+ spans.append((self._byte(a), self._byte(b), fg, bg))
+ self._node.ta_spans(spans)
+
+ def _raw_event(self, ev):
+ if ev.type in (EventType.Motion, EventType.ButtonPress, EventType.ButtonRelease,
+ EventType.Enter):
+ r = self._node.rect
+ self._current_off = self._char(self._node.ta_index_at(r[0] + ev.x, r[1] + ev.y))
+ if not self._tag_binds:
+ return
+ tags = self.tag_names("current") if ev.type != EventType.Leave else ()
+ if ev.type in (EventType.Motion, EventType.Enter, EventType.Leave):
+ for name in self._hover_tags:
+ if name not in tags:
+ self._fire_tag(name, Event(type=EventType.Leave, widget=self, x=ev.x,
+ y=ev.y))
+ for name in tags:
+ if name not in self._hover_tags:
+ self._fire_tag(name, Event(type=EventType.Enter, widget=self, x=ev.x,
+ y=ev.y))
+ self._hover_tags = tags
+ for name in tags:
+ self._fire_tag(name, ev)
+
+ def _fire_tag(self, name, ev):
+ table = self._tag_binds.get(name)
+ if table is not None:
+ for fn in list(table.match(ev)):
+ _call(self, fn, ev)
+
+ # -- embedded images/windows: listed, not drawn by the kit text area -----------------------
+ def image_create(self, index, cnf={}, **kw): # noqa: B006
+ name = kw.get("name") or "image%d" % (len(self._embedded) + 1)
+ self._embedded[name] = ("image", self._off(index), dict(cnf, **kw))
+ return name
+
+ def image_cget(self, index, option):
+ return ""
+
+ def image_configure(self, index, cnf=None, **kw):
+ return {}
+
+ def image_names(self):
+ return tuple(n for n, e in self._embedded.items() if e[0] == "image")
+
+ def window_create(self, index, cnf={}, **kw): # noqa: B006
+ w = kw.get("window")
+ self._embedded[str(w)] = ("window", self._off(index), dict(cnf, **kw))
+
+ def window_cget(self, index, option):
+ return ""
+
+ def window_configure(self, index, cnf=None, **kw):
+ return {}
+
+ window_config = window_configure
+
+ def window_names(self):
+ return tuple(n for n, e in self._embedded.items() if e[0] == "window")
+
+ # -- peers ----------------------------------------------------------------------------------
+ def peer_create(self, newPathName, cnf={}, **kw): # noqa: B006
+ """Creates a peer text widget sharing this widget's text."""
+ path = str(newPathName)
+ parent_path, _, name = path.rpartition(".")
+ master = self.nametowidget(parent_path or ".")
+ peer = Text(master, cnf, name=name, **kw)
+ peer._node.set("value", self._text())
+ peer._last = self._text()
+ peer._peers = [self] + self._peers
+ for p in self._peers:
+ p._peers.append(peer)
+ self._peers.append(peer)
+ return peer
+
+ def peer_names(self):
+ return tuple(p._w for p in self._peers if p.winfo_exists())
+
+ def scan_mark(self, x, y):
+ self._scan = (int(y), self._node.get("yfirst"))
+
+ def scan_dragto(self, x, y):
+ y0, first = getattr(self, "_scan", (int(y), self._node.get("yfirst")))
+ lines = max(1, self._text().count("\n") + 1)
+ self._node.set("yview", first - (int(y) - y0) * 10 / (buipy.kit_unit() * 0.8) / lines)
+ self._view_changed()
+
+ def debug(self, boolean=None):
+ return False
+
+ def _selected_text(self):
+ r = self._ranges("sel")
+ return self._text()[r[0][0]:r[0][1]] if r else ""
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE: # typed by the user: diff to keep tags and marks right
+ new = self._text()
+ if new != self._last:
+ if self._undo_enabled():
+ self._undo.append(self._last)
+ self._redo.clear()
+ idx, removed, inserted = _diff(self._last, new)
+ self._edited(idx, removed, inserted)
+ self._push_tags()
+
+
+# ==========================================================================
+# Menus
+
+
+_MENU_TYPES = ("command", "cascade", "checkbutton", "radiobutton", "separator")
+
+
+class Menu(Widget):
+ """Menu widget: a Blender menu bar (root.config(menu=m)), a cascade, or
+ a popup (post / tk_popup)."""
+
+ _KIND = None
+ _DEFAULTS = {"tearoff": 1, "type": "normal", "title": "", "postcommand": ""}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ self._entries = []
+ self._owners = []
+ self._bar = None
+ self._active = None
+ Widget.__init__(self, master, "menu", cnf, kw)
+ if "tearoff" not in self._opts: # Tk's default: a tearoff entry at index 0
+ self._apply("tearoff", 1)
+
+ def _apply(self, key, value):
+ if key == "tearoff":
+ has = bool(self._entries) and self._entries[0]["type"] == "tearoff"
+ if getboolean(value) and not has:
+ self._entries.insert(0, {"type": "tearoff"})
+ elif not getboolean(value) and has:
+ self._entries.pop(0)
+
+ # -- entries ----------------------------------------------------------------------------
+ def add(self, itemType, cnf={}, **kw): # noqa: B006
+ """Internal function."""
+ self.insert(len(self._entries), itemType, cnf, **kw)
+
+ def add_cascade(self, cnf={}, **kw): # noqa: B006
+ """Add hierarchical menu item."""
+ self.add("cascade", cnf or kw)
+
+ def add_checkbutton(self, cnf={}, **kw): # noqa: B006
+ """Add checkbutton menu item."""
+ self.add("checkbutton", cnf or kw)
+
+ def add_command(self, cnf={}, **kw): # noqa: B006
+ """Add command menu item."""
+ self.add("command", cnf or kw)
+
+ def add_radiobutton(self, cnf={}, **kw): # noqa: B006
+ """Add radio menu item."""
+ self.add("radiobutton", cnf or kw)
+
+ def add_separator(self, cnf={}, **kw): # noqa: B006
+ """Add separator."""
+ self.add("separator", cnf or kw)
+
+ def insert(self, index, itemType, cnf={}, **kw): # noqa: B006
+ """Internal function."""
+ if itemType not in _MENU_TYPES:
+ raise TclError('bad menu entry type "%s"' % itemType)
+ opts = dict(cnf, **kw)
+ entry = dict(opts, type=itemType)
+ if itemType == "checkbutton":
+ entry.setdefault("onvalue", 1)
+ entry.setdefault("offvalue", 0)
+ if "variable" not in entry:
+ entry["variable"] = IntVar()
+ if itemType == "radiobutton":
+ entry.setdefault("value", entry.get("label", ""))
+ if "variable" not in entry:
+ entry["variable"] = _radio_default_var()
+ var = entry.get("variable")
+ if isinstance(var, Variable):
+ var.trace_add("write", lambda *a: self._changed())
+ if isinstance(index, int):
+ i = max(0, min(len(self._entries), index))
+ elif str(index) in ("end", "last") or not self._entries:
+ i = len(self._entries)
+ else:
+ i = self.index(index)
+ self._entries.insert(i, entry)
+ self._changed()
+
+ def insert_cascade(self, index, cnf={}, **kw): # noqa: B006
+ self.insert(index, "cascade", cnf or kw)
+
+ def insert_checkbutton(self, index, cnf={}, **kw): # noqa: B006
+ self.insert(index, "checkbutton", cnf or kw)
+
+ def insert_command(self, index, cnf={}, **kw): # noqa: B006
+ self.insert(index, "command", cnf or kw)
+
+ def insert_radiobutton(self, index, cnf={}, **kw): # noqa: B006
+ self.insert(index, "radiobutton", cnf or kw)
+
+ def insert_separator(self, index, cnf={}, **kw): # noqa: B006
+ self.insert(index, "separator", cnf or kw)
+
+ def delete(self, index1, index2=None):
+ """Delete menu items between INDEX1 and INDEX2 (included)."""
+ a = self.index(index1)
+ b = a if index2 is None else self.index(index2)
+ if a is None or b is None:
+ return
+ if self._entries and self._entries[0]["type"] == "tearoff":
+ a = max(a, 1)
+ del self._entries[a:b + 1]
+ self._changed()
+
+ def entrycget(self, index, option):
+ """Return the resource value of a menu item for OPTION at INDEX."""
+ e = self._entries[self.index(index)]
+ return e.get(option.lstrip("-"), "")
+
+ def entryconfigure(self, index, cnf=None, **kw):
+ """Configure a menu item at INDEX."""
+ e = self._entries[self.index(index)]
+ kw = dict(cnf, **kw) if cnf else kw
+ if not kw:
+ return {k: (k, "", "", "", v) for k, v in e.items() if k != "type"}
+ e.update(kw)
+ self._changed()
+ return None
+
+ entryconfig = entryconfigure
+
+ def index(self, index):
+ """Return the index of a menu item identified by INDEX."""
+ n = len(self._entries)
+ if isinstance(index, int):
+ return max(0, min(n - 1, index)) if n else None
+ s = str(index)
+ if s in ("end", "last"):
+ return n - 1 if n else None
+ if s == "none":
+ return None
+ if s == "active":
+ return self._active
+ if s.startswith("@"):
+ y = int(s[1:].split(",")[-1])
+ return max(0, min(n - 1, y // buipy.kit_unit()))
+ if s.isdigit():
+ return min(n - 1, int(s))
+ for i, e in enumerate(self._entries): # label pattern
+ if e.get("label") is not None and re.fullmatch(
+ s.replace("*", ".*").replace("?", "."), str(e.get("label"))):
+ return i
+ raise TclError('bad menu entry index "%s"' % index)
+
+ def type(self, index):
+ """Return the type of the menu item at INDEX."""
+ return self._entries[self.index(index)]["type"]
+
+ def invoke(self, index):
+ """Invoke a menu item identified by INDEX and execute the associated command."""
+ e = self._entries[self.index(index)]
+ if e.get("state") == "disabled":
+ return ""
+ return self._activate_entry(e)
+
+ def _activate_entry(self, e):
+ var = e.get("variable")
+ if e["type"] == "checkbutton" and isinstance(var, Variable):
+ var.set(e["offvalue"] if str(var._raw()) == str(e["onvalue"]) else e["onvalue"])
+ elif e["type"] == "radiobutton" and isinstance(var, Variable):
+ var.set(e.get("value"))
+ cmd = e.get("command")
+ return _call(self, _command(cmd)) if cmd else ""
+
+ def activate(self, index):
+ """Activate entry at INDEX."""
+ self._active = self.index(index)
+
+ def xposition(self, index):
+ return 0
+
+ def yposition(self, index):
+ """Return the y-position of the topmost pixel of the menu item at INDEX."""
+ return (self.index(index) or 0) * buipy.kit_unit()
+
+ # -- kit menus ------------------------------------------------------------------------
+ def _items(self):
+ out = []
+ for e in self._entries:
+ t = e["type"]
+ if t == "tearoff":
+ continue
+ if t == "separator":
+ out.append("-")
+ elif t == "cascade":
+ sub = e.get("menu")
+ sub = sub if isinstance(sub, Menu) or sub in (None, "") else \
+ self.nametowidget(sub)
+ if isinstance(sub, Menu) and self not in sub._owners:
+ sub._owners.append(self)
+ out.append(MenuItem(str(e.get("label", "")),
+ submenu=sub._items() if isinstance(sub, Menu) else []))
+ else:
+ checked = None
+ var = e.get("variable")
+ if t == "checkbutton" and isinstance(var, Variable):
+ checked = str(var._raw()) == str(e["onvalue"])
+ elif t == "radiobutton" and isinstance(var, Variable):
+ checked = str(var._raw()) == str(e.get("value"))
+ out.append(MenuItem(str(e.get("label", "")),
+ (lambda e=e: self._activate_entry(e)),
+ shortcut=e.get("accelerator") or None, checked=checked,
+ enabled=e.get("state", "normal") != "disabled"))
+ return out
+
+ def _bar_node(self):
+ """The window header: a Blender menu bar of this menu's cascades."""
+ if self._bar is None:
+ self._bar = buipy.KitNode("menubar")
+ self._rebuild_bar()
+ return self._bar
+
+ def _rebuild_bar(self):
+ bar = self._bar
+ for c in bar.children:
+ bar.remove(c)
+ for e in self._entries:
+ if e["type"] in ("cascade", "command"):
+ b = buipy.KitNode("menubutton")
+ b.set("text", str(e.get("label", "")))
+ sub = e.get("menu")
+ if isinstance(sub, Menu):
+ if self not in sub._owners:
+ sub._owners.append(self)
+ b.set_menu(sub._items())
+ elif e["type"] == "command": # a command directly on the bar
+ b.set_menu([MenuItem(str(e.get("label", "")),
+ (lambda e=e: self._activate_entry(e)))])
+ bar.add(b)
+
+ def _changed(self):
+ if self._bar is not None:
+ self._rebuild_bar()
+ for owner in list(self._owners):
+ owner._menu_changed()
+
+ def _menu_changed(self):
+ self._changed()
+
+ def post(self, x, y):
+ """Display a menu at position X,Y (screen coordinates)."""
+ post = self.cget("postcommand")
+ if post:
+ _call(self, _command(post))
+ top = self.master._toplevel_window() if self.master is not None else \
+ _get_default_root()
+ pos = top._window.wm_get("pos") or (0, 0)
+ top._ctx.open_menu(None, self._items(), self.cget("title") or None,
+ (int(x) - int(pos[0]), int(y) - int(pos[1])))
+
+ def tk_popup(self, x, y, entry=""):
+ """Post the menu at position X,Y with entry ENTRY."""
+ self.post(x, y)
+
+ def unpost(self):
+ """Unmap a menu."""
+ self._toplevel_window()._ctx.close_popups()
+
+
+class Menubutton(_TextOptions, Widget):
+ """Menubutton widget, obsolete since Tk8.0 (a Blender header menu)."""
+
+ _KIND = "menubutton"
+ _DEFAULTS = {"text": "", "direction": "below", "indicatoron": 0, "state": "normal"}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "menubutton", cnf, kw)
+
+ def _apply(self, key, value):
+ if key == "menu":
+ menu = value if isinstance(value, Menu) or value in (None, "") else \
+ self.nametowidget(value)
+ if isinstance(menu, Menu):
+ if self not in menu._owners:
+ menu._owners.append(self)
+ self._opts["menu"] = menu
+ self._menu_changed()
+ elif not self._text_option(key, value):
+ super()._apply(key, value)
+
+ def _menu_changed(self):
+ menu = self._opts.get("menu")
+ if isinstance(menu, Menu) and self.winfo_exists():
+ self._node.set_menu(menu._items())
+
+
+class OptionMenu(Menubutton):
+ """OptionMenu which allows the user to select a value from a menu (a
+ Blender enum dropdown)."""
+
+ _KIND = "dropdown"
+
+ def __init__(self, master, variable, value, *values, **kwargs):
+ """Construct an optionmenu widget with the parent MASTER, with the
+ resource textvariable set to VARIABLE, the initially selected value
+ VALUE, the other menu values VALUES and an additional keyword
+ argument command."""
+ command = kwargs.pop("command", None)
+ if kwargs:
+ raise TclError("unknown option -" + next(iter(kwargs)))
+ Widget.__init__(self, master, "menubutton", {}, {})
+ self._variable = variable
+ self.__menu = Menu(self, name="menu", tearoff=0)
+ self._opts["menu"] = self.__menu
+ self._opts["textvariable"] = variable
+ self.__menu._owners.append(self)
+ for v in (value,) + values:
+ self.__menu.add_command(label=v, command=_setit(variable, v, command))
+ variable.set(value)
+ variable.trace_add("write", lambda *a: self.winfo_exists() and self._from_var())
+ self._menu_changed()
+
+ def _labels(self):
+ return [str(e.get("label", "")) for e in self.__menu._entries
+ if e["type"] in ("command", "radiobutton", "checkbutton")]
+
+ def _menu_changed(self):
+ if self.winfo_exists():
+ self._node.set("items", self._labels())
+ self._from_var()
+
+ def _from_var(self):
+ labels = self._labels()
+ v = str(self._variable._raw())
+ if v in labels:
+ self._node.set("value", float(labels.index(v)))
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ entries = [e for e in self.__menu._entries
+ if e["type"] in ("command", "radiobutton", "checkbutton")]
+ i = int(self._node.get("value"))
+ if 0 <= i < len(entries):
+ self.__menu._activate_entry(entries[i])
+
+ def __getitem__(self, name):
+ if name == "menu":
+ return self.__menu
+ return Widget.__getitem__(self, name)
+
+ def destroy(self):
+ """Destroy this widget and the associated menu."""
+ Menubutton.destroy(self)
+ self.__menu = None
+
+
+# ==========================================================================
+# PanedWindow
+
+
+class _Sash(buipy.KitNode):
+ """The divider between two panes (Blender's region edge)."""
+
+ def __init__(self, paned, index):
+ super().__init__("frame")
+ self.paned, self.index = paned, index
+ self.set("events", True)
+ self.set("bg", (0.11, 0.11, 0.11, 1.0))
+
+ def _on_event(self, kind, ref, a, b):
+ p = self.paned
+ horizontal = p._horizontal()
+ if kind == EV_PRESS:
+ pane = p._panes[self.index]
+ r = pane._node.rect
+ self._start = (r[2] if horizontal else r[3], self.rect[0] + int(a),
+ self.rect[1] + int(b))
+ elif kind == EV_MOTION and getattr(self, "_start", None):
+ size, x0, y0 = self._start
+ pos = self.rect[0] + int(a) if horizontal else self.rect[1] + int(b)
+ p._set_pane_size(self.index, size + pos - (x0 if horizontal else y0))
+ elif kind == 9: # release
+ self._start = None
+
+
+class PanedWindow(Widget):
+ """panedwindow widget: panes side by side with draggable sashes."""
+
+ _KIND = "frame"
+ _DEFAULTS = {"orient": "horizontal", "sashwidth": 4, "showhandle": 0, "handlesize": 8,
+ "opaqueresize": 1, "sashrelief": "flat"}
+
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ Widget.__init__(self, master, "panedwindow", cnf, kw)
+
+ def _setup(self):
+ self._panes = []
+ self._sashes = []
+ self._pane_opts = {}
+
+ def _horizontal(self):
+ return str(self.cget("orient")).startswith("h")
+
+ def _apply(self, key, value):
+ if key in ("orient", "sashwidth"):
+ self._relayout()
+ elif key in ("width", "height"):
+ self._node.geom(int(self._node.geom_get("manager")),
+ **{"req" + key: int(_pixels(value))})
+ else:
+ super()._apply(key, value)
+
+ def add(self, child, **kw):
+ """Add a child widget to the panedwindow in a new pane."""
+ if child in self._panes:
+ self.paneconfigure(child, **kw)
+ return
+ self._panes.append(child)
+ self._pane_opts[child] = dict(kw)
+ self._relayout()
+
+ def insert(self, pos, child, **kw):
+ if child in self._panes:
+ self._panes.remove(child)
+ i = len(self._panes) if str(pos) == "end" else (
+ pos if isinstance(pos, int) else self._panes.index(pos))
+ self._panes.insert(i, child)
+ self._pane_opts.setdefault(child, {}).update(kw)
+ self._relayout()
+
+ def remove(self, child):
+ """Remove the pane containing child from the panedwindow."""
+ if child in self._panes:
+ self._panes.remove(child)
+ self._pane_opts.pop(child, None)
+ child._node.geom(0)
+ child._ginfo = {}
+ self._relayout()
+
+ forget = remove
+
+ def panes(self):
+ """Returns an ordered list of the child panes."""
+ return tuple(self._panes)
+
+ def _weight(self, child):
+ o = self._pane_opts.get(child, {})
+ if "weight" in o:
+ return float(o["weight"])
+ stretch = str(o.get("stretch", "last"))
+ i = self._panes.index(child)
+ last = len(self._panes) - 1
+ return 1.0 if (stretch == "always" or (stretch == "last" and i == last) or
+ (stretch == "first" and i == 0) or
+ (stretch == "middle" and 0 < i < last)) else 0.0
+
+ def _relayout(self):
+ node = self._node
+ for s in self._sashes:
+ node.remove(s)
+ self._sashes = []
+ h = self._horizontal()
+ side = 2 if h else 0
+ sw = int(_pixels(self.cget("sashwidth")))
+ for i, child in enumerate(self._panes):
+ if i:
+ sash = _Sash(self, i - 1)
+ sash.set("cursor", 1.0 if h else 2.0)
+ node.add(sash)
+ sash.geom(1, side=side, fill=2 if h else 1,
+ **{"reqwidth" if h else "reqheight": sw})
+ self._sashes.append(sash)
+ node.add(child._node)
+ o = self._pane_opts.get(child, {})
+ px, py = _pads(o.get("padx", 0)), _pads(o.get("pady", 0))
+ size = o.get("width" if h else "height")
+ params = {"reqwidth" if h else "reqheight": int(_pixels(size)) if size else 0}
+ child._node.geom(1, side=side, fill=3, expand=1 if self._weight(child) else 0,
+ padx0=px[0], padx1=px[1], pady0=py[0], pady1=py[1], **params)
+ child._ginfo = {"manager": "panedwindow", "in": self}
+
+ def _set_pane_size(self, index, size):
+ child = self._panes[index]
+ o = self._pane_opts.setdefault(child, {})
+ minsize = int(_pixels(o.get("minsize", 0) or 0))
+ size = max(minsize, int(size))
+ o["width" if self._horizontal() else "height"] = size
+ child._node.geom(1, **{"reqwidth" if self._horizontal() else "reqheight": size})
+
+ def paneconfigure(self, tagOrId, cnf=None, **kw):
+ """Query or modify the configuration options of the pane."""
+ o = self._pane_opts.setdefault(tagOrId, {})
+ kw = dict(cnf, **kw) if cnf else kw
+ if not kw:
+ return {k: (k, "", "", "", v) for k, v in o.items()}
+ o.update(kw)
+ self._relayout()
+ return None
+
+ paneconfig = paneconfigure
+
+ def panecget(self, child, option):
+ """Query a management option for window."""
+ return self._pane_opts.get(child, {}).get(option.lstrip("-"), "")
+
+ def sash_coord(self, index):
+ """Return the current x and y pair for the sash given by index."""
+ r = self._sashes[int(index)].rect
+ own = self._node.rect
+ return (r[0] - own[0], r[1] - own[1])
+
+ def sash_mark(self, index):
+ self._mark = self.sash_coord(index)
+ return self._mark
+
+ def sash_place(self, index, x, y):
+ """Place the sash given by index at the given coordinates."""
+ child = self._panes[int(index)]
+ own = self._node.rect
+ r = child._node.rect
+ if self._horizontal():
+ self._set_pane_size(int(index), int(x) - (r[0] - own[0]))
+ else:
+ self._set_pane_size(int(index), int(y) - (r[1] - own[1]))
+
+ def sash(self, *args):
+ return getattr(self, "sash_" + args[0])(*args[1:])
+
+ def proxy_coord(self):
+ return getattr(self, "_proxy", (0, 0))
+
+ def proxy_forget(self):
+ self._proxy = (0, 0)
+
+ def proxy_place(self, x, y):
+ self._proxy = (int(x), int(y))
+
+ def proxy(self, *args):
+ return getattr(self, "proxy_" + args[0])(*args[1:])
+
+ def identify(self, x, y):
+ """Identify the panedwindow component at point x, y."""
+ own = self._node.rect
+ for i, s in enumerate(self._sashes):
+ r = s.rect
+ if r[0] - own[0] <= int(x) < r[0] - own[0] + r[2] and \
+ r[1] - own[1] <= int(y) < r[1] - own[1] + r[3]:
+ return (i, "sash")
+ return ""
diff --git a/bindings/python/bui/tksyntax/colorchooser.py b/bindings/python/bui/tksyntax/colorchooser.py
new file mode 100644
index 0000000..7a1698e
--- /dev/null
+++ b/bindings/python/bui/tksyntax/colorchooser.py
@@ -0,0 +1,91 @@
+"""tkinter.colorchooser: askcolor with Blender's color picker.
+
+The dialog shows a Blender color swatch; clicking it opens the picker (hue
+wheel, value slider, hex field).
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+from .commondialog import Dialog
+
+__all__ = ["Chooser", "askcolor"]
+
+
+class Chooser(Dialog):
+ """Create a dialog for the tk_chooseColor command."""
+
+ command = "tk_chooseColor"
+
+ def _fixoptions(self):
+ """Ensure initialcolor is a tk color string."""
+ try:
+ color = self.options["initialcolor"]
+ if isinstance(color, tuple):
+ self.options["initialcolor"] = "#%02x%02x%02x" % color
+ except KeyError:
+ pass
+
+ def _fixresult(self, widget, result):
+ """((r, g, b), '#rrggbb') or (None, None) when cancelled."""
+ if not result:
+ return None, None
+ r, g, b = (int(result[i:i + 2], 16) for i in (1, 3, 5))
+ return (r, g, b), result
+
+ def _show(self, options):
+ from . import (Button, Frame, Label, Toplevel, _get_temp_root, color)
+ from ._core import Widget, _hex
+ from .simpledialog import _place_window
+
+ class _Swatch(Widget):
+ _KIND = "swatch"
+
+ def __init__(self, master, rgba):
+ Widget.__init__(self, master, "swatch", {}, {})
+ self._node.set("value", rgba)
+
+ parent = options.get("parent") or self.master or _get_temp_root()
+ top = Toplevel(parent)
+ top.title(options.get("title", "Color"))
+ top.resizable(False, False)
+ result = {"value": None}
+ body = Frame(top, padx=12, pady=10)
+ body.pack(fill="both", expand=True)
+ Label(body, text="Click the color to pick", anchor="w").pack(fill="x")
+ initial = color(options.get("initialcolor") or "#808080")
+ sw = _Swatch(body, initial)
+ sw.pack(fill="x", pady=6, ipady=12)
+ buttons = Frame(top, padx=10, pady=8)
+ buttons.pack(fill="x")
+
+ def done(ok):
+ if ok:
+ result["value"] = _hex(sw._node.get_color("value"))
+ top.grab_release()
+ top.destroy()
+ Button(buttons, text="OK", command=lambda: done(True)).pack(side="left", fill="x",
+ expand=True, padx=3)
+ Button(buttons, text="Cancel", command=lambda: done(False)).pack(side="left",
+ fill="x", expand=True,
+ padx=3)
+ top.bind("<Return>", lambda e: done(True))
+ top.bind("<Escape>", lambda e: done(False))
+ top.protocol("WM_DELETE_WINDOW", lambda: done(False))
+ top.transient(parent)
+ _place_window(top, parent)
+ top.grab_set()
+ top.wait_window()
+ return result["value"]
+
+
+def askcolor(color=None, **options):
+ """Display dialog window for selection of a color.
+
+ Convenience wrapper for the Chooser class. Displays the color
+ chooser dialog with color as the initial value."""
+ if color:
+ options = options.copy()
+ options["initialcolor"] = color
+ return Chooser(**options).show()
diff --git a/bindings/python/bui/tksyntax/commondialog.py b/bindings/python/bui/tksyntax/commondialog.py
new file mode 100644
index 0000000..dfe8944
--- /dev/null
+++ b/bindings/python/bui/tksyntax/commondialog.py
@@ -0,0 +1,31 @@
+"""tkinter.commondialog: base class of the standard dialogs.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+__all__ = ["Dialog"]
+
+
+class Dialog:
+ command = None
+
+ def __init__(self, master=None, **options):
+ if master is None:
+ master = options.get("parent")
+ self.master = master
+ self.options = options
+
+ def _fixoptions(self):
+ pass
+
+ def _fixresult(self, widget, result):
+ return result
+
+ def _show(self, options):
+ raise NotImplementedError
+
+ def show(self, **options):
+ for k, v in options.items():
+ self.options[k] = v
+ self._fixoptions()
+ return self._fixresult(self.master, self._show(self.options))
diff --git a/bindings/python/bui/tksyntax/constants.py b/bindings/python/bui/tksyntax/constants.py
new file mode 100644
index 0000000..787dd72
--- /dev/null
+++ b/bindings/python/bui/tksyntax/constants.py
@@ -0,0 +1,113 @@
+"""tkinter.constants (same names and values).
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+# Booleans
+NO = FALSE = OFF = 0
+YES = TRUE = ON = 1
+
+# -anchor and -sticky
+N = 'n'
+S = 's'
+W = 'w'
+E = 'e'
+NW = 'nw'
+SW = 'sw'
+NE = 'ne'
+SE = 'se'
+NS = 'ns'
+EW = 'ew'
+NSEW = 'nsew'
+CENTER = 'center'
+
+# -fill
+NONE = 'none'
+X = 'x'
+Y = 'y'
+BOTH = 'both'
+
+# -side
+LEFT = 'left'
+TOP = 'top'
+RIGHT = 'right'
+BOTTOM = 'bottom'
+
+# -relief
+RAISED = 'raised'
+SUNKEN = 'sunken'
+FLAT = 'flat'
+RIDGE = 'ridge'
+GROOVE = 'groove'
+SOLID = 'solid'
+
+# -orient
+HORIZONTAL = 'horizontal'
+VERTICAL = 'vertical'
+
+# -tabs
+NUMERIC = 'numeric'
+
+# -wrap
+CHAR = 'char'
+WORD = 'word'
+
+# -align
+BASELINE = 'baseline'
+
+# -bordermode
+INSIDE = 'inside'
+OUTSIDE = 'outside'
+
+# Special tags, marks and insert positions
+SEL = 'sel'
+SEL_FIRST = 'sel.first'
+SEL_LAST = 'sel.last'
+END = 'end'
+INSERT = 'insert'
+CURRENT = 'current'
+ANCHOR = 'anchor'
+ALL = 'all' # e.g. Canvas.delete(ALL)
+
+# Text widget and button states
+NORMAL = 'normal'
+DISABLED = 'disabled'
+ACTIVE = 'active'
+# Canvas state
+HIDDEN = 'hidden'
+
+# Menu item types
+CASCADE = 'cascade'
+CHECKBUTTON = 'checkbutton'
+COMMAND = 'command'
+RADIOBUTTON = 'radiobutton'
+SEPARATOR = 'separator'
+
+# Selection modes for list boxes
+SINGLE = 'single'
+BROWSE = 'browse'
+MULTIPLE = 'multiple'
+EXTENDED = 'extended'
+
+# Activestyle for list boxes
+# NONE='none' is also valid
+DOTBOX = 'dotbox'
+UNDERLINE = 'underline'
+
+# Various canvas styles
+PIESLICE = 'pieslice'
+CHORD = 'chord'
+ARC = 'arc'
+FIRST = 'first'
+LAST = 'last'
+BUTT = 'butt'
+PROJECTING = 'projecting'
+ROUND = 'round'
+BEVEL = 'bevel'
+MITER = 'miter'
+
+# Arguments to xview/yview
+MOVETO = 'moveto'
+SCROLL = 'scroll'
+UNITS = 'units'
+PAGES = 'pages'
diff --git a/bindings/python/bui/tksyntax/dialog.py b/bindings/python/bui/tksyntax/dialog.py
new file mode 100644
index 0000000..bfe337a
--- /dev/null
+++ b/bindings/python/bui/tksyntax/dialog.py
@@ -0,0 +1,25 @@
+"""tkinter.dialog: the classic tk_dialog (a message with buttons).
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from . import Widget, _get_default_root
+
+__all__ = ["Dialog", "DIALOG_ICON"]
+
+DIALOG_ICON = "questhead"
+
+
+class Dialog(Widget):
+ def __init__(self, master=None, cnf={}, **kw): # noqa: B006
+ from .simpledialog import SimpleDialog
+ cnf = dict(cnf, **kw)
+ master = master or _get_default_root()
+ d = SimpleDialog(master, text=cnf.get("text", ""), buttons=list(cnf.get("strings",
+ ())),
+ default=cnf.get("default"), title=cnf.get("title"),
+ _icon=cnf.get("bitmap"))
+ self.num = d.go()
+
+ def destroy(self):
+ pass
diff --git a/bindings/python/bui/tksyntax/filedialog.py b/bindings/python/bui/tksyntax/filedialog.py
new file mode 100644
index 0000000..7ba8355
--- /dev/null
+++ b/bindings/python/bui/tksyntax/filedialog.py
@@ -0,0 +1,142 @@
+"""tkinter.filedialog: the operating system's file dialogs.
+
+Like Tk on Windows and macOS, these are native dialogs (shown through the
+stdlib Tk); the option names and return values are tkinter's.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import os
+
+from bui import _realtk
+from .commondialog import Dialog
+
+__all__ = ["FileDialog", "LoadFileDialog", "SaveFileDialog", "Open", "SaveAs", "Directory",
+ "askopenfilename", "asksaveasfilename", "askopenfilenames", "askopenfile",
+ "askopenfiles", "asksaveasfile", "askdirectory"]
+
+
+def _native(kind, options):
+ """Call the real tkinter.filedialog function `kind` with our options."""
+ from bui import host
+ real = _realtk.module("tkinter.filedialog")
+ opts = {k: v for k, v in options.items() if k != "parent"}
+ opts["parent"] = host._tk()
+ return getattr(real, kind)(**opts)
+
+
+class _Dialog(Dialog):
+ _KIND = "askopenfilename"
+
+ def _show(self, options):
+ return _native(self._KIND, options)
+
+ def _fixresult(self, widget, result):
+ if result and not isinstance(result, (tuple, list)):
+ self.options["initialdir"], self.options["initialfile"] = os.path.split(result)
+ return result
+
+
+class Open(_Dialog):
+ """Ask for a filename to open."""
+
+ command = "tk_getOpenFile"
+
+ def _show(self, options):
+ kind = "askopenfilenames" if options.get("multiple") else "askopenfilename"
+ opts = {k: v for k, v in options.items() if k != "multiple"}
+ return _native(kind, opts)
+
+
+class SaveAs(_Dialog):
+ """Ask for a filename to save as."""
+
+ command = "tk_getSaveFile"
+ _KIND = "asksaveasfilename"
+
+
+class Directory(Dialog):
+ """Ask for a directory."""
+
+ command = "tk_chooseDirectory"
+
+ def _show(self, options):
+ return _native("askdirectory", options)
+
+
+def askopenfilename(**options):
+ """Ask for a filename to open"""
+ return Open(**options).show()
+
+
+def asksaveasfilename(**options):
+ """Ask for a filename to save as"""
+ return SaveAs(**options).show()
+
+
+def askopenfilenames(**options):
+ """Ask for multiple filenames to open (a tuple, () if cancelled)."""
+ options["multiple"] = 1
+ return Open(**options).show()
+
+
+def askopenfile(mode="r", **options):
+ """Ask for a filename to open, and returned the opened file"""
+ filename = Open(**options).show()
+ return open(filename, mode) if filename else None
+
+
+def askopenfiles(mode="r", **options):
+ """Ask for multiple filenames and return the open file objects."""
+ files = askopenfilenames(**options)
+ return [open(f, mode) for f in files] if files else []
+
+
+def asksaveasfile(mode="w", **options):
+ """Ask for a filename to save as, and returned the opened file"""
+ filename = SaveAs(**options).show()
+ return open(filename, mode) if filename else None
+
+
+def askdirectory(**options):
+ """Ask for a directory, and return the file name"""
+ return Directory(**options).show()
+
+
+class FileDialog:
+ """Standard file selection dialog (go() returns the chosen path or None)."""
+
+ title = "File Selection Dialog"
+ _SAVE = False
+
+ def __init__(self, master, title=None):
+ self.master = master
+ if title is not None:
+ self.title = title
+
+ def go(self, dir_or_file=os.curdir, pattern="*", default="", key=None):
+ directory, file = (dir_or_file, default) if os.path.isdir(dir_or_file) else \
+ os.path.split(dir_or_file)
+ opts = {"title": self.title, "initialdir": directory or os.curdir,
+ "initialfile": file or default, "filetypes": [("Files", pattern),
+ ("All files", "*")]}
+ result = asksaveasfilename(**opts) if self._SAVE else askopenfilename(**opts)
+ return result or None
+
+ def quit(self, how=None):
+ pass
+
+
+class LoadFileDialog(FileDialog):
+ """File selection dialog which checks that the file exists."""
+
+ title = "Load File Selection Dialog"
+
+
+class SaveFileDialog(FileDialog):
+ """File selection dialog which checks that the file may be created."""
+
+ title = "Save File Selection Dialog"
+ _SAVE = True
diff --git a/bindings/python/bui/tksyntax/font.py b/bindings/python/bui/tksyntax/font.py
new file mode 100644
index 0000000..75180c0
--- /dev/null
+++ b/bindings/python/bui/tksyntax/font.py
@@ -0,0 +1,164 @@
+"""tkinter.font: Font objects and named fonts.
+
+Text is drawn in Blender's UI font; a font's size scales it (``font_scale``
+on the kit node) and "bold" selects the bold face. ``measure`` uses the
+native text engine.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import itertools
+
+import buipy
+
+NORMAL = "normal"
+ROMAN = "roman"
+BOLD = "bold"
+ITALIC = "italic"
+
+_counter = itertools.count(1)
+_named: dict = {}
+_DEFAULT = {"family": "Segoe UI", "size": 9, "weight": NORMAL, "slant": ROMAN,
+ "underline": 0, "overstrike": 0}
+
+
+def nametofont(name, root=None):
+ """Given the name of a tk named font, returns a Font representation."""
+ _ensure_named()
+ if str(name) not in _named:
+ raise RuntimeError('named font %s does not already exist' % name)
+ return _named[str(name)]
+
+
+def families(root=None, displayof=None):
+ """Get font families (as a tuple)."""
+ try:
+ from bui import _realtk, host
+ return tuple(_realtk.module("tkinter.font").families(host._tk()))
+ except Exception:
+ return ("Segoe UI", "Arial", "Courier New", "Times New Roman", "TkDefaultFont")
+
+
+def names(root=None):
+ """Get names of defined fonts (as a tuple)."""
+ _ensure_named()
+ return tuple(_named)
+
+
+def _parse(font):
+ from ._core import _font_parts
+ family, size, styles = _font_parts(font)
+ return {"family": family or _DEFAULT["family"], "size": int(size) if size else
+ _DEFAULT["size"], "weight": BOLD if "bold" in styles else NORMAL,
+ "slant": ITALIC if "italic" in styles else ROMAN,
+ "underline": 1 if "underline" in styles else 0,
+ "overstrike": 1 if "overstrike" in styles else 0}
+
+
+class Font:
+ """Represents a named font."""
+
+ def __init__(self, root=None, font=None, name=None, exists=False, **options):
+ _ensure_named()
+ self.name = str(name) if name else "font%d" % next(_counter)
+ if exists:
+ if self.name not in _named:
+ raise RuntimeError('named font %s does not already exist' % self.name)
+ self._opts = _named[self.name]._opts
+ return
+ self._opts = dict(_DEFAULT)
+ if font is not None:
+ self._opts.update(_parse(font))
+ self._opts.update({k: v for k, v in options.items() if v is not None})
+ if name is not None or exists is False:
+ _named.setdefault(self.name, self)
+ self.delete_font = True
+
+ def __str__(self):
+ return self.name
+
+ def __repr__(self):
+ return "<%s.%s object %r>" % (self.__class__.__module__, self.__class__.__qualname__,
+ self.name)
+
+ def __eq__(self, other):
+ return isinstance(other, Font) and self.name == other.name
+
+ def __hash__(self):
+ return hash(self.name)
+
+ def __getitem__(self, key):
+ return self.cget(key)
+
+ def __setitem__(self, key, value):
+ self.configure(**{key: value})
+
+ def copy(self):
+ """Return a distinct copy of the current font."""
+ return Font(**self.actual())
+
+ def actual(self, option=None, displayof=None):
+ """Return actual font attributes."""
+ if option:
+ return self._opts.get(option.lstrip("-"))
+ return dict(self._opts)
+
+ def cget(self, option):
+ """Get font attribute."""
+ return self._opts.get(option.lstrip("-"))
+
+ def config(self, **options):
+ """Modify font attributes."""
+ if not options:
+ return dict(self._opts)
+ self._opts.update(options)
+ return None
+
+ configure = config
+
+ def _px(self):
+ size = float(self._opts.get("size", 9))
+ points = size if size > 0 else -size * 0.75
+ return buipy.kit_unit() * 0.55 * (points / 9.0)
+
+ def measure(self, text, displayof=None):
+ """Return text width."""
+ text = str(text)
+ w = buipy.measure_text(text, self._px())
+ return int(round(w if w is not None else len(text) * self._px() * 0.55))
+
+ def metrics(self, *options, **kw):
+ """Return font metrics: ascent, descent, linespace, fixed."""
+ px = self._px()
+ m = {"ascent": int(round(px * 0.92)), "descent": int(round(px * 0.26)),
+ "linespace": int(round(px * 1.45)),
+ "fixed": 1 if "courier" in str(self._opts.get("family", "")).lower() or
+ "mono" in str(self._opts.get("family", "")).lower() else 0}
+ if options:
+ return m[options[0].lstrip("-")] if len(options) == 1 else \
+ {o.lstrip("-"): m[o.lstrip("-")] for o in options}
+ return m
+
+ def delete(self):
+ _named.pop(self.name, None)
+
+
+_NAMED_DEFAULTS = {"TkDefaultFont": 9, "TkTextFont": 9, "TkFixedFont": 10, "TkMenuFont": 9,
+ "TkHeadingFont": 9, "TkCaptionFont": 9, "TkSmallCaptionFont": 8,
+ "TkIconFont": 9, "TkTooltipFont": 8}
+
+
+def _ensure_named():
+ if _named:
+ return
+ for name, size in _NAMED_DEFAULTS.items():
+ f = Font.__new__(Font)
+ f.name = name
+ f._opts = dict(_DEFAULT, size=size)
+ if name == "TkFixedFont":
+ f._opts["family"] = "Courier New"
+ if name == "TkHeadingFont":
+ f._opts["weight"] = BOLD
+ _named[name] = f
diff --git a/bindings/python/bui/tksyntax/messagebox.py b/bindings/python/bui/tksyntax/messagebox.py
new file mode 100644
index 0000000..a198f9d
--- /dev/null
+++ b/bindings/python/bui/tksyntax/messagebox.py
@@ -0,0 +1,113 @@
+"""tkinter.messagebox: Blender-styled modal message boxes.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from .commondialog import Dialog
+
+__all__ = ["showinfo", "showwarning", "showerror", "askquestion", "askokcancel", "askyesno",
+ "askyesnocancel", "askretrycancel"]
+
+# icons
+ERROR = "error"
+INFO = "info"
+QUESTION = "question"
+WARNING = "warning"
+
+# types
+ABORTRETRYIGNORE = "abortretryignore"
+OK = "ok"
+OKCANCEL = "okcancel"
+RETRYCANCEL = "retrycancel"
+YESNO = "yesno"
+YESNOCANCEL = "yesnocancel"
+
+# replies
+ABORT = "abort"
+RETRY = "retry"
+IGNORE = "ignore"
+OK = "ok"
+CANCEL = "cancel"
+YES = "yes"
+NO = "no"
+
+_BUTTONS = {ABORTRETRYIGNORE: (ABORT, RETRY, IGNORE), OK: (OK,), OKCANCEL: (OK, CANCEL),
+ RETRYCANCEL: (RETRY, CANCEL), YESNO: (YES, NO), YESNOCANCEL: (YES, NO, CANCEL)}
+
+
+class Message(Dialog):
+ """A message box."""
+
+ command = "tk_messageBox"
+
+ def _show(self, options):
+ from .simpledialog import SimpleDialog
+ from . import _get_temp_root
+ kind = options.get("type", OK)
+ replies = _BUTTONS[kind]
+ default = options.get("default", replies[0])
+ cancel = CANCEL if CANCEL in replies else (NO if NO in replies else replies[-1])
+ parent = options.get("parent") or self.master or _get_temp_root()
+ d = SimpleDialog(parent, text=str(options.get("message", "")),
+ buttons=[r.capitalize() for r in replies],
+ default=replies.index(default) if default in replies else 0,
+ cancel=replies.index(cancel), title=options.get("title"),
+ _icon=options.get("icon", INFO), _detail=options.get("detail"))
+ num = d.go()
+ return replies[num] if num is not None else cancel
+
+
+def _show(title=None, message=None, _icon=None, _type=None, **options):
+ if _icon and "icon" not in options:
+ options["icon"] = _icon
+ if _type and "type" not in options:
+ options["type"] = _type
+ if title:
+ options["title"] = title
+ if message:
+ options["message"] = message
+ res = Message(**options).show()
+ return str(res)
+
+
+def showinfo(title=None, message=None, **options):
+ """Show an info message"""
+ return _show(title, message, INFO, OK, **options)
+
+
+def showwarning(title=None, message=None, **options):
+ """Show a warning message"""
+ return _show(title, message, WARNING, OK, **options)
+
+
+def showerror(title=None, message=None, **options):
+ """Show an error message"""
+ return _show(title, message, ERROR, OK, **options)
+
+
+def askquestion(title=None, message=None, **options):
+ """Ask a question"""
+ return _show(title, message, QUESTION, YESNO, **options)
+
+
+def askokcancel(title=None, message=None, **options):
+ """Ask if operation should proceed; return true if the answer is ok"""
+ return _show(title, message, QUESTION, OKCANCEL, **options) == OK
+
+
+def askyesno(title=None, message=None, **options):
+ """Ask a question; return true if the answer is yes"""
+ return _show(title, message, QUESTION, YESNO, **options) == YES
+
+
+def askyesnocancel(title=None, message=None, **options):
+ """Ask a question; return true if the answer is yes, None if cancelled."""
+ s = _show(title, message, QUESTION, YESNOCANCEL, **options)
+ if s == CANCEL:
+ return None
+ return s == YES
+
+
+def askretrycancel(title=None, message=None, **options):
+ """Ask if operation should be retried; return true if the answer is yes"""
+ return _show(title, message, WARNING, RETRYCANCEL, **options) == RETRY
diff --git a/bindings/python/bui/tksyntax/scrolledtext.py b/bindings/python/bui/tksyntax/scrolledtext.py
new file mode 100644
index 0000000..bf61b6a
--- /dev/null
+++ b/bindings/python/bui/tksyntax/scrolledtext.py
@@ -0,0 +1,31 @@
+"""A ScrolledText widget feels like a text widget but also has a vertical
+scroll bar on its right (tkinter.scrolledtext).
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from . import Frame, Grid, Pack, Place, Scrollbar, Text
+from .constants import BOTH, LEFT, RIGHT, Y
+
+__all__ = ["ScrolledText"]
+
+
+class ScrolledText(Text):
+ def __init__(self, master=None, **kw):
+ self.frame = Frame(master)
+ self.vbar = Scrollbar(self.frame)
+ self.vbar.pack(side=RIGHT, fill=Y)
+ kw["yscrollcommand"] = self.vbar.set
+ Text.__init__(self, self.frame, **kw)
+ self.pack(side=LEFT, fill=BOTH, expand=True)
+ self.vbar["command"] = self.yview
+ # Copy geometry methods of self.frame without overriding Text methods
+ text_meths = vars(Text).keys()
+ methods = vars(Pack).keys() | vars(Grid).keys() | vars(Place).keys()
+ methods = methods.difference(text_meths)
+ for m in methods:
+ if m[0] != "_" and m != "config" and m != "configure":
+ setattr(self, m, getattr(self.frame, m))
+
+ def __str__(self):
+ return str(self.frame)
diff --git a/bindings/python/bui/tksyntax/simpledialog.py b/bindings/python/bui/tksyntax/simpledialog.py
new file mode 100644
index 0000000..283aff5
--- /dev/null
+++ b/bindings/python/bui/tksyntax/simpledialog.py
@@ -0,0 +1,254 @@
+"""tkinter.simpledialog: Dialog, SimpleDialog, askstring / askinteger /
+askfloat — Blender-styled modal windows.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+from . import (ACTIVE, Button, Entry, Frame, Label, Message, TclError, Toplevel,
+ _get_temp_root, getdouble, getint)
+from .constants import BOTH, END, LEFT, W, X
+
+__all__ = ["SimpleDialog", "Dialog", "askinteger", "askfloat", "askstring"]
+
+
+def _place_window(w, parent=None):
+ """Center `w` over its parent (or the screen) and show it."""
+ w.wm_withdraw()
+ w.update_idletasks()
+ rw, rh = w._node.natural()
+ w.geometry("%dx%d" % (max(rw, 240), max(rh, 60)))
+ if parent is not None and parent.winfo_ismapped():
+ px, py = parent.winfo_rootx(), parent.winfo_rooty()
+ pw, ph = parent.winfo_width(), parent.winfo_height()
+ x, y = px + (pw - max(rw, 240)) // 2, py + (ph - max(rh, 60)) // 2
+ else:
+ x = (w.winfo_screenwidth() - max(rw, 240)) // 2
+ y = (w.winfo_screenheight() - max(rh, 60)) // 3
+ w.geometry("+%d+%d" % (max(0, x), max(0, y)))
+ w.wm_deiconify()
+
+
+class SimpleDialog:
+ """A message with a row of buttons; go() returns the chosen index."""
+
+ def __init__(self, master, text="", buttons=[], default=None, cancel=None, # noqa: B006
+ title=None, class_=None, *, _icon=None, _detail=None):
+ self.root = Toplevel(master, class_=class_) if class_ else Toplevel(master)
+ if title:
+ self.root.title(title)
+ self.root.iconname(title)
+ self.root.resizable(False, False)
+ body = Frame(self.root, padx=12, pady=10)
+ body.pack(fill=BOTH, expand=True)
+ if _icon:
+ Label(body, bitmap=_icon).pack(side=LEFT, anchor="n", padx=(0, 10))
+ texts = Frame(body)
+ texts.pack(side=LEFT, fill=BOTH, expand=True)
+ self.message = Message(texts, text=text, aspect=400, width=320)
+ self.message.pack(anchor=W, fill=X)
+ if _detail:
+ Message(texts, text=_detail, width=320).pack(anchor=W, fill=X, pady=(6, 0))
+ self.frame = Frame(self.root, padx=10, pady=8)
+ self.frame.pack(fill=X)
+ self.num = default
+ self.cancel = cancel
+ self.default = default
+ self.root.bind("<Return>", self.return_event)
+ for num, s in enumerate(buttons):
+ b = Button(self.frame, text=s, command=(lambda self=self, num=num: self.done(num)))
+ if num == default:
+ b.config(default=ACTIVE)
+ b.pack(side=LEFT, fill=X, expand=True, padx=3)
+ self.root.protocol("WM_DELETE_WINDOW", self.wm_delete_window)
+ self.root.transient(master)
+ _place_window(self.root, master)
+
+ def go(self):
+ self.root.wait_visibility()
+ self.root.grab_set()
+ self.root.wait_window()
+ return self.num
+
+ def return_event(self, event):
+ if self.default is None:
+ self.root.bell()
+ else:
+ self.done(self.default)
+
+ def wm_delete_window(self):
+ if self.cancel is None:
+ self.root.bell()
+ else:
+ self.done(self.cancel)
+
+ def done(self, num):
+ self.num = num
+ self.root.grab_release()
+ self.root.destroy()
+
+
+class Dialog(Toplevel):
+ """Class to open dialogs (override body(), validate(), apply())."""
+
+ def __init__(self, parent, title=None):
+ """Initialize a dialog."""
+ master = parent
+ if master is None:
+ master = _get_temp_root()
+ Toplevel.__init__(self, master)
+ self.withdraw()
+ if parent is not None and parent.winfo_viewable():
+ self.transient(parent)
+ if title:
+ self.title(title)
+ self.parent = parent
+ self.result = None
+ body = Frame(self)
+ self.initial_focus = self.body(body)
+ body.pack(padx=8, pady=8, fill=BOTH, expand=True)
+ self.buttonbox()
+ if self.initial_focus is None:
+ self.initial_focus = self
+ self.protocol("WM_DELETE_WINDOW", self.cancel)
+ _place_window(self, parent)
+ self.initial_focus.focus_set()
+ self.wait_visibility()
+ self.grab_set()
+ self.wait_window(self)
+
+ def destroy(self):
+ """Destroy the window."""
+ self.initial_focus = None
+ Toplevel.destroy(self)
+
+ def body(self, master):
+ """Create dialog body. Return widget that should have initial focus."""
+
+ def buttonbox(self):
+ """Add standard button box (override if you do not want the standard buttons)."""
+ box = Frame(self)
+ w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
+ w.pack(side=LEFT, padx=5, pady=5)
+ w = Button(box, text="Cancel", width=10, command=self.cancel)
+ w.pack(side=LEFT, padx=5, pady=5)
+ self.bind("<Return>", self.ok)
+ self.bind("<Escape>", self.cancel)
+ box.pack()
+
+ def ok(self, event=None):
+ if not self.validate():
+ self.initial_focus.focus_set() # put focus back
+ return
+ self.withdraw()
+ self.update_idletasks()
+ try:
+ self.apply()
+ finally:
+ self.cancel()
+
+ def cancel(self, event=None):
+ if self.parent is not None:
+ self.parent.focus_set()
+ self.grab_release()
+ self.destroy()
+
+ def validate(self):
+ """Validate the data (override)."""
+ return 1
+
+ def apply(self):
+ """Process the data (override)."""
+
+
+class _QueryDialog(Dialog):
+ def __init__(self, title, prompt, initialvalue=None, minvalue=None, maxvalue=None,
+ parent=None):
+ self.prompt = prompt
+ self.minvalue = minvalue
+ self.maxvalue = maxvalue
+ self.initialvalue = initialvalue
+ Dialog.__init__(self, parent, title)
+
+ def destroy(self):
+ self.entry = None
+ Dialog.destroy(self)
+
+ def body(self, master):
+ w = Label(master, text=self.prompt, justify=LEFT, anchor=W)
+ w.grid(row=0, padx=5, sticky=W)
+ self.entry = Entry(master, name="entry")
+ self.entry.grid(row=1, padx=5, sticky="we")
+ if self.initialvalue is not None:
+ self.entry.insert(0, self.initialvalue)
+ self.entry.select_range(0, END)
+ return self.entry
+
+ def validate(self):
+ try:
+ result = self.getresult()
+ except (ValueError, TclError):
+ from . import messagebox
+ messagebox.showwarning("Illegal value", self.errormessage + "\nPlease try again",
+ parent=self)
+ return 0
+ if self.minvalue is not None and result < self.minvalue:
+ from . import messagebox
+ messagebox.showwarning("Too small", "The allowed minimum value is %s. "
+ "Please try again." % self.minvalue, parent=self)
+ return 0
+ if self.maxvalue is not None and result > self.maxvalue:
+ from . import messagebox
+ messagebox.showwarning("Too large", "The allowed maximum value is %s. "
+ "Please try again." % self.maxvalue, parent=self)
+ return 0
+ self.result = result
+ return 1
+
+
+class _QueryInteger(_QueryDialog):
+ errormessage = "Not an integer."
+
+ def getresult(self):
+ return getint(self.entry.get())
+
+
+class _QueryFloat(_QueryDialog):
+ errormessage = "Not a floating-point value."
+
+ def getresult(self):
+ return getdouble(self.entry.get())
+
+
+class _QueryString(_QueryDialog):
+ def __init__(self, *args, **kw):
+ self.__show = kw.pop("show", None)
+ _QueryDialog.__init__(self, *args, **kw)
+
+ def body(self, master):
+ entry = _QueryDialog.body(self, master)
+ if self.__show is not None:
+ entry.configure(show=self.__show)
+ return entry
+
+ def getresult(self):
+ return self.entry.get()
+
+
+def askinteger(title, prompt, **kw):
+ """Get an integer from the user (None if cancelled)."""
+ d = _QueryInteger(title, prompt, **kw)
+ return d.result
+
+
+def askfloat(title, prompt, **kw):
+ """Get a float from the user (None if cancelled)."""
+ d = _QueryFloat(title, prompt, **kw)
+ return d.result
+
+
+def askstring(title, prompt, **kw):
+ """Get a string from the user (None if cancelled)."""
+ d = _QueryString(title, prompt, **kw)
+ return d.result
diff --git a/bindings/python/bui/tksyntax/ttk.py b/bindings/python/bui/tksyntax/ttk.py
new file mode 100644
index 0000000..7a416d5
--- /dev/null
+++ b/bindings/python/bui/tksyntax/ttk.py
@@ -0,0 +1,1414 @@
+"""tkinter.ttk on the BUI kit.
+
+Themed widgets reuse the classic implementations and add ttk's state API
+(``state`` / ``instate``); the theme is always Blender's, so ``Style`` keeps
+settings without changing the look.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import buipy
+
+from bui.components.core import EV_CHANGE, EV_CLICK, EV_TOGGLE
+
+from . import _core, _widgets
+from ._core import (BaseWidget, EventType, TclError, Variable, XView, YView, _call,
+ _command, _pixels, _var_value, getboolean)
+from ._widgets import _chars, _image_of
+
+__all__ = ["Button", "Checkbutton", "Combobox", "Entry", "Frame", "Label", "Labelframe",
+ "LabelFrame", "Menubutton", "Notebook", "Panedwindow", "PanedWindow",
+ "Progressbar", "Radiobutton", "Scale", "Scrollbar", "Separator", "Sizegrip",
+ "Spinbox", "Style", "Treeview", "LabeledScale", "OptionMenu", "tclobjs_to_py",
+ "setup_master"]
+
+__version__ = "0.3.1"
+
+
+def tclobjs_to_py(adict):
+ """Returns adict with its values converted from Tcl objects to Python objects."""
+ return dict(adict)
+
+
+def _convert_stringval(value):
+ """Converts a value to, hopefully, a more appropriate Python object
+ (tkinter.ttk's rule: integers become int)."""
+ value = str(value)
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return value
+
+
+def setup_master(master=None):
+ """If master is not None, itself is returned. Otherwise the default root."""
+ return master if master is not None else _core._get_default_root()
+
+
+# ==========================================================================
+# Style
+
+
+class Style:
+ """Manipulate style database (kept; widgets always use Blender's theme)."""
+
+ _name = "ttk::style"
+ _db: dict = {}
+ _maps: dict = {}
+ _layouts: dict = {}
+ _elements: dict = {}
+ _themes = ["blender", "default", "clam", "alt", "classic"]
+ _current = "blender"
+
+ def __init__(self, master=None):
+ self.master = setup_master(master)
+ self.tk = self.master.tk
+
+ def configure(self, style, query_opt=None, **kw):
+ """Query or sets the default value of the specified option(s) in style."""
+ opts = Style._db.setdefault(style, {})
+ if query_opt is not None:
+ return opts.get(query_opt.lstrip("-"), "")
+ if not kw:
+ return dict(opts)
+ opts.update(kw)
+ return None
+
+ def map(self, style, query_opt=None, **kw):
+ """Query or sets dynamic values of the specified option(s) in style."""
+ maps = Style._maps.setdefault(style, {})
+ if query_opt is not None:
+ return maps.get(query_opt.lstrip("-"), [])
+ if not kw:
+ return dict(maps)
+ maps.update(kw)
+ return None
+
+ def lookup(self, style, option, state=None, default=None):
+ """Returns the value specified for option in style."""
+ option = option.lstrip("-")
+ if state:
+ for spec in Style._maps.get(style, {}).get(option, []):
+ if all(s in state for s in spec[:-1]):
+ return spec[-1]
+ return Style._db.get(style, {}).get(option, default if default is not None else "")
+
+ def layout(self, style, layoutspec=None):
+ """Define the widget layout for given style."""
+ if layoutspec is None:
+ return Style._layouts.get(style, [])
+ Style._layouts[style] = layoutspec
+ return None
+
+ def element_create(self, elementname, etype, *args, **kw):
+ """Create a new element in the current theme of given etype."""
+ Style._elements[elementname] = (etype, args, kw)
+
+ def element_names(self):
+ """Returns the list of elements defined in the current theme."""
+ return tuple(Style._elements)
+
+ def element_options(self, elementname):
+ """Return the list of elementname's options."""
+ return tuple(Style._elements.get(elementname, (None, (), {}))[2])
+
+ def theme_create(self, themename, parent=None, settings=None):
+ """Creates a new theme."""
+ if themename in Style._themes:
+ raise TclError('Theme %s already exists' % themename)
+ Style._themes.append(themename)
+ if settings:
+ self.theme_settings(themename, settings)
+
+ def theme_settings(self, themename, settings):
+ """Temporarily sets the current theme to themename, apply specified settings."""
+ for style, spec in settings.items():
+ if "configure" in spec:
+ self.configure(style, **spec["configure"])
+ if "map" in spec:
+ self.map(style, **spec["map"])
+ if "layout" in spec:
+ self.layout(style, spec["layout"])
+
+ def theme_names(self):
+ """Returns a list of all known themes."""
+ return tuple(Style._themes)
+
+ def theme_use(self, themename=None):
+ """If themename is None, returns the theme in use, otherwise, set
+ the current theme to themename (the look stays Blender's)."""
+ if themename is None:
+ return Style._current
+ if themename not in Style._themes:
+ raise TclError('can\'t find theme "%s"' % themename)
+ Style._current = themename
+ return None
+
+
+# ==========================================================================
+# Widget base: ttk states
+
+
+_STATE_FLAGS = ("active", "disabled", "focus", "pressed", "selected", "background",
+ "readonly", "alternate", "invalid", "hover")
+
+
+class Widget(_core.Widget):
+ """Base class for Tk themed widgets."""
+
+ _TTK = True
+
+ def __init__(self, master, widgetname, kw=None):
+ _core.Widget.__init__(self, master, widgetname, {}, kw or {})
+
+ def winfo_class(self):
+ return getattr(self, "_class", None) or "T" + type(self).__name__
+
+ def _apply(self, key, value):
+ if key == "state":
+ self._flags().discard("disabled")
+ self._flags().discard("readonly")
+ if str(value) in ("disabled", "readonly"):
+ self._flags().add(str(value))
+ self._sync_state()
+ elif key in ("style", "padding", "takefocus", "class"):
+ if key == "padding" and self._KIND == "frame":
+ self._node.set("padding", int(max(_core._pads(value))))
+ else:
+ super()._apply(key, value)
+
+ def _flags(self):
+ return self.__dict__.setdefault("_state_flags", set())
+
+ def _sync_state(self):
+ flags = self._flags()
+ if self._node is not None:
+ self._node.set("enabled", "disabled" not in flags and "readonly" not in flags or
+ (self._KIND == "dropdown" and "disabled" not in flags))
+
+ def state(self, statespec=None):
+ """Modify or inquire widget state."""
+ flags = self._flags()
+ if statespec is None:
+ return tuple(sorted(flags))
+ specs = statespec.split() if isinstance(statespec, str) else statespec
+ old = []
+ for spec in specs:
+ neg = spec.startswith("!")
+ name = spec.lstrip("!")
+ if name not in _STATE_FLAGS:
+ raise TclError('Invalid state name %s' % name)
+ if (name in flags) == neg:
+ old.append(("!" if not neg else "") + name)
+ (flags.discard if neg else flags.add)(name)
+ self._sync_state()
+ return tuple(old)
+
+ def instate(self, statespec, callback=None, *args, **kw):
+ """Test the widget's state."""
+ flags = self._flags()
+ specs = statespec.split() if isinstance(statespec, str) else statespec
+ ok = all((s.lstrip("!") in flags) != s.startswith("!") for s in specs)
+ if ok and callback is not None:
+ return callback(*args, **kw)
+ return ok
+
+ def identify(self, x, y):
+ """Returns the name of the element at position x, y."""
+ if 0 <= int(x) < self.winfo_width() and 0 <= int(y) < self.winfo_height():
+ return self.winfo_class().lstrip("T").lower() + ".border"
+ return ""
+
+
+def _ttk(base, default_name):
+ """A themed version of a classic widget class (ttk.Widget + base)."""
+ class Themed(Widget, base):
+ def __init__(self, master=None, **kw):
+ base.__init__(self, master, **kw)
+ Themed.__name__ = Themed.__qualname__ = default_name
+ Themed.__doc__ = "Ttk %s widget." % default_name
+ return Themed
+
+
+class Button(Widget, _widgets.Button):
+ """Ttk Button widget, displays a textual label and/or image, and
+ evaluates a command when pressed."""
+
+ def __init__(self, master=None, **kw):
+ _widgets.Button.__init__(self, master, **kw)
+
+ def invoke(self):
+ """Invokes the command associated with the button."""
+ if "disabled" in self._flags():
+ return ""
+ return _widgets.Button.invoke(self)
+
+
+class Checkbutton(Widget, _widgets.Checkbutton):
+ """Ttk Checkbutton widget which is either in on- or off-state."""
+
+ def __init__(self, master=None, **kw):
+ _widgets.Checkbutton.__init__(self, master, **kw)
+
+ def _sync(self):
+ _widgets.Checkbutton._sync(self)
+ on = self._node.get("value") != 0
+ (self._flags().add if on else self._flags().discard)("selected")
+
+ def invoke(self):
+ """Toggles between the selected and deselected states and invokes
+ the associated command."""
+ if "disabled" in self._flags():
+ return ""
+ return _widgets.Checkbutton.invoke(self)
+
+
+class Radiobutton(Widget, _widgets.Radiobutton):
+ """Ttk Radiobutton widgets are used in groups to show or change a set
+ of mutually-exclusive options."""
+
+ def __init__(self, master=None, **kw):
+ _widgets.Radiobutton.__init__(self, master, **kw)
+
+ def _sync(self):
+ _widgets.Radiobutton._sync(self)
+ on = self._node.get("value") != 0
+ (self._flags().add if on else self._flags().discard)("selected")
+
+ def invoke(self):
+ """Sets the option variable to the option value, selects the widget,
+ and invokes the associated command."""
+ if "disabled" in self._flags():
+ return ""
+ return _widgets.Radiobutton.invoke(self)
+
+
+class Entry(Widget, _widgets.Entry):
+ """Ttk Entry widget displays a one-line text string and allows that
+ string to be edited by the user."""
+
+ def __init__(self, master=None, widget=None, **kw):
+ _widgets.Entry.__init__(self, master, **kw)
+
+ def bbox(self, index):
+ return _widgets.Entry.bbox(self, index)
+
+ def validate(self):
+ """Force revalidation, independent of the conditions specified by
+ the validate option."""
+ ok = self._validate("forced", self.get(), self.get())
+ (self._flags().discard if ok else self._flags().add)("invalid")
+ return ok
+
+
+class Frame(Widget, _widgets.Frame):
+ """Ttk Frame widget is a container, used to group other widgets together."""
+
+ def __init__(self, master=None, **kw):
+ _widgets.Frame.__init__(self, master, **kw)
+
+
+class Label(Widget, _widgets.Label):
+ """Ttk Label widget displays a textual label and/or image."""
+
+ def __init__(self, master=None, **kw):
+ _widgets.Label.__init__(self, master, **kw)
+
+
+class Labelframe(Widget, _widgets.LabelFrame):
+ """Ttk Labelframe widget is a container used to group other widgets
+ together. It has an optional label."""
+
+ def __init__(self, master=None, **kw):
+ _widgets.LabelFrame.__init__(self, master, **kw)
+
+ def winfo_class(self):
+ return "TLabelframe"
+
+
+LabelFrame = Labelframe
+
+
+class Menubutton(Widget, _widgets.Menubutton):
+ """Ttk Menubutton widget displays a textual label and/or image, and
+ displays a menu when pressed."""
+
+ def __init__(self, master=None, **kw):
+ _widgets.Menubutton.__init__(self, master, **kw)
+
+
+class Scrollbar(Widget, _widgets.Scrollbar):
+ """Ttk Scrollbar controls the viewport of a scrollable widget."""
+
+ def __init__(self, master=None, **kw):
+ _widgets.Scrollbar.__init__(self, master, **kw)
+
+
+class Scale(Widget, _widgets.Scale):
+ """Ttk Scale widget is typically used to control the numeric value of
+ a linked variable that varies uniformly over some range."""
+
+ _DEFAULTS = dict(_widgets.Scale._DEFAULTS, orient="horizontal", resolution=0, value=0.0)
+
+ def __init__(self, master=None, **kw):
+ kw.setdefault("orient", "horizontal")
+ _widgets.Scale.__init__(self, master, **kw)
+
+ def _setup(self):
+ _widgets.Scale._setup(self)
+ self._node.set("integer", False) # ttk scales are continuous
+ self._node.set("precision", 2)
+ self._node.set("step", 0.01)
+
+ def _apply(self, key, value):
+ if key == "value":
+ self._node.set("value", float(value))
+ else:
+ super()._apply(key, value)
+
+ def get(self, x=None, y=None):
+ """Get the current value of the value option, or the value
+ corresponding to the coordinates x, y if they are specified."""
+ if x is not None:
+ lo, hi = self._node.get("min"), self._node.get("max")
+ return lo + (hi - lo) * max(0.0, min(1.0, float(x) / max(1, self.winfo_width())))
+ return float(self._node.get("value"))
+
+ def configure(self, cnf=None, **kw):
+ """Modify or query scale options (setting value runs the command)."""
+ retval = _widgets.Scale.configure(self, cnf, **kw)
+ if not isinstance(cnf, str) and any(k in kw for k in ("from_", "to")):
+ self.event_generate("<<RangeChanged>>")
+ return retval
+
+ config = configure
+
+
+class Spinbox(Widget, _widgets.Spinbox):
+ """Ttk Spinbox is an Entry with increment and decrement arrows."""
+
+ def __init__(self, master=None, **kw):
+ _widgets.Spinbox.__init__(self, master, **kw)
+
+ def set(self, value):
+ """Sets the value of the Spinbox to value."""
+ self._set_text(str(value))
+
+ validate = Entry.validate
+
+
+class Separator(Widget):
+ """Ttk Separator widget displays a horizontal or vertical separator bar."""
+
+ _KIND = "separator"
+
+ def __init__(self, master=None, **kw):
+ Widget.__init__(self, master, "ttk::separator", kw)
+
+ def _setup(self):
+ self._node.set("line", True)
+
+ def _apply(self, key, value):
+ if key == "orient":
+ vertical = str(value).startswith("v")
+ self._node.geom(int(self._node.geom_get("manager")),
+ reqwidth=round(0.3 * buipy.kit_unit()) if vertical else 0,
+ reqheight=0 if vertical else round(0.3 * buipy.kit_unit()))
+ else:
+ super()._apply(key, value)
+
+
+class Sizegrip(Widget):
+ """Ttk Sizegrip allows the user to resize the containing toplevel
+ window by pressing and dragging the grip."""
+
+ _KIND = "frame"
+
+ def __init__(self, master=None, **kw):
+ Widget.__init__(self, master, "ttk::sizegrip", kw)
+ self.bind("<ButtonPress-1>", self._grab)
+ self.bind("<B1-Motion>", self._drag)
+
+ def _setup(self):
+ self._node.geom(0, reqwidth=round(0.6 * buipy.kit_unit()),
+ reqheight=round(0.6 * buipy.kit_unit()))
+ self._node.set("cursor", 6.0)
+
+ def _grab(self, ev):
+ top = self._toplevel_window()
+ self._start = (ev.x_root, ev.y_root) + tuple(top._window.size)
+
+ def _drag(self, ev):
+ x, y, w, h = self._start
+ top = self._toplevel_window()
+ top.geometry("%dx%d" % (max(50, w + ev.x_root - x), max(50, h + ev.y_root - y)))
+
+
+# ==========================================================================
+# Progressbar, Combobox, OptionMenu, LabeledScale
+
+
+class Progressbar(Widget):
+ """Ttk Progressbar widget shows the status of a long-running operation
+ (Blender's progress bar)."""
+
+ _KIND = "progress"
+ _DEFAULTS = {"orient": "horizontal", "length": 100, "mode": "determinate",
+ "maximum": 100, "value": 0.0, "phase": 0}
+
+ def __init__(self, master=None, **kw):
+ Widget.__init__(self, master, "ttk::progressbar", kw)
+
+ def _setup(self):
+ self._timer = None
+ self._node.set("text", "")
+
+ def _apply(self, key, value):
+ n = self._node
+ if key in ("value", "maximum"):
+ self._update()
+ elif key == "variable":
+ if isinstance(value, Variable):
+ value.trace_add("write", lambda *a: self.winfo_exists() and self._from_var())
+ self._from_var()
+ elif key in ("length", "orient"):
+ length = int(_pixels(self.cget("length")))
+ vertical = str(self.cget("orient")).startswith("v")
+ n.geom(int(n.geom_get("manager")), reqwidth=0 if vertical else length,
+ reqheight=length if vertical else 0)
+ else:
+ super()._apply(key, value)
+
+ def _from_var(self):
+ var = self._opts.get("variable")
+ if var not in (None, ""):
+ try:
+ self._opts["value"] = float(_var_value(var))
+ except (TypeError, ValueError):
+ return
+ self._update()
+
+ def _update(self):
+ mx = float(self.cget("maximum")) or 1.0
+ v = float(self.cget("value"))
+ if str(self.cget("mode")) == "indeterminate": # a bouncing block
+ phase = (v % (2 * mx)) / mx
+ v = (2 - phase if phase > 1 else phase) * mx
+ self._node.set("factor", max(0.0, min(1.0, v / mx)))
+
+ def start(self, interval=None):
+ """Begin autoincrement mode: schedules a recurring timer event that
+ calls method step every interval milliseconds."""
+ self.stop()
+ ms = int(interval or 50)
+
+ def tick():
+ self.step()
+ self._timer = self.after(ms, tick)
+ self._timer = self.after(ms, tick)
+
+ def step(self, amount=None):
+ """Increments the value option by amount (1.0 by default)."""
+ mx = float(self.cget("maximum")) or 1.0
+ v = float(self.cget("value")) + float(amount if amount is not None else 1.0)
+ if str(self.cget("mode")) == "determinate":
+ v = v % mx if v > mx else v
+ self.configure(value=v)
+ var = self._opts.get("variable")
+ if isinstance(var, Variable):
+ var.set(v)
+
+ def stop(self):
+ """Stop autoincrement mode."""
+ if self._timer:
+ self.after_cancel(self._timer)
+ self._timer = None
+
+
+class Combobox(Entry):
+ """Ttk Combobox widget combines a text field with a pop-down list of
+ values (a Blender enum dropdown)."""
+
+ _KIND = "dropdown"
+ _DEFAULTS = {"values": (), "state": "normal", "height": 10, "width": 20,
+ "justify": "left", "exportselection": 1}
+
+ def __init__(self, master=None, **kw):
+ Widget.__init__(self, master, "ttk::combobox", kw)
+
+ def _setup(self):
+ self._values = []
+ self._text = ""
+
+ def _apply(self, key, value):
+ n = self._node
+ if key == "values":
+ vals = value.split() if isinstance(value, str) else list(value)
+ self._values = [str(v) for v in vals]
+ self._push()
+ elif key == "textvariable":
+ if isinstance(value, Variable):
+ value.trace_add("write", lambda *a: self.winfo_exists() and self._from_var())
+ self._from_var()
+ elif key == "width":
+ n.geom(int(n.geom_get("manager")), reqwidth=_chars(int(value or 20)))
+ else:
+ Widget._apply(self, key, value)
+
+ def _push(self):
+ """Values plus a typed value that isn't one of them (editable box)."""
+ items = list(self._values)
+ if self._text and self._text not in items:
+ items.append(self._text)
+ self._node.set("items", items)
+ if self._text in items:
+ self._node.set("value", float(items.index(self._text)))
+
+ def _from_var(self):
+ var = self._opts.get("textvariable")
+ if var not in (None, ""):
+ self._text = str(_var_value(var))
+ self._push()
+
+ def current(self, newindex=None):
+ """If newindex is supplied, sets the combobox value to the element
+ at position newindex in the list of values. Otherwise, returns the
+ index of the current value in the list of values or -1."""
+ if newindex is None:
+ return self._values.index(self._text) if self._text in self._values else -1
+ i = int(newindex)
+ if not 0 <= i < len(self._values):
+ raise TclError("index %s out of range" % newindex)
+ self.set(self._values[i])
+ return None
+
+ def get(self):
+ return self._text
+
+ def set(self, value):
+ """Sets the value of the combobox to value."""
+ self._text = str(value)
+ self._push()
+ self._to_var(self._text)
+
+ def _set_text(self, text, reason="forced"):
+ self.set(text)
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ i = int(self._node.get("value"))
+ items = list(self._values) + ([self._text] if self._text and
+ self._text not in self._values else [])
+ if 0 <= i < len(items):
+ self._text = items[i]
+ self._to_var(self._text)
+ self.event_generate("<<ComboboxSelected>>")
+
+
+class OptionMenu(Menubutton, _widgets.OptionMenu):
+ """Themed OptionMenu, based after tkinter's OptionMenu, which allows the
+ user to select a value from a menu."""
+
+ def __init__(self, master, variable, default=None, *values, **kwargs):
+ command = kwargs.pop("command", None)
+ style = kwargs.pop("style", None)
+ kwargs.pop("direction", None)
+ _widgets.OptionMenu.__init__(self, master, variable, default if default is not None
+ else (values[0] if values else ""), *values,
+ command=command)
+ if style:
+ self._opts["style"] = style
+ self._command = command
+
+ def set_menu(self, default=None, *values):
+ """Build a new menu of radiobuttons with *values and optionally a default value."""
+ menu = self["menu"]
+ menu.delete(0, "end")
+ for v in values:
+ menu.add_radiobutton(label=v, command=None if self._command is None else
+ (lambda v=v: self._command(v)), variable=self._variable,
+ value=v)
+ if default:
+ self._variable.set(default)
+
+
+class LabeledScale(Frame):
+ """A Ttk Scale widget with a Ttk Label widget indicating its current value."""
+
+ def __init__(self, master=None, variable=None, from_=0, to=10, **kw):
+ self._label_top = kw.pop("compound", "top") == "top"
+ Frame.__init__(self, master, **kw)
+ self._variable = variable or _core.IntVar(master)
+ self._variable.set(from_)
+ self.label = Label(self)
+ self.scale = Scale(self, variable=self._variable, from_=from_, to=to)
+ side = "top" if self._label_top else "bottom"
+ self.label.pack(side=side, anchor="w")
+ self.scale.pack(side="top" if not self._label_top else "bottom", fill="x")
+ self._cb = self._variable.trace_add("write", self._adjust)
+ self._adjust()
+
+ def _adjust(self, *args):
+ try:
+ self.label.configure(text=str(self._variable.get()))
+ except TclError:
+ pass
+
+ def destroy(self):
+ """Destroy this widget and possibly its associated variable."""
+ try:
+ self._variable.trace_remove("write", self._cb)
+ except AttributeError:
+ pass
+ Frame.destroy(self)
+
+ @property
+ def value(self):
+ """Return current scale value."""
+ return self._variable.get()
+
+ @value.setter
+ def value(self, val):
+ """Set new scale value."""
+ self._variable.set(val)
+
+
+# ==========================================================================
+# Notebook
+
+
+class Notebook(Widget):
+ """Ttk Notebook widget manages a collection of windows and displays a
+ single one at a time (Blender tabs)."""
+
+ _KIND = "tabs"
+
+ def __init__(self, master=None, **kw):
+ Widget.__init__(self, master, "ttk::notebook", kw)
+
+ def _setup(self):
+ self._tabs = [] # [child, {"text": ..., "state": ...}]
+
+ def _container_for(self, child):
+ return None # pages are shown through add()
+
+ def _apply(self, key, value):
+ if key in ("width", "height"):
+ self._node.geom(int(self._node.geom_get("manager")),
+ **{"req" + key: int(_pixels(value))})
+ else:
+ super()._apply(key, value)
+
+ def _shown(self):
+ return [t for t in self._tabs if t[1].get("state") != "hidden"]
+
+ def _push(self):
+ node = self._node
+ for c in node.children:
+ node.remove(c)
+ shown = self._shown()
+ for child, opts in shown:
+ node.add(child._node)
+ child._node.geom(1)
+ child._ginfo = {"manager": "notebook", "in": self}
+ node.set("items", [str(o.get("text", "")) for _, o in shown])
+
+ def _child(self, tab_id):
+ if isinstance(tab_id, BaseWidget):
+ return tab_id
+ return self._tabs[self.index(tab_id)][0]
+
+ def add(self, child, **kw):
+ """Adds a new tab to the notebook."""
+ for t in self._tabs:
+ if t[0] is child:
+ t[1].update(kw)
+ t[1]["state"] = kw.get("state", "normal")
+ self._push()
+ return
+ self._tabs.append([child, dict({"state": "normal", "text": ""}, **kw)])
+ self._push()
+ if len(self._shown()) == 1:
+ self.event_generate("<<NotebookTabChanged>>")
+
+ def insert(self, pos, child, **kw):
+ """Inserts a pane at the specified position."""
+ existing = [t for t in self._tabs if t[0] is child]
+ if existing:
+ self._tabs.remove(existing[0])
+ kw = dict(existing[0][1], **kw)
+ i = len(self._tabs) if str(pos) == "end" else self.index(pos)
+ self._tabs.insert(i, [child, dict({"state": "normal", "text": ""}, **kw)])
+ self._push()
+
+ def forget(self, tab_id):
+ """Removes the tab specified by tab_id, unmaps and unmanages the
+ associated window."""
+ child = self._child(tab_id)
+ self._tabs = [t for t in self._tabs if t[0] is not child]
+ child._ginfo = {}
+ self._push()
+
+ def hide(self, tab_id):
+ """Hides the tab specified by tab_id (add() shows it again)."""
+ child = self._child(tab_id)
+ for t in self._tabs:
+ if t[0] is child:
+ t[1]["state"] = "hidden"
+ self._push()
+
+ def index(self, tab_id):
+ """Returns the numeric index of the tab specified by tab_id, or the
+ total number of tabs if tab_id is the string "end"."""
+ if isinstance(tab_id, int):
+ return tab_id
+ s = str(tab_id)
+ if s == "end":
+ return len(self._tabs)
+ if s == "current":
+ shown = self._shown()
+ i = int(self._node.get("current"))
+ return self._tabs.index(shown[i]) if 0 <= i < len(shown) else -1
+ if s.startswith("@"):
+ x = int(s[1:].split(",")[0])
+ shown = self._shown()
+ w = self.winfo_width() / max(1, len(shown))
+ return self._tabs.index(shown[min(len(shown) - 1, int(x // w))]) if shown else -1
+ for i, (child, _) in enumerate(self._tabs):
+ if child is tab_id or child._w == s:
+ return i
+ raise TclError('Slave %s not managed by %s' % (tab_id, self._w))
+
+ def select(self, tab_id=None):
+ """Selects the specified tab (returns the selected tab's name)."""
+ if tab_id is None:
+ i = self.index("current")
+ return self._tabs[i][0]._w if i >= 0 else ""
+ child = self._child(tab_id)
+ shown = [c for c, _ in self._shown()]
+ if child in shown:
+ changed = shown.index(child) != int(self._node.get("current"))
+ self._node.set("current", float(shown.index(child)))
+ if changed:
+ self.event_generate("<<NotebookTabChanged>>")
+ return None
+
+ def tab(self, tab_id, option=None, **kw):
+ """Query or modify the options of the specific tab_id."""
+ opts = self._tabs[self.index(tab_id)][1]
+ if option is not None:
+ return opts.get(option.lstrip("-"), "")
+ if not kw:
+ return dict(opts)
+ opts.update(kw)
+ self._push()
+ return None
+
+ def tabs(self):
+ """Returns a list of windows managed by the notebook."""
+ return tuple(c._w for c, _ in self._tabs)
+
+ def enable_traversal(self):
+ """Enable keyboard traversal (Ctrl+Tab, Ctrl+Shift+Tab)."""
+ top = self._toplevel_window()
+
+ def step(d):
+ shown = self._shown()
+ if shown:
+ i = (int(self._node.get("current")) + d) % len(shown)
+ self.select(shown[i][0])
+ return "break"
+ top.bind("<Control-Tab>", lambda e: step(1), add="+")
+ top.bind("<Control-Shift-Tab>", lambda e: step(-1), add="+")
+
+ def identify(self, x, y):
+ """Returns the name of the tab element at position x, y."""
+ return "label" if int(y) < buipy.kit_unit() else ""
+
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ self.event_generate("<<NotebookTabChanged>>")
+
+
+# ==========================================================================
+# Panedwindow
+
+
+class Panedwindow(Widget, _widgets.PanedWindow):
+ """Ttk Panedwindow widget displays a number of subwindows, stacked
+ either vertically or horizontally."""
+
+ _DEFAULTS = dict(_widgets.PanedWindow._DEFAULTS, orient="vertical")
+
+ def __init__(self, master=None, **kw):
+ _widgets.PanedWindow.__init__(self, master, **kw)
+
+ def add(self, child, **kw):
+ kw.setdefault("weight", 0)
+ _widgets.PanedWindow.add(self, child, **kw)
+
+ def insert(self, pos, child, **kw):
+ """Inserts a pane at the specified positions."""
+ kw.setdefault("weight", 0)
+ _widgets.PanedWindow.insert(self, pos, child, **kw)
+
+ def pane(self, pane, option=None, **kw):
+ """Query or modify the options of the specified pane."""
+ child = pane if isinstance(pane, BaseWidget) else self._panes[int(pane)]
+ if option is not None:
+ return self.panecget(child, option)
+ return self.paneconfigure(child, **kw)
+
+ def sashpos(self, index, newpos=None):
+ """If newpos is specified, sets the position of sash number index."""
+ if newpos is None:
+ x, y = self.sash_coord(index)
+ return x if self._horizontal() else y
+ self.sash_place(index, newpos, newpos)
+ return newpos
+
+ def _weight(self, child):
+ if not any(float(o.get("weight", 0)) for o in self._pane_opts.values()):
+ return 1.0 if child is self._panes[-1] else 0.0
+ return float(self._pane_opts.get(child, {}).get("weight", 0))
+
+
+PanedWindow = Panedwindow
+
+
+# ==========================================================================
+# Treeview
+
+
+class Treeview(Widget, XView, YView):
+ """Ttk Treeview widget displays a hierarchical collection of items."""
+
+ _KIND = "tree"
+ _DEFAULTS = {"columns": (), "displaycolumns": "#all", "height": 10,
+ "selectmode": "extended", "show": "tree headings", "padding": 0}
+
+ def __init__(self, master=None, **kw):
+ Widget.__init__(self, master, "ttk::treeview", kw)
+
+ def _setup(self):
+ self._items = {"": None}
+ self._kids = {"": []}
+ self._parent = {}
+ self._detached = set()
+ self._item_opts = {}
+ self._columns = []
+ self._headings = {"#0": {"text": "", "anchor": "w"}}
+ self._colopts = {}
+ self._next = 1
+ self._tagopts = {}
+ self._tag_binds = {}
+ self._focus = ""
+ self._last_sel = ()
+ self._node.set("rows", 10)
+ self._node.set("selmode", 2)
+
+ def _apply(self, key, value):
+ n = self._node
+ if key == "columns":
+ self._columns = [str(c) for c in (value.split() if isinstance(value, str)
+ else value)]
+ self._refresh_all()
+ elif key in ("displaycolumns", "show"):
+ self._refresh_all()
+ elif key == "height":
+ n.set("rows", int(value) or 10)
+ elif key == "selectmode":
+ n.set("selmode", float({"extended": 2, "browse": 3, "none": 0}.get(str(value), 2)))
+ elif key in ("xscrollcommand", "yscrollcommand"):
+ n.set("noscrollbar", True)
+ n.set("viewevents", True)
+ else:
+ super()._apply(key, value)
+
+ # -- columns ------------------------------------------------------------------------
+ def _display(self):
+ d = self.cget("displaycolumns")
+ if d in ("#all", ("#all",), ["#all"]):
+ return list(self._columns)
+ cols = d.split() if isinstance(d, str) else list(d)
+ return [self._columns[int(c)] if str(c).isdigit() else str(c) for c in cols]
+
+ def _tree_shown(self):
+ show = self.cget("show")
+ show = show.split() if isinstance(show, str) else list(show)
+ return "tree" in show
+
+ def _headings_shown(self):
+ show = self.cget("show")
+ show = show.split() if isinstance(show, str) else list(show)
+ return "headings" in show
+
+ def _push_headers(self):
+ cols = self._display()
+ names = ([str(self._headings.get("#0", {}).get("text", ""))] if self._tree_shown()
+ else []) + [str(self._headings.get(c, {}).get("text", c)) for c in cols]
+ self._node.set("headers", names if self._headings_shown() else [])
+
+ def _cells(self, iid):
+ """(label, other columns) for the kit row of an item."""
+ o = self._item_opts[iid]
+ vals = list(o.get("values", ()))
+ by_col = {c: (str(vals[i]) if i < len(vals) else "") for i, c in
+ enumerate(self._columns)}
+ shown = [by_col.get(c, "") for c in self._display()]
+ if self._tree_shown():
+ return str(o.get("text", "")), shown
+ return (shown[0] if shown else ""), shown[1:]
+
+ def _push_item(self, iid):
+ node = self._items[iid]
+ label, values = self._cells(iid)
+ node.label = label
+ node.set_values(values)
+
+ def _refresh_all(self):
+ self._push_headers()
+ for iid in self._items:
+ if iid:
+ self._push_item(iid)
+ self._node.invalidate()
+
+ def column(self, column, option=None, **kw):
+ """Query or modify the options for the specified column."""
+ col = self._colname(column)
+ opts = self._colopts.setdefault(col, {"width": 200, "minwidth": 20, "stretch": 1,
+ "anchor": "w", "id": col})
+ if option is not None:
+ return opts.get(option.lstrip("-"), "")
+ if not kw:
+ return dict(opts)
+ opts.update(kw)
+ return None
+
+ def _colname(self, column):
+ c = str(column)
+ if c.startswith("#") and c[1:].isdigit():
+ k = int(c[1:])
+ return "#0" if k == 0 else self._display()[k - 1]
+ return c
+
+ def heading(self, column, option=None, **kw):
+ """Query or modify the heading options for the specified column."""
+ col = self._colname(column)
+ opts = self._headings.setdefault(col, {"text": "", "anchor": "center"})
+ if option is not None:
+ return opts.get(option.lstrip("-"), "")
+ if not kw:
+ return dict(opts)
+ opts.update(kw)
+ self._push_headers()
+ return None
+
+ # -- items --------------------------------------------------------------------------
+ def insert(self, parent, index, iid=None, **kw):
+ """Creates a new item and return the item identifier of the newly
+ created item."""
+ if parent not in self._kids:
+ raise TclError('Item %s not found' % parent)
+ if iid is None:
+ while "I%03X" % self._next in self._items:
+ self._next += 1
+ iid = "I%03X" % self._next
+ self._next += 1
+ iid = str(iid)
+ if iid in self._items:
+ raise TclError('Item %s already exists' % iid)
+ node = buipy.KitTreeItem("")
+ node.set("expanded", 0.0) # Tk items start closed
+ node._iid = iid
+ self._items[iid] = node
+ self._kids[iid] = []
+ self._item_opts[iid] = {"text": "", "values": (), "open": False, "tags": (),
+ "image": ""}
+ self._attach(iid, parent, index)
+ self.item(iid, **kw)
+ return iid
+
+ def _attach(self, iid, parent, index):
+ siblings = self._kids.setdefault(parent, [])
+ i = len(siblings) if str(index) == "end" else max(0, min(len(siblings), int(index)))
+ siblings.insert(i, iid)
+ self._parent[iid] = parent
+ self._detached.discard(iid)
+ self._rebuild(parent)
+
+ def _detach_from_parent(self, iid):
+ parent = self._parent.get(iid, "")
+ if iid in self._kids.get(parent, []):
+ self._kids[parent].remove(iid)
+ self._rebuild(parent)
+
+ def _rebuild(self, parent):
+ """Kit children of `parent` follow the Tk order."""
+ if parent == "":
+ self._node.set_tree_roots([self._items[i] for i in self._kids[""]])
+ return
+ node = self._items[parent]
+ node.clear_children()
+ for i in self._kids[parent]:
+ node.add(self._items[i])
+ self._node.invalidate()
+
+ def item(self, item, option=None, **kw):
+ """Query or modify the options for the specified item."""
+ if item not in self._item_opts:
+ raise TclError('Item %s not found' % item)
+ opts = self._item_opts[item]
+ if option is not None:
+ v = opts.get(option.lstrip("-"), "")
+ return int(v) if isinstance(v, bool) else v
+ if not kw: # as tkinter.ttk converts Tcl results
+ out = dict(opts)
+ out["values"] = [_convert_stringval(v) for v in out["values"]] or ""
+ out["tags"] = list(out["tags"]) or ""
+ out["open"] = int(bool(out["open"]))
+ return out
+ node = self._items[item]
+ for k, v in kw.items():
+ if k == "values":
+ v = tuple(str(x) for x in (v.split() if isinstance(v, str) else v))
+ elif k == "tags":
+ v = tuple(v.split() if isinstance(v, str) else v)
+ elif k == "open":
+ v = getboolean(v)
+ node.set("expanded", 1.0 if v else 0.0)
+ elif k == "image":
+ img = _image_of(v) if v else None
+ if img is not None:
+ pass # tree rows show kit icons; images are kept
+ opts[k] = v
+ self._push_item(item)
+ self._node.invalidate()
+ return None
+
+ def delete(self, *items):
+ """Delete all specified items and all their descendants."""
+ for iid in items:
+ if iid not in self._items:
+ raise TclError('Item %s not found' % iid)
+ for iid in items:
+ self._remove(iid)
+ self._selection_changed()
+
+ def _remove(self, iid):
+ if iid not in self._items:
+ return
+ for kid in list(self._kids.get(iid, ())):
+ self._remove(kid)
+ if self._node.tree_selected() is self._items[iid]:
+ self._node.tree_select(None)
+ self._detach_from_parent(iid)
+ self._items.pop(iid, None)
+ self._kids.pop(iid, None)
+ self._parent.pop(iid, None)
+ self._item_opts.pop(iid, None)
+ if self._focus == iid:
+ self._focus = ""
+
+ def detach(self, *items):
+ """Unlinks all of the specified items from the tree (reattach brings them back)."""
+ for iid in items:
+ self._detach_from_parent(iid)
+ self._detached.add(iid)
+
+ def move(self, item, parent, index):
+ """Moves item to position index in parent's list of children."""
+ self._detach_from_parent(item)
+ self._attach(item, parent, index)
+
+ reattach = move
+
+ def exists(self, item):
+ """Returns True if the specified item is present in the tree."""
+ return item in self._items and item != ""
+
+ def get_children(self, item=None):
+ """Returns a tuple of children belonging to item."""
+ return tuple(self._kids.get(item or "", ()))
+
+ def set_children(self, item, *newchildren):
+ """Replaces item's child with newchildren."""
+ for kid in list(self._kids.get(item, ())):
+ if kid not in newchildren:
+ self._detach_from_parent(kid)
+ self._detached.add(kid)
+ for kid in newchildren:
+ self._detach_from_parent(kid)
+ self._kids[item] = []
+ for kid in newchildren:
+ self._attach(kid, item, "end")
+
+ def parent(self, item):
+ """Returns the ID of the parent of item, or '' if item is at the top level."""
+ return self._parent.get(item, "")
+
+ def index(self, item):
+ """Returns the integer index of item within its parent's list of children."""
+ return self._kids[self._parent.get(item, "")].index(item)
+
+ def next(self, item):
+ """Returns the identifier of item's next sibling, or '' if item is the last child."""
+ sibs = self._kids[self._parent.get(item, "")]
+ i = sibs.index(item)
+ return sibs[i + 1] if i + 1 < len(sibs) else ""
+
+ def prev(self, item):
+ """Returns the identifier of item's previous sibling, or '' if item is the first child."""
+ sibs = self._kids[self._parent.get(item, "")]
+ i = sibs.index(item)
+ return sibs[i - 1] if i > 0 else ""
+
+ def depth(self, item):
+ d = 0
+ while self._parent.get(item, ""):
+ item = self._parent[item]
+ d += 1
+ return d
+
+ def set(self, item, column=None, value=None):
+ """Query or set the value of given item."""
+ opts = self._item_opts[item]
+ vals = list(opts.get("values", ()))
+ vals += [""] * (len(self._columns) - len(vals))
+ if column is None:
+ return {c: vals[i] for i, c in enumerate(self._columns)}
+ col = self._colname(column)
+ ci = self._columns.index(col) if col in self._columns else int(str(column).lstrip("#"))
+ if value is None:
+ return vals[ci]
+ vals[ci] = value
+ self.item(item, values=vals)
+ return None
+
+ def see(self, item):
+ """Ensure that item is visible (opens its ancestors, scrolls to it)."""
+ p = self._parent.get(item, "")
+ while p:
+ self.item(p, open=True)
+ p = self._parent.get(p, "")
+ rows = self._visible_rows()
+ if item in rows:
+ i = rows.index(item)
+ total = max(1, len(rows))
+ first = int(round(self._node.get("yfirst") * total))
+ vis = max(1, int(self._node.get("yvisible")))
+ if i < first:
+ self._node.set("yview", i / total)
+ elif i >= first + vis:
+ self._node.set("yview", (i - vis + 1) / total)
+ self._view_changed()
+
+ def focus(self, item=None):
+ """If item is specified, sets the focus item to item. Otherwise,
+ returns the current focus item, or '' if there is none."""
+ if item is None:
+ sel = self._node.tree_selected()
+ return getattr(sel, "_iid", self._focus) if sel is not None else self._focus
+ self._focus = item
+ if item in self._items:
+ self._node.tree_select(self._items[item])
+ return None
+
+ def bbox(self, item, column=None):
+ """Returns the bounding box (relative to the treeview widget's
+ window) of the specified item in the form x y width height."""
+ rows = self._visible_rows()
+ if item not in rows:
+ return ""
+ u = buipy.kit_unit()
+ total = max(1, len(rows))
+ first = int(round(self._node.get("yfirst") * total))
+ i = rows.index(item) - first
+ if not 0 <= i < int(self._node.get("yvisible")):
+ return ""
+ top = round(0.15 * u) + (u if self._headings_shown() else 0)
+ return (round(0.15 * u), top + i * u, self.winfo_width() - round(0.3 * u), u)
+
+ # -- selection ------------------------------------------------------------------------
+ def selection(self):
+ """Returns the tuple of selected items."""
+ return tuple(iid for iid in self._visible_order(all_items=True)
+ if iid in self._items and self._items[iid].get("marked"))
+
+ def _visible_order(self, all_items=False):
+ out = []
+
+ def walk(parent):
+ for iid in self._kids.get(parent, ()):
+ out.append(iid)
+ if all_items or self._item_opts[iid].get("open"):
+ walk(iid)
+ walk("")
+ return out
+
+ def _visible_rows(self):
+ for iid, opts in self._item_opts.items(): # the kit owns the open state
+ opts["open"] = bool(self._items[iid].get("expanded"))
+ return self._visible_order()
+
+ def _set_marks(self, items, mode):
+ for iid in items:
+ if iid not in self._items:
+ raise TclError('Item %s not found' % iid)
+ if mode == "set":
+ for node in self._items.values():
+ if node is not None:
+ node.set("marked", 0.0)
+ for iid in items:
+ node = self._items[iid]
+ on = {"set": True, "add": True, "remove": False}.get(mode)
+ if on is None:
+ on = not node.get("marked")
+ node.set("marked", 1.0 if on else 0.0)
+ if items and mode in ("set", "add"):
+ self._node.tree_select(self._items[items[0]])
+ self._node.invalidate()
+ self._selection_changed()
+
+ @staticmethod
+ def _items_arg(items):
+ if len(items) == 1 and isinstance(items[0], (tuple, list)):
+ return tuple(items[0])
+ if len(items) == 1 and isinstance(items[0], str) and " " in items[0]:
+ return tuple(items[0].split())
+ return items
+
+ def selection_set(self, *items):
+ """The specified items becomes the new selection."""
+ self._set_marks(self._items_arg(items), "set")
+
+ def selection_add(self, *items):
+ """Add all of the specified items to the selection."""
+ self._set_marks(self._items_arg(items), "add")
+
+ def selection_remove(self, *items):
+ """Remove all of the specified items from the selection."""
+ self._set_marks(self._items_arg(items), "remove")
+
+ def selection_toggle(self, *items):
+ """Toggle the selection state of each specified item."""
+ self._set_marks(self._items_arg(items), "toggle")
+
+ def _selection_changed(self):
+ sel = self.selection()
+ if sel != self._last_sel:
+ self._last_sel = sel
+ if not getattr(self, "_select_pending", False): # Tk queues the event
+ self._select_pending = True
+ self.after_idle(self._fire_select)
+
+ def _fire_select(self):
+ self._select_pending = False
+ if self.winfo_exists():
+ self.event_generate("<<TreeviewSelect>>")
+
+ # -- identify -------------------------------------------------------------------------
+ def identify_row(self, y):
+ """Returns the item ID of the item at position y."""
+ rows = self._visible_rows()
+ u = buipy.kit_unit()
+ top = round(0.15 * u) + (u if self._headings_shown() else 0)
+ if int(y) < top:
+ return ""
+ first = int(round(self._node.get("yfirst") * max(1, len(rows))))
+ i = first + (int(y) - top) // u
+ return rows[i] if 0 <= i < len(rows) else ""
+
+ def identify_column(self, x):
+ """Returns the data column identifier of the cell at position x."""
+ n = len(self._display()) + (1 if self._tree_shown() else 0)
+ w = max(1, self.winfo_width())
+ if n <= 1:
+ k = 0
+ else:
+ first = w / 2 if n == 2 else w * 0.4
+ k = 0 if int(x) < first else 1 + int((int(x) - first) / ((w - first) / (n - 1)))
+ k = min(k, n - 1)
+ return "#%d" % (k if self._tree_shown() else k + 1)
+
+ def identify_region(self, x, y):
+ """'heading', 'separator', 'tree', 'cell' or 'nothing' at x, y."""
+ u = buipy.kit_unit()
+ if self._headings_shown() and int(y) < round(0.15 * u) + u:
+ return "heading"
+ if not self.identify_row(y):
+ return "nothing"
+ return "tree" if self.identify_column(x) == "#0" else "cell"
+
+ def identify_element(self, x, y):
+ return "text" if self.identify_row(y) else ""
+
+ def identify(self, component, x, y):
+ return getattr(self, "identify_" + component)(*((y,) if component == "row" else
+ (x,) if component == "column" else
+ (x, y)))
+
+ # -- tags -----------------------------------------------------------------------------
+ def tag_configure(self, tagname, option=None, **kw):
+ """Query or modify the options for the specified tagname (row colors
+ are kept; rows use Blender's list colors)."""
+ opts = self._tagopts.setdefault(tagname, {})
+ if option is not None:
+ return opts.get(option.lstrip("-"), "")
+ if not kw:
+ return dict(opts)
+ opts.update(kw)
+ return None
+
+ def tag_has(self, tagname, item=None):
+ """If item is specified, returns whether it has the given tagname.
+ Otherwise, returns all items which have the tag."""
+ if item is not None:
+ return tagname in self._item_opts[item].get("tags", ())
+ return tuple(i for i, o in self._item_opts.items() if tagname in o.get("tags", ()))
+
+ def tag_bind(self, tagname, sequence=None, callback=None):
+ """Bind a callback for the given event sequence to the tag tagname."""
+ table = self._tag_binds.setdefault(tagname, _core._BindTable())
+ self._node.set("events", True)
+ if callback is not None:
+ table.bind(sequence, callback, None)
+ return None
+
+ def _raw_event(self, ev):
+ if not self._tag_binds or ev.type not in (EventType.ButtonPress,
+ EventType.ButtonRelease, EventType.KeyPress):
+ return
+ item = self.identify_row(ev.y) if ev.type != EventType.KeyPress else self.focus()
+ if not item:
+ return
+ for tag in self._item_opts.get(item, {}).get("tags", ()):
+ table = self._tag_binds.get(tag)
+ if table is not None:
+ for fn in list(table.match(ev)):
+ _call(self, fn, ev)
+
+ # -- kit events -------------------------------------------------------------------------
+ def _event(self, kind, ref, a, b):
+ if kind == EV_CHANGE:
+ sel = self._node.tree_selected()
+ if sel is not None:
+ self._focus = getattr(sel, "_iid", self._focus)
+ if self._node.get("selmode") == 0 and sel is not None: # selectmode none
+ return
+ self._selection_changed()
+ elif kind == EV_CLICK: # a column heading
+ k = int(a)
+ cols = (["#0"] if self._tree_shown() else []) + self._display()
+ if 0 <= k < len(cols):
+ cmd = self._headings.get(cols[k], {}).get("command")
+ if cmd:
+ _call(self, _command(cmd))
+ elif kind == EV_TOGGLE and int(a) == -1 and ref is not None: # open / close
+ iid = getattr(ref, "_iid", None)
+ if iid is not None:
+ self._item_opts[iid]["open"] = bool(b)
+ self._focus = iid
+ self.event_generate("<<TreeviewOpen>>" if b else "<<TreeviewClose>>")
diff --git a/bindings/python/setup.py b/bindings/python/setup.py
new file mode 100644
index 0000000..3249459
--- /dev/null
+++ b/bindings/python/setup.py
@@ -0,0 +1,74 @@
+"""pip packaging for bui + buipy.
+
+Builds the native extension with CMake first, then packages the `bui` package
+together with the compiled buipy extension so `pip install` just works:
+
+ cmake -S . -B build -G "MinGW Makefiles"
+ cmake --build build --target buipy
+ python -m pip install bindings/python
+
+The extension is interpreter-specific; build it with the same interpreter you
+pip-install into (see INTEGRATION.md, "Testing the Python bindings").
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import glob
+import os
+import shutil
+import sys
+
+from setuptools import setup
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+
+
+def locate_extension() -> str:
+ """Find the built buipy extension matching THIS interpreter's ABI tag
+ (e.g. buipy.cp312-win_amd64.pyd), from BUIPY_BUILD_DIR or ../build*."""
+ tag = "cp%d%d" % sys.version_info[:2]
+ candidates = [os.environ.get("BUIPY_BUILD_DIR", "")]
+ candidates += sorted(
+ glob.glob(os.path.join(HERE, "..", "..", "build*", "bindings", "python")),
+ reverse=True,
+ )
+ for cand in candidates:
+ if not cand:
+ continue
+ for ext in ("*.pyd", "*.so"):
+ # Prefer an exact ABI match; fall back to any buipy extension.
+ hits = [h for h in glob.glob(os.path.join(cand, "buipy" + ext)) if tag in h]
+ hits = hits or glob.glob(os.path.join(cand, "buipy" + ext))
+ if hits:
+ return hits[0]
+ return ""
+
+
+def stage_extension() -> str:
+ src = locate_extension()
+ if not src:
+ print(
+ "error: no built buipy extension found. Build it first:\n"
+ " cmake -S . -B build && cmake --build build --target buipy\n"
+ "or set BUIPY_BUILD_DIR.",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+ dest = os.path.join(HERE, "bui", os.path.basename(src))
+ shutil.copy2(src, dest)
+ print("staged native extension:", dest)
+ return os.path.basename(src)
+
+
+ext_name = stage_extension()
+
+setup(
+ name="bui",
+ version="0.1.0",
+ description="BUI — Blender-derived UI toolkit with Qt/tkinter-style Python syntax",
+ packages=["bui"],
+ package_data={"bui": [ext_name]},
+ include_package_data=True,
+ python_requires=">=3.10",
+ license="GPL-2.0-or-later",
+)
diff --git a/bindings/python/src/buipy_kit.c b/bindings/python/src/buipy_kit.c
new file mode 100644
index 0000000..a13e834
--- /dev/null
+++ b/bindings/python/src/buipy_kit.c
@@ -0,0 +1,2244 @@
+/* buipy kit bindings: KitNode, KitTreeItem, KitContext.
+ *
+ * Thin wrappers over BUI_kit.h. The C kit owns all UI state and runs all
+ * layout, input and drawing; Python only builds trees, sets properties and
+ * receives callbacks (KitNode._on_event, menu/hotkey callables).
+ *
+ * Ownership: a node's Python wrapper owns the C node. Parents retain their
+ * children's wrappers (Py_INCREF via the kit's ref hooks), so a subtree
+ * lives as long as it is attached or referenced. C-owned nodes (a panel's
+ * body, popups, picker parts) are exposed as borrowed wrappers.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#define PY_SSIZE_T_CLEAN
+#include <Python.h>
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "BUI_kit.h"
+
+BuiRaster *buipy_current_raster(void);
+BuiRaster *buipy_raster_of(PyObject *obj);
+
+/* -------------------------------------------------------------------- */
+/** \name Error stash (exceptions raised inside callbacks)
+ * \{ */
+
+static PyObject *g_err_type, *g_err_value, *g_err_tb;
+
+static void stash_error(void)
+{
+ if (!PyErr_Occurred()) {
+ return;
+ }
+ if (g_err_type) {
+ PyErr_Clear(); /* keep the first error */
+ return;
+ }
+ PyErr_Fetch(&g_err_type, &g_err_value, &g_err_tb);
+}
+
+/* Returns 1 (with the exception restored) when a callback failed. */
+static int restore_error(void)
+{
+ if (!g_err_type) {
+ return 0;
+ }
+ PyErr_Restore(g_err_type, g_err_value, g_err_tb);
+ g_err_type = g_err_value = g_err_tb = NULL;
+ return 1;
+}
+
+static void ref_retain(void *ref)
+{
+ Py_INCREF((PyObject *)ref);
+}
+
+static void ref_release(void *ref)
+{
+ Py_DECREF((PyObject *)ref);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name KitNode
+ * \{ */
+
+typedef struct KitNodeObject {
+ PyObject_HEAD
+ BKNode *node;
+ int borrowed; /* C-owned node: never freed by this wrapper */
+ PyObject *dict;
+} KitNodeObject;
+
+static PyTypeObject KitNode_Type;
+static PyTypeObject KitTreeItem_Type;
+
+static PyObject *node_wrap(BKNode *node)
+{
+ if (!node) {
+ Py_RETURN_NONE;
+ }
+ if (BK_node_ref(node)) {
+ PyObject *o = (PyObject *)BK_node_ref(node);
+ Py_INCREF(o);
+ return o;
+ }
+ KitNodeObject *o = (KitNodeObject *)KitNode_Type.tp_alloc(&KitNode_Type, 0);
+ if (o) {
+ o->node = node;
+ o->borrowed = 1;
+ }
+ return (PyObject *)o;
+}
+
+static BKNode *node_of(PyObject *obj)
+{
+ if (!PyObject_TypeCheck(obj, &KitNode_Type) || !((KitNodeObject *)obj)->node) {
+ PyErr_SetString(PyExc_TypeError, "expected a KitNode");
+ return NULL;
+ }
+ return ((KitNodeObject *)obj)->node;
+}
+
+static int kitnode_init(KitNodeObject *self, PyObject *args, PyObject *kw)
+{
+ const char *type;
+ if (!PyArg_ParseTuple(args, "s:KitNode", &type)) {
+ return -1;
+ }
+ if (self->node) {
+ PyErr_SetString(PyExc_RuntimeError, "KitNode already initialized");
+ return -1;
+ }
+ self->node = BK_node_new(type);
+ if (!self->node) {
+ PyErr_Format(PyExc_ValueError, "unknown kit node type '%s'", type);
+ return -1;
+ }
+ BK_node_set_ref(self->node, self);
+ return 0;
+}
+
+static void kitnode_dealloc(KitNodeObject *self)
+{
+ PyObject_GC_UnTrack(self);
+ Py_CLEAR(self->dict);
+ if (self->node && !self->borrowed) {
+ BK_node_set_ref(self->node, NULL);
+ BK_node_free(self->node);
+ }
+ self->node = NULL;
+ Py_TYPE(self)->tp_free((PyObject *)self);
+}
+
+static int kitnode_traverse(KitNodeObject *self, visitproc visit, void *arg)
+{
+ Py_VISIT(self->dict);
+ return 0;
+}
+
+static int kitnode_clear(KitNodeObject *self)
+{
+ Py_CLEAR(self->dict);
+ return 0;
+}
+
+static int parse_rgba(PyObject *v, float out[4])
+{
+ PyObject *seq = PySequence_Fast(v, "color must be a sequence of 3 or 4 floats");
+ if (!seq) {
+ return 0;
+ }
+ const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
+ if (n != 3 && n != 4) {
+ Py_DECREF(seq);
+ PyErr_SetString(PyExc_ValueError, "color must have 3 or 4 components");
+ return 0;
+ }
+ out[3] = 1.0f;
+ for (Py_ssize_t i = 0; i < n; i++) {
+ out[i] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq, i));
+ }
+ Py_DECREF(seq);
+ return !PyErr_Occurred();
+}
+
+static PyObject *kitnode_set(KitNodeObject *self, PyObject *args)
+{
+ const char *key;
+ PyObject *v;
+ if (!PyArg_ParseTuple(args, "sO:set", &key, &v) || !self->node) {
+ return NULL;
+ }
+ int ok;
+ if (v == Py_None) {
+ ok = BK_set_str(self->node, key, "");
+ }
+ else if (PyUnicode_Check(v)) {
+ ok = BK_set_str(self->node, key, PyUnicode_AsUTF8(v));
+ }
+ else if (PyBool_Check(v) || PyLong_Check(v) || PyFloat_Check(v)) {
+ ok = BK_set_num(self->node, key, PyFloat_AsDouble(v));
+ }
+ else if (PySequence_Check(v)) {
+ const Py_ssize_t n = PySequence_Size(v);
+ PyObject *first = n > 0 ? PySequence_GetItem(v, 0) : NULL;
+ const int strings = first && (PyUnicode_Check(first) || first == Py_None);
+ Py_XDECREF(first);
+ if (strings || n == 0) {
+ const char **vals = (const char **)calloc((size_t)(n > 0 ? n : 1), sizeof(char *));
+ PyObject *seq = PySequence_Fast(v, "expected a sequence");
+ for (Py_ssize_t i = 0; seq && i < n; i++) {
+ PyObject *it = PySequence_Fast_GET_ITEM(seq, i);
+ vals[i] = (it == Py_None) ? "" : PyUnicode_AsUTF8(it);
+ }
+ ok = (seq && !PyErr_Occurred()) ? BK_set_strs(self->node, key, vals, (int)n) : 0;
+ Py_XDECREF(seq);
+ free(vals);
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ }
+ else {
+ float c[4];
+ if (!parse_rgba(v, c)) {
+ return NULL;
+ }
+ ok = BK_set_color(self->node, key, c);
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError, "unsupported value for '%s'", key);
+ return NULL;
+ }
+ if (restore_error()) {
+ return NULL;
+ }
+ if (!ok) {
+ PyErr_Format(PyExc_KeyError, "'%s' has no property '%s'", BK_node_type(self->node), key);
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_get(KitNodeObject *self, PyObject *args)
+{
+ const char *key;
+ if (!PyArg_ParseTuple(args, "s:get", &key) || !self->node) {
+ return NULL;
+ }
+ return PyFloat_FromDouble(BK_get_num(self->node, key));
+}
+
+static PyObject *kitnode_get_str(KitNodeObject *self, PyObject *args)
+{
+ const char *key;
+ if (!PyArg_ParseTuple(args, "s:get_str", &key) || !self->node) {
+ return NULL;
+ }
+ return PyUnicode_FromString(BK_get_str(self->node, key));
+}
+
+static PyObject *kitnode_get_color(KitNodeObject *self, PyObject *args)
+{
+ const char *key = "color";
+ if (!PyArg_ParseTuple(args, "|s:get_color", &key) || !self->node) {
+ return NULL;
+ }
+ float c[4] = {0, 0, 0, 0};
+ BK_get_color(self->node, key, c);
+ return Py_BuildValue("(dddd)", c[0], c[1], c[2], c[3]);
+}
+
+static PyObject *kitnode_strs(KitNodeObject *self, PyObject *args)
+{
+ const char *key = "items";
+ if (!PyArg_ParseTuple(args, "|s:strs", &key) || !self->node) {
+ return NULL;
+ }
+ const int n = BK_strs_count(self->node, key);
+ PyObject *list = PyList_New(n);
+ for (int i = 0; list && i < n; i++) {
+ PyList_SET_ITEM(list, i, PyUnicode_FromString(BK_strs_get(self->node, key, i)));
+ }
+ return list;
+}
+
+static PyObject *kitnode_add(KitNodeObject *self, PyObject *args)
+{
+ PyObject *child;
+ int index = -1;
+ if (!PyArg_ParseTuple(args, "O|i:add", &child, &index) || !self->node) {
+ return NULL;
+ }
+ BKNode *c = node_of(child);
+ if (!c) {
+ return NULL;
+ }
+ BK_node_add(self->node, c, index);
+ Py_INCREF(child);
+ return child;
+}
+
+static PyObject *kitnode_remove(KitNodeObject *self, PyObject *child)
+{
+ BKNode *c = node_of(child);
+ if (!c || !self->node) {
+ return NULL;
+ }
+ BK_node_remove(self->node, c);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_children(KitNodeObject *self, void *closure)
+{
+ const int n = self->node ? BK_node_child_count(self->node) : 0;
+ PyObject *list = PyList_New(n);
+ for (int i = 0; list && i < n; i++) {
+ PyList_SET_ITEM(list, i, node_wrap(BK_node_child(self->node, i)));
+ }
+ return list;
+}
+
+static PyObject *kitnode_parent(KitNodeObject *self, void *closure)
+{
+ return node_wrap(self->node ? BK_node_parent(self->node) : NULL);
+}
+
+static PyObject *kitnode_rect(KitNodeObject *self, void *closure)
+{
+ int r[4] = {0, 0, 0, 0};
+ if (self->node) {
+ BK_node_rect(self->node, r);
+ }
+ return Py_BuildValue("(iiii)", r[0], r[1], r[2], r[3]);
+}
+
+static PyObject *kitnode_coord(KitNodeObject *self, void *closure)
+{
+ int r[4] = {0, 0, 0, 0};
+ if (self->node) {
+ BK_node_rect(self->node, r);
+ }
+ return PyLong_FromLong(r[(intptr_t)closure]);
+}
+
+static PyObject *kitnode_type(KitNodeObject *self, void *closure)
+{
+ return PyUnicode_FromString(self->node ? BK_node_type(self->node) : "");
+}
+
+static PyObject *kitnode_natural(KitNodeObject *self, PyObject *unused)
+{
+ int s[2] = {0, 0};
+ if (self->node) {
+ BK_node_natural(self->node, s);
+ }
+ return Py_BuildValue("(ii)", s[0], s[1]);
+}
+
+static PyObject *kitnode_invalidate(KitNodeObject *self, PyObject *unused)
+{
+ if (self->node) {
+ BK_node_invalidate(self->node);
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_relayout(KitNodeObject *self, PyObject *unused)
+{
+ if (self->node) {
+ BK_node_relayout(self->node);
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_on_event(PyObject *self, PyObject *args)
+{
+ Py_RETURN_NONE; /* overridden by Python components */
+}
+
+/* -- data: ramp / curve / histogram / grid ------------------------------------ */
+
+static PyObject *kitnode_ramp(KitNodeObject *self, PyObject *unused)
+{
+ const int n = BK_ramp_count(self->node);
+ PyObject *list = PyList_New(n);
+ for (int i = 0; list && i < n; i++) {
+ float pos, c[4];
+ BK_ramp_get(self->node, i, &pos, c);
+ PyList_SET_ITEM(list, i, Py_BuildValue("(d(dddd))", pos, c[0], c[1], c[2], c[3]));
+ }
+ return list;
+}
+
+static PyObject *kitnode_set_ramp(KitNodeObject *self, PyObject *stops)
+{
+ PyObject *seq = PySequence_Fast(stops, "stops must be a sequence of (pos, color)");
+ if (!seq) {
+ return NULL;
+ }
+ const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
+ float *pos = (float *)calloc((size_t)(n + 1), sizeof(float));
+ float(*col)[4] = (float(*)[4])calloc((size_t)(n + 1), sizeof(float[4]));
+ for (Py_ssize_t i = 0; i < n; i++) {
+ PyObject *p, *c;
+ if (!PyArg_ParseTuple(PySequence_Fast_GET_ITEM(seq, i), "OO", &p, &c) || !parse_rgba(c, col[i])) {
+ break;
+ }
+ pos[i] = (float)PyFloat_AsDouble(p);
+ }
+ if (!PyErr_Occurred()) {
+ BK_ramp_set(self->node, pos, (const float(*)[4])col, (int)n);
+ }
+ free(pos);
+ free(col);
+ Py_DECREF(seq);
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_ramp_eval(KitNodeObject *self, PyObject *t)
+{
+ float c[4];
+ BK_ramp_evaluate(self->node, (float)PyFloat_AsDouble(t), c);
+ return Py_BuildValue("(dddd)", c[0], c[1], c[2], c[3]);
+}
+
+static PyObject *kitnode_set_ramp_color(KitNodeObject *self, PyObject *c)
+{
+ float rgba[4];
+ if (!parse_rgba(c, rgba)) {
+ return NULL;
+ }
+ BK_ramp_set_active_color(self->node, rgba);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_curve(KitNodeObject *self, PyObject *args)
+{
+ int ch = 0;
+ if (!PyArg_ParseTuple(args, "|i:curve", &ch)) {
+ return NULL;
+ }
+ const int n = BK_curve_count(self->node, ch);
+ PyObject *list = PyList_New(n);
+ for (int i = 0; list && i < n; i++) {
+ float xy[2];
+ BK_curve_get(self->node, ch, i, xy);
+ PyList_SET_ITEM(list, i, Py_BuildValue("(dd)", xy[0], xy[1]));
+ }
+ return list;
+}
+
+static PyObject *kitnode_set_curve(KitNodeObject *self, PyObject *args)
+{
+ int ch;
+ PyObject *pts;
+ if (!PyArg_ParseTuple(args, "iO:set_curve", &ch, &pts)) {
+ return NULL;
+ }
+ PyObject *seq = PySequence_Fast(pts, "points must be a sequence of (x, y)");
+ if (!seq) {
+ return NULL;
+ }
+ const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
+ float(*xy)[2] = (float(*)[2])calloc((size_t)(n + 1), sizeof(float[2]));
+ for (Py_ssize_t i = 0; i < n; i++) {
+ if (!PyArg_ParseTuple(PySequence_Fast_GET_ITEM(seq, i), "ff", &xy[i][0], &xy[i][1])) {
+ break;
+ }
+ }
+ if (!PyErr_Occurred()) {
+ BK_curve_set(self->node, ch, (const float(*)[2])xy, (int)n);
+ }
+ free(xy);
+ Py_DECREF(seq);
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_curve_eval(KitNodeObject *self, PyObject *args)
+{
+ int ch;
+ float x;
+ if (!PyArg_ParseTuple(args, "if:curve_eval", &ch, &x)) {
+ return NULL;
+ }
+ return PyFloat_FromDouble(BK_curve_evaluate(self->node, ch, x));
+}
+
+static PyObject *kitnode_set_histogram(KitNodeObject *self, PyObject *args)
+{
+ PyObject *bins;
+ int channels = 1;
+ if (!PyArg_ParseTuple(args, "O|i:set_histogram", &bins, &channels)) {
+ return NULL;
+ }
+ PyObject *seq = PySequence_Fast(bins, "bins must be a sequence");
+ if (!seq) {
+ return NULL;
+ }
+ const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
+ float *data = (float *)calloc((size_t)(n * channels + 1), sizeof(float));
+ for (Py_ssize_t i = 0; i < n; i++) {
+ PyObject *it = PySequence_Fast_GET_ITEM(seq, i);
+ if (channels == 1) {
+ data[i] = (float)PyFloat_AsDouble(it);
+ }
+ else {
+ for (int c = 0; c < channels; c++) {
+ PyObject *v = PySequence_GetItem(it, c);
+ data[i * channels + c] = v ? (float)PyFloat_AsDouble(v) : 0.0f;
+ Py_XDECREF(v);
+ }
+ }
+ }
+ if (!PyErr_Occurred()) {
+ BK_histogram_set(self->node, data, (int)n, channels);
+ }
+ free(data);
+ Py_DECREF(seq);
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_set_grid_colors(KitNodeObject *self, PyObject *colors)
+{
+ PyObject *seq = PySequence_Fast(colors, "colors must be a sequence");
+ if (!seq) {
+ return NULL;
+ }
+ const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
+ float(*c)[4] = (float(*)[4])calloc((size_t)(n + 1), sizeof(float[4]));
+ for (Py_ssize_t i = 0; i < n; i++) {
+ PyObject *it = PySequence_Fast_GET_ITEM(seq, i);
+ if (it != Py_None && !parse_rgba(it, c[i])) {
+ break;
+ }
+ }
+ if (!PyErr_Occurred()) {
+ BK_gridview_set_colors(self->node, (const float(*)[4])c, (int)n);
+ }
+ free(c);
+ Py_DECREF(seq);
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+/* -- menus: convert MenuItem-like Python objects to BKMenuSpec ---------------- */
+
+static int build_specs(PyObject *items, BKMenuSpec **r_specs, int *r_n);
+
+static void free_specs(BKMenuSpec *specs, int n)
+{
+ for (int i = 0; i < n; i++) {
+ free_specs((BKMenuSpec *)specs[i].sub, specs[i].nsub);
+ }
+ free(specs);
+}
+
+static int build_spec(PyObject *it, BKMenuSpec *s)
+{
+ memset(s, 0, sizeof(*s));
+ s->checked = -1;
+ s->enabled = 1;
+ if (it == Py_None || PyUnicode_Check(it)) {
+ s->text = it == Py_None ? "-" : PyUnicode_AsUTF8(it);
+ return s->text != NULL;
+ }
+ PyObject *v = PyObject_GetAttrString(it, "text");
+ if (!v) {
+ return 0;
+ }
+ s->text = PyUnicode_AsUTF8(v); /* owned by `it`, alive for the call */
+ Py_DECREF(v);
+ if (!s->text) {
+ return 0;
+ }
+#define OPT_ATTR(name, code) \
+ if ((v = PyObject_GetAttrString(it, name)) != NULL) { \
+ if (v != Py_None) { \
+ code; \
+ } \
+ Py_DECREF(v); \
+ } \
+ else { \
+ PyErr_Clear(); \
+ }
+ OPT_ATTR("icon", s->icon = BK_icon_id(PyUnicode_Check(v) ? PyUnicode_AsUTF8(v) : ""));
+ OPT_ATTR("shortcut", s->shortcut = PyUnicode_AsUTF8(v));
+ OPT_ATTR("checked", s->checked = PyObject_IsTrue(v));
+ OPT_ATTR("enabled", s->enabled = PyObject_IsTrue(v));
+ OPT_ATTR("on_click", s->ref = v);
+ OPT_ATTR("submenu", {
+ BKMenuSpec *sub;
+ int nsub;
+ if (!build_specs(v, &sub, &nsub)) {
+ Py_DECREF(v);
+ return 0;
+ }
+ s->sub = sub;
+ s->nsub = nsub;
+ });
+#undef OPT_ATTR
+ return !PyErr_Occurred();
+}
+
+static int build_specs(PyObject *items, BKMenuSpec **r_specs, int *r_n)
+{
+ PyObject *seq = PySequence_Fast(items, "menu items must be a sequence");
+ if (!seq) {
+ return 0;
+ }
+ const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
+ BKMenuSpec *specs = (BKMenuSpec *)calloc((size_t)(n + 1), sizeof(BKMenuSpec));
+ for (Py_ssize_t i = 0; i < n; i++) {
+ if (!build_spec(PySequence_Fast_GET_ITEM(seq, i), &specs[i])) {
+ free_specs(specs, (int)i);
+ Py_DECREF(seq);
+ return 0;
+ }
+ }
+ Py_DECREF(seq);
+ *r_specs = specs;
+ *r_n = (int)n;
+ return 1;
+}
+
+static PyObject *kitnode_set_menu(KitNodeObject *self, PyObject *items)
+{
+ BKMenuSpec *specs;
+ int n;
+ if (!build_specs(items, &specs, &n)) {
+ return NULL;
+ }
+ BK_menubutton_set_items(self->node, specs, n);
+ free_specs(specs, n);
+ Py_RETURN_NONE;
+}
+
+/* -- tree ------------------------------------------------------------------------ */
+
+typedef struct KitTreeItemObject {
+ PyObject_HEAD
+ BKTreeItem *item;
+ PyObject *dict;
+} KitTreeItemObject;
+
+static PyObject *item_wrap(BKTreeItem *it)
+{
+ if (!it || !BK_tree_item_ref(it)) {
+ Py_RETURN_NONE;
+ }
+ PyObject *o = (PyObject *)BK_tree_item_ref(it);
+ Py_INCREF(o);
+ return o;
+}
+
+static PyObject *kitnode_set_tree_roots(KitNodeObject *self, PyObject *roots)
+{
+ PyObject *seq = PySequence_Fast(roots, "roots must be a sequence of KitTreeItem");
+ if (!seq) {
+ return NULL;
+ }
+ const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
+ BKTreeItem **items = (BKTreeItem **)calloc((size_t)(n + 1), sizeof(BKTreeItem *));
+ for (Py_ssize_t i = 0; i < n; i++) {
+ PyObject *it = PySequence_Fast_GET_ITEM(seq, i);
+ if (!PyObject_TypeCheck(it, &KitTreeItem_Type)) {
+ PyErr_SetString(PyExc_TypeError, "expected KitTreeItem");
+ break;
+ }
+ items[i] = ((KitTreeItemObject *)it)->item;
+ }
+ if (!PyErr_Occurred()) {
+ BK_tree_set_roots(self->node, items, (int)n);
+ }
+ free(items);
+ Py_DECREF(seq);
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_tree_selected(KitNodeObject *self, PyObject *unused)
+{
+ return item_wrap(BK_tree_selected(self->node));
+}
+
+static PyObject *kitnode_tree_select(KitNodeObject *self, PyObject *item)
+{
+ BK_tree_select(self->node, item == Py_None ? NULL : ((KitTreeItemObject *)item)->item);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_tree_rows(KitNodeObject *self, PyObject *unused)
+{
+ const int n = BK_tree_row_count(self->node);
+ PyObject *list = PyList_New(n);
+ for (int i = 0; list && i < n; i++) {
+ int r[4];
+ BK_tree_row_rect(self->node, i, r);
+ PyObject *it = item_wrap(BK_tree_row(self->node, i));
+ PyList_SET_ITEM(list, i, Py_BuildValue("(N(iiii))", it, r[0], r[1], r[2], r[3]));
+ }
+ return list;
+}
+
+static PyObject *kit_link_fields(PyObject *mod, PyObject *fields)
+{
+ PyObject *seq = PySequence_Fast(fields, "expected a sequence of number nodes");
+ if (!seq) {
+ return NULL;
+ }
+ const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
+ BKNode **nodes = (BKNode **)calloc((size_t)(n + 1), sizeof(BKNode *));
+ for (Py_ssize_t i = 0; i < n; i++) {
+ nodes[i] = node_of(PySequence_Fast_GET_ITEM(seq, i));
+ if (!nodes[i]) {
+ break;
+ }
+ }
+ if (!PyErr_Occurred()) {
+ BK_link_fields(nodes, (int)n);
+ }
+ free(nodes);
+ Py_DECREF(seq);
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+/* -- geometry managers ----------------------------------------------------------- */
+
+static PyObject *kitnode_geom(KitNodeObject *self, PyObject *args, PyObject *kw)
+{
+ int manager;
+ if (!PyArg_ParseTuple(args, "i:geom", &manager)) {
+ return NULL;
+ }
+ BK_geom_set_manager(self->node, manager);
+ if (kw) {
+ PyObject *key, *value;
+ Py_ssize_t pos = 0;
+ while (PyDict_Next(kw, &pos, &key, &value)) {
+ const double v = PyFloat_AsDouble(value);
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ BK_geom_set(self->node, PyUnicode_AsUTF8(key), v);
+ }
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_geom_get(KitNodeObject *self, PyObject *args)
+{
+ const char *key;
+ if (!PyArg_ParseTuple(args, "s:geom_get", &key)) {
+ return NULL;
+ }
+ return PyFloat_FromDouble(BK_geom_get(self->node, key));
+}
+
+static PyObject *kitnode_grid_weight(KitNodeObject *self, PyObject *args)
+{
+ int column_axis, index, minsize = 0;
+ double weight;
+ if (!PyArg_ParseTuple(args, "iid|i:grid_weight", &column_axis, &index, &weight, &minsize)) {
+ return NULL;
+ }
+ BK_frame_grid_weight(self->node, column_axis, index, weight, minsize);
+ Py_RETURN_NONE;
+}
+
+/* -- canvas ---------------------------------------------------------------------- */
+
+static int opt_rgba(PyObject *v, float out[4])
+{
+ out[0] = out[1] = out[2] = out[3] = 0.0f;
+ if (!v || v == Py_None) {
+ return 1;
+ }
+ return parse_rgba(v, out);
+}
+
+static PyObject *kitnode_canvas_set(KitNodeObject *self, PyObject *args, PyObject *kw)
+{
+ static char *kwlist[] = {"id", "type", "coords", "fill", "outline", "width", "text", "anchor",
+ "radius", "size", "start", "extent", "image", "hidden", NULL};
+ int id, type, anchor = 0, hidden = 0;
+ PyObject *coords, *fill = NULL, *outline = NULL, *image = NULL;
+ float width = 1.0f, radius = 0.0f, size = 0.0f, start = 0.0f, extent = 90.0f;
+ const char *text = NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "iiO|OOfziffffOp:canvas_set", kwlist, &id, &type,
+ &coords, &fill, &outline, &width, &text, &anchor, &radius,
+ &size, &start, &extent, &image, &hidden))
+ {
+ return NULL;
+ }
+ BKCanvasItem it;
+ memset(&it, 0, sizeof(it));
+ it.id = id;
+ it.type = type;
+ it.width = width;
+ it.text = text;
+ it.anchor = anchor;
+ it.radius = radius;
+ it.size = size;
+ it.start = start;
+ it.extent = extent;
+ it.hidden = hidden;
+ if (!opt_rgba(fill, it.fill) || !opt_rgba(outline, it.outline)) {
+ return NULL;
+ }
+ PyObject *seq = PySequence_Fast(coords, "coords must be a sequence of numbers");
+ if (!seq) {
+ return NULL;
+ }
+ const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
+ float *c = (float *)calloc((size_t)(n + 1), sizeof(float));
+ for (Py_ssize_t i = 0; i < n; i++) {
+ c[i] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq, i));
+ }
+ Py_DECREF(seq);
+ it.coords = c;
+ it.ncoords = (int)n;
+ Py_buffer buf = {0};
+ if (image && image != Py_None) {
+ PyObject *data;
+ if (!PyArg_ParseTuple(image, "iiO", &it.iw, &it.ih, &data) ||
+ PyObject_GetBuffer(data, &buf, PyBUF_SIMPLE) < 0)
+ {
+ free(c);
+ return NULL;
+ }
+ if (buf.len < (Py_ssize_t)it.iw * it.ih * 4) {
+ PyBuffer_Release(&buf);
+ free(c);
+ PyErr_SetString(PyExc_ValueError, "image data too short (need w*h*4 RGBA bytes)");
+ return NULL;
+ }
+ it.rgba = (const unsigned char *)buf.buf;
+ }
+ if (!PyErr_Occurred()) {
+ BK_canvas_set_item(self->node, &it);
+ }
+ if (buf.buf) {
+ PyBuffer_Release(&buf);
+ }
+ free(c);
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_canvas_delete(KitNodeObject *self, PyObject *arg)
+{
+ BK_canvas_delete(self->node, (int)PyLong_AsLong(arg));
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_canvas_raise(KitNodeObject *self, PyObject *args)
+{
+ int id, top = 1;
+ if (!PyArg_ParseTuple(args, "i|p:canvas_raise", &id, &top)) {
+ return NULL;
+ }
+ BK_canvas_raise(self->node, id, top);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_set_image(KitNodeObject *self, PyObject *args)
+{
+ int w = 0, h = 0;
+ PyObject *data = Py_None;
+ if (!PyArg_ParseTuple(args, "|iiO:set_image", &w, &h, &data)) {
+ return NULL;
+ }
+ if (data == Py_None) {
+ BK_node_set_image(self->node, NULL, 0, 0);
+ Py_RETURN_NONE;
+ }
+ Py_buffer buf;
+ if (PyObject_GetBuffer(data, &buf, PyBUF_SIMPLE) < 0) {
+ return NULL;
+ }
+ if (buf.len < (Py_ssize_t)w * h * 4) {
+ PyBuffer_Release(&buf);
+ PyErr_SetString(PyExc_ValueError, "image data too short (need w*h*4 RGBA bytes)");
+ return NULL;
+ }
+ BK_node_set_image(self->node, (const unsigned char *)buf.buf, w, h);
+ PyBuffer_Release(&buf);
+ Py_RETURN_NONE;
+}
+
+/* -- text area -------------------------------------------------------------------- */
+
+static PyObject *kitnode_ta_insert(KitNodeObject *self, PyObject *args)
+{
+ int off;
+ const char *text;
+ if (!PyArg_ParseTuple(args, "is:ta_insert", &off, &text)) {
+ return NULL;
+ }
+ BK_textarea_insert(self->node, off, text);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_ta_delete(KitNodeObject *self, PyObject *args)
+{
+ int a, b;
+ if (!PyArg_ParseTuple(args, "ii:ta_delete", &a, &b)) {
+ return NULL;
+ }
+ BK_textarea_delete(self->node, a, b);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_ta_caret(KitNodeObject *self, PyObject *args)
+{
+ int off = -1;
+ if (!PyArg_ParseTuple(args, "|i:ta_caret", &off)) {
+ return NULL;
+ }
+ if (off >= 0) {
+ BK_textarea_set_caret(self->node, off);
+ }
+ return PyLong_FromLong(BK_textarea_caret(self->node));
+}
+
+static PyObject *kitnode_ta_selection(KitNodeObject *self, PyObject *args)
+{
+ int a = -1, b = -1;
+ if (!PyArg_ParseTuple(args, "|ii:ta_selection", &a, &b)) {
+ return NULL;
+ }
+ if (a >= 0) {
+ BK_textarea_set_selection(self->node, a, b);
+ }
+ if (!BK_textarea_selection(self->node, &a, &b)) {
+ Py_RETURN_NONE;
+ }
+ return Py_BuildValue("(ii)", a, b);
+}
+
+static PyObject *kitnode_ta_spans(KitNodeObject *self, PyObject *spans)
+{
+ PyObject *seq = PySequence_Fast(spans, "spans must be [(start, end, fg, bg=None)]");
+ if (!seq) {
+ return NULL;
+ }
+ const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
+ BKTextSpan *out = (BKTextSpan *)calloc((size_t)(n + 1), sizeof(BKTextSpan));
+ for (Py_ssize_t i = 0; i < n; i++) {
+ PyObject *fg = Py_None, *bg = Py_None;
+ BKTextSpan *s = &out[i];
+ if (!PyArg_ParseTuple(PySequence_Fast_GET_ITEM(seq, i), "iiO|O", &s->start, &s->end, &fg,
+ &bg))
+ {
+ break;
+ }
+ s->has_fg = fg != Py_None;
+ s->has_bg = bg != Py_None;
+ if ((s->has_fg && !parse_rgba(fg, s->fg)) || (s->has_bg && !parse_rgba(bg, s->bg))) {
+ break;
+ }
+ }
+ if (!PyErr_Occurred()) {
+ BK_textarea_set_spans(self->node, out, (int)n);
+ }
+ free(out);
+ Py_DECREF(seq);
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitnode_ta_index_at(KitNodeObject *self, PyObject *args)
+{
+ int x, y;
+ if (!PyArg_ParseTuple(args, "ii:ta_index_at", &x, &y)) {
+ return NULL;
+ }
+ return PyLong_FromLong(BK_textarea_index_at(self->node, x, y));
+}
+
+static PyObject *kitnode_ta_see(KitNodeObject *self, PyObject *arg)
+{
+ BK_textarea_see(self->node, (int)PyLong_AsLong(arg));
+ Py_RETURN_NONE;
+}
+
+static PyMethodDef kitnode_methods[] = {
+ {"geom", (PyCFunction)(void (*)(void))kitnode_geom, METH_VARARGS | METH_KEYWORDS,
+ "geom(manager, **params): pack=1 grid=2 place=3 (0 forgets)."},
+ {"geom_get", (PyCFunction)kitnode_geom_get, METH_VARARGS, "geom_get(key) -> float"},
+ {"grid_weight", (PyCFunction)kitnode_grid_weight, METH_VARARGS,
+ "grid_weight(column_axis, index, weight, minsize=0)"},
+ {"canvas_set", (PyCFunction)(void (*)(void))kitnode_canvas_set, METH_VARARGS | METH_KEYWORDS,
+ "canvas_set(id, type, coords, fill=None, outline=None, ...): insert or replace an item."},
+ {"canvas_delete", (PyCFunction)kitnode_canvas_delete, METH_O, "Delete item (id < 0: all)."},
+ {"canvas_raise", (PyCFunction)kitnode_canvas_raise, METH_VARARGS, "Raise/lower an item."},
+ {"set_image", (PyCFunction)kitnode_set_image, METH_VARARGS, "set_image(w, h, rgba_bytes)"},
+ {"ta_insert", (PyCFunction)kitnode_ta_insert, METH_VARARGS, "Insert text at a byte offset."},
+ {"ta_delete", (PyCFunction)kitnode_ta_delete, METH_VARARGS, "Delete [a, b)."},
+ {"ta_caret", (PyCFunction)kitnode_ta_caret, METH_VARARGS, "Get/set the caret offset."},
+ {"ta_selection", (PyCFunction)kitnode_ta_selection, METH_VARARGS, "Get/set the selection."},
+ {"ta_spans", (PyCFunction)kitnode_ta_spans, METH_O,
+ "Styled spans [(a, b, fg_rgba_or_None, bg_rgba_or_None)]."},
+ {"ta_index_at", (PyCFunction)kitnode_ta_index_at, METH_VARARGS,
+ "ta_index_at(x, y): byte offset under a window point."},
+ {"ta_see", (PyCFunction)kitnode_ta_see, METH_O, "Scroll an offset into view."},
+ {"set", (PyCFunction)kitnode_set, METH_VARARGS, "set(key, value): set a property."},
+ {"get", (PyCFunction)kitnode_get, METH_VARARGS, "get(key) -> float"},
+ {"get_str", (PyCFunction)kitnode_get_str, METH_VARARGS, "get_str(key) -> str"},
+ {"get_color", (PyCFunction)kitnode_get_color, METH_VARARGS, "get_color(key='color')"},
+ {"strs", (PyCFunction)kitnode_strs, METH_VARARGS, "strs(key='items') -> list[str]"},
+ {"add", (PyCFunction)kitnode_add, METH_VARARGS, "add(child, index=-1) -> child"},
+ {"remove", (PyCFunction)kitnode_remove, METH_O, "remove(child)"},
+ {"natural", (PyCFunction)kitnode_natural, METH_NOARGS, "natural() -> (w, h)"},
+ {"invalidate", (PyCFunction)kitnode_invalidate, METH_NOARGS, "Redraw this node."},
+ {"relayout", (PyCFunction)kitnode_relayout, METH_NOARGS, "Re-layout the window."},
+ {"_on_event", (PyCFunction)kitnode_on_event, METH_VARARGS, "Callback hook."},
+ {"ramp", (PyCFunction)kitnode_ramp, METH_NOARGS, "ramp() -> [(pos, rgba)]"},
+ {"set_ramp", (PyCFunction)kitnode_set_ramp, METH_O, "set_ramp([(pos, rgba)])"},
+ {"ramp_eval", (PyCFunction)kitnode_ramp_eval, METH_O, "ramp_eval(t) -> rgba"},
+ {"set_ramp_color", (PyCFunction)kitnode_set_ramp_color, METH_O, "Active stop color."},
+ {"curve", (PyCFunction)kitnode_curve, METH_VARARGS, "curve(channel=0) -> [(x, y)]"},
+ {"set_curve", (PyCFunction)kitnode_set_curve, METH_VARARGS, "set_curve(channel, pts)"},
+ {"curve_eval", (PyCFunction)kitnode_curve_eval, METH_VARARGS, "curve_eval(channel, x)"},
+ {"set_histogram", (PyCFunction)kitnode_set_histogram, METH_VARARGS, "set_histogram(bins, ch)"},
+ {"set_grid_colors", (PyCFunction)kitnode_set_grid_colors, METH_O, "Preview colors."},
+ {"set_menu", (PyCFunction)kitnode_set_menu, METH_O, "Menu button items."},
+ {"set_tree_roots", (PyCFunction)kitnode_set_tree_roots, METH_O, "Tree roots."},
+ {"tree_selected", (PyCFunction)kitnode_tree_selected, METH_NOARGS, "Selected item."},
+ {"tree_select", (PyCFunction)kitnode_tree_select, METH_O, "Select an item."},
+ {"tree_rows", (PyCFunction)kitnode_tree_rows, METH_NOARGS, "[(item, rect)] visible rows."},
+ {NULL, NULL, 0, NULL},
+};
+
+static PyGetSetDef kitnode_getset[] = {
+ {"children", (getter)kitnode_children, NULL, "child nodes", NULL},
+ {"parent", (getter)kitnode_parent, NULL, "parent node", NULL},
+ {"rect", (getter)kitnode_rect, NULL, "(x, y, w, h) from the last layout", NULL},
+ {"type", (getter)kitnode_type, NULL, "node type name", NULL},
+ {"x", (getter)kitnode_coord, NULL, "x from the last layout", (void *)0},
+ {"y", (getter)kitnode_coord, NULL, "y from the last layout", (void *)1},
+ {"w", (getter)kitnode_coord, NULL, "width from the last layout", (void *)2},
+ {"h", (getter)kitnode_coord, NULL, "height from the last layout", (void *)3},
+ {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
+ {NULL, NULL, NULL, NULL, NULL},
+};
+
+static PyTypeObject KitNode_Type = {
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name = "buipy.KitNode",
+ .tp_basicsize = sizeof(KitNodeObject),
+ .tp_dealloc = (destructor)kitnode_dealloc,
+ .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
+ .tp_doc = "KitNode(type): a node of the C UI kit (see BUI_kit.h).",
+ .tp_traverse = (traverseproc)kitnode_traverse,
+ .tp_clear = (inquiry)kitnode_clear,
+ .tp_methods = kitnode_methods,
+ .tp_getset = kitnode_getset,
+ .tp_dictoffset = offsetof(KitNodeObject, dict),
+ .tp_init = (initproc)kitnode_init,
+ .tp_new = PyType_GenericNew,
+};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name KitTreeItem
+ * \{ */
+
+static int treeitem_init(KitTreeItemObject *self, PyObject *args, PyObject *kw)
+{
+ const char *label = "", *icon = "";
+ static char *kwlist[] = {"label", "icon", NULL};
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "|sz:KitTreeItem", kwlist, &label, &icon)) {
+ return -1;
+ }
+ if (!self->item) {
+ self->item = BK_tree_item_new(label, BK_icon_id(icon ? icon : ""));
+ BK_tree_item_set_ref(self->item, self);
+ }
+ return 0;
+}
+
+static void treeitem_dealloc(KitTreeItemObject *self)
+{
+ PyObject_GC_UnTrack(self);
+ Py_CLEAR(self->dict);
+ if (self->item) {
+ BK_tree_item_set_ref(self->item, NULL);
+ BK_tree_item_free(self->item);
+ }
+ Py_TYPE(self)->tp_free((PyObject *)self);
+}
+
+static int treeitem_traverse(KitTreeItemObject *self, visitproc visit, void *arg)
+{
+ Py_VISIT(self->dict);
+ return 0;
+}
+
+static int treeitem_clear(KitTreeItemObject *self)
+{
+ Py_CLEAR(self->dict);
+ return 0;
+}
+
+static PyObject *treeitem_add(KitTreeItemObject *self, PyObject *child)
+{
+ if (!PyObject_TypeCheck(child, &KitTreeItem_Type)) {
+ PyErr_SetString(PyExc_TypeError, "expected KitTreeItem");
+ return NULL;
+ }
+ BK_tree_item_add(self->item, ((KitTreeItemObject *)child)->item);
+ Py_INCREF(child);
+ return child;
+}
+
+static PyObject *treeitem_clear_children(KitTreeItemObject *self, PyObject *unused)
+{
+ BK_tree_item_clear(self->item);
+ Py_RETURN_NONE;
+}
+
+static PyObject *treeitem_set(KitTreeItemObject *self, PyObject *args)
+{
+ const char *key;
+ double v;
+ if (!PyArg_ParseTuple(args, "sd:set", &key, &v)) {
+ return NULL;
+ }
+ BK_tree_item_set(self->item, key, v);
+ Py_RETURN_NONE;
+}
+
+static PyObject *treeitem_get(KitTreeItemObject *self, PyObject *args)
+{
+ const char *key;
+ if (!PyArg_ParseTuple(args, "s:get", &key)) {
+ return NULL;
+ }
+ return PyFloat_FromDouble(BK_tree_item_get(self->item, key));
+}
+
+static PyObject *treeitem_get_label(KitTreeItemObject *self, void *c)
+{
+ return PyUnicode_FromString(BK_tree_item_label(self->item));
+}
+
+static int treeitem_set_label(KitTreeItemObject *self, PyObject *v, void *c)
+{
+ const char *s = v ? PyUnicode_AsUTF8(v) : NULL;
+ if (!s) {
+ return -1;
+ }
+ BK_tree_item_set_label(self->item, s);
+ return 0;
+}
+
+static PyObject *treeitem_get_children(KitTreeItemObject *self, void *c)
+{
+ const int n = BK_tree_item_child_count(self->item);
+ PyObject *list = PyList_New(n);
+ for (int i = 0; list && i < n; i++) {
+ PyList_SET_ITEM(list, i, item_wrap(BK_tree_item_child(self->item, i)));
+ }
+ return list;
+}
+
+static PyObject *treeitem_set_values(KitTreeItemObject *self, PyObject *values)
+{
+ PyObject *seq = PySequence_Fast(values, "values must be a sequence of str");
+ if (!seq) {
+ return NULL;
+ }
+ const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
+ const char **v = (const char **)calloc((size_t)(n + 1), sizeof(char *));
+ PyObject **tmp = (PyObject **)calloc((size_t)(n + 1), sizeof(PyObject *));
+ for (Py_ssize_t i = 0; i < n; i++) {
+ tmp[i] = PyObject_Str(PySequence_Fast_GET_ITEM(seq, i));
+ v[i] = tmp[i] ? PyUnicode_AsUTF8(tmp[i]) : "";
+ }
+ if (!PyErr_Occurred()) {
+ BK_tree_item_set_values(self->item, v, (int)n);
+ }
+ for (Py_ssize_t i = 0; i < n; i++) {
+ Py_XDECREF(tmp[i]);
+ }
+ free(tmp);
+ free(v);
+ Py_DECREF(seq);
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyMethodDef treeitem_methods[] = {
+ {"set_values", (PyCFunction)treeitem_set_values, METH_O, "Extra column values."},
+ {"add", (PyCFunction)treeitem_add, METH_O, "add(child) -> child"},
+ {"clear_children", (PyCFunction)treeitem_clear_children, METH_NOARGS,
+ "Detach all child items."},
+ {"set", (PyCFunction)treeitem_set, METH_VARARGS, "set('expanded'|'toggleN', value)"},
+ {"get", (PyCFunction)treeitem_get, METH_VARARGS, "get(key) -> float"},
+ {NULL, NULL, 0, NULL},
+};
+
+static PyGetSetDef treeitem_getset[] = {
+ {"label", (getter)treeitem_get_label, (setter)treeitem_set_label, "label", NULL},
+ {"children", (getter)treeitem_get_children, NULL, "child items", NULL},
+ {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
+ {NULL, NULL, NULL, NULL, NULL},
+};
+
+static PyTypeObject KitTreeItem_Type = {
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name = "buipy.KitTreeItem",
+ .tp_basicsize = sizeof(KitTreeItemObject),
+ .tp_dealloc = (destructor)treeitem_dealloc,
+ .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
+ .tp_doc = "KitTreeItem(label, icon=None): a tree view item.",
+ .tp_traverse = (traverseproc)treeitem_traverse,
+ .tp_clear = (inquiry)treeitem_clear,
+ .tp_methods = treeitem_methods,
+ .tp_getset = treeitem_getset,
+ .tp_dictoffset = offsetof(KitTreeItemObject, dict),
+ .tp_init = (initproc)treeitem_init,
+ .tp_new = PyType_GenericNew,
+};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name KitContext
+ * \{ */
+
+typedef struct KitContextObject {
+ PyObject_HEAD
+ BKContext *ctx;
+ PyObject *root, *header;
+ PyObject *on_request, *on_cursor, *on_warp, *on_clip_get, *on_clip_set, *on_schedule;
+} KitContextObject;
+
+static void call_quiet(PyObject *fn, PyObject *args)
+{
+ if (!fn || fn == Py_None) {
+ return;
+ }
+ PyObject *r = PyObject_CallObject(fn, args);
+ if (!r) {
+ stash_error();
+ }
+ Py_XDECREF(r);
+}
+
+static void host_request(void *data)
+{
+ call_quiet(((KitContextObject *)data)->on_request, NULL);
+}
+
+static void host_set_cursor(void *data, int cursor)
+{
+ PyObject *a = Py_BuildValue("(i)", cursor);
+ call_quiet(((KitContextObject *)data)->on_cursor, a);
+ Py_XDECREF(a);
+}
+
+static void host_warp(void *data, int x, int y)
+{
+ PyObject *a = Py_BuildValue("(ii)", x, y);
+ call_quiet(((KitContextObject *)data)->on_warp, a);
+ Py_XDECREF(a);
+}
+
+static char *host_clip_get(void *data)
+{
+ KitContextObject *self = (KitContextObject *)data;
+ if (!self->on_clip_get || self->on_clip_get == Py_None) {
+ return NULL;
+ }
+ PyObject *r = PyObject_CallObject(self->on_clip_get, NULL);
+ if (!r) {
+ PyErr_Clear(); /* empty / non-text clipboard */
+ return NULL;
+ }
+ char *out = NULL;
+ const char *s = PyUnicode_Check(r) ? PyUnicode_AsUTF8(r) : NULL;
+ if (s) {
+ out = (char *)malloc(strlen(s) + 1);
+ strcpy(out, s);
+ }
+ PyErr_Clear();
+ Py_DECREF(r);
+ return out;
+}
+
+static void host_clip_set(void *data, const char *text)
+{
+ PyObject *a = Py_BuildValue("(s)", text);
+ call_quiet(((KitContextObject *)data)->on_clip_set, a);
+ Py_XDECREF(a);
+}
+
+static void host_schedule(void *data, int ms, int timer)
+{
+ PyObject *a = Py_BuildValue("(ii)", ms, timer);
+ call_quiet(((KitContextObject *)data)->on_schedule, a);
+ Py_XDECREF(a);
+}
+
+static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, double b)
+{
+ if (kind == BK_EV_CALL && ref) {
+ call_quiet((PyObject *)ref, NULL);
+ return;
+ }
+ PyObject *target = node ? (PyObject *)BK_node_ref(node) : NULL;
+ if (!target) {
+ return;
+ }
+ PyObject *r;
+ if ((kind >= BK_EV_PRESS && kind <= BK_EV_WHEEL) || kind == BK_EV_KEYRELEASE) {
+ /* raw events: ref is a C string */
+ r = PyObject_CallMethod(target, "_on_event", "isdd", kind, ref ? (const char *)ref : "", a,
+ b);
+ }
+ else {
+ r = PyObject_CallMethod(target, "_on_event", "iOdd", kind, ref ? (PyObject *)ref : Py_None,
+ a, b);
+ }
+ if (!r) {
+ stash_error();
+ }
+ Py_XDECREF(r);
+}
+
+static int kitctx_init(KitContextObject *self, PyObject *args, PyObject *kw)
+{
+ PyObject *root;
+ if (!PyArg_ParseTuple(args, "O:KitContext", &root)) {
+ return -1;
+ }
+ BKNode *r = node_of(root);
+ if (!r) {
+ return -1;
+ }
+ if (self->ctx) {
+ BK_context_free(self->ctx);
+ }
+ self->ctx = BK_context_new(r);
+ Py_XSETREF(self->root, Py_NewRef(root));
+ BKHost host = {self, host_request, host_set_cursor, host_warp,
+ host_clip_get, host_clip_set, host_schedule, host_emit};
+ BK_context_set_host(self->ctx, &host);
+ return 0;
+}
+
+static void kitctx_dealloc(KitContextObject *self)
+{
+ PyObject_GC_UnTrack(self);
+ if (self->ctx) {
+ BK_context_free(self->ctx);
+ self->ctx = NULL;
+ }
+ Py_CLEAR(self->root);
+ Py_CLEAR(self->header);
+ Py_CLEAR(self->on_request);
+ Py_CLEAR(self->on_cursor);
+ Py_CLEAR(self->on_warp);
+ Py_CLEAR(self->on_clip_get);
+ Py_CLEAR(self->on_clip_set);
+ Py_CLEAR(self->on_schedule);
+ Py_TYPE(self)->tp_free((PyObject *)self);
+}
+
+static int kitctx_traverse(KitContextObject *self, visitproc visit, void *arg)
+{
+ Py_VISIT(self->root);
+ Py_VISIT(self->header);
+ Py_VISIT(self->on_request);
+ Py_VISIT(self->on_cursor);
+ Py_VISIT(self->on_warp);
+ Py_VISIT(self->on_clip_get);
+ Py_VISIT(self->on_clip_set);
+ Py_VISIT(self->on_schedule);
+ return 0;
+}
+
+static int kitctx_clear(KitContextObject *self)
+{
+ Py_CLEAR(self->on_request);
+ Py_CLEAR(self->on_cursor);
+ Py_CLEAR(self->on_warp);
+ Py_CLEAR(self->on_clip_get);
+ Py_CLEAR(self->on_clip_set);
+ Py_CLEAR(self->on_schedule);
+ return 0;
+}
+
+static PyObject *kitctx_set_host(KitContextObject *self, PyObject *args, PyObject *kw)
+{
+ static char *kwlist[] = {"request", "cursor", "warp", "clipboard_get", "clipboard_set",
+ "schedule", NULL};
+ PyObject *req = NULL, *cur = NULL, *warp = NULL, *cg = NULL, *cs = NULL, *sch = NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOO:set_host", kwlist, &req, &cur, &warp, &cg,
+ &cs, &sch))
+ {
+ return NULL;
+ }
+#define SETCB(field, v) \
+ if (v) { \
+ Py_XSETREF(self->field, Py_NewRef(v)); \
+ }
+ SETCB(on_request, req);
+ SETCB(on_cursor, cur);
+ SETCB(on_warp, warp);
+ SETCB(on_clip_get, cg);
+ SETCB(on_clip_set, cs);
+ SETCB(on_schedule, sch);
+#undef SETCB
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitctx_set_header(KitContextObject *self, PyObject *header)
+{
+ if (header == Py_None) {
+ BK_context_set_header(self->ctx, NULL);
+ Py_CLEAR(self->header);
+ Py_RETURN_NONE;
+ }
+ BKNode *h = node_of(header);
+ if (!h) {
+ return NULL;
+ }
+ BK_context_set_header(self->ctx, h);
+ Py_XSETREF(self->header, Py_NewRef(header));
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitctx_render(KitContextObject *self, PyObject *args, PyObject *kw)
+{
+ static char *kwlist[] = {"width", "height", "raster", "full", NULL};
+ int w, h, full = 0;
+ PyObject *raster_obj = Py_None;
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "ii|Op:render", kwlist, &w, &h, &raster_obj, &full)) {
+ return NULL;
+ }
+ BuiRaster *r = raster_obj == Py_None ? buipy_current_raster() : buipy_raster_of(raster_obj);
+ if (!r) {
+ PyErr_SetString(PyExc_RuntimeError, "render: no raster (pass one or set_backend(Raster))");
+ return NULL;
+ }
+ const int regions = BK_render(self->ctx, r, w, h, full);
+ if (restore_error()) {
+ return NULL;
+ }
+ return PyLong_FromLong(regions);
+}
+
+#define INPUT3(name, call) \
+ static PyObject *kitctx_##name(KitContextObject *self, PyObject *args) \
+ { \
+ int x, y, mods = 0; \
+ if (!PyArg_ParseTuple(args, "ii|i:" #name, &x, &y, &mods)) { \
+ return NULL; \
+ } \
+ const int r = call(self->ctx, x, y, mods); \
+ if (restore_error()) { \
+ return NULL; \
+ } \
+ return PyBool_FromLong(r); \
+ }
+
+INPUT3(press, BK_press)
+INPUT3(release, BK_release)
+INPUT3(motion, BK_motion)
+INPUT3(context_menu, BK_context_menu)
+
+static PyObject *kitctx_wheel(KitContextObject *self, PyObject *args)
+{
+ int x, y, delta, mods = 0;
+ if (!PyArg_ParseTuple(args, "iii|i:wheel", &x, &y, &delta, &mods)) {
+ return NULL;
+ }
+ const int r = BK_wheel(self->ctx, x, y, delta, mods);
+ if (restore_error()) {
+ return NULL;
+ }
+ return PyBool_FromLong(r);
+}
+
+static PyObject *kitctx_key(KitContextObject *self, PyObject *args)
+{
+ const char *text, *keysym;
+ int mods = 0;
+ if (!PyArg_ParseTuple(args, "zz|i:key", &text, &keysym, &mods)) {
+ return NULL;
+ }
+ const int r = BK_key(self->ctx, text ? text : "", keysym ? keysym : "", mods);
+ if (restore_error()) {
+ return NULL;
+ }
+ return PyBool_FromLong(r);
+}
+
+static PyObject *kitctx_key_release(KitContextObject *self, PyObject *args)
+{
+ const char *keysym;
+ int mods = 0;
+ if (!PyArg_ParseTuple(args, "s|i:key_release", &keysym, &mods)) {
+ return NULL;
+ }
+ const int r = BK_key_release(self->ctx, keysym, mods);
+ if (restore_error()) {
+ return NULL;
+ }
+ return PyBool_FromLong(r);
+}
+
+static PyObject *kitctx_button(KitContextObject *self, PyObject *args)
+{
+ int x, y, button, release, mods = 0;
+ if (!PyArg_ParseTuple(args, "iiip|i:button", &x, &y, &button, &release, &mods)) {
+ return NULL;
+ }
+ const int r = BK_button(self->ctx, x, y, button, release, mods);
+ if (restore_error()) {
+ return NULL;
+ }
+ return PyBool_FromLong(r);
+}
+
+static PyObject *kitctx_focus_node(KitContextObject *self, PyObject *arg)
+{
+ BKNode *n = NULL;
+ if (arg != Py_None) {
+ if (!PyObject_TypeCheck(arg, &KitNode_Type)) {
+ PyErr_SetString(PyExc_TypeError, "focus_node(node or None)");
+ return NULL;
+ }
+ n = ((KitNodeObject *)arg)->node;
+ }
+ BK_focus_node(self->ctx, n);
+ if (restore_error()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitctx_clipboard_get(KitContextObject *self, PyObject *unused)
+{
+ char *s = BK_clipboard_get(self->ctx);
+ PyObject *r = PyUnicode_FromString(s ? s : "");
+ free(s);
+ return r;
+}
+
+static PyObject *kitctx_clipboard_set(KitContextObject *self, PyObject *arg)
+{
+ const char *s = PyUnicode_AsUTF8(arg);
+ if (!s) {
+ return NULL;
+ }
+ BK_clipboard_set(self->ctx, s);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitctx_timer(KitContextObject *self, PyObject *arg)
+{
+ BK_timer(self->ctx, (int)PyLong_AsLong(arg));
+ if (restore_error()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitctx_bind(KitContextObject *self, PyObject *args)
+{
+ const char *combo;
+ PyObject *fn;
+ if (!PyArg_ParseTuple(args, "sO:bind", &combo, &fn)) {
+ return NULL;
+ }
+ BK_bind(self->ctx, combo, fn);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitctx_close_popups(KitContextObject *self, PyObject *unused)
+{
+ BK_close_popups(self->ctx);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitctx_set_pointer(KitContextObject *self, PyObject *args)
+{
+ int x, y;
+ if (!PyArg_ParseTuple(args, "ii:set_pointer", &x, &y)) {
+ return NULL;
+ }
+ BK_set_pointer(self->ctx, x, y);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitctx_needs_render(KitContextObject *self, PyObject *unused)
+{
+ return PyBool_FromLong(BK_needs_render(self->ctx));
+}
+
+static PyObject *kitctx_popup_count(KitContextObject *self, PyObject *unused)
+{
+ return PyLong_FromLong(BK_popup_count(self->ctx));
+}
+
+static PyObject *kitctx_popup(KitContextObject *self, PyObject *arg)
+{
+ const long i = PyLong_AsLong(arg);
+ BKNode *p = BK_popup(self->ctx, (int)(i < 0 ? BK_popup_count(self->ctx) + i : i));
+ return node_wrap(p);
+}
+
+static PyObject *kitctx_popup_owner(KitContextObject *self, PyObject *arg)
+{
+ const long i = PyLong_AsLong(arg);
+ return node_wrap(BK_popup_owner(self->ctx, (int)(i < 0 ? BK_popup_count(self->ctx) + i : i)));
+}
+
+static PyObject *kitctx_menu_rows(KitContextObject *self, PyObject *arg)
+{
+ const long i = PyLong_AsLong(arg);
+ BKNode *p = BK_popup(self->ctx, (int)(i < 0 ? BK_popup_count(self->ctx) + i : i));
+ if (!p) {
+ return PyList_New(0);
+ }
+ const int n = BK_menu_row_count(p);
+ PyObject *list = PyList_New(n);
+ for (int k = 0; list && k < n; k++) {
+ int r[4];
+ BK_menu_row_rect(p, k, r);
+ PyList_SET_ITEM(list, k,
+ Py_BuildValue("(s(iiii))", BK_menu_row_text(p, k), r[0], r[1], r[2], r[3]));
+ }
+ return list;
+}
+
+static PyObject *kitctx_picker_part(KitContextObject *self, PyObject *args)
+{
+ const char *name;
+ int i = -1;
+ if (!PyArg_ParseTuple(args, "s|i:picker_part", &name, &i)) {
+ return NULL;
+ }
+ BKNode *p = BK_popup(self->ctx, i < 0 ? BK_popup_count(self->ctx) + i : i);
+ return node_wrap(p ? BK_picker_part(p, name) : NULL);
+}
+
+static PyObject *kitctx_open_menu(KitContextObject *self, PyObject *args, PyObject *kw)
+{
+ static char *kwlist[] = {"owner", "items", "title", "at", NULL};
+ PyObject *owner, *items;
+ const char *title = NULL;
+ PyObject *at = Py_None;
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|zO:open_menu", kwlist, &owner, &items, &title,
+ &at))
+ {
+ return NULL;
+ }
+ BKNode *o = owner == Py_None ? NULL : node_of(owner);
+ if (owner != Py_None && !o) {
+ return NULL;
+ }
+ int ax = -100000, ay = -100000;
+ if (at != Py_None && !PyArg_ParseTuple(at, "ii", &ax, &ay)) {
+ return NULL;
+ }
+ BKMenuSpec *specs;
+ int n;
+ if (!build_specs(items, &specs, &n)) {
+ return NULL;
+ }
+ BK_open_menu(self->ctx, o, specs, n, title, ax, ay);
+ free_specs(specs, n);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitctx_open_pie(KitContextObject *self, PyObject *args)
+{
+ PyObject *items;
+ const char *title = NULL;
+ if (!PyArg_ParseTuple(args, "O|z:open_pie", &items, &title)) {
+ return NULL;
+ }
+ BKMenuSpec *specs;
+ int n;
+ if (!build_specs(items, &specs, &n)) {
+ return NULL;
+ }
+ BK_open_pie(self->ctx, specs, n, title);
+ free_specs(specs, n);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitctx_cursor(KitContextObject *self, void *c)
+{
+ return PyLong_FromLong(BK_cursor(self->ctx));
+}
+static PyObject *kitctx_hover(KitContextObject *self, void *c)
+{
+ return node_wrap(BK_hover(self->ctx));
+}
+static PyObject *kitctx_focus(KitContextObject *self, void *c)
+{
+ return node_wrap(BK_focus(self->ctx));
+}
+static PyObject *kitctx_modal(KitContextObject *self, void *c)
+{
+ return PyBool_FromLong(BK_modal_active(self->ctx));
+}
+static PyObject *kitctx_tooltip(KitContextObject *self, void *c)
+{
+ return PyBool_FromLong(BK_tooltip_visible(self->ctx));
+}
+
+static PyObject *kitctx_undo(KitContextObject *self, PyObject *unused)
+{
+ const int r = BK_undo(self->ctx);
+ if (restore_error()) {
+ return NULL;
+ }
+ return PyBool_FromLong(r);
+}
+
+static PyObject *kitctx_redo(KitContextObject *self, PyObject *unused)
+{
+ const int r = BK_redo(self->ctx);
+ if (restore_error()) {
+ return NULL;
+ }
+ return PyBool_FromLong(r);
+}
+
+static PyObject *kitctx_undo_depth(KitContextObject *self, PyObject *unused)
+{
+ int redo = 0;
+ const int undo = BK_undo_depth(self->ctx, &redo);
+ return Py_BuildValue("(ii)", undo, redo);
+}
+
+static PyObject *kitctx_animating(KitContextObject *self, PyObject *unused)
+{
+ return PyBool_FromLong(BK_animating(self->ctx));
+}
+
+static PyMethodDef kitctx_methods[] = {
+ {"undo", (PyCFunction)kitctx_undo, METH_NOARGS, "Undo the last UI edit (Ctrl+Z)."},
+ {"redo", (PyCFunction)kitctx_redo, METH_NOARGS, "Redo (Ctrl+Shift+Z)."},
+ {"undo_depth", (PyCFunction)kitctx_undo_depth, METH_NOARGS, "(undo steps, redo steps)"},
+ {"animating", (PyCFunction)kitctx_animating, METH_NOARGS, "Animations running."},
+ {"set_host", (PyCFunction)(void (*)(void))kitctx_set_host, METH_VARARGS | METH_KEYWORDS,
+ "set_host(request, cursor, warp, clipboard_get, clipboard_set, schedule)"},
+ {"set_header", (PyCFunction)kitctx_set_header, METH_O, "Fixed top bar node."},
+ {"render", (PyCFunction)(void (*)(void))kitctx_render, METH_VARARGS | METH_KEYWORDS,
+ "render(width, height, raster=None, full=False) -> regions redrawn"},
+ {"needs_render", (PyCFunction)kitctx_needs_render, METH_NOARGS, ""},
+ {"press", (PyCFunction)kitctx_press, METH_VARARGS, "press(x, y, mods)"},
+ {"release", (PyCFunction)kitctx_release, METH_VARARGS, "release(x, y, mods)"},
+ {"motion", (PyCFunction)kitctx_motion, METH_VARARGS, "motion(x, y, mods)"},
+ {"context_menu", (PyCFunction)kitctx_context_menu, METH_VARARGS, "Right click."},
+ {"wheel", (PyCFunction)kitctx_wheel, METH_VARARGS, "wheel(x, y, delta, mods)"},
+ {"key", (PyCFunction)kitctx_key, METH_VARARGS, "key(text, keysym, mods)"},
+ {"focus_node", (PyCFunction)kitctx_focus_node, METH_O,
+ "focus_node(node): start editing a text node (None ends editing)."},
+ {"clipboard_get", (PyCFunction)kitctx_clipboard_get, METH_NOARGS, "Clipboard text."},
+ {"clipboard_set", (PyCFunction)kitctx_clipboard_set, METH_O, "Set the clipboard text."},
+ {"key_release", (PyCFunction)kitctx_key_release, METH_VARARGS,
+ "key_release(keysym, mods): raw <KeyRelease> for bindings."},
+ {"button", (PyCFunction)kitctx_button, METH_VARARGS,
+ "button(x, y, button, release, mods): raw press/release of buttons 2/3."},
+ {"timer", (PyCFunction)kitctx_timer, METH_O, "Fire a scheduled timer."},
+ {"bind", (PyCFunction)kitctx_bind, METH_VARARGS, "bind(combo, fn)"},
+ {"close_popups", (PyCFunction)kitctx_close_popups, METH_NOARGS, ""},
+ {"set_pointer", (PyCFunction)kitctx_set_pointer, METH_VARARGS, ""},
+ {"popup_count", (PyCFunction)kitctx_popup_count, METH_NOARGS, ""},
+ {"popup", (PyCFunction)kitctx_popup, METH_O, "Popup node i (borrowed)."},
+ {"popup_owner", (PyCFunction)kitctx_popup_owner, METH_O, ""},
+ {"menu_rows", (PyCFunction)kitctx_menu_rows, METH_O, "[(text, rect)] of menu popup i"},
+ {"picker_part", (PyCFunction)kitctx_picker_part, METH_VARARGS, "Color picker part."},
+ {"open_menu", (PyCFunction)(void (*)(void))kitctx_open_menu, METH_VARARGS | METH_KEYWORDS,
+ "open_menu(owner, items, title=None, at=None)"},
+ {"open_pie", (PyCFunction)kitctx_open_pie, METH_VARARGS, "open_pie(items, title=None)"},
+ {NULL, NULL, 0, NULL},
+};
+
+static PyGetSetDef kitctx_getset[] = {
+ {"cursor", (getter)kitctx_cursor, NULL, "current cursor id", NULL},
+ {"hover", (getter)kitctx_hover, NULL, "hovered node", NULL},
+ {"focus", (getter)kitctx_focus, NULL, "node with text focus", NULL},
+ {"modal", (getter)kitctx_modal, NULL, "modal tool active (eyedropper)", NULL},
+ {"tooltip", (getter)kitctx_tooltip, NULL, "tooltip shown", NULL},
+ {NULL, NULL, NULL, NULL, NULL},
+};
+
+static PyTypeObject KitContext_Type = {
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name = "buipy.KitContext",
+ .tp_basicsize = sizeof(KitContextObject),
+ .tp_dealloc = (destructor)kitctx_dealloc,
+ .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
+ .tp_doc = "KitContext(root): one window's input + rendering context.",
+ .tp_traverse = (traverseproc)kitctx_traverse,
+ .tp_clear = (inquiry)kitctx_clear,
+ .tp_methods = kitctx_methods,
+ .tp_getset = kitctx_getset,
+ .tp_init = (initproc)kitctx_init,
+ .tp_new = PyType_GenericNew,
+};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Module functions
+ * \{ */
+
+static PyObject *kit_set_scale(PyObject *m, PyObject *arg)
+{
+ BK_set_scale((float)PyFloat_AsDouble(arg));
+ Py_RETURN_NONE;
+}
+
+static PyObject *kit_scale(PyObject *m, PyObject *unused)
+{
+ return PyFloat_FromDouble(BK_scale());
+}
+
+static PyObject *kit_unit(PyObject *m, PyObject *unused)
+{
+ return PyLong_FromLong(BK_unit());
+}
+
+static PyObject *kit_set_font(PyObject *m, PyObject *arg)
+{
+ BK_set_font(PyUnicode_AsUTF8(arg));
+ Py_RETURN_NONE;
+}
+
+static PyObject *kit_icon_names(PyObject *m, PyObject *unused)
+{
+ const int n = BK_icon_count();
+ PyObject *list = PyList_New(n);
+ for (int i = 0; list && i < n; i++) {
+ PyList_SET_ITEM(list, i, PyUnicode_FromString(BK_icon_name(i + 1)));
+ }
+ return list;
+}
+
+static PyObject *kit_eval_number(PyObject *m, PyObject *arg)
+{
+ const char *s = PyUnicode_AsUTF8(arg);
+ double v;
+ if (!s) {
+ return NULL;
+ }
+ if (!BK_eval_number(s, &v)) {
+ Py_RETURN_NONE;
+ }
+ return PyFloat_FromDouble(v);
+}
+
+static PyMethodDef kit_functions[] = {
+ {"kit_set_scale", kit_set_scale, METH_O, "UI scale (1.0 = 20 px widgets)."},
+ {"kit_scale", kit_scale, METH_NOARGS, ""},
+ {"kit_unit", kit_unit, METH_NOARGS, "U.widget_unit in pixels."},
+ {"kit_set_font", kit_set_font, METH_O, "UI font family."},
+ {"kit_icon_names", kit_icon_names, METH_NOARGS, "All icon names."},
+ {"kit_eval_number", kit_eval_number, METH_O, "Evaluate number input ('2*pi')."},
+ {"kit_link_fields", kit_link_fields, METH_O, "Link number fields for Alt editing."},
+ {NULL, NULL, 0, NULL},
+};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name KitWindow (native host)
+ * \{ */
+
+typedef struct KitWindowObject {
+ PyObject_HEAD
+ BKWindow *win;
+ PyObject *ctx; /* KitContext (kept alive) */
+ PyObject *timers; /* id -> callable */
+ PyObject *on_close; /* callable -> bool, or None */
+} KitWindowObject;
+
+static int stop_check(void)
+{
+ return g_err_type != NULL; /* a Python callback raised: leave the loop */
+}
+
+static void win_on_timer(void *data, BKWindow *w, int id)
+{
+ KitWindowObject *self = (KitWindowObject *)data;
+ PyObject *key = PyLong_FromLong(id);
+ PyObject *fn = key ? PyDict_GetItemWithError(self->timers, key) : NULL;
+ if (fn) {
+ Py_INCREF(fn);
+ PyDict_DelItem(self->timers, key);
+ call_quiet(fn, NULL);
+ Py_DECREF(fn);
+ }
+ Py_XDECREF(key);
+ if (PyErr_Occurred()) {
+ stash_error();
+ }
+}
+
+static int win_on_close(void *data, BKWindow *w)
+{
+ KitWindowObject *self = (KitWindowObject *)data;
+ if (!self->on_close || self->on_close == Py_None) {
+ return 1;
+ }
+ PyObject *r = PyObject_CallObject(self->on_close, NULL);
+ if (!r) {
+ stash_error();
+ return 1;
+ }
+ const int allow = (r == Py_None) ? 0 : PyObject_IsTrue(r); /* Tk protocol: handler decides */
+ Py_DECREF(r);
+ return allow;
+}
+
+static int kitwin_init(KitWindowObject *self, PyObject *args, PyObject *kw)
+{
+ static char *kwlist[] = {"context", "title", "width", "height", NULL};
+ PyObject *ctx;
+ const char *title = "BUI";
+ int w = 640, h = 480;
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "O|sii:KitWindow", kwlist, &ctx, &title, &w, &h)) {
+ return -1;
+ }
+ if (!PyObject_TypeCheck(ctx, &KitContext_Type)) {
+ PyErr_SetString(PyExc_TypeError, "KitWindow needs a KitContext");
+ return -1;
+ }
+ if (!BK_window_supported()) {
+ PyErr_SetString(PyExc_NotImplementedError, "native windows are not supported here");
+ return -1;
+ }
+ self->win = BK_window_new(((KitContextObject *)ctx)->ctx, title, w, h);
+ if (!self->win) {
+ PyErr_SetString(PyExc_OSError, "could not create the native window");
+ return -1;
+ }
+ Py_XSETREF(self->ctx, Py_NewRef(ctx));
+ Py_XSETREF(self->timers, PyDict_New());
+ BKWindowCallbacks cb = {self, win_on_timer, win_on_close};
+ BK_window_set_callbacks(self->win, &cb);
+ return 0;
+}
+
+static void kitwin_dealloc(KitWindowObject *self)
+{
+ PyObject_GC_UnTrack(self);
+ if (self->win) {
+ BK_window_free(self->win);
+ self->win = NULL;
+ }
+ Py_CLEAR(self->ctx);
+ Py_CLEAR(self->timers);
+ Py_CLEAR(self->on_close);
+ Py_TYPE(self)->tp_free((PyObject *)self);
+}
+
+static int kitwin_traverse(KitWindowObject *self, visitproc visit, void *arg)
+{
+ Py_VISIT(self->ctx);
+ Py_VISIT(self->timers);
+ Py_VISIT(self->on_close);
+ return 0;
+}
+
+static int kitwin_clear(KitWindowObject *self)
+{
+ Py_CLEAR(self->timers);
+ Py_CLEAR(self->on_close);
+ return 0;
+}
+
+static PyObject *kitwin_show(KitWindowObject *self, PyObject *unused)
+{
+ BK_window_show(self->win);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitwin_close(KitWindowObject *self, PyObject *unused)
+{
+ BK_window_close(self->win);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitwin_is_open(KitWindowObject *self, PyObject *unused)
+{
+ return PyBool_FromLong(BK_window_is_open(self->win));
+}
+
+static PyObject *kitwin_set_title(KitWindowObject *self, PyObject *arg)
+{
+ const char *t = PyUnicode_AsUTF8(arg);
+ if (!t) {
+ return NULL;
+ }
+ BK_window_set_title(self->win, t);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitwin_set_size(KitWindowObject *self, PyObject *args)
+{
+ int w, h;
+ if (!PyArg_ParseTuple(args, "ii:set_size", &w, &h)) {
+ return NULL;
+ }
+ BK_window_set_size(self->win, w, h);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitwin_wm(KitWindowObject *self, PyObject *args)
+{
+ const char *key;
+ double a = 0.0, b = 0.0;
+ if (!PyArg_ParseTuple(args, "s|dd:wm", &key, &a, &b)) {
+ return NULL;
+ }
+ BK_window_wm(self->win, key, a, b);
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitwin_wm_get(KitWindowObject *self, PyObject *args)
+{
+ const char *key;
+ if (!PyArg_ParseTuple(args, "s:wm_get", &key)) {
+ return NULL;
+ }
+ double a, b;
+ if (!BK_window_wm_get(self->win, key, &a, &b)) {
+ Py_RETURN_NONE;
+ }
+ return Py_BuildValue("(dd)", a, b);
+}
+
+static PyObject *kitwin_size(KitWindowObject *self, void *c)
+{
+ int w, h;
+ BK_window_get_size(self->win, &w, &h);
+ return Py_BuildValue("(ii)", w, h);
+}
+
+static PyObject *kitwin_frames(KitWindowObject *self, void *c)
+{
+ return PyLong_FromLong(BK_window_frames(self->win));
+}
+
+static PyObject *kitwin_hwnd(KitWindowObject *self, void *c)
+{
+ return PyLong_FromVoidPtr(BK_window_handle(self->win));
+}
+
+static PyObject *kitwin_render_now(KitWindowObject *self, PyObject *unused)
+{
+ BK_window_render_now(self->win);
+ if (restore_error()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitwin_pixel(KitWindowObject *self, PyObject *args)
+{
+ int x, y;
+ if (!PyArg_ParseTuple(args, "ii:pixel", &x, &y)) {
+ return NULL;
+ }
+ BuiRaster *r = BK_window_raster(self->win);
+ const int w = BUI_raster_width(r), h = BUI_raster_height(r);
+ if (x < 0 || y < 0 || x >= w || y >= h) {
+ PyErr_SetString(PyExc_IndexError, "pixel out of range");
+ return NULL;
+ }
+ const uint32_t p = BUI_raster_pixels(r)[(size_t)y * w + x];
+ return Py_BuildValue("(iii)", (int)((p >> 16) & 255), (int)((p >> 8) & 255), (int)(p & 255));
+}
+
+static PyObject *kitwin_after(KitWindowObject *self, PyObject *args)
+{
+ int ms;
+ PyObject *fn;
+ if (!PyArg_ParseTuple(args, "iO:after", &ms, &fn)) {
+ return NULL;
+ }
+ const int id = BK_window_timer(self->win, ms);
+ PyObject *key = PyLong_FromLong(id);
+ if (!key || PyDict_SetItem(self->timers, key, fn) < 0) {
+ Py_XDECREF(key);
+ return NULL;
+ }
+ return key;
+}
+
+static PyObject *kitwin_after_cancel(KitWindowObject *self, PyObject *arg)
+{
+ const long id = PyLong_AsLong(arg);
+ if (id == -1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ BK_window_cancel_timer(self->win, (int)id);
+ if (PyDict_DelItem(self->timers, arg) < 0) {
+ PyErr_Clear();
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kitwin_get_on_close(KitWindowObject *self, void *c)
+{
+ return Py_NewRef(self->on_close ? self->on_close : Py_None);
+}
+
+static int kitwin_set_on_close(KitWindowObject *self, PyObject *v, void *c)
+{
+ Py_XSETREF(self->on_close, Py_NewRef(v ? v : Py_None));
+ return 0;
+}
+
+static PyMethodDef kitwin_methods[] = {
+ {"show", (PyCFunction)kitwin_show, METH_NOARGS, ""},
+ {"close", (PyCFunction)kitwin_close, METH_NOARGS, ""},
+ {"is_open", (PyCFunction)kitwin_is_open, METH_NOARGS, ""},
+ {"set_title", (PyCFunction)kitwin_set_title, METH_O, ""},
+ {"set_size", (PyCFunction)kitwin_set_size, METH_VARARGS, "Logical size (DPI scaled)."},
+ {"wm", (PyCFunction)kitwin_wm, METH_VARARGS,
+ "wm(key, a=0, b=0): pos, minsize, maxsize, resizable, topmost, alpha, override, state, "
+ "lift, lower, focus."},
+ {"wm_get", (PyCFunction)kitwin_wm_get, METH_VARARGS,
+ "wm_get(key) -> (a, b) or None: pos, state, screen, pointer, scale."},
+ {"render_now", (PyCFunction)kitwin_render_now, METH_NOARGS, "Render + present now."},
+ {"pixel", (PyCFunction)kitwin_pixel, METH_VARARGS, "Frame buffer pixel (r, g, b)."},
+ {"after", (PyCFunction)kitwin_after, METH_VARARGS, "after(ms, fn) -> id (one-shot)."},
+ {"after_cancel", (PyCFunction)kitwin_after_cancel, METH_O, ""},
+ {NULL, NULL, 0, NULL},
+};
+
+static PyGetSetDef kitwin_getset[] = {
+ {"size", (getter)kitwin_size, NULL, "client size in pixels", NULL},
+ {"frames", (getter)kitwin_frames, NULL, "presented frames", NULL},
+ {"hwnd", (getter)kitwin_hwnd, NULL, "native handle", NULL},
+ {"on_close", (getter)kitwin_get_on_close, (setter)kitwin_set_on_close,
+ "called on the close button; return True to close", NULL},
+ {NULL, NULL, NULL, NULL, NULL},
+};
+
+static PyTypeObject KitWindow_Type = {
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name = "buipy.KitWindow",
+ .tp_basicsize = sizeof(KitWindowObject),
+ .tp_dealloc = (destructor)kitwin_dealloc,
+ .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
+ .tp_doc = "KitWindow(context, title='BUI', width=640, height=480): native window.",
+ .tp_traverse = (traverseproc)kitwin_traverse,
+ .tp_clear = (inquiry)kitwin_clear,
+ .tp_methods = kitwin_methods,
+ .tp_getset = kitwin_getset,
+ .tp_init = (initproc)kitwin_init,
+ .tp_new = PyType_GenericNew,
+};
+
+static PyObject *kit_run(PyObject *m, PyObject *unused)
+{
+ BK_window_run();
+ if (restore_error()) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *kit_pump(PyObject *m, PyObject *unused)
+{
+ const int open = BK_window_pump();
+ if (restore_error()) {
+ return NULL;
+ }
+ return PyLong_FromLong(open);
+}
+
+static PyObject *kit_quit(PyObject *m, PyObject *unused)
+{
+ BK_window_quit();
+ Py_RETURN_NONE;
+}
+
+static PyObject *kit_window_supported(PyObject *m, PyObject *unused)
+{
+ return PyBool_FromLong(BK_window_supported());
+}
+
+static PyObject *kit_set_animations(PyObject *m, PyObject *arg)
+{
+ BK_set_animations(PyObject_IsTrue(arg));
+ Py_RETURN_NONE;
+}
+
+static PyMethodDef window_functions[] = {
+ {"kit_run", kit_run, METH_NOARGS, "Run the native message loop until all windows close."},
+ {"kit_pump", kit_pump, METH_NOARGS, "Handle pending native messages; returns open windows."},
+ {"kit_quit", kit_quit, METH_NOARGS, "Leave kit_run()."},
+ {"kit_window_supported", kit_window_supported, METH_NOARGS, ""},
+ {"kit_set_animations", kit_set_animations, METH_O, "Enable/disable UI animations."},
+ {NULL, NULL, 0, NULL},
+};
+
+/** \} */
+
+int buipy_kit_init(PyObject *module)
+{
+ if (PyType_Ready(&KitNode_Type) < 0 || PyType_Ready(&KitTreeItem_Type) < 0 ||
+ PyType_Ready(&KitContext_Type) < 0 || PyType_Ready(&KitWindow_Type) < 0)
+ {
+ return -1;
+ }
+ if (PyModule_AddObjectRef(module, "KitWindow", (PyObject *)&KitWindow_Type) < 0 ||
+ PyModule_AddFunctions(module, window_functions) < 0)
+ {
+ return -1;
+ }
+ BK_window_set_stop_check(stop_check);
+ if (PyModule_AddObjectRef(module, "KitNode", (PyObject *)&KitNode_Type) < 0 ||
+ PyModule_AddObjectRef(module, "KitTreeItem", (PyObject *)&KitTreeItem_Type) < 0 ||
+ PyModule_AddObjectRef(module, "KitContext", (PyObject *)&KitContext_Type) < 0)
+ {
+ return -1;
+ }
+ if (PyModule_AddFunctions(module, kit_functions) < 0) {
+ return -1;
+ }
+ BK_set_ref_hooks(ref_retain, ref_release);
+ return 0;
+}
+
+
diff --git a/bindings/python/src/buipy_module.c b/bindings/python/src/buipy_module.c
new file mode 100644
index 0000000..273a287
--- /dev/null
+++ b/bindings/python/src/buipy_module.c
@@ -0,0 +1,1289 @@
+/* buipy — CPython bindings for the BUI stable C API.
+ *
+ * Lets Python hosts receive every primitive the BUI toolkit draws through a
+ * "sink" object (see bui.Backend) and drive the toolkit's GPU seam. Qt hosts
+ * should use bui.qt.BuiCanvas, which installs a QPainter backend on top of
+ * this module.
+ *
+ * Build: linked against bui_api + bui_gpu; no third-party dependencies.
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#define PY_SSIZE_T_CLEAN
+#include <Python.h>
+
+#include "bui_c_api.h"
+#include "GPU_raster.h"
+
+#include <stdint.h>
+#include <stdio.h>
+
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* Current text font (set_font); applies to Raster targets. */
+static char g_font_family[64] = "";
+static int g_font_flags = 0;
+
+/* -------------------------------------------------------------------- */
+/** \name Sink holder: forwards BUI primitives to a Python object
+ * \{ */
+
+typedef struct BuiPySinkHolder {
+ PyObject *backend; /* owned reference; methods looked up per call */
+} BuiPySinkHolder;
+
+static BuiPySinkHolder *g_holder = NULL;
+
+/* Call `backend.method(args...)`; returns without touching exceptions on
+ * failure other than printing them, so the C draw path stays alive. */
+static void buipy_call_backend(const char *method, const char *format, ...)
+{
+ if (!g_holder || !g_holder->backend) {
+ return;
+ }
+ PyGILState_STATE gstate = PyGILState_Ensure();
+ PyObject *func = PyObject_GetAttrString(g_holder->backend, method);
+ if (func && PyCallable_Check(func)) {
+ va_list args;
+ va_start(args, format);
+ PyObject *argtuple = Py_VaBuildValue(format, args);
+ va_end(args);
+ if (argtuple) {
+ PyObject *result = PyObject_CallObject(func, argtuple);
+ if (result == NULL) {
+ PyErr_Print();
+ }
+ else {
+ Py_DECREF(result);
+ }
+ Py_DECREF(argtuple);
+ }
+ else {
+ PyErr_Print();
+ }
+ }
+ Py_XDECREF(func);
+ PyGILState_Release(gstate);
+}
+
+static void sink_begin_frame(void *user, int w, int h)
+{
+ buipy_call_backend("begin_frame", "(ii)", w, h);
+}
+
+static void sink_scissor(void *user, int x, int y, int w, int h)
+{
+ buipy_call_backend("scissor", "(iiii)", x, y, w, h);
+}
+
+/* coords: float[count][2]; colors: float[count][4]. */
+static PyObject *bui_coords_list(const float (*coords)[2], int count)
+{
+ PyObject *list = PyList_New(count);
+ for (int i = 0; i < count; i++) {
+ PyList_SET_ITEM(list, i, Py_BuildValue("(ff)", coords[i][0], coords[i][1]));
+ }
+ return list;
+}
+static PyObject *bui_colors_list(const float (*colors)[4], int count)
+{
+ PyObject *list = PyList_New(count);
+ for (int i = 0; i < count; i++) {
+ PyList_SET_ITEM(
+ list, i, Py_BuildValue("(ffff)", colors[i][0], colors[i][1], colors[i][2], colors[i][3]));
+ }
+ return list;
+}
+
+static void sink_triangles(void *user,
+ const float (*coords)[2],
+ const float (*colors)[4],
+ int count)
+{
+ PyObject *c = bui_coords_list(coords, count);
+ PyObject *k = bui_colors_list(colors, count);
+ buipy_call_backend("triangles", "(NN)", c, k);
+}
+
+static void sink_lines(void *user,
+ const float (*coords)[2],
+ const float (*colors)[4],
+ int count)
+{
+ PyObject *c = bui_coords_list(coords, count);
+ PyObject *k = bui_colors_list(colors, count);
+ buipy_call_backend("lines", "(NN)", c, k);
+}
+
+static void sink_points(void *user,
+ const float (*coords)[2],
+ const float (*colors)[4],
+ int count,
+ float size)
+{
+ PyObject *c = bui_coords_list(coords, count);
+ PyObject *k = bui_colors_list(colors, count);
+ buipy_call_backend("points", "(NNf)", c, k, size);
+}
+
+static void sink_text(void *user,
+ float x,
+ float y,
+ const char *text,
+ float size,
+ const float rgba[4])
+{
+ buipy_call_backend(
+ "text", "(ffs#f(ffff))", x, y, text, (Py_ssize_t)strlen(text), size, rgba[0], rgba[1],
+ rgba[2], rgba[3]);
+}
+
+static void sink_end_frame(void *user)
+{
+ buipy_call_backend("end_frame", "()");
+}
+
+static BuiGpuSink g_py_sink = {
+ NULL,
+ sink_begin_frame,
+ sink_scissor,
+ sink_triangles,
+ sink_lines,
+ sink_points,
+ sink_text,
+ sink_end_frame,
+};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Demo scene: exercises the GPU seam from C
+ * \{ */
+
+/* Draws a small showcase (rects, lines, points) through the immediate-mode
+ * seam; everything flows into the installed backend. */
+static PyObject *buipy_demo_scene(PyObject *self, PyObject *args)
+{
+ int w = 640, h = 480;
+ if (!PyArg_ParseTuple(args, "|ii:demo_scene", &w, &h)) {
+ return NULL;
+ }
+ const BuiGpuSink *sink = bui_get_render_sink();
+ if (sink && sink->begin_frame) {
+ sink->begin_frame(sink->user, w, h);
+ }
+ bui_set_viewport(w, h);
+
+ const float panel[4] = {0.16f, 0.16f, 0.18f, 1.0f};
+ const float accent[4] = {0.25f, 0.47f, 0.85f, 1.0f};
+ const float white[4] = {0.92f, 0.92f, 0.94f, 1.0f};
+ const float line_col[4] = {0.4f, 0.7f, 0.95f, 1.0f};
+
+ /* Filled panel (two triangles). */
+ float coords[6][2] = {{40, 40}, {w - 40, 40}, {w - 40, h - 40}, {40, 40}, {w - 40, h - 40}, {40, h - 40}};
+ float colors[12][4]; /* reused below for up to NPTS (12) points */
+ for (int i = 0; i < 6; i++) {
+ memcpy(colors[i], panel, sizeof(panel));
+ }
+ if (sink && sink->triangles) {
+ sink->triangles(sink->user, coords, colors, 6);
+ }
+
+ /* Accent bar. */
+ float bar[6][2] = {{40, 40}, {w - 40, 40}, {w - 40, 70}, {40, 40}, {w - 40, 70}, {40, 70}};
+ for (int i = 0; i < 6; i++) {
+ memcpy(colors[i], accent, sizeof(accent));
+ }
+ if (sink && sink->triangles) {
+ sink->triangles(sink->user, bar, colors, 6);
+ }
+
+ /* Cross lines. */
+ float lc[4][2] = {{40, 80}, {w - 40, h - 40}, {40, h - 40}, {w - 40, 80}};
+ for (int i = 0; i < 4; i++) {
+ memcpy(colors[i], line_col, sizeof(line_col));
+ }
+ if (sink && sink->lines) {
+ sink->lines(sink->user, lc, colors, 4);
+ }
+
+ /* Diagonal point row. */
+ enum { NPTS = 12 };
+ float pc[NPTS][2];
+ for (int i = 0; i < NPTS; i++) {
+ pc[i][0] = 80.0f + i * ((w - 160.0f) / (NPTS - 1));
+ pc[i][1] = h - 80.0f;
+ }
+ for (int i = 0; i < NPTS; i++) {
+ memcpy(colors[i], white, sizeof(white));
+ }
+ if (sink && sink->points) {
+ sink->points(sink->user, pc, colors, NPTS, 3.0f);
+ }
+
+ if (sink && sink->text) {
+ sink->text(sink->user, 60.0f, 110.0f, "BUI demo scene", 14.0f, white);
+ }
+
+ if (sink && sink->end_frame) {
+ sink->end_frame(sink->user);
+ }
+ Py_RETURN_NONE;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Raster target: native frame renderer (GPU_raster.h)
+ *
+ * When a Raster is the active target, every draw_* call below renders
+ * straight into its frame buffer in C — no Python callbacks, no per-primitive
+ * host objects. Hosts then present the frame with one blit per damaged rect.
+ * \{ */
+
+typedef struct BuiPyRaster {
+ PyObject_HEAD
+ BuiRaster *raster;
+ PyObject *text_runs; /* list of fallback text runs when no native text */
+} BuiPyRaster;
+
+static PyTypeObject BuiPyRaster_Type;
+
+/* Active raster target (borrowed by the C seam, owned reference here). */
+static BuiPyRaster *g_target = NULL;
+
+static int raster_init(BuiPyRaster *self, PyObject *args, PyObject *kw)
+{
+ int w = 1, h = 1;
+ static char *kwlist[] = {"width", "height", NULL};
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "|ii:Raster", kwlist, &w, &h)) {
+ return -1;
+ }
+ if (self->raster) {
+ BUI_raster_free(self->raster);
+ }
+ self->raster = BUI_raster_create(w, h);
+ if (!self->raster) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ Py_XSETREF(self->text_runs, PyList_New(0));
+ return self->text_runs ? 0 : -1;
+}
+
+static void raster_dealloc(BuiPyRaster *self)
+{
+ if (g_target == self) {
+ g_target = NULL;
+ bui_set_render_sink(NULL);
+ }
+ BUI_raster_free(self->raster);
+ Py_XDECREF(self->text_runs);
+ Py_TYPE(self)->tp_free((PyObject *)self);
+}
+
+static PyObject *raster_size(BuiPyRaster *self, void *closure)
+{
+ (void)closure;
+ return Py_BuildValue("(ii)", BUI_raster_width(self->raster), BUI_raster_height(self->raster));
+}
+
+static PyObject *raster_damage(BuiPyRaster *self, PyObject *noargs)
+{
+ (void)noargs;
+ const int(*rects)[4];
+ const int n = BUI_raster_damage(self->raster, &rects);
+ PyObject *list = PyList_New(n);
+ for (int i = 0; i < n; i++) {
+ PyList_SET_ITEM(list, i, Py_BuildValue("(iiii)", rects[i][0], rects[i][1], rects[i][2], rects[i][3]));
+ }
+ return list;
+}
+
+static PyObject *raster_invalidate(BuiPyRaster *self, PyObject *noargs)
+{
+ (void)noargs;
+ BUI_raster_invalidate(self->raster);
+ Py_RETURN_NONE;
+}
+
+/* present_native(window_handle, full=False) -> bool */
+static PyObject *raster_present_native(BuiPyRaster *self, PyObject *args)
+{
+ unsigned long long handle = 0;
+ int full = 0;
+ if (!PyArg_ParseTuple(args, "K|p:present_native", &handle, &full)) {
+ return NULL;
+ }
+ return PyBool_FromLong(BUI_raster_present_native(self->raster, (void *)(uintptr_t)handle, full));
+}
+
+/* ppm(x, y, w, h) -> bytes: binary P6 of a sub-rect (Tk PhotoImage.put). */
+static PyObject *raster_ppm(BuiPyRaster *self, PyObject *args)
+{
+ int x, y, w, h;
+ if (!PyArg_ParseTuple(args, "iiii:ppm", &x, &y, &w, &h)) {
+ return NULL;
+ }
+ const int rw = BUI_raster_width(self->raster), rh = BUI_raster_height(self->raster);
+ if (x < 0) { w += x; x = 0; }
+ if (y < 0) { h += y; y = 0; }
+ if (x + w > rw) { w = rw - x; }
+ if (y + h > rh) { h = rh - y; }
+ if (w <= 0 || h <= 0) {
+ return PyBytes_FromStringAndSize(NULL, 0);
+ }
+ char header[64];
+ const int hl = snprintf(header, sizeof(header), "P6\n%d %d\n255\n", w, h);
+ PyObject *out = PyBytes_FromStringAndSize(NULL, hl + (Py_ssize_t)w * h * 3);
+ if (!out) {
+ return NULL;
+ }
+ unsigned char *dst = (unsigned char *)PyBytes_AS_STRING(out);
+ memcpy(dst, header, (size_t)hl);
+ dst += hl;
+ const uint32_t *pix = BUI_raster_pixels(self->raster);
+ for (int row = 0; row < h; row++) {
+ const uint32_t *src = pix + (size_t)(y + row) * rw + x;
+ for (int col = 0; col < w; col++) {
+ const uint32_t p = src[col];
+ *dst++ = (unsigned char)(p >> 16);
+ *dst++ = (unsigned char)(p >> 8);
+ *dst++ = (unsigned char)p;
+ }
+ }
+ return out;
+}
+
+/* rgb32() -> bytes: the whole frame, 0x00RRGGBB little-endian (QImage
+ * Format_RGB32 / Win32 DIB layout). */
+static PyObject *raster_rgb32(BuiPyRaster *self, PyObject *noargs)
+{
+ (void)noargs;
+ const int rw = BUI_raster_width(self->raster), rh = BUI_raster_height(self->raster);
+ return PyBytes_FromStringAndSize((const char *)BUI_raster_pixels(self->raster),
+ (Py_ssize_t)rw * rh * 4);
+}
+
+/* pixel(x, y) -> (r, g, b) — for tests and color pickers. */
+static PyObject *raster_pixel(BuiPyRaster *self, PyObject *args)
+{
+ int x, y;
+ if (!PyArg_ParseTuple(args, "ii:pixel", &x, &y)) {
+ return NULL;
+ }
+ const int rw = BUI_raster_width(self->raster), rh = BUI_raster_height(self->raster);
+ if (x < 0 || y < 0 || x >= rw || y >= rh) {
+ PyErr_SetString(PyExc_IndexError, "pixel out of range");
+ return NULL;
+ }
+ const uint32_t p = BUI_raster_pixels(self->raster)[(size_t)y * rw + x];
+ return Py_BuildValue("(iii)", (int)((p >> 16) & 255), (int)((p >> 8) & 255), (int)(p & 255));
+}
+
+/* text_runs() -> list of (x, y, text, size, rgba, family, flags) drawn this
+ * frame that the host must render itself (only when no native text). */
+static PyObject *raster_text_runs(BuiPyRaster *self, PyObject *noargs)
+{
+ (void)noargs;
+ return Py_NewRef(self->text_runs);
+}
+
+static PyMethodDef raster_methods[] = {
+ {"damage", (PyCFunction)raster_damage, METH_NOARGS,
+ "damage() -> [(x, y, w, h)]: regions that changed in the last frame."},
+ {"invalidate", (PyCFunction)raster_invalidate, METH_NOARGS,
+ "invalidate(): report the whole frame as damaged next time."},
+ {"present_native", (PyCFunction)raster_present_native, METH_VARARGS,
+ "present_native(hwnd, full=False) -> bool: blit damage to a native window."},
+ {"ppm", (PyCFunction)raster_ppm, METH_VARARGS, "ppm(x, y, w, h) -> bytes (binary P6)."},
+ {"rgb32", (PyCFunction)raster_rgb32, METH_NOARGS, "rgb32() -> bytes (QImage Format_RGB32)."},
+ {"pixel", (PyCFunction)raster_pixel, METH_VARARGS, "pixel(x, y) -> (r, g, b)."},
+ {"text_runs", (PyCFunction)raster_text_runs, METH_NOARGS,
+ "text_runs() -> host-drawn text runs for this frame (no native text engine)."},
+ {NULL, NULL, 0, NULL},
+};
+
+static PyGetSetDef raster_getset[] = {
+ {"size", (getter)raster_size, NULL, "(width, height) of the frame buffer", NULL},
+ {NULL, NULL, NULL, NULL, NULL},
+};
+
+static PyTypeObject BuiPyRaster_Type = {
+ PyVarObject_HEAD_INIT(NULL, 0)
+ .tp_name = "buipy.Raster",
+ .tp_basicsize = sizeof(BuiPyRaster),
+ .tp_dealloc = (destructor)raster_dealloc,
+ .tp_flags = Py_TPFLAGS_DEFAULT,
+ .tp_doc = "Raster(width, height): native anti-aliased frame renderer.\n\n"
+ "Pass to buipy.set_backend() to render everything in C, then present\n"
+ "with present_native() / ppm() / rgb32().",
+ .tp_methods = raster_methods,
+ .tp_getset = raster_getset,
+ .tp_init = (initproc)raster_init,
+ .tp_new = PyType_GenericNew,
+};
+
+/* Fast RGBA parse: tuples of 4 numbers (the model's color format). */
+static int parse_color(PyObject *color, float rgba[4])
+{
+ if (PyTuple_CheckExact(color) && PyTuple_GET_SIZE(color) == 4) {
+ for (int i = 0; i < 4; i++) {
+ PyObject *v = PyTuple_GET_ITEM(color, i);
+ rgba[i] = (float)(PyFloat_CheckExact(v) ? PyFloat_AS_DOUBLE(v) : PyFloat_AsDouble(v));
+ }
+ return PyErr_Occurred() ? 0 : 1;
+ }
+ return PyArg_ParseTuple(color, "ffff", &rgba[0], &rgba[1], &rgba[2], &rgba[3]);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Drawing API: drive the BUI seam from Python
+ *
+ * These emit primitives directly into the installed sink, so pure-Python UI
+ * layers (Qt-syntax, tkinter-syntax) render through the same BUI pipeline.
+ * \{ */
+
+static PyObject *buipy_begin_frame(PyObject *self, PyObject *args)
+{
+ int w, h;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "ii:begin_frame", &w, &h)) {
+ return NULL;
+ }
+ if (g_target) {
+ BUI_raster_begin_frame(g_target->raster, w, h);
+ PyList_SetSlice(g_target->text_runs, 0, PY_SSIZE_T_MAX, NULL);
+ bui_set_viewport(w, h);
+ Py_RETURN_NONE;
+ }
+ const BuiGpuSink *sink = bui_get_render_sink();
+ if (sink && sink->begin_frame) {
+ sink->begin_frame(sink->user, w, h);
+ }
+ bui_set_viewport(w, h);
+ Py_RETURN_NONE;
+}
+
+static PyObject *buipy_end_frame(PyObject *self, PyObject *args)
+{
+ const BuiGpuSink *sink = bui_get_render_sink();
+ (void)self; (void)args;
+ if (g_target) {
+ BUI_raster_end_frame(g_target->raster);
+ Py_RETURN_NONE;
+ }
+ if (sink && sink->end_frame) {
+ sink->end_frame(sink->user);
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *buipy_draw_rect(PyObject *self, PyObject *args)
+{
+ float x, y, w, h;
+ PyObject *color;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "ffffO:draw_rect", &x, &y, &w, &h, &color)) {
+ return NULL;
+ }
+ float rgba[4];
+ if (!parse_color(color, rgba)) {
+ return NULL;
+ }
+ if (g_target) {
+ BUI_raster_fill_rect(g_target->raster, x, y, w, h, rgba);
+ Py_RETURN_NONE;
+ }
+ const BuiGpuSink *sink = bui_get_render_sink();
+ if (sink && sink->triangles) {
+ float coords[6][2] = {{x, y}, {x + w, y}, {x + w, y + h}, {x, y}, {x + w, y + h}, {x, y + h}};
+ float colors[6][4];
+ for (int i = 0; i < 6; i++) {
+ memcpy(colors[i], rgba, sizeof(rgba));
+ }
+ sink->triangles(sink->user, coords, colors, 6);
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *buipy_draw_frame(PyObject *self, PyObject *args)
+{
+ float x, y, w, h, thickness;
+ PyObject *color;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "fffffO:draw_frame", &x, &y, &w, &h, &thickness, &color)) {
+ return NULL;
+ }
+ float rgba[4];
+ if (!parse_color(color, rgba)) {
+ return NULL;
+ }
+ if (g_target) {
+ BUI_raster_frame_rect(g_target->raster, x, y, w, h, thickness, rgba);
+ Py_RETURN_NONE;
+ }
+ const BuiGpuSink *sink = bui_get_render_sink();
+ if (sink && sink->triangles) {
+ float t = thickness;
+ float top[6][2] = {{x, y}, {x + w, y}, {x + w, y + t}, {x, y}, {x + w, y + t}, {x, y + t}};
+ float bottom[6][2] = {{x, y + h - t}, {x + w, y + h - t}, {x + w, y + h},
+ {x, y + h - t}, {x + w, y + h}, {x, y + h}};
+ float left[6][2] = {{x, y}, {x + t, y}, {x + t, y + h}, {x, y}, {x + t, y + h}, {x, y + h}};
+ float right[6][2] = {{x + w - t, y}, {x + w, y}, {x + w, y + h},
+ {x + w - t, y}, {x + w, y + h}, {x + w - t, y + h}};
+ float *sides[4] = {&top[0][0], &bottom[0][0], &left[0][0], &right[0][0]};
+ for (int r = 0; r < 4; r++) {
+ float colors[6][4];
+ for (int i = 0; i < 6; i++) {
+ memcpy(colors[i], rgba, sizeof(rgba));
+ }
+ sink->triangles(sink->user, (const float (*)[2])sides[r], colors, 6);
+ }
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *buipy_draw_line(PyObject *self, PyObject *args)
+{
+ float x1, y1, x2, y2, width = 1.0f;
+ PyObject *color;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "ffffO|f:draw_line", &x1, &y1, &x2, &y2, &color, &width)) {
+ return NULL;
+ }
+ float rgba[4];
+ if (!parse_color(color, rgba)) {
+ return NULL;
+ }
+ if (g_target) {
+ BUI_raster_line(g_target->raster, x1, y1, x2, y2, width, rgba);
+ Py_RETURN_NONE;
+ }
+ const BuiGpuSink *sink = bui_get_render_sink();
+ if (sink && sink->lines) {
+ float coords[2][2] = {{x1, y1}, {x2, y2}};
+ float colors[2][4];
+ for (int i = 0; i < 2; i++) {
+ memcpy(colors[i], rgba, sizeof(rgba));
+ }
+ sink->lines(sink->user, coords, colors, 2);
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *buipy_draw_circle(PyObject *self, PyObject *args)
+{
+ float cx, cy, radius;
+ int filled = 1;
+ int segments = 48;
+ PyObject *color;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "fffO|ii:draw_circle", &cx, &cy, &radius, &color, &filled, &segments)) {
+ return NULL;
+ }
+ float rgba[4];
+ if (!parse_color(color, rgba)) {
+ return NULL;
+ }
+ if (g_target) {
+ BUI_raster_circle(g_target->raster, cx, cy, radius, filled ? 0.0f : 1.0f, rgba);
+ Py_RETURN_NONE;
+ }
+ if (segments < 3) {
+ segments = 3;
+ }
+ const BuiGpuSink *sink = bui_get_render_sink();
+ if (!sink) {
+ Py_RETURN_NONE;
+ }
+ if (filled && sink->triangles) {
+ for (int i = 0; i < segments; i++) {
+ float a0 = (float)(2.0 * 3.141592653589793 * i / segments);
+ float a1 = (float)(2.0 * 3.141592653589793 * (i + 1) / segments);
+ float coords[3][2] = {{cx, cy},
+ {cx + radius * cosf(a0), cy + radius * sinf(a0)},
+ {cx + radius * cosf(a1), cy + radius * sinf(a1)}};
+ float colors[3][4];
+ for (int v = 0; v < 3; v++) {
+ memcpy(colors[v], rgba, sizeof(rgba));
+ }
+ sink->triangles(sink->user, coords, colors, 3);
+ }
+ }
+ else if (!filled && sink->lines) {
+ for (int i = 0; i < segments; i++) {
+ float a0 = (float)(2.0 * 3.141592653589793 * i / segments);
+ float a1 = (float)(2.0 * 3.141592653589793 * (i + 1) / segments);
+ float coords[2][2] = {{cx + radius * cosf(a0), cy + radius * sinf(a0)},
+ {cx + radius * cosf(a1), cy + radius * sinf(a1)}};
+ float colors[2][4];
+ for (int v = 0; v < 2; v++) {
+ memcpy(colors[v], rgba, sizeof(rgba));
+ }
+ sink->lines(sink->user, coords, colors, 2);
+ }
+ }
+ Py_RETURN_NONE;
+}
+
+/* draw_ellipse(cx, cy, rx, ry, color, filled=True, line_width=1) */
+static PyObject *buipy_draw_ellipse(PyObject *self, PyObject *args)
+{
+ float cx, cy, rx, ry, lw = 1.0f;
+ int filled = 1;
+ PyObject *color;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "ffffO|pf:draw_ellipse", &cx, &cy, &rx, &ry, &color, &filled, &lw)) {
+ return NULL;
+ }
+ float rgba[4];
+ if (!parse_color(color, rgba)) {
+ return NULL;
+ }
+ if (g_target) {
+ BUI_raster_ellipse(g_target->raster, cx, cy, rx, ry, filled ? 0.0f : lw, rgba);
+ Py_RETURN_NONE;
+ }
+ const BuiGpuSink *sink = bui_get_render_sink();
+ if (!sink) {
+ Py_RETURN_NONE;
+ }
+ enum { SEG = 48 };
+ for (int i = 0; i < SEG; i++) {
+ const float a0 = (float)(2.0 * 3.141592653589793 * i / SEG);
+ const float a1 = (float)(2.0 * 3.141592653589793 * (i + 1) / SEG);
+ const float p0[2] = {cx + rx * cosf(a0), cy + ry * sinf(a0)};
+ const float p1[2] = {cx + rx * cosf(a1), cy + ry * sinf(a1)};
+ float colors[3][4];
+ for (int v = 0; v < 3; v++) {
+ memcpy(colors[v], rgba, sizeof(rgba));
+ }
+ if (filled && sink->triangles) {
+ float coords[3][2] = {{cx, cy}, {p0[0], p0[1]}, {p1[0], p1[1]}};
+ sink->triangles(sink->user, coords, colors, 3);
+ }
+ else if (!filled && sink->lines) {
+ float coords[2][2] = {{p0[0], p0[1]}, {p1[0], p1[1]}};
+ sink->lines(sink->user, coords, colors, 2);
+ }
+ }
+ Py_RETURN_NONE;
+}
+
+/* draw_polygon([(x, y), ...], color): filled polygon (even-odd). */
+static PyObject *buipy_draw_polygon(PyObject *self, PyObject *args)
+{
+ PyObject *pts_obj, *color;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "OO:draw_polygon", &pts_obj, &color)) {
+ return NULL;
+ }
+ float rgba[4];
+ if (!parse_color(color, rgba)) {
+ return NULL;
+ }
+ PyObject *seq = PySequence_Fast(pts_obj, "points must be a sequence of (x, y)");
+ if (!seq) {
+ return NULL;
+ }
+ const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
+ float(*pts)[2] = (float(*)[2])malloc(sizeof(float[2]) * (size_t)(n > 0 ? n : 1));
+ if (!pts) {
+ Py_DECREF(seq);
+ return PyErr_NoMemory();
+ }
+ for (Py_ssize_t i = 0; i < n; i++) {
+ if (!PyArg_ParseTuple(PySequence_Fast_GET_ITEM(seq, i), "ff", &pts[i][0], &pts[i][1])) {
+ free(pts);
+ Py_DECREF(seq);
+ return NULL;
+ }
+ }
+ Py_DECREF(seq);
+ if (g_target) {
+ BUI_raster_polygon(g_target->raster, (const float(*)[2])pts, (int)n, rgba);
+ }
+ else {
+ const BuiGpuSink *sink = bui_get_render_sink();
+ if (sink && sink->triangles) {
+ float colors[3][4];
+ for (int v = 0; v < 3; v++) {
+ memcpy(colors[v], rgba, sizeof(rgba));
+ }
+ for (Py_ssize_t i = 1; i + 1 < n; i++) { /* fan: exact for convex */
+ float coords[3][2] = {{pts[0][0], pts[0][1]}, {pts[i][0], pts[i][1]},
+ {pts[i + 1][0], pts[i + 1][1]}};
+ sink->triangles(sink->user, coords, colors, 3);
+ }
+ }
+ }
+ free(pts);
+ Py_RETURN_NONE;
+}
+
+/* Emit triangles to the active target (raster) or the installed sink. */
+static void emit_triangles(const float (*co)[2], const float (*col)[4], int n)
+{
+ if (g_target) {
+ BUI_raster_triangles(g_target->raster, co, col, n);
+ return;
+ }
+ const BuiGpuSink *sink = bui_get_render_sink();
+ if (sink && sink->triangles && n >= 3) {
+ sink->triangles(sink->user, co, col, n);
+ }
+}
+
+static void hsv_rgb(float h, float s, float v, float out[4])
+{
+ h = h - floorf(h);
+ const float h6 = h * 6.0f;
+ float c[3] = {fabsf(h6 - 3.0f) - 1.0f, 2.0f - fabsf(h6 - 2.0f), 2.0f - fabsf(h6 - 4.0f)};
+ for (int k = 0; k < 3; k++) {
+ c[k] = c[k] < 0 ? 0 : (c[k] > 1 ? 1 : c[k]);
+ out[k] = ((c[k] - 1.0f) * s + 1.0f) * v;
+ }
+ out[3] = 1.0f;
+}
+
+static PyObject *buipy_draw_triangles(PyObject *self, PyObject *args)
+{
+ PyObject *co_obj, *col_obj;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "OO:draw_triangles", &co_obj, &col_obj)) {
+ return NULL;
+ }
+ PyObject *cs = PySequence_Fast(co_obj, "coords must be a sequence of (x, y)");
+ if (!cs) {
+ return NULL;
+ }
+ PyObject *ks = PySequence_Fast(col_obj, "colors must be a sequence of (r, g, b, a)");
+ if (!ks) {
+ Py_DECREF(cs);
+ return NULL;
+ }
+ Py_ssize_t n = PySequence_Fast_GET_SIZE(cs);
+ if (PySequence_Fast_GET_SIZE(ks) != n) {
+ Py_DECREF(cs);
+ Py_DECREF(ks);
+ PyErr_SetString(PyExc_ValueError, "coords and colors must have the same length");
+ return NULL;
+ }
+ n -= n % 3;
+ float(*co)[2] = (float(*)[2])malloc(sizeof(float[2]) * (size_t)(n > 0 ? n : 1));
+ float(*col)[4] = (float(*)[4])malloc(sizeof(float[4]) * (size_t)(n > 0 ? n : 1));
+ int ok = co && col;
+ for (Py_ssize_t i = 0; ok && i < n; i++) {
+ ok = PyArg_ParseTuple(PySequence_Fast_GET_ITEM(cs, i), "ff", &co[i][0], &co[i][1]) &&
+ parse_color(PySequence_Fast_GET_ITEM(ks, i), col[i]);
+ }
+ Py_DECREF(cs);
+ Py_DECREF(ks);
+ if (ok) {
+ emit_triangles((const float(*)[2])co, (const float(*)[4])col, (int)n);
+ }
+ free(co);
+ free(col);
+ if (!ok) {
+ return PyErr_Occurred() ? NULL : PyErr_NoMemory();
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *buipy_draw_gradient(PyObject *self, PyObject *args)
+{
+ float x, y, w, h;
+ PyObject *o[4];
+ float c[4][4];
+ (void)self;
+ if (!PyArg_ParseTuple(args, "ffffOOOO:draw_gradient", &x, &y, &w, &h, &o[0], &o[1], &o[2],
+ &o[3]))
+ {
+ return NULL;
+ }
+ for (int i = 0; i < 4; i++) {
+ if (!parse_color(o[i], c[i])) {
+ return NULL;
+ }
+ }
+ if (g_target) {
+ BUI_raster_gradient(g_target->raster, x, y, w, h, c[0], c[1], c[2], c[3]);
+ }
+ else {
+ const float co[6][2] = {{x, y}, {x + w, y}, {x + w, y + h}, {x, y}, {x + w, y + h}, {x, y + h}};
+ float col[6][4];
+ const int idx[6] = {0, 1, 2, 0, 2, 3};
+ for (int i = 0; i < 6; i++) {
+ memcpy(col[i], c[idx[i]], sizeof(float[4]));
+ }
+ emit_triangles(co, (const float(*)[4])col, 6);
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *buipy_draw_hsv_circle(PyObject *self, PyObject *args)
+{
+ float cx, cy, radius, value;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "ffff:draw_hsv_circle", &cx, &cy, &radius, &value)) {
+ return NULL;
+ }
+ if (g_target) {
+ BUI_raster_hsv_circle(g_target->raster, cx, cy, radius, value);
+ Py_RETURN_NONE;
+ }
+ enum { SEG = 64 };
+ float co[3][2], col[3][4];
+ for (int i = 0; i < SEG; i++) {
+ const float a0 = (float)(2.0 * 3.141592653589793 * i / SEG);
+ const float a1 = (float)(2.0 * 3.141592653589793 * (i + 1) / SEG);
+ co[0][0] = cx;
+ co[0][1] = cy;
+ co[1][0] = cx + radius * sinf(a0);
+ co[1][1] = cy - radius * cosf(a0);
+ co[2][0] = cx + radius * sinf(a1);
+ co[2][1] = cy - radius * cosf(a1);
+ hsv_rgb(0.0f, 0.0f, value, col[0]);
+ hsv_rgb(a0 / 6.2831853f + 0.5f, 1.0f, value, col[1]);
+ hsv_rgb(a1 / 6.2831853f + 0.5f, 1.0f, value, col[2]);
+ emit_triangles((const float(*)[2])co, (const float(*)[4])col, 3);
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *buipy_draw_sphere(PyObject *self, PyObject *args)
+{
+ float cx, cy, radius, light[3];
+ PyObject *color;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "fff(fff)O:draw_sphere", &cx, &cy, &radius, &light[0], &light[1],
+ &light[2], &color))
+ {
+ return NULL;
+ }
+ float rgba[4];
+ if (!parse_color(color, rgba)) {
+ return NULL;
+ }
+ if (g_target) {
+ BUI_raster_sphere(g_target->raster, cx, cy, radius, light, rgba);
+ Py_RETURN_NONE;
+ }
+ enum { SEG = 48 };
+ float co[3][2], col[3][4];
+ for (int v = 0; v < 3; v++) {
+ memcpy(col[v], rgba, sizeof(rgba));
+ }
+ for (int i = 0; i < SEG; i++) {
+ const float a0 = (float)(2.0 * 3.141592653589793 * i / SEG);
+ const float a1 = (float)(2.0 * 3.141592653589793 * (i + 1) / SEG);
+ co[0][0] = cx;
+ co[0][1] = cy;
+ co[1][0] = cx + radius * cosf(a0);
+ co[1][1] = cy + radius * sinf(a0);
+ co[2][0] = cx + radius * cosf(a1);
+ co[2][1] = cy + radius * sinf(a1);
+ emit_triangles((const float(*)[2])co, (const float(*)[4])col, 3);
+ }
+ Py_RETURN_NONE;
+}
+
+/* Optional color argument: None -> NULL. */
+static int parse_opt_color(PyObject *obj, float rgba[4], const float **r_ptr)
+{
+ if (obj == NULL || obj == Py_None) {
+ *r_ptr = NULL;
+ return 1;
+ }
+ if (!parse_color(obj, rgba)) {
+ return 0;
+ }
+ *r_ptr = rgba;
+ return 1;
+}
+
+/* draw_widget(x, y, w, h, radius, inner, outline=None, emboss=None,
+ * inner_bottom=None, corners=15, outline_width=1.0)
+ * Blender widget base: shaded inner, inside outline, emboss underline. */
+static PyObject *buipy_draw_widget(PyObject *self, PyObject *args, PyObject *kw)
+{
+ static char *kwlist[] = {"x", "y", "w", "h", "radius", "inner", "outline", "emboss",
+ "inner_bottom", "corners", "outline_width", NULL};
+ float x, y, w, h, radius, outline_width = 1.0f;
+ PyObject *inner_o = Py_None, *outline_o = Py_None, *emboss_o = Py_None, *bottom_o = Py_None;
+ int corners = 15;
+ (void)self;
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "fffffO|OOOif:draw_widget", kwlist, &x, &y, &w,
+ &h, &radius, &inner_o, &outline_o, &emboss_o, &bottom_o,
+ &corners, &outline_width))
+ {
+ return NULL;
+ }
+ float c_in[4], c_out[4], c_emb[4], c_bot[4];
+ const float *in, *out, *emb, *bot;
+ if (!parse_opt_color(inner_o, c_in, &in) || !parse_opt_color(outline_o, c_out, &out) ||
+ !parse_opt_color(emboss_o, c_emb, &emb) || !parse_opt_color(bottom_o, c_bot, &bot))
+ {
+ return NULL;
+ }
+ if (g_target) {
+ BUI_raster_widget(g_target->raster, x, y, w, h, radius, corners, in, bot ? bot : in, out,
+ outline_width, emb);
+ Py_RETURN_NONE;
+ }
+ /* Python sinks: approximate with rounded rects (outline, then inner). */
+ PyObject *res;
+ if (out) {
+ res = PyObject_CallMethod(PyImport_AddModule("buipy"), "draw_roundrect", "fffffO", x, y, w,
+ h, radius, outline_o);
+ if (!res) {
+ return NULL;
+ }
+ Py_DECREF(res);
+ }
+ if (in) {
+ const float o = out ? outline_width : 0.0f;
+ res = PyObject_CallMethod(PyImport_AddModule("buipy"), "draw_roundrect", "fffffO", x + o,
+ y + o, w - 2 * o, h - 2 * o, radius > o ? radius - o : 0.0f,
+ inner_o);
+ if (!res) {
+ return NULL;
+ }
+ Py_DECREF(res);
+ }
+ Py_RETURN_NONE;
+}
+
+/* draw_shadow(x, y, w, h, radius, size, alpha): soft popup shadow. */
+static PyObject *buipy_draw_shadow(PyObject *self, PyObject *args)
+{
+ float x, y, w, h, radius, size, alpha;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "fffffff:draw_shadow", &x, &y, &w, &h, &radius, &size, &alpha)) {
+ return NULL;
+ }
+ if (g_target) {
+ BUI_raster_shadow(g_target->raster, x, y, w, h, radius, size, alpha);
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *buipy_draw_roundrect(PyObject *self, PyObject *args)
+{
+ float x, y, w, h, radius;
+ PyObject *color;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "fffffO:draw_roundrect", &x, &y, &w, &h, &radius, &color)) {
+ return NULL;
+ }
+ float rgba[4];
+ if (!parse_color(color, rgba)) {
+ return NULL;
+ }
+ if (g_target) {
+ BUI_raster_round_rect(g_target->raster, x, y, w, h, radius, rgba);
+ Py_RETURN_NONE;
+ }
+ const BuiGpuSink *sink = bui_get_render_sink();
+ if (!sink || !sink->triangles) {
+ Py_RETURN_NONE;
+ }
+ const float max_r = (w < h ? w : h) / 2.0f;
+ if (radius < 0.0f) {
+ radius = 0.0f;
+ }
+ if (radius > max_r) {
+ radius = max_r;
+ }
+ const float cx = x + w / 2.0f;
+ const float cy = y + h / 2.0f;
+ /* Build the rounded-rect outline as a polyline, then emit a triangle fan. */
+ const int seg = 6; /* segments per corner */
+ const int points = seg * 4 + 1; /* closed loop; last == first */
+ float(*outline)[2] = malloc(sizeof(float) * 2 * points);
+ const float centers[4][2] = {{x + w - radius, y + radius},
+ {x + radius, y + radius},
+ {x + radius, y + h - radius},
+ {x + w - radius, y + h - radius}};
+ const float starts[4] = {0.0f, 1.5707963f, 3.1415926f, 4.7123890f};
+ int n = 0;
+ for (int c = 0; c < 4; c++) {
+ for (int i = 0; i <= seg; i++) {
+ if (c > 0 && i == 0) {
+ continue; /* corner start equals previous corner end */
+ }
+ const float a = starts[c] + (float)(1.5707963267948966 * i / seg);
+ outline[n][0] = centers[c][0] + radius * cosf(a);
+ outline[n][1] = centers[c][1] + radius * sinf(a);
+ n++;
+ }
+ }
+ for (int i = 0; i < n; i++) {
+ float coords[3][2] = {{cx, cy}, {outline[i][0], outline[i][1]},
+ {outline[(i + 1) % n][0], outline[(i + 1) % n][1]}};
+ float colors[3][4];
+ for (int v = 0; v < 3; v++) {
+ memcpy(colors[v], rgba, sizeof(rgba));
+ }
+ sink->triangles(sink->user, coords, colors, 3);
+ }
+ free(outline);
+ Py_RETURN_NONE;
+}
+
+static PyObject *buipy_set_clip(PyObject *self, PyObject *args)
+{
+ int x, y, w, h;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "iiii:set_clip", &x, &y, &w, &h)) {
+ return NULL;
+ }
+ if (g_target) {
+ BUI_raster_set_clip(g_target->raster, x, y, w, h);
+ Py_RETURN_NONE;
+ }
+ const BuiGpuSink *sink = bui_get_render_sink();
+ if (sink && sink->scissor) {
+ sink->scissor(sink->user, x, y, w, h);
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *buipy_draw_text(PyObject *self, PyObject *args)
+{
+ float x, y, size;
+ const char *text;
+ Py_ssize_t text_len;
+ PyObject *color;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "fffs#O:draw_text", &x, &y, &size, &text, &text_len, &color)) {
+ return NULL;
+ }
+ float rgba[4];
+ if (!parse_color(color, rgba)) {
+ return NULL;
+ }
+ if (g_target) {
+ if (!BUI_raster_text(g_target->raster, x, y, text, (int)text_len, size, rgba)) {
+ /* No native text engine: hand the run to the host (drawn on top). */
+ PyObject *run = Py_BuildValue("(ffs#f(ffff)si)", x, y, text, text_len, size, rgba[0],
+ rgba[1], rgba[2], rgba[3], g_font_family, g_font_flags);
+ if (!run || PyList_Append(g_target->text_runs, run) < 0) {
+ Py_XDECREF(run);
+ return NULL;
+ }
+ Py_DECREF(run);
+ }
+ Py_RETURN_NONE;
+ }
+ const BuiGpuSink *sink = bui_get_render_sink();
+ if (sink && sink->text) {
+ sink->text(sink->user, x, y, text, size, rgba);
+ }
+ Py_RETURN_NONE;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Module glue
+ * \{ */
+
+/* set_font(family, flags): font for subsequent draw_text (flags: 1 bold,
+ * 2 italic, 4 underline). Cheap; widgets call it before painting text. */
+static PyObject *buipy_set_font(PyObject *self, PyObject *args)
+{
+ const char *family = "";
+ int flags = 0;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "|zi:set_font", &family, &flags)) {
+ return NULL;
+ }
+ if (!family) {
+ family = "";
+ }
+ if (strcmp(family, g_font_family) != 0 || flags != g_font_flags) {
+ strncpy(g_font_family, family, sizeof(g_font_family) - 1);
+ g_font_family[sizeof(g_font_family) - 1] = '\0';
+ g_font_flags = flags;
+ if (g_target) {
+ BUI_raster_set_font(g_target->raster, g_font_family, g_font_flags);
+ }
+ }
+ Py_RETURN_NONE;
+}
+
+/* measure_text(text, size, family="", flags=0) -> float advance in pixels,
+ * or None when no native text engine exists (callers fall back). */
+static PyObject *buipy_measure_text(PyObject *self, PyObject *args)
+{
+ const char *text;
+ Py_ssize_t len;
+ float size;
+ const char *family = "";
+ int flags = 0;
+ (void)self;
+ if (!PyArg_ParseTuple(args, "s#f|zi:measure_text", &text, &len, &size, &family, &flags)) {
+ return NULL;
+ }
+ float width;
+ if (!BUI_text_measure(family, flags, size, text, (int)len, &width)) {
+ Py_RETURN_NONE;
+ }
+ return PyFloat_FromDouble(width);
+}
+
+static PyObject *buipy_has_native_text(PyObject *self, PyObject *noargs)
+{
+ (void)self;
+ (void)noargs;
+ return PyBool_FromLong(BUI_text_native());
+}
+
+static PyObject *buipy_version(PyObject *self, PyObject *args)
+{
+ int major, minor, patch;
+ bui_get_version(&major, &minor, &patch);
+ return PyUnicode_FromFormat("%d.%d.%d", major, minor, patch);
+}
+
+static void target_clear(void)
+{
+ if (g_target) {
+ BuiPyRaster *t = g_target;
+ g_target = NULL;
+ Py_DECREF(t);
+ }
+}
+
+static PyObject *buipy_set_backend(PyObject *self, PyObject *arg)
+{
+ if (PyObject_TypeCheck(arg, &BuiPyRaster_Type)) {
+ /* Native path: drop any Python sink, render into the raster. */
+ if (g_holder) {
+ Py_XDECREF(g_holder->backend);
+ free(g_holder);
+ g_holder = NULL;
+ }
+ target_clear();
+ g_target = (BuiPyRaster *)Py_NewRef(arg);
+ BUI_raster_set_font(g_target->raster, g_font_family, g_font_flags);
+ /* C toolkit code drawing through the GPU seam lands in the raster too. */
+ bui_set_render_sink(BUI_raster_sink(g_target->raster));
+ Py_RETURN_NONE;
+ }
+ target_clear();
+ if (arg == Py_None) {
+ bui_set_render_sink(NULL);
+ if (g_holder) {
+ Py_XDECREF(g_holder->backend);
+ free(g_holder);
+ g_holder = NULL;
+ }
+ Py_RETURN_NONE;
+ }
+ if (!PyObject_HasAttrString(arg, "triangles")) {
+ PyErr_SetString(PyExc_TypeError, "backend must implement the bui.Backend protocol");
+ return NULL;
+ }
+ /* Drop an existing holder first. */
+ if (g_holder) {
+ bui_set_render_sink(NULL);
+ Py_XDECREF(g_holder->backend);
+ free(g_holder);
+ g_holder = NULL;
+ }
+ g_holder = (BuiPySinkHolder *)malloc(sizeof(BuiPySinkHolder));
+ g_holder->backend = Py_NewRef(arg);
+ bui_set_render_sink(&g_py_sink);
+ Py_RETURN_NONE;
+}
+
+static PyObject *buipy_set_viewport(PyObject *self, PyObject *args)
+{
+ int w, h;
+ if (!PyArg_ParseTuple(args, "ii:set_viewport", &w, &h)) {
+ return NULL;
+ }
+ bui_set_viewport(w, h);
+ Py_RETURN_NONE;
+}
+
+static PyMethodDef buipy_methods[] = {
+ {"version", buipy_version, METH_NOARGS, "Return the BUI version string."},
+ {"set_backend", buipy_set_backend, METH_O, "Install a bui.Backend (or None to clear)."},
+ {"set_viewport", buipy_set_viewport, METH_VARARGS, "Record the host viewport size in pixels."},
+ {"demo_scene", buipy_demo_scene, METH_VARARGS, "Draw a small showcase scene through the backend."},
+ {"begin_frame", buipy_begin_frame, METH_VARARGS, "begin_frame(w, h): start a frame batch."},
+ {"end_frame", buipy_end_frame, METH_NOARGS, "end_frame(): finish the frame batch."},
+ {"draw_rect", buipy_draw_rect, METH_VARARGS, "draw_rect(x, y, w, h, (r, g, b, a)): filled rectangle."},
+ {"draw_frame", buipy_draw_frame, METH_VARARGS, "draw_frame(x, y, w, h, thickness, (r, g, b, a)): rectangle outline."},
+ {"draw_line", buipy_draw_line, METH_VARARGS, "draw_line(x1, y1, x2, y2, (r, g, b, a), width=1): line."},
+ {"draw_widget", (PyCFunction)(void (*)(void))buipy_draw_widget, METH_VARARGS | METH_KEYWORDS, "draw_widget(x, y, w, h, radius, inner, outline=None, emboss=None, inner_bottom=None, corners=15, outline_width=1): Blender widget base."},
+ {"draw_shadow", buipy_draw_shadow, METH_VARARGS, "draw_shadow(x, y, w, h, radius, size, alpha): soft popup shadow."},
+ {"draw_ellipse", buipy_draw_ellipse, METH_VARARGS, "draw_ellipse(cx, cy, rx, ry, (r, g, b, a), filled=True, line_width=1)."},
+ {"draw_polygon", buipy_draw_polygon, METH_VARARGS, "draw_polygon([(x, y), ...], (r, g, b, a)): filled polygon."},
+ {"draw_circle", buipy_draw_circle, METH_VARARGS, "draw_circle(cx, cy, radius, (r, g, b, a), filled=True, segments=48)."},
+ {"draw_text", buipy_draw_text, METH_VARARGS, "draw_text(x, y, size, text, (r, g, b, a)): text run at baseline."},
+ {"draw_roundrect", buipy_draw_roundrect, METH_VARARGS, "draw_roundrect(x, y, w, h, radius, (r, g, b, a)): filled rounded rectangle."},
+ {"set_font", buipy_set_font, METH_VARARGS, "set_font(family='', flags=0): font for draw_text (1 bold, 2 italic, 4 underline)."},
+ {"measure_text", buipy_measure_text, METH_VARARGS, "measure_text(text, size, family='', flags=0) -> float | None."},
+ {"has_native_text", buipy_has_native_text, METH_NOARGS, "True when draw_text renders natively into a Raster."},
+ {"draw_triangles", buipy_draw_triangles, METH_VARARGS, "draw_triangles([(x, y), ...], [(r, g, b, a), ...]): per-vertex colored triangles."},
+ {"draw_gradient", buipy_draw_gradient, METH_VARARGS, "draw_gradient(x, y, w, h, tl, tr, br, bl): bilinear corner-color rectangle."},
+ {"draw_hsv_circle", buipy_draw_hsv_circle, METH_VARARGS, "draw_hsv_circle(cx, cy, radius, value): Blender HSV color wheel."},
+ {"draw_sphere", buipy_draw_sphere, METH_VARARGS, "draw_sphere(cx, cy, radius, (lx, ly, lz), color): lit sphere (normal ball)."},
+ {"set_clip", buipy_set_clip, METH_VARARGS, "set_clip(x, y, w, h): clip subsequent drawing (w/h <= 0 clears)."},
+ {NULL, NULL, 0, NULL},
+};
+
+static struct PyModuleDef buipy_module = {
+ PyModuleDef_HEAD_INIT,
+ "buipy",
+ "Python bindings for the BUI UI toolkit (Blender-derived).",
+ -1,
+ buipy_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+};
+
+/* Shared with buipy_kit.c: the active raster target / a Raster object. */
+BuiRaster *buipy_current_raster(void)
+{
+ return g_target ? g_target->raster : NULL;
+}
+
+BuiRaster *buipy_raster_of(PyObject *obj)
+{
+ if (obj && PyObject_TypeCheck(obj, &BuiPyRaster_Type)) {
+ return ((BuiPyRaster *)obj)->raster;
+ }
+ return NULL;
+}
+
+int buipy_kit_init(PyObject *module); /* buipy_kit.c */
+
+PyMODINIT_FUNC PyInit_buipy(void)
+{
+ if (PyType_Ready(&BuiPyRaster_Type) < 0) {
+ return NULL;
+ }
+ PyObject *m = PyModule_Create(&buipy_module);
+ if (!m) {
+ return NULL;
+ }
+ if (PyModule_AddObjectRef(m, "Raster", (PyObject *)&BuiPyRaster_Type) < 0 ||
+ buipy_kit_init(m) < 0)
+ {
+ Py_DECREF(m);
+ return NULL;
+ }
+ return m;
+}
+
+/** \} */
diff --git a/bindings/python/tests/__pycache__/test_components.cpython-314.pyc b/bindings/python/tests/__pycache__/test_components.cpython-314.pyc
new file mode 100644
index 0000000..d88b668
Binary files /dev/null and b/bindings/python/tests/__pycache__/test_components.cpython-314.pyc differ
diff --git a/bindings/python/tests/__pycache__/test_tk_compat.cpython-314.pyc b/bindings/python/tests/__pycache__/test_tk_compat.cpython-314.pyc
new file mode 100644
index 0000000..c1b1678
Binary files /dev/null and b/bindings/python/tests/__pycache__/test_tk_compat.cpython-314.pyc differ
diff --git a/bindings/python/tests/__pycache__/test_tk_input.cpython-314.pyc b/bindings/python/tests/__pycache__/test_tk_input.cpython-314.pyc
new file mode 100644
index 0000000..85708a2
Binary files /dev/null and b/bindings/python/tests/__pycache__/test_tk_input.cpython-314.pyc differ
diff --git a/bindings/python/tests/test_advanced.py b/bindings/python/tests/test_advanced.py
new file mode 100644
index 0000000..917a7f7
--- /dev/null
+++ b/bindings/python/tests/test_advanced.py
@@ -0,0 +1,208 @@
+"""Tests for the advanced surface: Text, Treeview/Table, Notebook, Menu and
+menubars, PhotoImage, QPainter custom painting, timers and animation.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import os
+import sys
+import time
+
+_here = os.path.dirname(os.path.abspath(__file__))
+for p in (os.environ.get("BUIPY_BUILD_DIR", ""), os.path.dirname(_here)):
+ if p and p not in sys.path:
+ sys.path.insert(0, p)
+
+import bui # noqa: E402,F401 (auto-locates buipy)
+import buipy # noqa: E402
+from bui import host # noqa: E402
+
+
+
+def pos(w):
+ """Window coordinates of a widget (Qt widgets are kit nodes; tk widgets wrap one)."""
+ return w.absolutePos() if hasattr(w, "absolutePos") else tuple(w._node.rect[:2])
+
+def test_tk_text_treeview_notebook_menu():
+ from bui.tksyntax import Frame, Menu, Notebook, Text, Tk, Treeview
+
+ root = Tk()
+ t = Text(root, undo=True)
+ t.insert("1.0", "hello\nworld")
+ assert t.index("insert") == "2.5", t.index("insert")
+ t.tag_add("warn", "1.1", "1.3")
+ t.tag_configure("warn", foreground="#ffcc00")
+ assert t.tag_names("1.2") == ("warn",)
+ t.delete("1.0", "1.1")
+ assert t.get("1.0", "1.end") == "ello"
+ t.edit_undo()
+ assert t.get("1.0", "1.end") == "hello"
+ assert t.search("world", "1.0") == "2.0"
+ assert t.get("1.0", "end") == "hello\nworld\n"
+
+ tv = Treeview(root, columns=("size", "mod"))
+ tv.heading("#0", text="Name")
+ i1 = tv.insert("", "end", text="src", values=("4 KB", "today"))
+ i2 = tv.insert(i1, "end", text="main.py")
+ tv.selection_set(i1)
+ assert tv.selection() == (i1,) and tv.get_children() == (i1,)
+ assert tv.exists(i2) and tv.depth(i2) == 1 and tv.parent(i2) == i1
+ tv.item(i1, open=True)
+ assert tv.item(i1)["values"] == ["4 KB", "today"]
+
+ nb = Notebook(root)
+ p1, p2 = Frame(nb), Frame(nb)
+ nb.add(p1, text="Tab One")
+ nb.add(p2, text="Tab Two")
+ nb.select(1)
+ assert nb.index(p2) == 1 and nb.tabs() == (str(p1), str(p2)) and nb.index("current") == 1
+
+ calls = []
+ bar = Menu(root)
+ fm = Menu(bar, tearoff=0)
+ fm.add_command(label="Open", command=lambda: calls.append("open"))
+ fm.add_separator()
+ fm.add_command(label="Save", command=lambda: calls.append("save"))
+ bar.add_cascade(label="File", menu=fm)
+ root.config(menu=bar)
+ fm.invoke(2)
+ assert calls == ["save"], calls
+
+ # open the menubar dropdown and pick the first entry with the pointer
+ for w in (t, tv, nb):
+ w.pack(fill="x")
+ ctx = root._ctx
+ ctx.render(400, 600, buipy.Raster(400, 600), True)
+ mb = root._menubar._bar
+ fx, fy, fw, fh = mb.children[0].rect
+ ctx.press(fx + 5, fy + 5, 0)
+ ctx.release(fx + 5, fy + 5, 0)
+ assert ctx.popup_count() == 1, "menubar dropdown did not open"
+ px, py, pw, ph = ctx.popup(0).rect
+ ctx.motion(px + 20, py + 12, 0)
+ ctx.press(px + 20, py + 12, 0)
+ ctx.release(px + 20, py + 12, 0)
+ assert calls == ["save", "open"], calls
+ root.destroy()
+
+
+def test_photoimage():
+ from bui.tksyntax import PhotoImage
+
+ ppm = b"P3\n2 2\n255\n255 0 0 0 255 0 0 0 255 255 255 0\n"
+ photo = PhotoImage(data=ppm.decode())
+ assert photo.width() == 2 and photo.height() == 2
+ assert photo.get(0, 0) == (255, 0, 0)
+ assert photo.get(1, 1) == (255, 255, 0)
+ photo.put("#00ff00", (0, 0))
+ assert photo.get(0, 0) == (0, 255, 0)
+
+
+def test_qt_advanced():
+ from bui.qtsyntax import (QApplication, QColor, QFont, QMenuBar, QPainter, QPen,
+ QPropertyAnimation, QTableWidget, QTableWidgetItem,
+ QTimer, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget)
+
+ QApplication([])
+
+ class CustomWidget(QWidget):
+ painted = []
+
+ def paintEvent(self, event): # noqa: N802 (Qt naming)
+ p = QPainter(self)
+ p.setBrush(QColor("#224488"))
+ p.setPen(QPen(QColor("#ffcc00"), 2))
+ p.drawRect(4, 4, 60, 40)
+ p.drawRoundedRect(70, 4, 40, 40, 8, 8)
+ p.setPen(QColor("#ffffff"))
+ p.setFont(QFont("Segoe UI", 12))
+ p.drawText(10, 60, "custom painted!")
+ CustomWidget.painted.append(1)
+
+ win = QWidget()
+ lay = QVBoxLayout(win)
+ cw = CustomWidget()
+ cw.setFixedHeight(80)
+ lay.addWidget(cw)
+ tree = QTreeWidget()
+ tree.setHeaderLabels(["Name", "Size"])
+ top = QTreeWidgetItem(["src", "4 KB"])
+ tree.addTopLevelItem(top)
+ QTreeWidgetItem(top, ["main.py", "1 KB"])
+ tree.addTopLevelItem(QTreeWidgetItem(["docs", "8 KB"]))
+ tree.expandAll()
+ lay.addWidget(tree)
+ table = QTableWidget(2, 2)
+ table.setHorizontalHeaderLabels(["A", "B"])
+ table.setItem(0, 0, QTableWidgetItem("cell-a"))
+ lay.addWidget(table)
+ mb = QMenuBar()
+ menu_hits = []
+ mb.addMenu("File").addAction("Open", lambda: menu_hits.append("open"))
+ win.setMenuBar(mb)
+
+ ctx = buipy.KitContext(win)
+ win._ctx = ctx
+ ctx.set_header(mb._node)
+ r = buipy.Raster(360, 420)
+ ctx.render(360, 420, r, True)
+ cw.update()
+ ctx.render(360, 420, r, False)
+ assert CustomWidget.painted, "custom paintEvent not called"
+ x, y = pos(cw)
+ assert r.pixel(x + 30, y + 20) == (0x22, 0x44, 0x88), r.pixel(x + 30, y + 20)
+ assert tree.topLevelItemCount() == 2 and top.childCount() == 1 and top.isExpanded()
+
+ table.setItem(0, 1, QTableWidgetItem("cell-b2"))
+ assert table.item(0, 1).text() == "cell-b2"
+ table.setCurrentCell(1, 0)
+ assert table.currentRow() == 1
+ tree.setCurrentItem(top)
+ assert tree.currentItem() is top
+
+ bx, by, bw, bh = mb._node.children[0].rect
+ ctx.press(bx + 5, by + 5, 0)
+ ctx.release(bx + 5, by + 5, 0)
+ assert ctx.popup_count() == 1, "menubar dropdown did not open"
+ px, py, pw, ph = ctx.popup(0).rect
+ ctx.motion(px + 20, py + 12, 0)
+ ctx.press(px + 20, py + 12, 0)
+ ctx.release(px + 20, py + 12, 0)
+ assert menu_hits == ["open"], menu_hits
+
+ # timers + property animation run on a real window's clock
+ w2 = QWidget()
+ w2.resize(120, 60)
+ w2.show()
+ ticks = []
+ timer = QTimer()
+ timer.timeout.connect(lambda: ticks.append(1))
+ timer.start(5)
+ target = type("T", (), {"value": 0})()
+ anim = QPropertyAnimation(target, b"value")
+ anim.setStartValue(0)
+ anim.setEndValue(100)
+ anim.setDuration(60)
+ anim.start()
+ deadline = time.time() + 2
+ while (anim.state() or len(ticks) < 3) and time.time() < deadline:
+ host.update()
+ time.sleep(0.005)
+ timer.stop()
+ assert target.value == 100, target.value
+ assert len(ticks) >= 3, ticks
+ w2.close()
+ host.update()
+
+
+def main() -> int:
+ for k, v in sorted(globals().items()):
+ if k.startswith("test_"):
+ v()
+ print("ok", k)
+ print("advanced surface tests OK")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bindings/python/tests/test_buipy.py b/bindings/python/tests/test_buipy.py
new file mode 100644
index 0000000..a5ef215
--- /dev/null
+++ b/bindings/python/tests/test_buipy.py
@@ -0,0 +1,53 @@
+"""End-to-end test: BUI -> sink dispatch -> Python backend -> SVG output.
+
+Run standalone (PYTHONPATH must contain the built buipy extension and the
+bindings/python source dir) or via ctest.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import os
+import sys
+import tempfile
+
+# Make both the built extension and this package importable when run by hand.
+_here = os.path.dirname(os.path.abspath(__file__))
+_build = os.environ.get("BUIPY_BUILD_DIR", os.path.join(os.path.dirname(_here), "..", "..", "build", "bindings", "python"))
+for p in (_build, os.path.dirname(_here)):
+ if os.path.isdir(p) and p not in sys.path:
+ sys.path.insert(0, p)
+
+import buipy # noqa: E402
+from bui.svg import SvgSink # noqa: E402
+
+
+def main() -> int:
+ assert buipy.version().startswith("0."), buipy.version()
+
+ sink = SvgSink(640, 480)
+ buipy.set_backend(sink)
+ try:
+ buipy.demo_scene(640, 480)
+ finally:
+ buipy.set_backend(None)
+
+ svg = sink.to_svg()
+ assert "<polygon" in svg, "expected triangles in SVG output"
+ assert "<line" in svg, "expected lines in SVG output"
+ assert "<circle" in svg, "expected points in SVG output"
+
+ # A clean double-install and clear round-trip must not crash.
+ buipy.set_backend(SvgSink(320, 240))
+ buipy.demo_scene(320, 240)
+ buipy.set_backend(None)
+
+ out = os.path.join(tempfile.gettempdir(), "bui_py_test.svg")
+ with open(out, "w", encoding="utf-8") as f:
+ f.write(svg)
+
+ print("buipy test OK; SVG written to", out)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bindings/python/tests/test_components.py b/bindings/python/tests/test_components.py
new file mode 100644
index 0000000..69ba91a
--- /dev/null
+++ b/bindings/python/tests/test_components.py
@@ -0,0 +1,767 @@
+"""bui.components on the C kit: layout, Blender interactions, popups,
+rendering and frame-time budgets.
+
+Input is driven through the same scene protocol the Tk host uses (press /
+motion / release / key / wheel / context_menu), headlessly.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import os
+import sys
+import time
+from types import SimpleNamespace
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
+
+import bui # noqa: E402,F401 (locates buipy)
+import buipy # noqa: E402
+from bui.components import (App, Button, Checkbox, ColorSwatch, Column, Dropdown, # noqa: E402
+ EnumRow, Label, ListView, NumberField, NumberSlider, Panel, Row,
+ Split, TextField, Toggle, VectorField, eval_number)
+
+CNR_TOP, CNR_BOTTOM, CNR_LEFT, CNR_RIGHT = 3, 12, 9, 6
+
+buipy.kit_set_animations(False) # deterministic sizes; test_panel_animation turns them on
+
+
+def mods(shift=False, ctrl=False, alt=False, button1=False):
+ return SimpleNamespace(shift=shift, ctrl=ctrl, alt=alt, button1=button1)
+
+
+class Driver:
+ """Headless app + input helpers."""
+
+ def __init__(self, *children, size=(400, 600), header=None):
+ self.app = App("test", size, *children, header=header)
+ self.timers, self.cursors, self.warps = [], [], []
+ self.app.ctx.set_host(schedule=lambda ms, tid: self.timers.append(tid),
+ cursor=self.cursors.append,
+ warp=lambda x, y: self.warps.append((x, y)))
+ self.frame()
+
+ @property
+ def ctx(self):
+ return self.app.ctx
+
+ def frame(self):
+ return self.app.render_raster()
+
+ @staticmethod
+ def center(c):
+ x, y, w, h = c.rect
+ return (x + w // 2, y + h // 2)
+
+ def click(self, c=None, dx=None, m=None, at=None):
+ x, y = at or self.center(c)
+ if dx is not None:
+ x = c.rect[0] + dx
+ self.app.press(x, y, m or mods())
+ self.app.release(x, y, m or mods())
+ self.frame()
+
+ def drag(self, c, dx, m=None, start_dx=None):
+ x, y = self.center(c)
+ if start_dx is not None:
+ x = c.x + start_dx
+ self.app.press(x, y, m or mods())
+ for step in (dx / 3, 2 * dx / 3, dx):
+ self.app.motion(int(x + step), y, m or mods(button1=True))
+ self.app.release(int(x + dx), y, m or mods())
+ self.frame()
+
+ def hover(self, c):
+ self.app.motion(*self.center(c), mods())
+
+ def key(self, keysym, char="", m=None):
+ self.app.key(char, keysym, 0, m or mods())
+ self.frame()
+
+ def type(self, text):
+ for ch in text:
+ self.key(ch, ch)
+
+ def wheel(self, c, delta, m=None):
+ r = self.app.wheel(*self.center(c), delta, m or mods())
+ self.frame()
+ return r
+
+ def popups(self):
+ return self.ctx.popup_count()
+
+
+# -- layout ---------------------------------------------------------------------
+
+
+def test_layout():
+ a, b = Button("A"), Button("B", weight=3)
+ Driver(Row(a, b))
+ assert abs(b.w - 3 * a.w) <= 2, (a.w, b.w)
+ left, right = Label("L"), NumberField("", 1.0)
+ Driver(Split(left, right, factor=0.4))
+ assert abs(left.w / (left.w + right.w) - 0.4) < 0.03
+ x, y, z = Button("x"), Button("y"), Button("z")
+ Driver(Column(x, y, z, align=True))
+ assert x.corners == CNR_TOP and y.corners == 0 and z.corners == CNR_BOTTOM
+ assert y.y == x.y + x.h, "aligned column must have no gaps"
+ t1, t2 = Toggle("a"), Toggle("b")
+ Driver(Row(t1, t2, align=True))
+ assert t1.corners == CNR_LEFT and t2.corners == CNR_RIGHT
+ icon = Button("", icon="ADD", weight=0)
+ wide = Button("wide")
+ Driver(Row(wide, icon))
+ assert icon.w == buipy.kit_unit(), "weight=0 keeps the natural width"
+
+
+# -- numbers ---------------------------------------------------------------------
+
+
+def test_number_scrub_and_modifiers():
+ changes = []
+ f = NumberField("Size", 1.0, step=0.1, on_change=changes.append)
+ d = Driver(f)
+ d.drag(f, 50) # drag right increases
+ plain = f.value
+ assert plain > 1.0 and changes, plain
+ f.set_value(1.0)
+ d.drag(f, 50, m=mods(shift=True)) # Shift: 10x finer
+ assert 1.0 < f.value < plain and abs((f.value - 1) * 10 - (plain - 1)) < 0.2, f.value
+ f.set_value(1.0)
+ d.drag(f, 37, m=mods(ctrl=True)) # Ctrl: snaps to increments
+ assert abs(f.value - round(f.value)) < 1e-9, f.value
+
+
+def test_number_arrows_and_typing():
+ f = NumberField("N", 5, min=0, max=10)
+ d = Driver(f)
+ d.click(f, dx=f.w - 3) # right arrow
+ assert f.value == 6
+ d.click(f, dx=3) # left arrow
+ assert f.value == 5
+ d.click(f) # middle: type a value
+ assert f.editing and d.ctx.focus is f
+ d.type("2*3")
+ d.key("Return")
+ assert f.value == 6 and not f.editing
+ d.click(f)
+ d.type("9")
+ d.key("Escape") # cancel keeps the old value
+ assert f.value == 6
+ d.click(f)
+ d.type("99")
+ d.key("Return")
+ assert f.value == 10, "typed values are clamped to max"
+
+
+def test_slider_relative_drag():
+ s = NumberSlider("Level", 0.5, min=0.0, max=1.0)
+ d = Driver(s)
+ d.drag(s, s.w // 4)
+ assert abs(s.value - 0.75) < 0.02, s.value
+ d.drag(s, -10 * s.w)
+ assert s.value == 0.0
+
+
+def test_value_shortcuts():
+ a, b = NumberField("A", 3.5), NumberField("B", 0.0)
+ d = Driver(Column(a, b))
+ d.hover(a)
+ d.key("c", "c", mods(ctrl=True)) # copy
+ d.hover(b)
+ d.key("v", "v", mods(ctrl=True)) # paste
+ assert b.value == 3.5
+ d.key("minus", "-") # negate
+ assert b.value == -3.5
+ d.key("BackSpace") # clear
+ assert b.value == 0
+ assert d.wheel(b, +1, mods(ctrl=True)) and abs(b.value - 0.1) < 1e-9 # Ctrl+Wheel
+
+
+def test_checkbox_drag_toggle():
+ boxes = [Checkbox("c%d" % i, False) for i in range(4)]
+ d = Driver(Column(*boxes))
+ d.app.press(boxes[0].x + 4, d.center(boxes[0])[1], mods())
+ for c in boxes[1:3]:
+ d.app.motion(c.x + 4, c.y + c.h // 2, mods(button1=True))
+ d.app.release(boxes[2].x + 4, boxes[2].y + 5, mods())
+ assert [c.value for c in boxes] == [True, True, True, False]
+
+
+def test_text_field_editing():
+ got = []
+ t = TextField("", "hello world", on_change=got.append)
+ d = Driver(t)
+ d.click(t)
+ assert t.editing
+ d.key("a", "a", mods(ctrl=True)) # select all
+ d.type("Cube")
+ d.key("BackSpace", m=mods(ctrl=True)) # Ctrl+Backspace: word
+ d.type("Sphere")
+ d.key("Return")
+ assert t.value == "Sphere" and got == ["Sphere"], (t.value, got)
+
+
+def test_dropdown_menu():
+ dd = Dropdown("", ["One", "Two", "Three"])
+ other = Button("other")
+ d = Driver(Column(other, dd)) # the menu opens below dd
+ d.click(dd)
+ assert d.popups() == 1
+ text, (x, y, w, h) = d.ctx.menu_rows(0)[2]
+ assert text == "Three"
+ d.app.motion(x + 10, y + h // 2, mods())
+ d.app.press(x + 10, y + h // 2, mods())
+ d.app.release(x + 10, y + h // 2, mods())
+ assert dd.value == "Three" and not d.popups()
+ clicks = []
+ other.on_click = lambda: clicks.append(1)
+ d.click(dd)
+ d.click(other) # outside click only closes
+ assert not d.popups() and clicks == []
+ d.click(dd)
+ d.key("Escape")
+ assert not d.popups()
+ d.hover(dd)
+ d.wheel(dd, +1, mods(ctrl=True)) # Ctrl+Wheel cycles
+ assert dd.value == "Two"
+
+
+def test_enum_row():
+ e = EnumRow("", ["A", "B", "C"])
+ d = Driver(e)
+ d.click(e, dx=int(e.w * 0.9))
+ assert e.value == "C"
+
+
+def test_panel_collapse_and_solo():
+ p1 = Panel("One", Button("x"))
+ p2 = Panel("Two", Button("y"))
+ d = Driver(p1, p2)
+ h = p1.h
+ d.click(at=(p1.x + 20, p1.y + 5))
+ assert p1.collapsed and p1.h < h
+ d.click(at=(p2.x + 20, p2.y + 5), m=mods(ctrl=True)) # solo
+ assert p1.collapsed and not p2.collapsed
+
+
+def test_listview():
+ renamed = []
+ lv = ListView(["a%d" % i for i in range(20)], rows=4,
+ on_rename=lambda i, n: renamed.append((i, n)))
+ d = Driver(lv)
+ u = buipy.kit_unit()
+ pad = round(0.15 * u)
+ d.click(at=(lv.x + 20, lv.y + pad + u + 2))
+ assert lv.value == 1
+ d.wheel(lv, -1) # scroll down
+ assert lv.scroll == 1
+ x, y = lv.x + 20, lv.y + pad + 2
+ d.app.press(x, y, mods())
+ d.app.release(x, y, mods())
+ d.app.press(x, y, mods()) # double-click: rename
+ d.app.release(x, y, mods())
+ assert lv.editing
+ d.key("a", "a", mods(ctrl=True))
+ d.type("Renamed")
+ d.key("Return")
+ assert renamed == [(1, "Renamed")] and lv.items[1] == "Renamed", renamed
+
+
+def test_vector_and_color():
+ seen = []
+ v = VectorField("Loc", (1.0, 2.0, 3.0), on_change=seen.append)
+ sw = ColorSwatch("", (1.0, 0.0, 0.0, 1.0))
+ d = Driver(Column(v, sw))
+ d.hover(v.fields[1])
+ d.key("BackSpace")
+ assert v.value == (1.0, 0.0, 3.0) and seen[-1] == (1.0, 0.0, 3.0)
+ d.click(sw)
+ tabs = d.ctx.picker_part("tabs")
+ d.click(tabs, dx=5) # RGB tab
+ g = d.ctx.picker_part("slider1")
+ d.drag(g, g.w) # G -> 1
+ r, gg, b, a = sw.value
+ assert r > 0.99 and gg > 0.99 and b < 0.01, sw.value
+ assert ColorSwatch.to_text(sw.value) == "#ffff00ff"
+
+
+def test_tooltip():
+ b = Button("tip", description="Does a thing")
+ d = Driver(b)
+ d.hover(b)
+ assert d.timers, "tooltip timer not scheduled"
+ d.ctx.timer(d.timers[-1])
+ assert d.ctx.tooltip
+ d.frame() # draws without error
+ d.app.motion(b.x + 2, b.y + 2, mods()) # moving hides it
+ assert not d.ctx.tooltip
+
+
+def test_disabled_ignores_input():
+ f = NumberField("", 1.0, enabled=False)
+ d = Driver(f)
+ d.drag(f, 60)
+ d.click(f)
+ assert f.value == 1.0 and not f.editing
+
+
+def test_eval_number():
+ assert abs(eval_number("2*pi") - 2 * 3.141592653589793) < 1e-12
+ assert eval_number("__import__('os')") is None
+ assert eval_number("1/0") is None
+ assert eval_number("10 ** 2 - 1") == 99
+ assert eval_number("2^3") == 8 and eval_number("sqrt(16)") == 4
+
+
+# -- cursors, continuous grab, context menus -------------------------------------
+
+
+def test_cursors_and_continuous_grab():
+ f, t = NumberSlider("S", 0.5), TextField("", "abc")
+ d = Driver(Column(f, t))
+ d.hover(f)
+ assert d.app.cursor == "ew", "number fields show Blender's horizontal arrows"
+ d.hover(t)
+ assert d.app.cursor == "text"
+ x, y = d.center(f)
+ d.app.press(x, y, mods())
+ d.app.motion(x + 20, y, mods(button1=True))
+ assert d.app.cursor == "none", "scrubbing hides the pointer"
+ before = f.value
+ w = d.app.size[0]
+ d.app.motion(w - 2, y, mods(button1=True)) # hits the edge -> warp
+ assert d.warps, "continuous grab must warp the pointer"
+ wx, wy = d.warps[-1]
+ d.app.motion(wx, wy, mods(button1=True)) # the warp's own event: ignored
+ d.app.motion(wx + 10, wy, mods(button1=True)) # keeps scrubbing past the edge
+ assert f.value >= before
+ d.app.release(wx + 10, wy, mods())
+ assert d.warps[-1] == (x, y), "pointer returns to where the drag began"
+ assert d.app.cursor == "ew"
+
+
+def test_context_menu():
+ f = NumberField("N", 2.0, default=1.0)
+ d = Driver(f)
+ f.set_value(5.0)
+ x, y = d.center(f)
+ d.app.context_menu(x, y, mods())
+ rows = [t for t, _ in d.ctx.menu_rows(0) if t != "-"]
+ assert rows == ["Copy Value", "Paste Value", "Reset to Default Value"], rows
+ d.frame()
+ _, (rx, ry, rw, rh) = d.ctx.menu_rows(0)[3]
+ d.click(at=(rx + 10, ry + rh // 2))
+ assert f.value == 1.0 and not d.popups()
+
+
+# -- menus ------------------------------------------------------------------------
+
+
+def test_menu_search_submenu_and_bar():
+ from bui.components import MenuBar, MenuItem
+ picked = []
+ bar = MenuBar(("File", [MenuItem("New", lambda: picked.append("new")),
+ MenuItem("Recent", submenu=[MenuItem("a.blend",
+ lambda: picked.append("a"))]),
+ "-", MenuItem("Quit")]),
+ ("Edit", [MenuItem("Undo")]))
+ d = Driver(Label("body"), header=bar)
+ file_b, edit_b = bar.buttons
+ d.click(file_b)
+ _, (x, y, w, h) = d.ctx.menu_rows(0)[1]
+ d.app.motion(x + 10, y + h // 2, mods()) # hover "Recent"
+ assert d.popups() == 2, "hovering a submenu item opens it"
+ d.frame()
+ d.hover(edit_b) # switch menus
+ assert d.popups() == 1 and d.ctx.popup_owner(0) is edit_b
+ d.ctx.close_popups()
+ d.click(file_b)
+ d.type("blend") # type to search
+ assert [t for t, _ in d.ctx.menu_rows(0)] == ["Recent \u25b8 a.blend"]
+ d.key("Return")
+ assert picked == ["a"] and not d.popups()
+
+
+def test_press_drag_release_picks():
+ dd = Dropdown("", ["One", "Two", "Three"])
+ d = Driver(dd)
+ x, y = d.center(dd)
+ d.app.press(x, y, mods())
+ d.frame()
+ _, (rx, ry, rw, rh) = d.ctx.menu_rows(0)[1]
+ d.app.motion(rx + 10, ry + rh // 2, mods(button1=True))
+ d.app.release(rx + 10, ry + rh // 2, mods())
+ assert dd.value == "Two"
+
+
+def test_pie_menu():
+ from bui.components import MenuItem, PieMenu
+ got = []
+ d = Driver(Label("x"), size=(600, 500))
+ d.ctx.set_pointer(300, 250)
+ d.app.bind("q", lambda: PieMenu.show(d.ctx, [
+ MenuItem(n, (lambda n=n: got.append(n))) for n in "WESN"]))
+ d.app.key("q", "q", 0, mods())
+ d.frame()
+ d.app.motion(300, 120, mods()) # aim north
+ d.app.press(300, 120, mods())
+ assert got == ["N"] and not d.popups()
+
+
+# -- color ------------------------------------------------------------------------------
+
+
+def test_color_wheel_and_eyedropper():
+ sw = ColorSwatch("", (1.0, 1.0, 1.0, 1.0))
+ d = Driver(sw)
+ d.click(sw)
+ wheel = d.ctx.picker_part("area")
+ x, y, w, h = wheel.rect
+ cx, cy, r = x + w / 2, y + h / 2, min(w, h) / 2 - 1
+ d.click(at=(int(cx), int(cy + r - 3))) # bottom rim = red (Blender)
+ rr, g, b, _ = sw.value
+ assert rr > 0.9 and g < 0.15 and b < 0.15, sw.value
+ strip = d.ctx.picker_part("strip")
+ sx, sy, sw_, sh = strip.rect
+ d.click(at=(sx + sw_ // 2, sy + sh - 1)) # value -> 0
+ assert max(sw.value[:3]) < 0.02
+ d.click(at=(sx + sw_ // 2, sy + 1)) # back up: hue survived black
+ assert sw.value[0] > 0.9 and sw.value[1] < 0.15
+ d.click(d.ctx.picker_part("dropper"))
+ assert d.ctx.modal and d.app.cursor == "crosshair"
+ d.app.press(2, d.app.size[1] - 2, mods()) # region background
+ d.app.release(2, d.app.size[1] - 2, mods())
+ assert not d.ctx.modal
+ assert abs(sw.value[0] - 0x30 / 255) < 0.02, sw.value
+
+
+# -- views ------------------------------------------------------------------------------
+
+
+def test_tree_view():
+ from bui.components import TreeItem, TreeView
+ toggled = []
+ a = TreeItem("A", TreeItem("A1"), TreeItem("A2"), toggles={"hide": False})
+ b = TreeItem("B")
+ tv = TreeView([a, b], columns=("hide",), on_toggle=lambda *t: toggled.append(t))
+ d = Driver(tv)
+ assert tv.row_count() == 4
+ rows = tv.rows_info()
+ x, y, w, h = rows[0][1]
+ d.click(at=(x + 3, y + 5)) # arrow: collapse A
+ assert tv.row_count() == 2
+ d.click(at=(x + 60, tv.rows_info()[1][1][1] + 5)) # select B
+ assert tv.value is b
+ d.key("Up")
+ assert tv.value is a
+ d.key("Right")
+ assert a.expanded and tv.row_count() == 4
+ col_x = x + w - buipy.kit_unit()
+ d.click(at=(col_x + 5, y + 5)) # eye toggle
+ assert a.toggles["hide"] is True and toggled
+
+
+def test_grid_view():
+ from bui.components import GridView
+ act = []
+ g = GridView([("a", (1, 0, 0, 1)), ("b", "WORLD"), ("c", None)], on_activate=act.append)
+ d = Driver(g)
+ tx, ty, tw, th = g.tile_rect(1)
+ d.click(at=(tx + tw // 2, ty + th // 2))
+ assert g.value == 1
+ d.key("Right")
+ assert g.value == 2
+ d.key("Return")
+ assert act == [2]
+
+
+# -- editors -----------------------------------------------------------------------------
+
+
+def test_color_ramp():
+ from bui.components import ColorRamp
+ ramp = ColorRamp()
+ d = Driver(ramp)
+ band = ramp.band
+ mid = (band.x + band.w // 2, band.y + 5)
+ d.app.press(*mid, mods(ctrl=True)) # Ctrl+click adds a stop
+ d.app.release(*mid, mods())
+ assert len(ramp.stops) == 3 and abs(ramp.active.pos - 0.5) < 0.02
+ assert abs(ramp.active.color[0] - 0.5) < 0.03 # evaluated mid color
+ assert abs(ramp.pos_field.value - ramp.active.pos) < 1e-6, "fields follow the active stop"
+ d.drag(band, band.w // 4, start_dx=band.w // 2) # drag it right
+ assert ramp.active.pos > 0.7
+ d.hover(band)
+ d.key("x", "x")
+ assert len(ramp.stops) == 2
+ ramp.interpolation = "Constant"
+ assert ramp.evaluate(0.99) == ramp.sorted_stops()[0].color
+
+
+def test_curve_mapping():
+ from bui.components import CurveMapping
+ cm = CurveMapping()
+ d = Driver(cm)
+ g = cm.graph
+ x, y = g.x + g.w // 2, g.y + g.h // 2 # on the diagonal
+ d.app.press(x, y, mods())
+ d.app.motion(x, y - 30, mods(button1=True))
+ d.app.motion(x, y - 40, mods(button1=True))
+ d.app.release(x, y - 40, mods())
+ assert len(cm.points) == 3 and cm.evaluate(0.5) > 0.6
+ d.hover(g)
+ d.key("Delete")
+ assert len(cm.points) == 2 and abs(cm.evaluate(0.5) - 0.5) < 1e-6
+
+
+def test_normal_ball_hotkey_path():
+ from bui.components import HotkeyField, NormalBall, PathField
+ nb = NormalBall("", (0, 0, 1))
+ hk = HotkeyField("", "F3")
+ pf = PathField("", "//", on_browse=lambda: "C:/tmp/x.png")
+ d = Driver(Column(nb, hk, pf))
+ d.click(at=(nb.x + nb.w - 4, nb.y + nb.h // 2))
+ assert nb.value[0] > 0.9
+ d.click(hk)
+ assert hk.capturing
+ d.key("Control_L") # modifiers alone don't bind
+ d.key("k", "k", mods(ctrl=True, shift=True))
+ assert hk.value == "Ctrl Shift K" and not hk.capturing
+ d.click(pf.button)
+ assert pf.value == "C:/tmp/x.png"
+
+
+def test_id_selector():
+ from bui.components import IDSelector
+ ids = IDSelector(["Mat", "Glass"], "Mat")
+ d = Driver(ids)
+ d.click(ids.new)
+ assert ids.value == "Mat.001" and "Mat.001" in ids.items
+ ids.browse.set_value("Glass")
+ assert ids.value == "Glass"
+ assert ids.new.w == ids.unlink.w == buipy.kit_unit(), "icon buttons keep their size"
+
+
+# -- containers ---------------------------------------------------------------------------
+
+
+def test_panel_drag_collapse_and_reorder():
+ ps = [Panel("P%d" % i, Button("b%d" % i)) for i in range(3)]
+ d = Driver(*ps)
+ x = ps[0].x + 30
+ d.app.press(x, ps[0].y + 5, mods()) # collapse P0 ...
+ for p in ps[1:]:
+ d.frame()
+ d.app.motion(x, p.y + 5, mods(button1=True)) # ... and drag over the others
+ d.app.release(x, ps[2].y + 5, mods())
+ d.frame()
+ assert all(p.collapsed for p in ps)
+ gx = ps[0].x + ps[0].w - 5 # drag P0's grip below P2
+ d.app.press(gx, ps[0].y + 5, mods())
+ d.app.motion(gx, ps[2].y + ps[2].h, mods(button1=True))
+ d.app.motion(gx, ps[2].y + ps[2].h + 5, mods(button1=True))
+ d.app.release(gx, ps[2].y + ps[2].h + 5, mods())
+ assert [p.title for p in d.app.root.children] == ["P1", "P2", "P0"]
+
+
+def test_vector_alt_and_copy():
+ v = VectorField("", (1.0, 2.0, 3.0))
+ d = Driver(v)
+ d.drag(v.fields[0], 40, m=mods(alt=True)) # Alt: all axes together
+ delta = v.value[0] - 1.0
+ assert delta > 0 and abs(v.value[1] - 2.0 - delta) < 1e-6 and abs(v.value[2] - 3.0 - delta) < 1e-6
+ d.hover(v.fields[1])
+ d.key("c", "c", mods(ctrl=True, alt=True))
+ v.set_value((0, 0, 0))
+ d.key("v", "v", mods(ctrl=True, alt=True))
+ assert abs(v.value[2] - 3.0 - delta) < 1e-3, v.value
+
+
+def test_scroll_side_tabs_popover():
+ from bui.components import Popover, ScrollView, SideTabs
+ sv = ScrollView(Column(*[Button(str(i)) for i in range(30)]), rows=4)
+ inner = Dropdown("", ["a", "b"])
+ pop = Popover("Opts", inner)
+ tabs = SideTabs([("OBJECT_DATA", "Object", Column(sv, pop)),
+ ("MODIFIER", "Modifiers", Label("mods"))])
+ d = Driver(tabs)
+ d.wheel(sv, -1)
+ assert sv.scroll > 0
+ d.click(pop)
+ assert d.popups() == 1
+ d.click(inner) # a menu inside the popover ...
+ assert d.popups() == 2, "... nests instead of closing the popover"
+ d.ctx.close_popups()
+ u = buipy.kit_unit()
+ d.click(at=(tabs.x + 5, tabs.y + round(0.4 * u) + round(1.4 * u) + 5))
+ assert tabs.current == 1
+
+
+def test_icons_render():
+ names = buipy.kit_icon_names()
+ assert len(names) > 100
+ d = Driver(Column(*[Label(n, icon=n) for n in names]), size=(300, 3000))
+ d.frame()
+
+
+# -- rendering & performance ------------------------------------------------------------
+
+
+def test_damage_driven_rendering():
+ f = NumberField("N", 1.0)
+ other = [Button("b%d" % i) for i in range(20)]
+ d = Driver(Column(f, *other))
+ raster = d.app._raster
+ assert d.ctx.render(*d.app.size, raster) == 0, "idle frames draw nothing"
+ d.hover(f)
+ assert d.ctx.render(*d.app.size, raster) >= 1
+ dmg = raster.damage()
+ assert dmg and all(h <= 64 for _, _, _, h in dmg), "hover damages only the widget's tiles"
+
+
+def test_render_and_perf():
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)),
+ "..", "..", "..", "examples"))
+ import components_demo
+ app = components_demo.build()
+ r = app.render_raster()
+ assert r.size == app.size
+ w, h = app.size
+ n = 50
+ t0 = time.perf_counter()
+ for _ in range(n):
+ app.ctx.render(w, h, r, True)
+ full_ms = (time.perf_counter() - t0) / n * 1000
+ # hover over a number field and back: partial frames
+ page = app.root.children[0].children[0]
+ field = page.children[1].body.children[0].children[1].children[0]
+ fx, fy = field.x + field.w // 2, field.y + field.h // 2
+ fields = page.children[1].body.children[0].children[1].children
+ points = [(f.x + f.w // 2, f.y + f.h // 2) for f in fields]
+ t0 = time.perf_counter()
+ for i in range(n): # hover moves between fields
+ app.motion(*points[i % len(points)], None)
+ assert app.ctx.render(w, h, r) >= 1
+ del fx, fy
+ hover_ms = (time.perf_counter() - t0) / n * 1000
+ print(" demo full frame: %.3f ms, hover frame: %.3f ms" % (full_ms, hover_ms))
+ assert full_ms < 8.3, "full frames must fit a 120 Hz budget"
+ assert hover_ms < 1.0, "interaction frames must be far below 1 ms"
+
+
+# -- interaction polish: undo, Tab, multi-drag, animation, text areas ------------
+
+
+def test_undo_redo():
+ f = NumberField("Size", 1.0, step=0.1)
+ t = TextField("Name", "abc")
+ d = Driver(f, t)
+ d.drag(f, 50)
+ scrubbed = f.value
+ assert scrubbed > 1.0
+ d.click(t)
+ d.type("d")
+ d.key("Return")
+ assert t.value == "abcd", t.value
+ d.key("z", "z", mods(ctrl=True)) # undo the text edit
+ assert t.value == "abc", t.value
+ d.key("z", "z", mods(ctrl=True)) # undo the scrub (one step)
+ assert f.value == 1.0, f.value
+ assert d.ctx.undo_depth()[0] == 0
+ d.key("z", "Z", mods(ctrl=True, shift=True)) # redo
+ assert f.value == scrubbed, f.value
+ d.key("y", "y", mods(ctrl=True)) # Ctrl+Y redo too
+ assert t.value == "abcd", t.value
+
+
+def test_tab_moves_between_fields():
+ a, b, c = TextField("A", ""), NumberField("B", 1), TextField("C", "")
+ d = Driver(a, b, c)
+ d.click(a)
+ d.type("x")
+ d.key("Tab")
+ assert a.value == "x", "Tab must confirm the field it leaves"
+ d.type("5")
+ d.key("Tab")
+ assert b.value == 5, b.value
+ d.type("z")
+ d.key("ISO_Left_Tab", m=mods(shift=True)) # Shift+Tab goes back
+ assert c.value == "z", c.value
+ d.key("Escape")
+ assert d.ctx.focus is None or d.ctx.focus is b
+
+
+def test_vertical_multi_drag():
+ fields = [NumberField(n, 0.0, step=0.1) for n in "XYZ"]
+ d = Driver(Column(*fields, align=True))
+ x, y = d.center(fields[0])
+ _, y2 = d.center(fields[2])
+ d.app.press(x, y, mods())
+ for yy in range(y + 2, y2 + 1, 4): # drag down over the fields
+ d.app.motion(x, yy, mods(button1=True))
+ for dx in (20, 40, 60): # then sideways: edit all
+ d.app.motion(x + dx, y2, mods(button1=True))
+ d.app.release(x + 60, y2, mods())
+ d.frame()
+ vals = [f.value for f in fields]
+ assert vals[0] > 0 and all(abs(v - vals[0]) < 1e-9 for v in vals), vals
+ d.key("z", "z", mods(ctrl=True)) # one undo step for the group
+ assert [f.value for f in fields] == [0.0, 0.0, 0.0]
+
+
+def test_panel_animation():
+ buipy.kit_set_animations(True)
+ try:
+ p = Panel("One", Column(*[Button(str(i)) for i in range(6)]))
+ d = Driver(p, Button("after"))
+ h = p.h
+ d.click(at=(p.x + 20, p.y + 5))
+ assert p.collapsed and d.ctx.animating()
+ seen, deadline = set(), time.time() + 2
+ while d.ctx.animating() and time.time() < deadline:
+ time.sleep(0.01)
+ d.frame()
+ seen.add(p.h)
+ assert not d.ctx.animating() and p.h < h
+ assert any(p.h < v < h for v in seen), "no in-between frames"
+ finally:
+ buipy.kit_set_animations(False)
+
+
+def test_textarea_editing():
+ root = buipy.KitNode("frame")
+ ta = buipy.KitNode("textarea")
+ root.add(ta)
+ ta.geom(1, fill=3, expand=1)
+ ctx = buipy.KitContext(root)
+ r = buipy.Raster(300, 200)
+ ctx.render(300, 200, r, True)
+ x, y, w, h = ta.rect
+ ctx.press(x + 10, y + 10, 0)
+ ctx.release(x + 10, y + 10, 0)
+ for ch in "ab":
+ ctx.key(ch, ch, 0)
+ ctx.key("", "Return", 0)
+ ctx.key("c", "c", 0)
+ assert ta.get_str("value") == "ab\nc", repr(ta.get_str("value"))
+ ctx.key("", "Up", 0)
+ ctx.key("", "BackSpace", 0)
+ assert ta.get_str("value") == "b\nc", repr(ta.get_str("value")) # caret was after "a"
+ ctx.key("z", "z", 2) # a typing burst is one undo step
+ assert ta.get_str("value") == "", repr(ta.get_str("value"))
+ ctx.key("Z", "Z", 3)
+ assert ta.get_str("value") == "b\nc"
+ ctx.render(300, 200, r, False)
+
+
+def main() -> int:
+ tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
+ for t in tests:
+ t()
+ print("ok", t.__name__)
+ print("all component tests passed")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bindings/python/tests/test_render.py b/bindings/python/tests/test_render.py
new file mode 100644
index 0000000..2ce8c1f
--- /dev/null
+++ b/bindings/python/tests/test_render.py
@@ -0,0 +1,263 @@
+"""Native raster pipeline + host behavior regressions.
+
+Covers the Raster renderer (AA primitives, blending, damage tracking, text),
+redraw coalescing in the window host, input semantics (hover vs. drag,
+pointer grab), popup z-order, Toplevel windows, timers.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import os
+import sys
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
+
+import bui # noqa: E402,F401 (locates buipy)
+import buipy # noqa: E402
+from bui import host # noqa: E402
+
+BG = (0.11, 0.11, 0.13, 1.0)
+
+
+
+def pos(w):
+ """Window coordinates of a widget (Qt widgets are kit nodes; tk widgets wrap one)."""
+ return w.absolutePos() if hasattr(w, "absolutePos") else tuple(w._node.rect[:2])
+
+def frame(r, w, h, draw):
+ buipy.set_backend(r)
+ try:
+ buipy.begin_frame(w, h)
+ buipy.draw_rect(0, 0, w, h, BG)
+ draw()
+ buipy.end_frame()
+ finally:
+ buipy.set_backend(None)
+
+
+def test_raster_primitives():
+ r = buipy.Raster(200, 120)
+ frame(r, 200, 120, lambda: (
+ buipy.draw_rect(10, 10, 50, 20, (1.0, 0.0, 0.0, 1.0)),
+ buipy.draw_rect(100, 10, 50, 20, (1.0, 1.0, 1.0, 0.5)),
+ buipy.draw_roundrect(10, 50, 80, 40, 12, (0.0, 0.0, 1.0, 1.0)),
+ buipy.draw_ellipse(150, 80, 30, 15, (0.0, 1.0, 0.0, 1.0)),
+ buipy.draw_polygon([(100, 100), (130, 100), (115, 118)], (1.0, 1.0, 0.0, 1.0)),
+ ))
+ assert r.size == (200, 120)
+ assert r.pixel(30, 20) == (255, 0, 0), r.pixel(30, 20) # solid fill
+ assert r.pixel(9, 20) == (28, 28, 33), r.pixel(9, 20) # crisp edge
+ half = r.pixel(120, 20) # 50% white over bg
+ assert all(abs(a - b) <= 2 for a, b in zip(half, (142, 142, 144))), half
+ assert r.pixel(11, 51) == (28, 28, 33) # outside the arc
+ corner = r.pixel(13, 53) # AA on the arc
+ assert corner != (0, 0, 255) and corner != (28, 28, 33), corner
+ assert r.pixel(50, 70) == (0, 0, 255) # round-rect interior
+ assert r.pixel(170, 80)[1] > 200 and r.pixel(150, 64) == (28, 28, 33) # ellipse, not circle
+ assert r.pixel(115, 104) == (255, 255, 0) # polygon filled
+
+
+def test_damage_tracking():
+ r = buipy.Raster(256, 128)
+ draw = lambda c: (lambda: buipy.draw_rect(70, 40, 20, 10, c)) # noqa: E731
+ frame(r, 256, 128, draw((1.0, 0.0, 0.0, 1.0)))
+ assert r.damage() == [(0, 0, 256, 128)] # first frame: everything
+ frame(r, 256, 128, draw((1.0, 0.0, 0.0, 1.0)))
+ assert r.damage() == [] # identical frame: nothing
+ frame(r, 256, 128, draw((0.0, 1.0, 0.0, 1.0)))
+ dmg = r.damage()
+ assert len(dmg) == 1 and dmg[0][0] <= 70 and dmg[0][2] <= 128, dmg # just that tile
+
+
+def test_damage_reaches_right_edge():
+ # Width not a multiple of the 64px tile: a change touching the right edge
+ # must still be reported (it used to be dropped -> stale window).
+ r = buipy.Raster(400, 64)
+ frame(r, 400, 64, lambda: buipy.draw_rect(300, 10, 100, 20, (1.0, 0.0, 0.0, 1.0)))
+ frame(r, 400, 64, lambda: buipy.draw_rect(300, 10, 100, 20, (0.0, 1.0, 0.0, 1.0)))
+ dmg = r.damage()
+ assert dmg and max(x + w for x, y, w, h in dmg) == 400, dmg
+
+
+def test_window_matches_buffer_after_real_events():
+ """Drive the native window with real Win32 messages and compare what the
+ window shows with the frame buffer."""
+ if not host.native_available():
+ return
+ import ctypes
+ import time
+ from bui.tksyntax import Entry, Scale, Tk
+ root = Tk()
+ root.geometry("400x200")
+ e = Entry(root)
+ e.pack(fill="x", padx=10, pady=10)
+ s = Scale(root, from_=0, to=100, orient="horizontal")
+ s.pack(fill="x", padx=10)
+ for _ in range(10):
+ root.update()
+ time.sleep(0.01)
+ win = root._window
+ hwnd = win.handle
+ u, g = ctypes.windll.user32, ctypes.windll.gdi32
+ u.GetDC.restype = ctypes.c_void_p
+ u.GetDC.argtypes = [ctypes.c_void_p]
+ u.ReleaseDC.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
+ g.GetPixel.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
+ u.PostMessageW.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_size_t, ctypes.c_ssize_t]
+
+ def stale():
+ hdc = u.GetDC(hwnd)
+ bad = 0
+ w, h = win.size
+ for y in range(0, h, 4):
+ for x in range(0, w, 4):
+ c = g.GetPixel(hdc, x, y)
+ if (c & 255, (c >> 8) & 255, (c >> 16) & 255) != win.pixel(x, y):
+ bad += 1
+ u.ReleaseDC(hwnd, hdc)
+ return bad
+
+ def post(msg, x, y, wp=0):
+ # PostMessage (not SendMessage): the window procedure runs Python
+ # callbacks and must be entered from the pump, holding the GIL.
+ u.PostMessageW(hwnd, msg, wp, (y << 16) | (x & 0xFFFF))
+ root.update()
+
+ sx, sy = pos(s)
+ post(0x200, sx + 10, sy + 5)
+ post(0x201, sx + 10, sy + 5, 1)
+ post(0x200, sx + 3000, sy + 5, 1)
+ post(0x202, sx + 3000, sy + 5)
+ assert s.get() > 50, s.get()
+ assert stale() == 0, "slider drag not visible in the window"
+ ex, ey = pos(e)
+ post(0x201, ex + 10, ey + 5, 1)
+ post(0x202, ex + 10, ey + 5)
+ for ch in "hi":
+ u.PostMessageW(hwnd, 0x102, ord(ch), 0) # WM_CHAR
+ root.update()
+ assert e.get() == "hi", e.get()
+ assert stale() == 0, "typed text not visible in the window"
+ root.destroy()
+
+
+def test_text():
+ w = buipy.measure_text("Hello", 13)
+ if not buipy.has_native_text():
+ assert w is None
+ return
+ assert 20 < w < 60, w
+ assert buipy.measure_text("Hello Hello", 13) > w
+ r = buipy.Raster(120, 40)
+ frame(r, 120, 40, lambda: buipy.draw_text(4, 26, 16, "Wg", (1.0, 1.0, 1.0, 1.0)))
+ lit = sum(1 for x in range(120) for y in range(40) if r.pixel(x, y)[0] > 128)
+ assert lit > 30, lit
+
+
+def test_coalesced_redraws():
+ import time
+ from bui.tksyntax import Button, Tk
+ root = Tk()
+ btns = [Button(root, text="b%d" % i) for i in range(5)]
+ for b in btns:
+ b.pack()
+ for _ in range(5): # settle mapping/first frames
+ root.update()
+ time.sleep(0.01)
+ before = root._window.frames
+ for i in range(50): # 50 changes ...
+ btns[i % 5].configure(text="x%d" % i)
+ root.update() # ... one frame
+ assert root._window.frames == before + 1, root._window.frames - before
+ root.destroy()
+
+
+def test_hover_does_not_drag_and_grab():
+ from bui.tksyntax import Scale, Tk
+ root = Tk()
+ sc = Scale(root, from_=0, to=100, orient="horizontal")
+ sc.pack(fill="x")
+ ctx = root._ctx
+ r = buipy.Raster(420, 200)
+ ctx.render(420, 200, r, True)
+ sx, sy = pos(sc)
+ ctx.motion(sx + 5, sy + 5, 0) # enter: hover highlight
+ assert ctx.hover is sc._node
+ ctx.render(420, 200, r, False)
+ for dx in (10, 60, 120): # plain hover across the slider
+ ctx.motion(sx + dx, sy + 5, 0)
+ assert sc.get() == 0, "hover changed the slider value"
+ assert not ctx.needs_render(), "hover within one widget should not redraw"
+ ctx.press(sx + 10, sy + 5, 0)
+ ctx.motion(sx + 5000, sy + 300, 8) # drag far outside
+ assert sc.get() == 100, sc.get() # implicit grab keeps the drag
+ ctx.release(sx + 5000, sy + 300, 0)
+ root.destroy()
+
+
+def test_popup_on_top():
+ from bui.tksyntax import Button, Combobox, Tk
+ root = Tk()
+ cb = Combobox(root, values=["one", "two", "three"])
+ cb.pack(fill="x")
+ below = Button(root, text="below")
+ below.pack(fill="x")
+ ctx = root._ctx
+ r = buipy.Raster(300, 200)
+ ctx.render(300, 200, r, True)
+ bx, by = pos(below)
+ before = r.pixel(bx + 3, by + 3)
+ cx, cy = pos(cb)
+ ctx.press(cx + 5, cy + 5, 0) # open the dropdown
+ ctx.release(cx + 5, cy + 5, 0)
+ assert ctx.popup_count() == 1
+ ctx.render(300, 200, r, False)
+ px, py, pw, ph = ctx.popup(0).rect
+ assert py <= by + 3 < py + ph, "dropdown does not cover the button below"
+ assert r.pixel(bx + 3, by + 3) != before, "dropdown painted under a later sibling"
+ root.destroy()
+
+
+def test_toplevel_has_its_own_content():
+ from bui.tksyntax import Label, Tk, Toplevel
+ root = Tk()
+ top = Toplevel(root, title="second")
+ top.geometry("200x100")
+ lab = Label(top, text="in toplevel")
+ lab.pack()
+ root.update()
+ assert lab.master is top, "child not parented to its Toplevel"
+ assert lab._node in top._node.children and lab._node not in root._node.children
+ assert top._ctx is not root._ctx and top._window.frames >= 1
+ top.destroy()
+ root.destroy()
+
+
+def test_after_cancel():
+ import time
+ from bui.tksyntax import Tk
+ root = Tk()
+ root.update()
+ fired = []
+ tok = root.after(1, lambda: fired.append(1))
+ root.after(1, lambda: fired.append(2))
+ root.after_cancel(tok)
+ deadline = time.time() + 1
+ while not fired and time.time() < deadline:
+ time.sleep(0.005)
+ root.update()
+ assert fired == [2], fired
+ root.destroy()
+
+
+def main() -> int:
+ tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
+ for t in tests:
+ t()
+ print("ok", t.__name__)
+ print("all render tests passed")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bindings/python/tests/test_syntax.py b/bindings/python/tests/test_syntax.py
new file mode 100644
index 0000000..7e38ac5
--- /dev/null
+++ b/bindings/python/tests/test_syntax.py
@@ -0,0 +1,267 @@
+"""Tests for the high-level syntax layers (Qt syntax, tkinter syntax).
+
+Both facades are thin Python over the C kit: widgets are kit nodes, layout is
+the kit's C geometry managers. Input is simulated through the kit context —
+the same entry points the native window calls.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import os
+import sys
+
+_here = os.path.dirname(os.path.abspath(__file__))
+for p in (os.environ.get("BUIPY_BUILD_DIR", ""), os.path.dirname(_here)):
+ if p and p not in sys.path:
+ sys.path.insert(0, p)
+
+import bui # noqa: E402,F401 (auto-locates buipy)
+import buipy # noqa: E402
+
+
+
+def pos(w):
+ """Window coordinates of a widget (Qt widgets are kit nodes; tk widgets wrap one)."""
+ return w.absolutePos() if hasattr(w, "absolutePos") else tuple(w._node.rect[:2])
+
+def click(ctx, w, dx=5, dy=5):
+ x, y = pos(w)
+ ctx.press(x + dx, y + dy, 0)
+ ctx.release(x + dx, y + dy, 0)
+
+
+def test_qt_syntax():
+ from bui.qtsyntax import (QApplication, QLabel, QLineEdit, QProgressBar, QPushButton,
+ QRadioButton, QSlider, QSpinBox, QVBoxLayout, QWidget)
+
+ QApplication([])
+ window = QWidget()
+ layout = QVBoxLayout()
+ label = QLabel("Hello, BUI!")
+ button = QPushButton("Click me")
+ button.clicked.connect(lambda: label.setText("Clicked!"))
+ entry = QLineEdit()
+ edits = []
+ entry.textChanged.connect(edits.append)
+ slider = QSlider()
+ slider.setRange(0, 10)
+ spin = QSpinBox()
+ spin.setRange(0, 5)
+ bar = QProgressBar()
+ bar.setValue(4)
+ radio1, radio2 = QRadioButton("one"), QRadioButton("two")
+ for w in (label, button, entry, slider, spin, bar, radio1, radio2):
+ layout.addWidget(w)
+ window.setLayout(layout)
+
+ ctx = buipy.KitContext(window)
+ r = buipy.Raster(320, 420)
+ ctx.render(320, 420, r, True)
+ for w in (label, button, entry, slider, bar):
+ assert w.width() > 200 and w.height() > 0, (type(w).__name__, w.geometry().width())
+
+ click(ctx, button)
+ assert label.text() == "Clicked!", label.text()
+
+ click(ctx, entry) # click-to-edit, then type
+ for ch in "ok":
+ ctx.key(ch, ch, 0)
+ ctx.key("", "Return", 0)
+ assert entry.text() == "ok", entry.text()
+ assert edits and edits[-1] == "ok", edits
+
+ sx, sy = pos(slider)
+ ctx.press(sx + slider.width() - 3, sy + 5, 0)
+ ctx.motion(sx + slider.width() + 3000, sy + 5, 8)
+ ctx.release(sx + slider.width() + 3000, sy + 5, 0)
+ assert slider.value() == 10, slider.value()
+
+ spin.stepUp()
+ assert spin.value() == 1
+ radio1.setChecked(True)
+ click(ctx, radio2)
+ assert radio2.isChecked() and not radio1.isChecked()
+ assert bar.value() == 4 and bar.get_str("text") == "4%"
+
+
+def test_qt_layout_semantics():
+ from bui.qtsyntax import (QGridLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton,
+ QVBoxLayout, QWidget)
+ win = QWidget()
+ root = QVBoxLayout()
+ grid = QGridLayout()
+ name, edit = QLabel("Name:"), QLineEdit()
+ grid.addWidget(name, 0, 0)
+ grid.addWidget(edit, 0, 1)
+ root.addLayout(grid)
+ row = QHBoxLayout()
+ a, b = QPushButton("A"), QPushButton("B")
+ row.addWidget(a)
+ row.addWidget(b)
+ root.addLayout(row)
+ win.setLayout(root)
+ buipy.KitContext(win).render(400, 200, buipy.Raster(400, 200), True)
+ for w in (name, edit, a, b):
+ assert w.parentWidget() is win, "widget in nested layout not parented"
+ assert w.width() > 0 and w.height() > 0
+ assert edit.width() > name.width(), "expanding line edit did not take the space"
+ assert abs(a.width() - b.width()) <= 1, (a.width(), b.width()) # row shared evenly
+ assert a.x() < b.x() and a.y() == b.y()
+ assert a.x() == name.x(), "nested layouts must not add margins"
+
+
+def test_qt_painter_and_signals():
+ from bui.qtsyntax import QColor, QPainter, QVBoxLayout, QWidget, Signal
+
+ class Swatch(QWidget):
+ def paintEvent(self, event): # noqa: N802
+ p = QPainter(self)
+ p.setBrush(QColor("#ff0000"))
+ p.setPen(None)
+ p.drawRect(0, 0, 30, 20)
+ p.end()
+
+ win = QWidget()
+ lay = QVBoxLayout(win)
+ sw = Swatch()
+ sw.setFixedHeight(40)
+ lay.addWidget(sw)
+ ctx = buipy.KitContext(win)
+ r = buipy.Raster(200, 100)
+ ctx.render(200, 100, r, True)
+ sw.update()
+ ctx.render(200, 100, r, False)
+ x, y = pos(sw)
+ assert sw.height() == 40, sw.height()
+ assert r.pixel(x + 10, y + 10) == (255, 0, 0), r.pixel(x + 10, y + 10)
+
+ class Emitter(QWidget):
+ valueChanged = Signal(int)
+
+ e, got = Emitter(), []
+ e.valueChanged.connect(got.append)
+ e.valueChanged.emit(42)
+ e.valueChanged.connect(lambda: got.append("no-arg slot"))
+ e.valueChanged.emit(1)
+ assert got == [42, 1, "no-arg slot"], got
+
+
+def test_tk_syntax():
+ from bui.tksyntax import (Button, Canvas, Checkbutton, Entry, IntVar, Label, Listbox,
+ Radiobutton, Scale, Spinbox, StringVar, Tk)
+
+ root = Tk()
+ root.geometry("420x520")
+ name = StringVar()
+ entry = Entry(root, textvariable=name)
+ entry.pack(fill="x", pady=4)
+ mirror = Label(root, textvariable=name)
+ mirror.pack()
+ out = Label(root, text="")
+ out.pack()
+ btn = Button(root, text="Go", command=lambda: out.configure(text=name.get() + "!"))
+ btn.pack()
+ lb = Listbox(root)
+ lb.insert("end", "one", "two", "three")
+ lb.pack(fill="x")
+ cv = Canvas(root, width=100, height=50)
+ tag_hits = []
+ cv.create_rectangle(0, 0, 40, 40, fill="red", tags=("hot",))
+ cv.tag_bind("hot", "<Button-1>", lambda ev: tag_hits.append(1))
+ cv.pack()
+ sc = Scale(root, from_=0, to=10, orient="horizontal")
+ sc.pack(fill="x")
+ sp = Spinbox(root, from_=0, to=5)
+ sp.pack()
+ cb = Checkbutton(root, text="opt")
+ cb.pack()
+ var2 = IntVar()
+ rb = Radiobutton(root, text="r1", value=1, variable=var2)
+ rb.pack()
+ ctx = root._ctx
+ r = buipy.Raster(420, 520)
+ ctx.render(420, 520, r, True)
+
+ bx, by = pos(btn)
+ assert r.pixel(bx + btn.winfo_width() // 2, by + 3) != r.pixel(2, 2), "button not drawn"
+
+ click(ctx, entry)
+ for ch in "hi":
+ ctx.key(ch, ch, 0)
+ assert name.get() == "hi", name.get() # Entry is live, like Tk
+ assert mirror.cget("text") == "hi"
+ ctx.key("", "Return", 0)
+
+ click(ctx, btn)
+ assert out.cget("text") == "hi!", out.cget("text")
+
+ click(ctx, lb, 10, 10)
+ assert lb.curselection() == (0,), lb.curselection()
+
+ sx, sy = pos(sc)
+ ctx.press(sx + sc.winfo_width() - 2, sy + 5, 0)
+ ctx.motion(sx + sc.winfo_width() + 3000, sy + 5, 8)
+ ctx.release(sx + sc.winfo_width() + 3000, sy + 5, 0)
+ assert sc.get() == 10, sc.get()
+
+ click(ctx, rb)
+ assert var2.get() == 1
+
+ calls = []
+ btn.bind("<Button-1>", lambda e: calls.append((e.x, e.y)))
+ click(ctx, btn)
+ assert calls, "bind() did not fire"
+
+ click(ctx, cv, 10, 10)
+ assert tag_hits == [1], tag_hits
+
+ cb.invoke()
+ assert root.getvar(str(cb.cget("variable"))) == 1
+ root.destroy()
+
+
+def test_tk_geometry_managers():
+ from bui.tksyntax import Button, Frame, Label, Tk
+
+ root = Tk()
+ fr = Frame(root)
+ fr.pack(fill="both", expand=True)
+ inner = Label(fr, text="inside")
+ inner.pack()
+ Button(root, text="bottom").pack()
+ ctx = root._ctx
+ ctx.render(300, 300, buipy.Raster(300, 300), True)
+ fx, fy = pos(fr)
+ ix, iy = pos(inner)
+ assert fx <= ix < fx + fr.winfo_width() and fy <= iy < fy + fr.winfo_height()
+ big = fr.winfo_height()
+ ctx.render(300, 150, buipy.Raster(300, 150), True)
+ assert fr.winfo_height() < big, "expanded size stuck after shrinking"
+
+ g = Frame(root)
+ g.pack(fill="x")
+ cells = [Label(g, text="c%d" % i) for i in range(3)]
+ for i, c in enumerate(cells):
+ c.grid(row=0, column=i, sticky="ew")
+ g.columnconfigure(1, weight=1)
+ p = Label(root, text="placed")
+ p.place(x=7, y=9)
+ ctx.render(300, 300, buipy.Raster(300, 300), True)
+ assert cells[1].winfo_width() > cells[0].winfo_width() * 2, "grid weight ignored"
+ assert cells[0].winfo_x() < cells[1].winfo_x() < cells[2].winfo_x()
+ assert (p.winfo_x(), p.winfo_y()) == (7, 9)
+ assert g.grid_slaves() and inner.pack_info()["side"] == "top"
+ root.destroy()
+
+
+def main() -> int:
+ for k, v in sorted(globals().items()):
+ if k.startswith("test_"):
+ v()
+ print("ok", k)
+ print("syntax layer tests OK")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bindings/python/tests/test_tk_compat.py b/bindings/python/tests/test_tk_compat.py
new file mode 100644
index 0000000..cc7f59a
--- /dev/null
+++ b/bindings/python/tests/test_tk_compat.py
@@ -0,0 +1,545 @@
+"""tkinter compatibility: the same programs run on the stdlib tkinter and on
+BUI (``bui.tksyntax``), and must observe the same results.
+
+Each program is ordinary tkinter code written against ``tk`` / ``ttk``
+modules handed in; it returns a dict of observations. The stdlib run is the
+reference (skipped when Tk isn't installed).
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import os
+import sys
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
+
+import bui # noqa: E402,F401 (locates buipy)
+
+
+# ==========================================================================
+# Programs (plain tkinter)
+
+
+def settle(root, widget):
+ """Run the event loop until `widget` is mapped (a window manager maps
+ windows asynchronously)."""
+ for _ in range(200):
+ root.update()
+ if widget.winfo_viewable():
+ break
+ root.after(5)
+ root.update()
+
+
+def prog_calculator(tk, ttk):
+ root = tk.Tk()
+ root.title("Calc")
+ expr = tk.StringVar()
+ entry = tk.Entry(root, textvariable=expr, width=16, justify="right")
+ entry.grid(row=0, column=0, columnspan=4, sticky="we", padx=4, pady=4)
+ out = []
+
+ def press(key):
+ if key == "=":
+ try:
+ expr.set(str(eval(expr.get() or "0")))
+ except Exception:
+ expr.set("error")
+ elif key == "C":
+ expr.set("")
+ else:
+ expr.set(expr.get() + key)
+ buttons = {}
+ for r, row in enumerate(("789/", "456*", "123-", "0C=+")):
+ for c, key in enumerate(row):
+ b = tk.Button(root, text=key, width=4, command=lambda k=key: press(k))
+ b.grid(row=r + 1, column=c, sticky="nsew")
+ buttons[key] = b
+ for c in range(4):
+ root.columnconfigure(c, weight=1)
+ for key in "12+30=":
+ buttons[key].invoke()
+ out.append(expr.get())
+ buttons["C"].invoke()
+ entry.insert(0, "6*7")
+ buttons["="].invoke()
+ out.append(entry.get())
+ info = buttons["5"].grid_info()
+ result = {"results": out, "grid": (info["row"], info["column"]), "size": root.grid_size(),
+ "slaves": len(root.grid_slaves(row=1)), "class": buttons["1"].winfo_class(),
+ "name": str(buttons["1"]).startswith(".!button")}
+ root.destroy()
+ return result
+
+
+def prog_todo(tk, ttk):
+ root = tk.Tk()
+ frame = tk.Frame(root)
+ frame.pack(fill="both", expand=True)
+ sb = tk.Scrollbar(frame)
+ sb.pack(side="right", fill="y")
+ lb = tk.Listbox(frame, yscrollcommand=sb.set, selectmode="extended", height=5)
+ lb.pack(side="left", fill="both", expand=True)
+ sb.config(command=lb.yview)
+ entry = tk.Entry(root)
+ entry.pack(fill="x")
+ events = []
+ lb.bind("<<ListboxSelect>>", lambda e: events.append("select"))
+
+ def add():
+ if entry.get():
+ lb.insert("end", entry.get())
+ entry.delete(0, "end")
+ tk.Button(root, text="Add", command=add).pack()
+ for item in ("milk", "eggs", "bread", "tea", "jam", "rice", "beans", "soap"):
+ entry.insert(0, item)
+ add()
+ lb.selection_set(1, 3)
+ sel = lb.curselection()
+ lb.selection_clear(2)
+ sel2 = lb.curselection()
+ lb.delete(0)
+ after_delete = lb.curselection()
+ lb.insert(0, "first")
+ root.update()
+ first, last = lb.yview()
+ lb.yview_moveto(1.0)
+ root.update()
+ moved = lb.yview()[0] > 0
+ lb.see(0)
+ root.update()
+ result = {"size": lb.size(), "sel": sel, "sel2": sel2, "after_delete": after_delete,
+ "get": lb.get(0, 2), "end": lb.get("end"), "includes": lb.selection_includes(3),
+ "view_start": first == 0.0 and last < 1.0, "moved": moved,
+ "back": lb.yview()[0] == 0.0, "events": events, "entry": entry.get(),
+ "sb": tuple(round(v, 1) for v in sb.get())[:1]}
+ root.destroy()
+ return result
+
+
+def prog_form(tk, ttk):
+ root = tk.Tk()
+ vcmd = (root.register(lambda p: p.isdigit() or p == ""), "%P")
+ age = ttk.Entry(root, validate="key", validatecommand=vcmd)
+ age.grid(row=0, column=1)
+ age.insert(0, "42")
+ age.insert("end", "x") # rejected
+ color = tk.StringVar(value="red")
+ combo = ttk.Combobox(root, textvariable=color, values=("red", "green", "blue"),
+ state="readonly")
+ combo.grid(row=1, column=1)
+ picked = []
+ combo.bind("<<ComboboxSelected>>", lambda e: picked.append(combo.get()))
+ combo.current(2)
+ agree = tk.BooleanVar()
+ chk = ttk.Checkbutton(root, text="Agree", variable=agree)
+ chk.grid(row=2, column=1)
+ chk.invoke()
+ level = tk.IntVar(value=1)
+ radios = [ttk.Radiobutton(root, text=t, variable=level, value=v)
+ for t, v in (("low", 1), ("mid", 2), ("high", 3))]
+ radios[2].invoke()
+ spin = tk.Spinbox(root, from_=0, to=10, increment=2)
+ spin.grid(row=4, column=1)
+ spin.invoke("buttonup")
+ spin.invoke("buttonup")
+ words = tk.Spinbox(root, values=("a", "b", "c"))
+ words.invoke("buttonup")
+ scale_log = []
+ scale = tk.Scale(root, from_=0, to=100, orient="horizontal",
+ command=lambda v: scale_log.append(v))
+ scale.set(30)
+ tscale = ttk.Scale(root, from_=0, to=1)
+ tscale.set(0.25)
+ result = {"age": age.get(), "color": color.get(), "combo_current": combo.current(),
+ "agree": agree.get(), "level": level.get(), "spin": spin.get(),
+ "words": words.get(), "scale": scale.get(), "scale_log": scale_log[-1:],
+ "tscale": round(tscale.get(), 2), "chk_state": "selected" in chk.state(),
+ "combo_class": combo.winfo_class(), "radio_val": radios[0].cget("value")}
+ chk.state(["disabled"])
+ result["disabled"] = chk.instate(["disabled"])
+ root.destroy()
+ return result
+
+
+def prog_editor(tk, ttk):
+ root = tk.Tk()
+ text = tk.Text(root, width=40, height=8, undo=True)
+ sb = ttk.Scrollbar(root, orient="vertical", command=text.yview)
+ text.configure(yscrollcommand=sb.set)
+ text.pack(side="left", fill="both", expand=True)
+ sb.pack(side="right", fill="y")
+ menubar = tk.Menu(root)
+ filemenu = tk.Menu(menubar, tearoff=0)
+ log = []
+ filemenu.add_command(label="New", command=lambda: log.append("new"), accelerator="Ctrl+N")
+ filemenu.add_separator()
+ filemenu.add_command(label="Quit", command=lambda: log.append("quit"))
+ menubar.add_cascade(label="File", menu=filemenu)
+ wrap = tk.BooleanVar(value=False)
+ view = tk.Menu(menubar) # with the default tearoff entry
+ view.add_checkbutton(label="Wrap", variable=wrap)
+ menubar.add_cascade(label="View", menu=view)
+ root.config(menu=menubar)
+ filemenu.invoke(0)
+ filemenu.invoke("Quit")
+ view.invoke(1)
+ text.insert("1.0", "hello world\nsecond line\n")
+ text.insert("end", "third")
+ text.tag_configure("hl", foreground="red", background="yellow")
+ text.tag_add("hl", "1.0", "1.5")
+ text.mark_set("m", "2.3")
+ text.insert("1.0", ">> ")
+ pos = text.search("second", "1.0")
+ count = tk.IntVar()
+ text.search(r"l+", "1.0", regexp=True, count=count)
+ text.delete("1.0", "1.3")
+ text.edit_separator()
+ text.insert("end", "!")
+ text.edit_undo()
+ mods = []
+ text.bind("<<Modified>>", lambda e: mods.append(1))
+ text.edit_modified(False)
+ for _ in range(25):
+ text.insert("end", "\nline")
+ root.update()
+ text.see("end")
+ root.update()
+ result = {"menu_log": log, "wrap": wrap.get(), "view_types": (view.type(0), view.type(1)),
+ "end_index": filemenu.index("end"), "accel": filemenu.entrycget(0, "accelerator"),
+ "content": text.get("1.0", "4.0"), "hl": text.tag_ranges("hl"),
+ "mark": text.index("m"), "search": pos, "count": count.get(),
+ "line3": text.get("3.0", "3.end"), "lineend": text.index("1.2 lineend"),
+ "wordstart": text.index("2.3 wordstart"), "compare": text.compare("1.0", "<", "2.0"),
+ "end": text.index("end"), "names": "hl" in text.tag_names("1.1"),
+ "scrolled": text.yview()[1] == 1.0 and text.yview()[0] > 0,
+ "sb_follows": sb.get()[1] == 1.0,
+ "count_lines": text.count("1.0", "3.0", "lines")}
+ root.destroy()
+ return result
+
+
+def prog_table(tk, ttk):
+ root = tk.Tk()
+ tree = ttk.Treeview(root, columns=("size", "kind"), show="headings", height=4)
+ order = []
+
+ def sort_by(col):
+ rows = [(tree.set(i, col), i) for i in tree.get_children("")]
+ rows.sort(reverse=True)
+ for k, (_, i) in enumerate(rows):
+ tree.move(i, "", k)
+ order.append(col)
+ for col in ("size", "kind"):
+ tree.heading(col, text=col.title(), command=lambda c=col: sort_by(c))
+ tree.column(col, width=80, anchor="e")
+ ids = [tree.insert("", "end", values=(n, k)) for n, k in
+ (("10", "a"), ("30", "b"), ("20", "c"))]
+ folder = tree.insert("", "end", iid="dir", values=("5", "d"), open=False)
+ child = tree.insert("dir", "end", values=("1", "e"))
+ sort_by("size")
+ sel = []
+ tree.bind("<<TreeviewSelect>>", lambda e: sel.append(tree.selection()))
+ tree.selection_set(ids[0], ids[2])
+ tree.selection_add("dir")
+ tree.selection_remove(ids[0])
+ tree.item(ids[1], values=("31", "b2"))
+ tree.set(ids[2], "kind", "z")
+ tree.detach(ids[1])
+ detached = tree.get_children("")
+ tree.reattach(ids[1], "", 0)
+ tree.see(child)
+ result = {"order": order, "children": len(tree.get_children("")),
+ "first": tree.set(tree.get_children("")[0], "size"),
+ "selection": tree.selection(), "sel_events": len(sel) > 0,
+ "item": tree.item(ids[1])["values"], "set": tree.set(ids[2], "kind"),
+ "detached": len(detached), "parent": tree.parent(child),
+ "next": tree.next(ids[1]) != "", "exists": tree.exists("dir"),
+ "open": tree.item("dir", "open") in (True, 1),
+ "heading": tree.heading("size")["text"], "index": tree.index(ids[1]),
+ "focus_empty": tree.focus() in ("", ids[0], ids[2], "dir"),
+ "tag_has": tree.tag_has("x")}
+ tree.delete("dir")
+ result["after_delete"] = len(tree.get_children(""))
+ result["exists_child"] = tree.exists(child)
+ root.destroy()
+ return result
+
+
+def prog_canvas(tk, ttk):
+ root = tk.Tk()
+ canvas = tk.Canvas(root, width=200, height=150, scrollregion=(0, 0, 400, 300))
+ hbar = tk.Scrollbar(root, orient="horizontal", command=canvas.xview)
+ canvas.configure(xscrollcommand=hbar.set)
+ canvas.pack()
+ hbar.pack(fill="x")
+ r = canvas.create_rectangle(10, 10, 60, 40, fill="blue", tags=("box", "shape"))
+ o = canvas.create_oval(100, 100, 140, 140, outline="red", tags="shape")
+ ln = canvas.create_line(0, 0, 50, 50, 90, 10, arrow="last", smooth=True)
+ t = canvas.create_text(30, 80, text="hi", anchor="nw")
+ clicks = []
+ canvas.tag_bind("box", "<Button-1>", lambda e: clicks.append("box"))
+ canvas.move("shape", 5, 5)
+ canvas.itemconfigure(r, fill="green")
+ canvas.addtag_withtag("all_shapes", "shape")
+ canvas.dtag(o, "shape")
+ settle(root, canvas)
+ canvas.xview_moveto(0.5)
+ root.update()
+ x_after = canvas.canvasx(0)
+ canvas.xview_scroll(-1, "pages")
+ result = {"coords": canvas.coords(r), "fill": canvas.itemcget(r, "fill"),
+ "shape": canvas.find_withtag("shape"), "all_shapes": canvas.find_withtag(
+ "all_shapes"), "type": canvas.type(t), "gettags": canvas.gettags(o),
+ "overlap": canvas.find_overlapping(0, 0, 70, 50)[:1],
+ "enclosed": canvas.find_enclosed(0, 0, 200, 200)[:2], "above": canvas.find_above(r),
+ "xview": canvas.xview()[0] < 0.5, "canvasx": x_after,
+ "hbar": round(hbar.get()[0], 2), "bbox_box": canvas.bbox("box")[:2],
+ "line_type": canvas.type(ln)}
+ canvas.delete("shape")
+ result["after_delete"] = canvas.find_all()
+ root.destroy()
+ return result
+
+
+def prog_scrollable_frame(tk, ttk):
+ root = tk.Tk()
+ root.geometry("300x200")
+ container = ttk.Frame(root)
+ canvas = tk.Canvas(container, height=150)
+ scrollbar = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
+ inner = ttk.Frame(canvas)
+ inner.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
+ win = canvas.create_window((0, 0), window=inner, anchor="nw")
+ canvas.configure(yscrollcommand=scrollbar.set)
+ for i in range(30):
+ ttk.Label(inner, text="Row %d" % i).pack(anchor="w")
+ container.pack(fill="both", expand=True)
+ canvas.pack(side="left", fill="both", expand=True)
+ scrollbar.pack(side="right", fill="y")
+ settle(root, inner)
+ region = canvas.cget("scrollregion")
+ canvas.yview_moveto(1.0)
+ root.update()
+ result = {"region_set": bool(region), "win_type": canvas.type(win),
+ "scrolled": canvas.yview()[1] == 1.0, "sb": scrollbar.get()[1] == 1.0,
+ "inner_children": len(inner.winfo_children()),
+ "toplevel": inner.winfo_toplevel() is root}
+ root.destroy()
+ return result
+
+
+def prog_widgets(tk, ttk):
+ root = tk.Tk()
+ nb = ttk.Notebook(root)
+ tab1, tab2 = ttk.Frame(nb), ttk.Frame(nb)
+ nb.add(tab1, text="One")
+ nb.add(tab2, text="Two")
+ nb.pack(fill="both", expand=True)
+ changes = []
+ nb.bind("<<NotebookTabChanged>>", lambda e: changes.append(nb.index("current")))
+ nb.select(tab2)
+ pw = tk.PanedWindow(root, orient="horizontal")
+ left, right = tk.Label(pw, text="L"), tk.Label(pw, text="R")
+ pw.add(left)
+ pw.add(right)
+ pw.pack(fill="both", expand=True)
+ var = tk.StringVar(value="b")
+ om = tk.OptionMenu(root, var, "a", "b", "c")
+ om.pack()
+ om["menu"].invoke(2)
+ menu = om["menu"]
+ menu.delete(0, "end")
+ for v in ("x", "y"):
+ menu.add_command(label=v, command=tk._setit(var, v))
+ menu.invoke(1)
+ mb = ttk.Menubutton(root, text="Menu")
+ mbm = tk.Menu(mb, tearoff=0)
+ mb["menu"] = mbm
+ mbm.add_radiobutton(label="r1", variable=var, value="r1")
+ mbm.invoke(0)
+ pb = ttk.Progressbar(root, maximum=10, value=3)
+ pb.step(2)
+ sep = ttk.Separator(root, orient="horizontal")
+ sep.pack(fill="x")
+ lf = tk.LabelFrame(root, text="Group")
+ lf.pack()
+ msg = tk.Message(root, text="a long message " * 4, width=120)
+ msg.pack()
+ lbl = tk.Label(root, text="x", font=("Arial", 18, "bold"), fg="red", cursor="hand2")
+ lbl.pack()
+ img = tk.PhotoImage(width=4, height=3)
+ img.put("#ff0000", to=(0, 0, 4, 3))
+ img.put("#00ff00", (1, 1))
+ lbl2 = tk.Label(root, image=img)
+ lbl2.pack()
+ style = ttk.Style()
+ style.configure("My.TButton", padding=6)
+ top = tk.Toplevel(root)
+ top.title("second")
+ top_lbl = tk.Label(top, text="top")
+ top_lbl.pack()
+ root.update()
+ result = {"nb": (nb.index("current"), len(nb.tabs()), nb.tab(tab1, "text")),
+ "nb_changes": changes[-1:], "panes": len(pw.panes()), "var": var.get(),
+ "pb": float(pb["value"]), "lf": lf.cget("text"),
+ "img": (img.width(), img.height(), img.get(1, 1), img.get(0, 0)),
+ "style": style.configure("My.TButton")["padding"] if isinstance(
+ style.configure("My.TButton"), dict) else 6,
+ "top_title": top.title(), "top_parent": top_lbl.winfo_toplevel() is top,
+ "class_top": top.winfo_class(), "lbl_font": lbl.cget("font"),
+ "keys": "text" in lbl.keys(), "cursor": lbl["cursor"]}
+ top.destroy()
+ result["top_gone"] = not top.winfo_exists()
+ root.destroy()
+ return result
+
+
+def prog_events(tk, ttk):
+ root = tk.Tk()
+ log = []
+ btn = tk.Button(root, text="b")
+ btn.pack()
+ settle(root, btn) # Tk delivers events to mapped windows
+ btn.bind("<<Custom>>", lambda e: log.append(("custom", e.widget is btn)))
+ btn.bind("<Control-s>", lambda e: log.append("ctrl-s"))
+ root.bind_all("<<Global>>", lambda e: log.append("global"))
+ root.bind_class("Button", "<<Custom>>", lambda e: log.append("class"), add="+")
+ btn.event_generate("<<Custom>>")
+ btn.event_generate("<<Global>>")
+ btn.bind("<<Stop>>", lambda e: (log.append("stop"), "break")[1])
+ root.bind_class("Button", "<<Stop>>", lambda e: log.append("not reached"))
+ btn.event_generate("<<Stop>>")
+ root.event_add("<<Save>>", "<Control-q>")
+ btn.bind("<<Save>>", lambda e: log.append("save"))
+ btn.event_generate("<Control-q>")
+ tags = btn.bindtags()
+ fired = []
+ v = tk.StringVar()
+ cb = v.trace_add("write", lambda *a: fired.append(v.get()))
+ v.set("one")
+ v.trace_remove("write", cb)
+ v.set("two")
+ after_ids = []
+ aid = root.after(10000, lambda: None)
+ after_ids.append(aid in root.after_info())
+ root.after_cancel(aid)
+ ran = []
+ root.after(1, lambda: ran.append(1))
+ for _ in range(50):
+ root.update()
+ if ran:
+ break
+ root.after(5)
+ result = {"log": log, "tags": (tags[1], tags[2], tags[3]), "traces": fired,
+ "after_known": after_ids, "after_ran": ran, "getvar": root.getvar(str(v)),
+ "bool": root.getboolean("yes"), "int": root.winfo_pixels("1i") > 50,
+ "rgb": root.winfo_rgb("#ff0000")[0] > 60000}
+ root.destroy()
+ return result
+
+
+PROGRAMS = [prog_calculator, prog_todo, prog_form, prog_editor, prog_table, prog_canvas,
+ prog_scrollable_frame, prog_widgets, prog_events]
+
+
+# ==========================================================================
+# Harness
+
+
+def _bui_modules():
+ import bui.tksyntax as tk
+ from bui.tksyntax import ttk
+ return tk, ttk
+
+
+def _real_modules():
+ try:
+ from bui import _realtk
+ tk = _realtk.module("tkinter")
+ import importlib
+ ttk = importlib.import_module("tkinter.ttk")
+ tk.Tk().destroy()
+ return tk, ttk
+ except Exception:
+ return None
+
+
+def _normalize(v):
+ """Values that legitimately differ in type between Tcl and Python."""
+ if hasattr(v, "string"): # Tcl_Obj
+ return str(v)
+ if isinstance(v, tuple):
+ return tuple(_normalize(x) for x in v)
+ if isinstance(v, list):
+ return [_normalize(x) for x in v]
+ if isinstance(v, dict):
+ return {k: _normalize(x) for k, x in v.items()}
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
+ return float(v)
+ return v
+
+
+# Observations that depend on fonts / pixel metrics: compared loosely.
+_LOOSE = {"prog_canvas": {"canvasx", "hbar", "xview"}, "prog_widgets": {"lbl_font"},
+ "prog_todo": {"sb"}, "prog_editor": {"scrolled", "sb_follows"},
+ "prog_scrollable_frame": {"scrolled", "sb", "region_set"}}
+# ... and what BUI must observe for them (stdlib Tk's depends on window mapping timing)
+_BUI_EXPECT = {"prog_editor": {"scrolled": True, "sb_follows": True},
+ "prog_canvas": {"xview": True, "canvasx": 200.0},
+ "prog_scrollable_frame": {"scrolled": True, "sb": True, "region_set": True}}
+
+
+def test_programs_match_stdlib():
+ real = _real_modules()
+ bui_tk, bui_ttk = _bui_modules()
+ for prog in PROGRAMS:
+ got = prog(bui_tk, bui_ttk)
+ for key, value in _BUI_EXPECT.get(prog.__name__, {}).items():
+ assert got[key] == value, "%s[%s]: bui %r" % (prog.__name__, key, got[key])
+ if real is None:
+ print("ran", prog.__name__, "(no stdlib Tk to compare)")
+ continue
+ want = prog(*real)
+ loose = _LOOSE.get(prog.__name__, set())
+ for key, ref in want.items():
+ if key in loose:
+ continue
+ a, b = _normalize(got.get(key)), _normalize(ref)
+ assert a == b, "%s[%s]: bui %r != tkinter %r" % (prog.__name__, key, a, b)
+ print("ok", prog.__name__)
+
+
+def test_install_runs_unchanged_scripts():
+ """`import tkinter` after install() is BUI; dialogs modules resolve too."""
+ import importlib
+ import bui.tksyntax as tks
+ saved = {k: v for k, v in sys.modules.items() if k == "tkinter" or k.startswith("tkinter.")}
+ try:
+ tks.install()
+ tkinter = importlib.import_module("tkinter")
+ from tkinter import messagebox, ttk # noqa: F401
+ from tkinter.scrolledtext import ScrolledText
+ assert tkinter is tks and ttk is tks.ttk
+ root = tkinter.Tk()
+ st = ScrolledText(root, height=4)
+ st.pack(fill="both", expand=True)
+ st.insert("end", "x\n" * 20)
+ root.update()
+ assert st.vbar.get()[1] <= 1.0 and isinstance(st, tkinter.Text)
+ root.destroy()
+ finally:
+ for k in [k for k in sys.modules if k == "tkinter" or k.startswith("tkinter.")]:
+ del sys.modules[k]
+ sys.modules.update(saved)
+
+
+def main() -> int:
+ test_programs_match_stdlib()
+ test_install_runs_unchanged_scripts()
+ print("tkinter compatibility tests passed")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bindings/python/tests/test_tk_input.py b/bindings/python/tests/test_tk_input.py
new file mode 100644
index 0000000..33b6c24
--- /dev/null
+++ b/bindings/python/tests/test_tk_input.py
@@ -0,0 +1,232 @@
+"""tkinter-syntax widgets driven with real input through the kit (pointer,
+keys), checking the C behaviour behind the tkinter API: scrollbars,
+selection modes, sortable headings, tree open/close, raw bindings
+(<Button-3>, <KeyRelease>, modifiers), password fields, <Configure>.
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import os
+import sys
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
+
+import bui # noqa: E402,F401
+import buipy # noqa: E402
+import bui.tksyntax as tk # noqa: E402
+from bui.tksyntax import ttk # noqa: E402
+
+CTRL, SHIFT, B1 = 2, 1, 8
+
+
+class App:
+ def __init__(self, w=360, h=400):
+ self.root = tk.Tk()
+ self.w, self.h = w, h
+ self.raster = buipy.Raster(w, h)
+
+ @property
+ def ctx(self):
+ return self.root._ctx
+
+ def frame(self):
+ self.ctx.render(self.w, self.h, self.raster, False)
+
+ def at(self, widget, dx=None, dy=None):
+ x, y, w, h = widget._node.rect
+ return x + (w // 2 if dx is None else dx), y + (h // 2 if dy is None else dy)
+
+ def click(self, widget, dx=None, dy=None, mods=0):
+ x, y = self.at(widget, dx, dy)
+ self.ctx.motion(x, y, mods)
+ self.ctx.press(x, y, mods)
+ self.ctx.release(x, y, mods)
+ self.frame()
+
+ def close(self):
+ self.root.destroy()
+
+
+def test_scrollbar_drives_listbox():
+ app = App()
+ frame = tk.Frame(app.root)
+ frame.pack(fill="both", expand=True)
+ sb = tk.Scrollbar(frame)
+ sb.pack(side="right", fill="y")
+ lb = tk.Listbox(frame, yscrollcommand=sb.set, height=5)
+ lb.pack(side="left", fill="both", expand=True)
+ sb.config(command=lb.yview)
+ for i in range(40):
+ lb.insert("end", "item %d" % i)
+ app.frame()
+ first, last = sb.get()
+ assert first == 0.0 and 0 < last < 0.5, (first, last) # yscrollcommand ran
+ x, y = app.at(sb, dy=3)
+ app.ctx.press(x, y, 0) # grab the thumb at the top
+ app.ctx.motion(x, y + sb.winfo_height() // 2, B1)
+ app.ctx.release(x, y + sb.winfo_height() // 2, 0)
+ app.frame()
+ assert lb.yview()[0] > 0.3 and sb.get()[0] > 0.3, (lb.yview(), sb.get())
+ x, y = app.at(lb)
+ app.ctx.wheel(x, y, 3, 0) # wheel on the list: the scrollbar follows
+ app.frame()
+ assert abs(sb.get()[0] - lb.yview()[0]) < 1e-6
+ app.close()
+
+
+def test_listbox_selection_modes():
+ app = App()
+ lb = tk.Listbox(app.root, selectmode="extended", height=8)
+ lb.pack(fill="both", expand=True)
+ for i in range(8):
+ lb.insert("end", "row %d" % i)
+ events = []
+ lb.bind("<<ListboxSelect>>", lambda e: events.append(lb.curselection()))
+ app.frame()
+ row_h = buipy.kit_unit()
+ pad = round(0.15 * row_h)
+
+ def row(i, mods=0):
+ app.click(lb, dx=20, dy=pad + i * row_h + row_h // 2, mods=mods)
+ row(1)
+ row(4, SHIFT)
+ assert lb.curselection() == (1, 2, 3, 4), lb.curselection()
+ row(2, CTRL)
+ assert lb.curselection() == (1, 3, 4), lb.curselection()
+ row(6)
+ assert lb.curselection() == (6,) and events[-1] == (6,), (lb.curselection(), events)
+ lb.selection_clear(0, "end")
+ assert lb.curselection() == ()
+ lb.config(selectmode="multiple")
+ row(0)
+ row(2)
+ row(0)
+ assert lb.curselection() == (2,), lb.curselection()
+ app.close()
+
+
+def test_treeview_heading_sort_and_open_events():
+ app = App()
+ tree = ttk.Treeview(app.root, columns=("size",), height=6)
+ sorted_by = []
+ tree.heading("#0", text="Name", command=lambda: sorted_by.append("#0"))
+ tree.heading("size", text="Size", command=lambda: sorted_by.append("size"))
+ tree.pack(fill="both", expand=True)
+ parent = tree.insert("", "end", text="folder", values=("3",))
+ tree.insert(parent, "end", text="a.txt", values=("1",))
+ opened = []
+ tree.bind("<<TreeviewOpen>>", lambda e: opened.append(tree.focus()))
+ app.frame()
+ u = buipy.kit_unit()
+ pad = round(0.15 * u)
+ app.click(tree, dx=tree.winfo_width() - 30, dy=pad + u // 2) # the "Size" heading
+ assert sorted_by == ["size"], sorted_by
+ app.click(tree, dx=pad + u // 3, dy=pad + u + u // 2) # the expander of row 0
+ assert opened == [parent] and tree.item(parent, "open") == 1, (opened, tree.item(parent))
+ app.close()
+
+
+def test_raw_bindings():
+ app = App()
+ btn = tk.Button(app.root, text="target")
+ btn.pack(fill="x")
+ log = []
+ btn.bind("<Button-3>", lambda e: log.append(("b3", e.num)))
+ btn.bind("<Control-Button-1>", lambda e: log.append("ctrl-click"))
+ btn.bind("<Button-1>", lambda e: log.append("click"))
+ app.root.bind("<KeyRelease-a>", lambda e: log.append(("release", e.keysym)))
+ sizes = []
+ btn.bind("<Configure>", lambda e: sizes.append((e.width, e.height)))
+ app.frame()
+ x, y = app.at(btn)
+ app.ctx.motion(x, y, 0)
+ app.ctx.context_menu(x, y, 0)
+ app.click(btn, mods=CTRL)
+ app.click(btn)
+ app.ctx.key_release("a", 0)
+ assert log == [("b3", 3), "ctrl-click", "click", ("release", "a")], log
+ assert sizes and sizes[-1] == (btn.winfo_width(), btn.winfo_height()), sizes
+ app.w = 300
+ app.raster = buipy.Raster(300, app.h)
+ app.frame()
+ assert sizes[-1][0] == btn.winfo_width() and len(sizes) >= 2, sizes
+ app.close()
+
+
+def test_entry_password_and_validation():
+ app = App()
+ pw = tk.Entry(app.root, show="*")
+ pw.pack(fill="x")
+ digits = tk.Entry(app.root, validate="key",
+ validatecommand=(app.root.register(str.isdigit), "%S"))
+ digits.pack(fill="x")
+ app.frame()
+ app.click(pw)
+ for ch in "secret":
+ app.ctx.key(ch, ch, 0)
+ app.frame()
+ assert pw.get() == "secret"
+ x, y, w, h = pw._node.rect
+ shown = [app.raster.pixel(xx, y + h // 2) for xx in range(x, x + w)]
+ assert len(set(shown)) > 2 # bullets are drawn
+ app.ctx.key("", "Return", 0)
+ app.click(digits)
+ for ch in "1a2":
+ app.ctx.key(ch, ch, 0)
+ app.ctx.key("", "Return", 0)
+ assert digits.get() == "12", digits.get() # the letter was rejected while typing
+ app.close()
+
+
+def test_text_tag_click_and_font_scale():
+ app = App()
+ text = tk.Text(app.root, height=4, width=30)
+ text.pack()
+ text.insert("1.0", "click here please")
+ text.tag_add("link", "1.6", "1.10")
+ text.tag_configure("link", foreground="#4772b3", background="#202020")
+ hits = []
+ text.tag_bind("link", "<Button-1>", lambda e: hits.append(text.index("current")))
+ big = tk.Label(app.root, text="Title\nsecond line", font=("Arial", 18, "bold"))
+ big.pack()
+ small = tk.Label(app.root, text="Title")
+ small.pack()
+ app.frame()
+ char_w = buipy.measure_text("click h", buipy.kit_unit() * 0.55) or 40
+ app.click(text, dx=int(buipy.kit_unit() * 0.4 + char_w), dy=buipy.kit_unit() // 2)
+ assert hits and text.compare(hits[0], ">=", "1.6"), hits
+ assert big.winfo_reqheight() > 2 * small.winfo_reqheight(), (big.winfo_reqheight(),
+ small.winfo_reqheight())
+ app.close()
+
+
+def test_panedwindow_sash_drag():
+ app = App()
+ pw = tk.PanedWindow(app.root, orient="horizontal")
+ pw.pack(fill="both", expand=True)
+ left, right = tk.Label(pw, text="left"), tk.Label(pw, text="right")
+ pw.add(left, width=120)
+ pw.add(right)
+ app.frame()
+ w0 = left.winfo_width()
+ sx, sy = pw.sash_coord(0)
+ x0, y0 = pw._node.rect[:2]
+ app.ctx.press(x0 + sx + 1, y0 + sy + 5, 0)
+ app.ctx.motion(x0 + sx + 41, y0 + sy + 5, B1)
+ app.ctx.release(x0 + sx + 41, y0 + sy + 5, 0)
+ app.frame()
+ assert abs(left.winfo_width() - (w0 + 40)) <= 2, (w0, left.winfo_width())
+ app.close()
+
+
+def main() -> int:
+ for name, fn in sorted(globals().items()):
+ if name.startswith("test_"):
+ fn()
+ print("ok", name)
+ print("tk input tests passed")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/compat/CMakeLists.txt b/compat/CMakeLists.txt
index 0b915bd..e5d14df 100644
--- a/compat/CMakeLists.txt
+++ b/compat/CMakeLists.txt
@@ -1,21 +1,16 @@
-# bui_compat - seam headers and stubs
-#
-# These headers carry the same names as the Blender-app APIs the extracted UI
-# code calls (RNA, CTX, BLF, IMB, ED, WM). Implementations here are BUI-owned:
-# opaque types, stubs, or thin extension points. Over time each seam either
-# gets a real implementation or the toolkit call-sites migrate to a native
-# BUI API.
+# bui_compat - seam headers and stub implementations
#
# SPDX-License-Identifier: GPL-2.0-or-later
-add_library(bui_compat INTERFACE)
+add_library(bui_compat STATIC
+ intern/bui_stubs.cc
+)
add_library(bui::compat ALIAS bui_compat)
-target_include_directories(bui_compat INTERFACE
+target_include_directories(bui_compat PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/include
${CMAKE_SOURCE_DIR}/types/dna/include
${CMAKE_SOURCE_DIR}/gpu/include
${CMAKE_SOURCE_DIR}/core/include
)
-
-target_link_libraries(bui_compat INTERFACE bui::core bui::types bui::gpu)
+target_link_libraries(bui_compat PUBLIC bui::core bui::types bui::gpu)
diff --git a/compat/include/ANIM_action.hh b/compat/include/ANIM_action.hh
new file mode 100644
index 0000000..91f33db
--- /dev/null
+++ b/compat/include/ANIM_action.hh
@@ -0,0 +1,27 @@
+/* BUI seam: minimal animrig Action/Slot wrappers.
+ * Only what the toolkit needs for search-item icons: the DNA structs carry
+ * the data; the wrapper adds no members so pointers stay interchangeable.
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#include "DNA_action_types.h"
+
+namespace blender::animrig {
+
+class Slot : public ActionSlot {
+ public:
+ Slot() = default;
+};
+
+} // namespace blender::animrig
+
+namespace blender {
+inline animrig::Slot &ActionSlot::wrap()
+{
+ return *static_cast<animrig::Slot *>(this);
+}
+inline const animrig::Slot &ActionSlot::wrap() const
+{
+ return *static_cast<const animrig::Slot *>(this);
+}
+} // namespace blender
diff --git a/compat/include/AS_asset_representation.hh b/compat/include/AS_asset_representation.hh
new file mode 100644
index 0000000..89a28ae
--- /dev/null
+++ b/compat/include/AS_asset_representation.hh
@@ -0,0 +1,4 @@
+/* BUI seam: minimal stand-in. SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+struct AssetRepresentation;
+
diff --git a/ui/include/BIF_glutil.hh b/compat/include/BIF_glutil.hh
similarity index 100%
rename from ui/include/BIF_glutil.hh
rename to compat/include/BIF_glutil.hh
diff --git a/compat/include/BKE_addon.h b/compat/include/BKE_addon.h
new file mode 100644
index 0000000..ee1cd72
--- /dev/null
+++ b/compat/include/BKE_addon.h
@@ -0,0 +1,42 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+/** \file
+ * \ingroup bke
+ */
+
+#include "DNA_listBase.h"
+
+namespace blender {
+
+struct bAddon;
+
+#ifdef __RNA_TYPES_H__
+struct bAddonPrefType {
+ /** Type info, match #bAddon::module. */
+ char idname[128];
+
+ /* RNA integration */
+ ExtensionRNA rna_ext;
+};
+
+#else
+struct bAddonPrefType;
+#endif
+
+bAddonPrefType *BKE_addon_pref_type_find(const char *idname, bool quiet);
+void BKE_addon_pref_type_add(bAddonPrefType *apt);
+void BKE_addon_pref_type_remove(const bAddonPrefType *apt);
+
+void BKE_addon_pref_type_init();
+void BKE_addon_pref_type_free();
+
+struct bAddon *BKE_addon_new();
+struct bAddon *BKE_addon_find(const ListBaseT<bAddon> *addon_list, const char *module);
+struct bAddon *BKE_addon_ensure(ListBaseT<bAddon> *addon_list, const char *module);
+bool BKE_addon_remove_safe(ListBaseT<bAddon> *addon_list, const char *module);
+void BKE_addon_free(struct bAddon *addon);
+
+} // namespace blender
diff --git a/compat/include/BKE_appdir.hh b/compat/include/BKE_appdir.hh
new file mode 100644
index 0000000..5ed9128
--- /dev/null
+++ b/compat/include/BKE_appdir.hh
@@ -0,0 +1,192 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+/** \file
+ * \ingroup bke
+ *
+ * \note on naming: typical _get() suffix is omitted here,
+ * since its the main purpose of the API.
+ */
+
+#include <cstddef>
+
+#include <optional>
+#include <string>
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_string_ref.hh"
+
+#include "DNA_listBase.h"
+
+namespace blender {
+
+/**
+ * Sanity check to ensure correct API use in debug mode.
+ *
+ * Run this once the first level of arguments has been passed so we can be sure
+ * `--env-system-datafiles`, and other `--env-*` arguments has been passed.
+ *
+ * Without this any callers to this module that run early on,
+ * will miss out on changes from parsing arguments.
+ */
+void BKE_appdir_init();
+void BKE_appdir_exit();
+
+/**
+ * Get the folder that's the "natural" starting point for browsing files on an OS.
+ * - Unix: `$HOME`
+ * - Windows: `%userprofile%/Documents`
+ *
+ * \note On Windows `Users/{MyUserName}/Documents` is used as it's the default location to save
+ * documents.
+ */
+const char *BKE_appdir_folder_default() ATTR_WARN_UNUSED_RESULT;
+const char *BKE_appdir_folder_root() ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL;
+const char *BKE_appdir_folder_default_or_root() ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL;
+/**
+ * Get the user's document directory, i.e.
+ * - Linux: `$HOME/Documents`
+ * - Windows: `%userprofile%/Documents`
+ *
+ * If this can't be found using OS queries (via Ghost), try manually finding it.
+ *
+ * \returns True if the path is valid and points to an existing directory.
+ */
+bool BKE_appdir_folder_documents(char *dir) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT;
+/**
+ * Get the user's cache directory, i.e.
+ * - Linux: `$HOME/.cache/blender/`
+ * - Windows: `%USERPROFILE%\AppData\Local\Blender Foundation\Blender\Cache\`
+ * - MacOS: `$HOME/Library/Caches/Blender/`
+ *
+ * \returns True if the path is valid. It doesn't create or checks format
+ * if the `blender` folder exists. It does check if the parent of the path exists.
+ */
+bool BKE_appdir_folder_caches(char *path, size_t path_maxncpy) ATTR_NONNULL(1);
+
+/**
+ * Get a folder out of the \a folder_id presets for paths.
+ *
+ * \param subfolder: The name of a directory to check for,
+ * this may contain path separators but must resolve to a directory, checked with #BLI_is_dir.
+ * \return The path if found, NULL string if not.
+ */
+bool BKE_appdir_folder_id_ex(int folder_id,
+ const char *subfolder,
+ char *path,
+ size_t path_maxncpy);
+std::optional<std::string> BKE_appdir_folder_id(int folder_id,
+ const char *subfolder) ATTR_WARN_UNUSED_RESULT;
+/**
+ * Returns the path to a folder in the user area, creating it if it doesn't exist.
+ */
+std::optional<std::string> BKE_appdir_folder_id_create(int folder_id, const char *subfolder)
+ ATTR_WARN_UNUSED_RESULT;
+/**
+ * Returns the path to a folder in the user area without checking that it actually exists first.
+ */
+std::optional<std::string> BKE_appdir_folder_id_user_notest(int folder_id, const char *subfolder)
+ ATTR_WARN_UNUSED_RESULT;
+/**
+ * Returns the path of the top-level version-specific local, user or system directory.
+ * If check_is_dir, then the result will be NULL if the directory doesn't exist.
+ */
+std::optional<std::string> BKE_appdir_resource_path_id_with_version(int folder_id,
+ bool check_is_dir,
+ int version);
+std::optional<std::string> BKE_appdir_resource_path_id(int folder_id, bool check_is_dir);
+
+/**
+ * Return true if templates exist
+ */
+bool BKE_appdir_app_template_any();
+bool BKE_appdir_app_template_id_search(const char *app_template, char *path, size_t path_maxncpy)
+ ATTR_NONNULL(1);
+bool BKE_appdir_app_template_has_userpref(const char *app_template) ATTR_NONNULL(1);
+void BKE_appdir_app_templates(ListBaseT<LinkData> *templates) ATTR_NONNULL(1);
+
+/**
+ * Initialize path to program executable.
+ */
+void BKE_appdir_program_path_init(const char *argv0) ATTR_NONNULL(1);
+
+/**
+ * Path to executable
+ */
+const char *BKE_appdir_program_path() ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL;
+/**
+ * Path to directory of executable
+ */
+const char *BKE_appdir_program_dir() ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL;
+
+/**
+ * Gets a good default directory for fonts.
+ */
+bool BKE_appdir_font_folder_default(char *dir, size_t dir_maxncpy);
+
+/**
+ * Find Python executable.
+ */
+bool BKE_appdir_program_python_search(char *program_filepath,
+ size_t program_filepath_maxncpy,
+ int version_major,
+ int version_minor) ATTR_NONNULL(1);
+
+/**
+ * Initialize path to temporary directory.
+ */
+void BKE_tempdir_init(const char *userdir);
+
+/**
+ * Path to persistent temporary directory (with trailing slash)
+ */
+const char *BKE_tempdir_base() ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL;
+/**
+ * Path to temporary directory (with trailing slash)
+ */
+const char *BKE_tempdir_session() ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL;
+/**
+ * Delete content of this instance's temp dir.
+ */
+void BKE_tempdir_session_purge();
+
+/**
+ * The `folder_id` for #BKE_appdir_folder_id and related functions.
+ *
+ * Run-time only so existing values may change.
+ */
+enum {
+ /* general, will find based on user/local/system priority */
+ BLENDER_DATAFILES = 2,
+
+ /* user-specific */
+ BLENDER_USER_CONFIG = 31,
+ BLENDER_USER_DATAFILES = 32,
+ BLENDER_USER_SCRIPTS = 33,
+ BLENDER_USER_EXTENSIONS = 34,
+
+ /* system */
+ BLENDER_SYSTEM_DATAFILES = 52,
+ BLENDER_SYSTEM_SCRIPTS = 53,
+ BLENDER_SYSTEM_EXTENSIONS = 54,
+ BLENDER_SYSTEM_PYTHON = 55,
+};
+
+/** For #BKE_appdir_folder_id_version only. */
+enum {
+ BLENDER_RESOURCE_PATH_USER = 0,
+ BLENDER_RESOURCE_PATH_LOCAL = 1,
+ BLENDER_RESOURCE_PATH_SYSTEM = 2,
+};
+
+#define BLENDER_STARTUP_FILE "startup.blend"
+#define BLENDER_USERPREF_FILE "userpref.blend"
+#define BLENDER_QUIT_FILE "quit.blend"
+#define BLENDER_BOOKMARK_FILE "bookmarks.txt"
+#define BLENDER_HISTORY_FILE "recent-files.txt"
+#define BLENDER_RECENT_SEARCHES_FILE "recent-searches.txt"
+#define BLENDER_PLATFORM_SUPPORT_FILE "platform_support.txt"
+
+} // namespace blender
diff --git a/compat/include/BKE_colorband.hh b/compat/include/BKE_colorband.hh
new file mode 100644
index 0000000..97b425b
--- /dev/null
+++ b/compat/include/BKE_colorband.hh
@@ -0,0 +1,33 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+/** \file
+ * \ingroup bke
+ */
+
+namespace blender {
+
+struct CBData;
+struct ColorBand;
+struct IDTypeForeachColorFunctionCallback;
+
+/** #ColorBand.data length. */
+#define MAXCOLORBAND 32
+
+void BKE_colorband_init(ColorBand *coba, bool rangetype);
+void BKE_colorband_init_from_table_rgba(ColorBand *coba,
+ const float (*array)[4],
+ int array_len,
+ bool filter_samples);
+ColorBand *BKE_colorband_add(bool rangetype);
+bool BKE_colorband_evaluate(const ColorBand *coba, float in, float out[4]);
+void BKE_colorband_evaluate_table_rgba(const ColorBand *coba, float **array, int *size);
+CBData *BKE_colorband_element_add(ColorBand *coba, float position);
+bool BKE_colorband_element_remove(ColorBand *coba, int index);
+void BKE_colorband_update_sort(ColorBand *coba);
+void BKE_colorband_foreach_working_space_color(ColorBand *coba,
+ const IDTypeForeachColorFunctionCallback &fn);
+
+} // namespace blender
diff --git a/compat/include/BKE_colortools.hh b/compat/include/BKE_colortools.hh
new file mode 100644
index 0000000..9ea7587
--- /dev/null
+++ b/compat/include/BKE_colortools.hh
@@ -0,0 +1,244 @@
+/* SPDX-FileCopyrightText: 2006 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+/** \file
+ * \ingroup bke
+ */
+#include "BLI_math_vector_types.hh"
+#include <cstdint>
+
+namespace blender {
+
+struct BlendDataReader;
+struct BlendWriter;
+struct ColorManagedColorspaceSettings;
+struct ColorManagedDisplaySettings;
+struct ColorManagedViewSettings;
+struct CurveMap;
+struct CurveMapPoint;
+struct CurveMapping;
+struct Histogram;
+struct ImBuf;
+struct Scopes;
+struct rctf;
+
+void BKE_curvemapping_set_defaults(CurveMapping *cumap,
+ int tot,
+ float minx,
+ float miny,
+ float maxx,
+ float maxy,
+ short default_handle_type);
+CurveMapping *BKE_curvemapping_add(int tot, float minx, float miny, float maxx, float maxy);
+void BKE_curvemapping_free_data_single(CurveMapping *cumap, int index);
+void BKE_curvemapping_free_data(CurveMapping *cumap);
+void BKE_curvemapping_free(CurveMapping *cumap);
+void BKE_curvemapping_copy_data_single(
+ CurveMapping *target, const CurveMapping *cumap, int to_idx, int from_idx, bool make_copy);
+void BKE_curvemapping_copy_data(CurveMapping *target, const CurveMapping *cumap);
+CurveMapping *BKE_curvemapping_copy(const CurveMapping *cumap);
+void BKE_curvemapping_set_black_white_ex(const float black[3],
+ const float white[3],
+ float r_bwmul[3]);
+void BKE_curvemapping_set_black_white(CurveMapping *cumap,
+ const float black[3],
+ const float white[3]);
+
+enum class CurveMapSlopeType : int8_t {
+ Negative = 0,
+ Positive = 1,
+ PositiveNegative = 2,
+};
+
+/**
+ * Reset the view for current curve.
+ */
+void BKE_curvemapping_reset_view(CurveMapping *cumap);
+void BKE_curvemap_reset(CurveMap *cuma, const rctf *clipr, int preset, CurveMapSlopeType slope);
+/**
+ * When the current point is deselected, activate the closest remaining point
+ * by index. The function searches for the nearest valid index relative to the previously
+ * active index, not the nearest point by distance.
+ */
+void BKE_curvemap_activate_nearest_point(struct CurveMap *cuma, const int i_last);
+/**
+ * Removes with flag set.
+ */
+void BKE_curvemap_remove(CurveMap *cuma, short flag);
+/**
+ * Remove specified point.
+ */
+bool BKE_curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point);
+CurveMapPoint *BKE_curvemap_insert(CurveMap *cuma, float x, float y);
+/**
+ * Shift all selected points.
+ */
+void BKE_curvemap_translate_selection(CurveMap *cuma, const blender::float2 &offset);
+/**
+ * \param type: #eBezTriple_Handle
+ */
+void BKE_curvemap_handle_set(CurveMap *cuma, int type);
+
+CurveMapPoint *BKE_curvemap_active_get(CurveMap *cuma);
+
+/**
+ * \note only does current curvemap!.
+ */
+void BKE_curvemapping_changed(CurveMapping *cumap, bool rem_doubles);
+void BKE_curvemapping_changed_all(CurveMapping *cumap);
+
+/**
+ * Call before _all_ evaluation functions.
+ */
+void BKE_curvemapping_init(CurveMapping *cumap);
+
+/**
+ * Keep these `const CurveMap` - to help with thread safety.
+ * \note Single curve, no table check.
+ * \note Table should be verified.
+ */
+float BKE_curvemap_evaluateF(const CurveMapping *cumap, const CurveMap *cuma, float value);
+/**
+ * Single curve, with table check.
+ * Works with curve 'cur'.
+ */
+float BKE_curvemapping_evaluateF(const CurveMapping *cumap, int cur, float value);
+/**
+ * Vector case.
+ */
+void BKE_curvemapping_evaluate3F(const CurveMapping *cumap, float vecout[3], const float vecin[3]);
+/**
+ * RGB case, no black/white points, no pre-multiply.
+ */
+void BKE_curvemapping_evaluateRGBF(const CurveMapping *cumap,
+ float vecout[3],
+ const float vecin[3]);
+/**
+ * Byte version of #BKE_curvemapping_evaluateRGBF.
+ */
+void BKE_curvemapping_evaluate_premulRGB(const CurveMapping *cumap,
+ unsigned char vecout_byte[3],
+ const unsigned char vecin_byte[3]);
+/**
+ * Same as #BKE_curvemapping_evaluate_premulRGBF
+ * but black/bwmul are passed as args for the compositor
+ * where they can change per pixel.
+ *
+ * Use in conjunction with #BKE_curvemapping_set_black_white_ex
+ *
+ * \param black: Use instead of cumap->black
+ * \param bwmul: Use instead of cumap->bwmul
+ */
+void BKE_curvemapping_evaluate_premulRGBF_ex(const CurveMapping *cumap,
+ float vecout[3],
+ const float vecin[3],
+ const float black[3],
+ const float bwmul[3]);
+/**
+ * RGB with black/white points and pre-multiply. tables are checked.
+ */
+void BKE_curvemapping_evaluate_premulRGBF(const CurveMapping *cumap,
+ float vecout[3],
+ const float vecin[3]);
+bool BKE_curvemapping_RGBA_does_something(const CurveMapping *cumap);
+void BKE_curvemapping_table_F(const CurveMapping *cumap, float **array, int *size);
+void BKE_curvemapping_table_RGBA(const CurveMapping *cumap, float **array, int *size);
+int BKE_curvemapping_num_channels(const CurveMapping *cumap);
+
+/** Get the minimum x value of each curve map table. */
+void BKE_curvemapping_get_range_minimums(const CurveMapping *curve_mapping, float minimums[4]);
+
+/**
+ * Get the reciprocal of the difference between the maximum and the minimum x value of each curve
+ * map table. Evaluation parameters can be multiplied by this value to be normalized. If the
+ * difference is zero, 1^8 is returned.
+ */
+void BKE_curvemapping_compute_range_dividers(const CurveMapping *curve_mapping, float dividers[4]);
+
+/**
+ * Compute the slopes at the start and end points of each curve map. The slopes are multiplied by
+ * the range of the curve map to compensate for parameter normalization. If the slope is vertical,
+ * 1^8 is returned.
+ */
+void BKE_curvemapping_compute_slopes(const CurveMapping *curve_mapping,
+ float start_slopes[4],
+ float end_slopes[4]);
+
+/**
+ * Check if the curve map at the index is identity, that is, does nothing.
+ * A curve map is said to be identity if:
+ * - The curve mapping uses extrapolation.
+ * - Its range is 1.
+ * - The slope at its start point is 1.
+ * - The slope at its end point is 1.
+ * - The number of points is 2.
+ * - The start point is at (0, 0).
+ * - The end point is at (1, 1).
+ * Note that this could return false even if the curve map is identity, this happens in the case
+ * when more than 2 points exist in the curve map but all points are collinear. */
+bool BKE_curvemapping_is_map_identity(const CurveMapping *curve_mapping, int index);
+
+/**
+ * Call when you do images etc, needs restore too. also verifies tables.
+ * non-const (these modify the curve).
+ */
+void BKE_curvemapping_premultiply(CurveMapping *cumap, bool restore);
+
+void BKE_curvemapping_blend_write(BlendWriter *writer, const CurveMapping *cumap);
+void BKE_curvemapping_curves_blend_write(BlendWriter *writer, const CurveMapping *cumap);
+
+/**
+ * \note `cumap` itself has been read already.
+ */
+void BKE_curvemapping_blend_read(BlendDataReader *reader, CurveMapping *cumap);
+
+void BKE_histogram_update_sample_line(Histogram *hist,
+ ImBuf *ibuf,
+ const ColorManagedViewSettings *view_settings,
+ const ColorManagedDisplaySettings *display_settings);
+void BKE_scopes_update(Scopes *scopes,
+ ImBuf *ibuf,
+ const ColorManagedViewSettings *view_settings,
+ const ColorManagedDisplaySettings *display_settings);
+void BKE_scopes_free(Scopes *scopes);
+void BKE_scopes_new(Scopes *scopes);
+
+void BKE_color_managed_display_settings_init(ColorManagedDisplaySettings *settings);
+void BKE_color_managed_display_settings_copy(ColorManagedDisplaySettings *new_settings,
+ const ColorManagedDisplaySettings *settings);
+
+/**
+ * Initialize view settings to the default.
+ */
+void BKE_color_managed_view_settings_init(ColorManagedViewSettings *view_settings,
+ const ColorManagedDisplaySettings *display_settings,
+ const char *view_transform);
+
+void BKE_color_managed_view_settings_copy(ColorManagedViewSettings *new_settings,
+ const ColorManagedViewSettings *settings);
+
+/**
+ * Copy view settings that are not related to the curve mapping. Keep the curve mapping unchanged
+ * in the new_settings.
+ */
+void BKE_color_managed_view_settings_copy_keep_curve_mapping(
+ ColorManagedViewSettings *new_settings, const ColorManagedViewSettings *settings);
+
+void BKE_color_managed_view_settings_free(ColorManagedViewSettings *settings);
+
+void BKE_color_managed_view_settings_blend_write(BlendWriter *writer,
+ const ColorManagedViewSettings *settings);
+void BKE_color_managed_view_settings_blend_read_data(BlendDataReader *reader,
+ ColorManagedViewSettings *settings);
+
+void BKE_color_managed_colorspace_settings_init(
+ ColorManagedColorspaceSettings *colorspace_settings);
+void BKE_color_managed_colorspace_settings_copy(
+ ColorManagedColorspaceSettings *colorspace_settings,
+ const ColorManagedColorspaceSettings *settings);
+bool BKE_color_managed_colorspace_settings_equals(const ColorManagedColorspaceSettings *settings1,
+ const ColorManagedColorspaceSettings *settings2);
+
+} // namespace blender
diff --git a/compat/include/BKE_context.hh b/compat/include/BKE_context.hh
new file mode 100644
index 0000000..ff31d3c
--- /dev/null
+++ b/compat/include/BKE_context.hh
@@ -0,0 +1,516 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bke
+ */
+
+#include <variant>
+
+#include "BLI_enum_flags.hh"
+#include "BLI_string_ref.hh"
+#include "BLI_vector.hh"
+
+#include "DNA_listBase.h"
+#include "DNA_object_enums.h"
+#include "RNA_types.hh"
+
+namespace blender {
+
+struct ARegion;
+struct AssetLibraryReference;
+struct AssetWeakReference;
+struct Base;
+struct bGPDframe;
+struct bGPDlayer;
+struct bPoseChannel;
+struct bScreen;
+struct CacheFile;
+struct Collection;
+struct Depsgraph;
+struct EditBone;
+struct ID;
+struct Image;
+struct LayerCollection;
+struct Main;
+struct Mask;
+struct MovieClip;
+struct Object;
+struct PointerRNA;
+struct RegionView3D;
+struct RenderEngineType;
+struct ReportList;
+struct Scene;
+struct ScrArea;
+struct SpaceAction;
+struct SpaceClip;
+struct SpaceClip;
+struct SpaceConsole;
+struct SpaceFile;
+struct SpaceGraph;
+struct SpaceImage;
+struct SpaceInfo;
+struct SpaceLink;
+struct SpaceNla;
+struct SpaceNode;
+struct SpaceOutliner;
+struct SpaceProperties;
+struct SpaceSeq;
+struct SpaceSpreadsheet;
+struct SpaceText;
+struct SpaceTopBar;
+struct SpaceUserPref;
+struct StructRNA;
+struct Text;
+struct ToolSettings;
+struct View3D;
+struct ViewLayer;
+struct wmGizmoGroup;
+struct wmMsgBus;
+struct wmWindow;
+struct wmWindowManager;
+struct WorkSpace;
+
+/**
+ * Context logging control flags.
+ */
+enum class CTX_LogFlag : uint8_t {
+ /** Enable logging of context member access. */
+ Access = (1 << 0),
+ /** Hide missing/None values from logging. */
+ HideMissing = (1 << 1),
+};
+ENUM_OPERATORS(CTX_LogFlag);
+
+/* Structs */
+
+struct bContext;
+
+struct bContextDataResult;
+
+/* Result of context lookups.
+ * The specific values are important, and used implicitly in ctx_data_get(). Some functions also
+ * still accept/return `int` instead, to ensure that the compiler uses the correct storage size
+ * when mixing C/C++ code. */
+enum eContextResult {
+ /* The context member was found, and its data is available. */
+ CTX_RESULT_OK = 1,
+
+ /* The context member was not found. */
+ CTX_RESULT_MEMBER_NOT_FOUND = 0,
+
+ /* The context member was found, but its data is not available.
+ * For example, "active_bone" is a valid context member, but has not data in Object mode. */
+ CTX_RESULT_NO_DATA = -1,
+};
+
+/* Function mapping a context member name to its value. */
+using bContextDataCallback = int /*eContextResult*/ (*)(const bContext *C,
+ const char *member,
+ bContextDataResult *result);
+
+struct bContextStoreEntry {
+ std::string name;
+ std::variant<PointerRNA, std::string, int64_t> value;
+};
+
+struct bContextStore {
+ Vector<bContextStoreEntry> entries;
+ bool used = false;
+};
+
+namespace asset_system {
+class AssetRepresentation;
+}
+
+/* for the context's rna mode enum
+ * keep aligned with data_mode_strings in context.cc */
+enum eContextObjectMode {
+ CTX_MODE_EDIT_MESH = 0,
+ CTX_MODE_EDIT_CURVE,
+ CTX_MODE_EDIT_SURFACE,
+ CTX_MODE_EDIT_TEXT,
+ CTX_MODE_EDIT_ARMATURE,
+ CTX_MODE_EDIT_METABALL,
+ CTX_MODE_EDIT_LATTICE,
+ CTX_MODE_EDIT_CURVES,
+ CTX_MODE_EDIT_GREASE_PENCIL,
+ CTX_MODE_EDIT_POINTCLOUD,
+ CTX_MODE_POSE,
+ CTX_MODE_SCULPT,
+ CTX_MODE_PAINT_WEIGHT,
+ CTX_MODE_PAINT_VERTEX,
+ CTX_MODE_PAINT_TEXTURE,
+ CTX_MODE_PARTICLE,
+ CTX_MODE_OBJECT,
+ CTX_MODE_PAINT_GPENCIL_LEGACY,
+ CTX_MODE_EDIT_GPENCIL_LEGACY,
+ CTX_MODE_SCULPT_GPENCIL_LEGACY,
+ CTX_MODE_WEIGHT_GPENCIL_LEGACY,
+ CTX_MODE_VERTEX_GPENCIL_LEGACY,
+ CTX_MODE_SCULPT_CURVES,
+ CTX_MODE_PAINT_GREASE_PENCIL,
+ CTX_MODE_SCULPT_GREASE_PENCIL,
+ CTX_MODE_WEIGHT_GREASE_PENCIL,
+ CTX_MODE_VERTEX_GREASE_PENCIL,
+};
+#define CTX_MODE_NUM (CTX_MODE_VERTEX_GREASE_PENCIL + 1)
+
+/* Context */
+
+bContext *CTX_create();
+void CTX_free(bContext *C);
+
+bContext *CTX_copy(const bContext *C);
+
+/* Stored Context */
+
+bContextStore *CTX_store_add(Vector<std::unique_ptr<bContextStore>> &contexts,
+ StringRef name,
+ const PointerRNA *ptr);
+bContextStore *CTX_store_add(Vector<std::unique_ptr<bContextStore>> &contexts,
+ StringRef name,
+ StringRef str);
+bContextStore *CTX_store_add(Vector<std::unique_ptr<bContextStore>> &contexts,
+ StringRef name,
+ int64_t value);
+bContextStore *CTX_store_add_all(Vector<std::unique_ptr<bContextStore>> &contexts,
+ const bContextStore *context);
+const bContextStore *CTX_store_get(const bContext *C);
+void CTX_store_set(bContext *C, const bContextStore *store);
+const PointerRNA *CTX_store_ptr_lookup(const bContextStore *store,
+ StringRef name,
+ const StructRNA *type = nullptr);
+std::optional<StringRefNull> CTX_store_string_lookup(const bContextStore *store, StringRef name);
+std::optional<int64_t> CTX_store_int_lookup(const bContextStore *store, StringRef name);
+
+/* Set a temporary flag to indicate when writing via RNA is disallowed. */
+void CTX_rna_disallow_write_set_p(bContext *C, const bool *rna_disallow_writes);
+
+/** Needed to store if Python is initialized or not. */
+bool CTX_py_init_get(const bContext *C);
+void CTX_py_init_set(bContext *C, bool value);
+
+void *CTX_py_dict_get(const bContext *C);
+void *CTX_py_dict_get_orig(const bContext *C);
+
+struct bContext_PyState {
+ void *py_context;
+ void *py_context_orig;
+};
+void CTX_py_state_push(bContext *C, bContext_PyState *pystate, void *value);
+void CTX_py_state_pop(bContext *C, bContext_PyState *pystate);
+
+/* Window Manager Context */
+
+wmWindowManager *CTX_wm_manager(const bContext *C);
+wmWindow *CTX_wm_window(const bContext *C);
+WorkSpace *CTX_wm_workspace(const bContext *C);
+bScreen *CTX_wm_screen(const bContext *C);
+ScrArea *CTX_wm_area(const bContext *C);
+SpaceLink *CTX_wm_space_data(const bContext *C);
+ARegion *CTX_wm_region(const bContext *C);
+void *CTX_wm_region_data(const bContext *C);
+ARegion *CTX_wm_region_popup(const bContext *C);
+wmGizmoGroup *CTX_wm_gizmo_group(const bContext *C);
+wmMsgBus *CTX_wm_message_bus(const bContext *C);
+ReportList *CTX_wm_reports(const bContext *C);
+
+View3D *CTX_wm_view3d(const bContext *C);
+RegionView3D *CTX_wm_region_view3d(const bContext *C);
+SpaceText *CTX_wm_space_text(const bContext *C);
+SpaceImage *CTX_wm_space_image(const bContext *C);
+SpaceConsole *CTX_wm_space_console(const bContext *C);
+SpaceProperties *CTX_wm_space_properties(const bContext *C);
+SpaceFile *CTX_wm_space_file(const bContext *C);
+SpaceSeq *CTX_wm_space_seq(const bContext *C);
+SpaceOutliner *CTX_wm_space_outliner(const bContext *C);
+SpaceNla *CTX_wm_space_nla(const bContext *C);
+SpaceNode *CTX_wm_space_node(const bContext *C);
+SpaceGraph *CTX_wm_space_graph(const bContext *C);
+SpaceAction *CTX_wm_space_action(const bContext *C);
+SpaceInfo *CTX_wm_space_info(const bContext *C);
+SpaceUserPref *CTX_wm_space_userpref(const bContext *C);
+SpaceClip *CTX_wm_space_clip(const bContext *C);
+SpaceTopBar *CTX_wm_space_topbar(const bContext *C);
+SpaceSpreadsheet *CTX_wm_space_spreadsheet(const bContext *C);
+
+void CTX_wm_manager_set(bContext *C, wmWindowManager *wm);
+void CTX_wm_window_set(bContext *C, wmWindow *win);
+void CTX_wm_screen_set(bContext *C, bScreen *screen); /* to be removed */
+void CTX_wm_area_set(bContext *C, ScrArea *area);
+void CTX_wm_region_set(bContext *C, ARegion *region);
+void CTX_wm_region_popup_set(bContext *C, ARegion *region_popup);
+void CTX_wm_gizmo_group_set(bContext *C, wmGizmoGroup *gzgroup);
+
+/**
+ * Values to create the message that describes the reason poll failed.
+ *
+ * \note This must be called in the same context as the poll function that created it.
+ */
+struct bContextPollMsgDyn_Params {
+ /** The result is allocated. */
+ char *(*get_fn)(bContext *C, void *user_data);
+ /** Optionally free the user-data. */
+ void (*free_fn)(bContext *C, void *user_data);
+ void *user_data;
+};
+
+const char *CTX_wm_operator_poll_msg_get(bContext *C, bool *r_free);
+
+/**
+ * Set a message to be shown when the operator is disabled in the UI.
+ *
+ * \note even though the function name does not include the word "disabled", the
+ * message is only shown when the operator (in the UI) is in fact disabled.
+ *
+ * \note even though the function name suggests this is limited to situations
+ * when the poll function returns false, this is not the case. Even when the
+ * operator is disabled because it is added to a disabled ui::Layout, this message
+ * will show.
+ */
+void CTX_wm_operator_poll_msg_set(bContext *C, const char *msg);
+void CTX_wm_operator_poll_msg_set_dynamic(bContext *C, const bContextPollMsgDyn_Params *params);
+void CTX_wm_operator_poll_msg_clear(bContext *C);
+
+/* Data Context
+ *
+ * - The dir #ListBaseT consists of #LinkData items.
+ */
+
+/** Data type, needed so we can tell between a NULL pointer and an empty list. */
+enum class ContextDataType : uint8_t {
+ Pointer = 0,
+ Collection,
+ Property,
+ String,
+ Int64,
+};
+
+PointerRNA CTX_data_pointer_get(const bContext *C, const char *member);
+PointerRNA CTX_data_pointer_get_type(const bContext *C, const char *member, StructRNA *type);
+PointerRNA CTX_data_pointer_get_type_silent(const bContext *C,
+ const char *member,
+ StructRNA *type);
+Vector<PointerRNA> CTX_data_collection_get(const bContext *C, const char *member);
+
+/**
+ * For each pointer in collection_pointers, remap it to point to `ptr->propname`.
+ *
+ * Example:
+ *
+ * lb = CTX_data_collection_get(C, "selected_pose_bones"); // lb contains pose bones.
+ * CTX_data_collection_remap_property(lb, "color"); // lb now contains bone colors.
+ */
+void CTX_data_collection_remap_property(MutableSpan<PointerRNA> collection_pointers,
+ const char *propname);
+
+std::optional<StringRefNull> CTX_data_string_get(const bContext *C, const char *member);
+std::optional<int64_t> CTX_data_int_get(const bContext *C, const char *member);
+
+/**
+ * \param C: Context.
+ * \param use_store: Use 'C->wm.store'.
+ * \param use_rna: Use Include the properties from #RNA_Context.
+ * \param use_all: Don't skip values (currently only "scene").
+ */
+ListBaseT<LinkData> CTX_data_dir_get_ex(const bContext *C,
+ bool use_store,
+ bool use_rna,
+ bool use_all);
+ListBaseT<LinkData> CTX_data_dir_get(const bContext *C);
+int /*eContextResult*/ CTX_data_get(const bContext *C,
+ const char *member,
+ PointerRNA *r_ptr,
+ Vector<PointerRNA> *r_lb,
+ PropertyRNA **r_prop,
+ int *r_index,
+ StringRef *r_str,
+ std::optional<int64_t> *r_int_value,
+ ContextDataType *r_type);
+
+void CTX_data_id_pointer_set(bContextDataResult *result, ID *id);
+void CTX_data_pointer_set_ptr(bContextDataResult *result, const PointerRNA *ptr);
+void CTX_data_pointer_set(bContextDataResult *result, ID *id, StructRNA *type, void *data);
+
+void CTX_data_id_list_add(bContextDataResult *result, ID *id);
+void CTX_data_list_add_ptr(bContextDataResult *result, const PointerRNA *ptr);
+void CTX_data_list_add(bContextDataResult *result, ID *id, StructRNA *type, void *data);
+
+/**
+ * Stores a property in a result. Make sure to also call
+ * `CTX_data_type_set(result, ContextDataType::Property)`.
+ * \param result: The result to store the property in.
+ * \param prop: The property to store.
+ * \param index: The particular index in the property to store.
+ */
+void CTX_data_prop_set(bContextDataResult *result, PropertyRNA *prop, int index);
+
+void CTX_data_dir_set(bContextDataResult *result, const char **dir);
+
+void CTX_data_type_set(bContextDataResult *result, ContextDataType type);
+ContextDataType CTX_data_type_get(bContextDataResult *result);
+
+bool CTX_data_equals(const char *member, const char *str);
+bool CTX_data_dir(const char *member);
+
+#define CTX_DATA_BEGIN(C, Type, instance, member) \
+ { \
+ Vector<PointerRNA> ctx_data_list; \
+ CTX_data_##member(C, &ctx_data_list); \
+ for (PointerRNA &ctx_link : ctx_data_list) { \
+ Type instance = (Type)ctx_link.data;
+
+#define CTX_DATA_END \
+ } \
+ } \
+ (void)0
+
+#define CTX_DATA_BEGIN_WITH_ID(C, Type, instance, member, Type_id, instance_id) \
+ CTX_DATA_BEGIN (C, Type, instance, member) \
+ Type_id instance_id = (Type_id)ctx_link.owner_id;
+
+int ctx_data_list_count(const bContext *C, bool (*func)(const bContext *, Vector<PointerRNA> *));
+
+#define CTX_DATA_COUNT(C, member) ctx_data_list_count(C, CTX_data_##member)
+
+/* Data Context Members */
+
+Main *CTX_data_main(const bContext *C);
+Scene *CTX_data_scene(const bContext *C);
+Scene *CTX_data_sequencer_scene(const bContext *C);
+/**
+ * This is tricky. Sometimes the user overrides the render_layer
+ * but not the scene_collection. In this case what to do?
+ *
+ * If the scene_collection is linked to the #ViewLayer we use it.
+ * Otherwise we fall back to the active one of the #ViewLayer.
+ */
+LayerCollection *CTX_data_layer_collection(const bContext *C);
+Collection *CTX_data_collection(const bContext *C);
+ViewLayer *CTX_data_view_layer(const bContext *C);
+RenderEngineType *CTX_data_engine_type(const bContext *C);
+ToolSettings *CTX_data_tool_settings(const bContext *C);
+
+const char *CTX_data_mode_string(const bContext *C);
+enum eContextObjectMode CTX_data_mode_enum_ex(const Object *obedit,
+ const Object *ob,
+ eObjectMode object_mode);
+enum eContextObjectMode CTX_data_mode_enum(const bContext *C);
+
+void CTX_data_main_set(bContext *C, Main *bmain);
+void CTX_data_scene_set(bContext *C, Scene *scene);
+
+/* Only Outliner currently! */
+bool CTX_data_selected_ids(const bContext *C, Vector<PointerRNA> *list);
+
+bool CTX_data_selected_editable_objects(const bContext *C, Vector<PointerRNA> *list);
+bool CTX_data_selected_editable_bases(const bContext *C, Vector<PointerRNA> *list);
+
+bool CTX_data_editable_objects(const bContext *C, Vector<PointerRNA> *list);
+bool CTX_data_editable_bases(const bContext *C, Vector<PointerRNA> *list);
+
+bool CTX_data_selected_objects(const bContext *C, Vector<PointerRNA> *list);
+bool CTX_data_selected_bases(const bContext *C, Vector<PointerRNA> *list);
+
+bool CTX_data_visible_objects(const bContext *C, Vector<PointerRNA> *list);
+bool CTX_data_visible_bases(const bContext *C, Vector<PointerRNA> *list);
+
+bool CTX_data_selectable_objects(const bContext *C, Vector<PointerRNA> *list);
+bool CTX_data_selectable_bases(const bContext *C, Vector<PointerRNA> *list);
+
+Object *CTX_data_active_object(const bContext *C);
+Base *CTX_data_active_base(const bContext *C);
+Object *CTX_data_edit_object(const bContext *C);
+
+Image *CTX_data_edit_image(const bContext *C);
+
+Text *CTX_data_edit_text(const bContext *C);
+MovieClip *CTX_data_edit_movieclip(const bContext *C);
+Mask *CTX_data_edit_mask(const bContext *C);
+
+CacheFile *CTX_data_edit_cachefile(const bContext *C);
+
+bool CTX_data_selected_nodes(const bContext *C, Vector<PointerRNA> *list);
+
+EditBone *CTX_data_active_bone(const bContext *C);
+bool CTX_data_selected_bones(const bContext *C, Vector<PointerRNA> *list);
+bool CTX_data_selected_editable_bones(const bContext *C, Vector<PointerRNA> *list);
+bool CTX_data_visible_bones(const bContext *C, Vector<PointerRNA> *list);
+bool CTX_data_editable_bones(const bContext *C, Vector<PointerRNA> *list);
+
+bPoseChannel *CTX_data_active_pose_bone(const bContext *C);
+bool CTX_data_selected_pose_bones(const bContext *C, Vector<PointerRNA> *list);
+bool CTX_data_selected_pose_bones_from_active_object(const bContext *C, Vector<PointerRNA> *list);
+bool CTX_data_visible_pose_bones(const bContext *C, Vector<PointerRNA> *list);
+
+const AssetLibraryReference *CTX_wm_asset_library_ref(const bContext *C);
+class asset_system::AssetRepresentation *CTX_wm_asset(const bContext *C);
+
+bool CTX_wm_interface_locked(const bContext *C);
+
+/**
+ * Gets pointer to the dependency graph.
+ * If it doesn't exist yet, it will be allocated.
+ *
+ * The result dependency graph is NOT guaranteed to be up-to-date neither from relation nor from
+ * evaluated data points of view.
+ *
+ * \note Can not be used if access to a fully evaluated data-block is needed.
+ */
+Depsgraph *CTX_data_depsgraph_pointer(const bContext *C);
+
+/**
+ * Get dependency graph which is expected to be fully evaluated.
+ *
+ * In the release builds it is the same as CTX_data_depsgraph_pointer(). In the debug builds extra
+ * sanity checks are done. Additionally, this provides more semantic meaning to what is exactly
+ * expected to happen.
+ */
+Depsgraph *CTX_data_expect_evaluated_depsgraph(const bContext *C);
+
+/**
+ * Gets fully updated and evaluated dependency graph.
+ *
+ * All the relations and evaluated objects are guaranteed to be up to date.
+ *
+ * \note Will be expensive if there are relations or objects tagged for update.
+ * \note If there are pending updates depsgraph hooks will be invoked.
+ * \warning In many cases, runtime data on associated objects will be destroyed & recreated.
+ * \warning Returns null pointer if #rna_write_check is true and RNA writing is disallowed. If
+ * #rna_write_check is false then RNA writes must be allowed when calling this function.
+ */
+Depsgraph *CTX_data_ensure_evaluated_depsgraph(const bContext *C, bool rna_write_check = false);
+
+/* Will Return NULL if depsgraph is not allocated yet.
+ * Only used by handful of operators which are run on file load.
+ */
+Depsgraph *CTX_data_depsgraph_on_load(const bContext *C);
+
+/**
+ * Set context member logging flags.
+ */
+void CTX_member_logging_flag_set(bContext *C, CTX_LogFlag flag);
+
+/**
+ * Get context member logging flag.
+ */
+CTX_LogFlag CTX_member_logging_flag_get(const bContext *C);
+
+/**
+ * \return true when context access should be logged.
+ */
+bool CTX_member_logging_get(const bContext *C);
+
+/**
+ * Check if writing to RNA is allowed.
+ *
+ * RNA can use this to disable writes during callbacks, such as when accessing the evaluated
+ * depsgraph (#150024).
+ */
+bool CTX_member_rna_write_check(const bContext *C);
+
+} // namespace blender
diff --git a/compat/include/BKE_curveprofile.h b/compat/include/BKE_curveprofile.h
new file mode 100644
index 0000000..2b4643b
--- /dev/null
+++ b/compat/include/BKE_curveprofile.h
@@ -0,0 +1,175 @@
+/* SPDX-FileCopyrightText: 2019 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bke
+ */
+
+#include "BLI_math_vector_types.hh"
+#include "DNA_curveprofile_types.h"
+
+namespace blender {
+
+struct BlendDataReader;
+struct BlendWriter;
+struct CurveProfile;
+struct CurveProfilePoint;
+
+/**
+ * Sets the default settings and clip range for the profile widget.
+ * Does not generate either table.
+ */
+void BKE_curveprofile_set_defaults(struct CurveProfile *profile);
+
+/**
+ * Returns a pointer to a newly allocated curve profile, using the given preset.
+ */
+struct CurveProfile *BKE_curveprofile_add(eCurveProfilePresets preset);
+
+void BKE_curveprofile_free_data(struct CurveProfile *profile);
+
+void BKE_curveprofile_free(struct CurveProfile *profile);
+
+void BKE_curveprofile_copy_data(struct CurveProfile *target, const struct CurveProfile *profile);
+
+struct CurveProfile *BKE_curveprofile_copy(const struct CurveProfile *profile);
+
+/**
+ * Move a point's handle, accounting for the alignment of handles with the #HD_ALIGN type.
+ *
+ * \param handle_1: Whether to move the 1st or 2nd control point.
+ * \param delta: The *relative* change in the handle's position.
+ * \note Requires #BKE_curveprofile_update call after.
+ * \return Whether the handle moved from its start position.
+ */
+bool BKE_curveprofile_move_handle(struct CurveProfilePoint *point,
+ bool handle_1,
+ bool snap,
+ const float delta[2]);
+
+/**
+ * Moves a control point, accounting for clipping and snapping, and moving free handles.
+ *
+ * \param snap: Whether to snap the point to the grid
+ * \param delta: The *relative* change of the point's location.
+ * \return Whether the point moved from its start position.
+ * \note Requires #BKE_curveprofile_update call after.
+ */
+bool BKE_curveprofile_move_point(struct CurveProfile *profile,
+ struct CurveProfilePoint *point,
+ bool snap,
+ const float delta[2]);
+
+void BKE_curveprofile_translate_selection(struct CurveProfile *profile,
+ const blender::float2 &offset);
+
+/**
+ * Removes a specific point from the path of control points.
+ * \note Requires #BKE_curveprofile_update call after.
+ */
+bool BKE_curveprofile_remove_point(struct CurveProfile *profile, struct CurveProfilePoint *point);
+
+/**
+ * Removes every point in the widget with the supplied flag set, except for the first and last.
+ *
+ * \param flag: #CurveProfilePoint.flag.
+ *
+ * \note Requires #BKE_curveprofile_update call after.
+ */
+void BKE_curveprofile_remove_by_flag(struct CurveProfile *profile, short flag);
+
+/**
+ * Adds a new point at the specified location. The choice for which points to place the new vertex
+ * between is made by checking which control point line segment is closest to the new point and
+ * placing the new vertex in between that segment's points.
+ *
+ * \note Requires #BKE_curveprofile_update call after.
+ */
+struct CurveProfilePoint *BKE_curveprofile_insert(struct CurveProfile *profile, float x, float y);
+
+/**
+ * Sets the handle type of the selected control points.
+ * \param type_1, type_2: Handle type for the first handle. HD_VECT, HD_AUTO, HD_FREE, or HD_ALIGN.
+ * \note Requires #BKE_curveprofile_update call after.
+ */
+void BKE_curveprofile_selected_handle_set(struct CurveProfile *profile, int type_1, int type_2);
+
+/**
+ * Flips the profile across the diagonal so that its orientation is reversed.
+ *
+ * \note Requires #BKE_curveprofile_update call after.
+ */
+void BKE_curveprofile_reverse(struct CurveProfile *profile);
+
+/**
+ * Reset the view to the clipping rectangle.
+ */
+void BKE_curveprofile_reset_view(struct CurveProfile *profile);
+
+/**
+ * Resets the profile to the current preset.
+ *
+ * \note Requires #BKE_curveprofile_update call after.
+ */
+void BKE_curveprofile_reset(struct CurveProfile *profile);
+
+/**
+ * When the current point is deselected, activate the closest remaining point
+ * by index. The function searches for the nearest valid index relative to the previously
+ * active index, not the nearest point by distance.
+ */
+void BKE_curveprofile_activate_nearest_point(struct CurveProfile *profile, const int i_last);
+
+int BKE_curveprofile_table_size(const struct CurveProfile *profile);
+
+/**
+ * Refreshes the higher resolution table sampled from the input points. A call to this or
+ * #BKE_curveprofile_update is needed before evaluation functions that use the table.
+ * Also sets the number of segments used for the display preview of the locations
+ * of the sampled points.
+ */
+void BKE_curveprofile_init(struct CurveProfile *profile, short segments_len);
+
+/* Called for a complete update of the widget after modifications */
+enum {
+ PROF_UPDATE_NONE = 0,
+ PROF_UPDATE_REMOVE_DOUBLES = (1 << 0),
+ PROF_UPDATE_CLIP = (1 << 1),
+};
+/**
+ * Should be called after the widget is changed. Does profile and remove double checks and more
+ * importantly, recreates the display / evaluation and segments tables.
+ * \param update_flags: Bit-field with fields defined in header file.
+ * Controls removing doubles and clipping.
+ */
+void BKE_curveprofile_update(struct CurveProfile *profile, int update_flags);
+
+/**
+ * Does a single evaluation along the profile's path.
+ * Travels down (length_portion * path) length and returns the position at that point.
+ * Where length portion is the fraction of the total path length where we want the location.
+ *
+ * \param length_portion: The portion (0 to 1) of the path's full length to sample at.
+ * \note Requires #BKE_curveprofile_init or #BKE_curveprofile_update call before to fill table.
+ */
+void BKE_curveprofile_evaluate_length_portion(const struct CurveProfile *profile,
+ float length_portion,
+ float *x_out,
+ float *y_out);
+CurveProfilePoint *BKE_curveprofile_active_get(CurveProfile *profile);
+
+/**
+ * Return a pointer to the location of the active point or handle associated with a selected point.
+ */
+float *BKE_curveprofile_active_location_get(struct CurveProfilePoint *point);
+
+void BKE_curveprofile_blend_write(struct BlendWriter *writer, const struct CurveProfile *profile);
+/**
+ * Expects that the curve profile itself has been read already.
+ */
+void BKE_curveprofile_blend_read(struct BlendDataReader *reader, struct CurveProfile *profile);
+
+} // namespace blender
diff --git a/compat/include/BKE_fcurve.hh b/compat/include/BKE_fcurve.hh
new file mode 100644
index 0000000..864afe4
--- /dev/null
+++ b/compat/include/BKE_fcurve.hh
@@ -0,0 +1,3 @@
+/* BUI seam: minimal stand-in. SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+/* No FCurve functionality in BUI; include kept for source compatibility. */
diff --git a/compat/include/BKE_global.hh b/compat/include/BKE_global.hh
new file mode 100644
index 0000000..fcea555
--- /dev/null
+++ b/compat/include/BKE_global.hh
@@ -0,0 +1,379 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+/** \file
+ * \ingroup bke
+ * \section aboutglobal Global settings
+ * Global settings, handles, pointers. This is the root for finding
+ * any data in Blender. This block is not serialized, but built anew
+ * for every fresh Blender run.
+ */
+
+#include "DNA_listBase.h"
+
+namespace blender {
+
+struct Main;
+struct RecentFile;
+
+/**
+ * Global data, typically accessed from #G.
+ * See: #BKE_blender_globals_init & #BKE_blender_globals_clear.
+ *
+ * \note This is run-time only but some global data is written
+ * to #FileGlobal which is used to initialize members of #Global.
+ */
+struct Global {
+
+ /**
+ * Data for the current active blend file.
+ *
+ * Note that `CTX_data_main(C)` should be used where possible.
+ * Otherwise access via #G_MAIN.
+ */
+ Main *main;
+
+ /**
+ * Preview main is stored to avoid loading the preview file in multiple scenarios.
+ * It is actually shared between shader node previews and asset previews.
+ */
+ Main *pr_main;
+
+ /** Last saved location for images. */
+ char filepath_last_image[/*FILE_MAX*/ 1024];
+ /** Last used location for library link/append. */
+ char filepath_last_library[/*FILE_MAX*/ 1024];
+ /**
+ * Last saved location for .blend files.
+ * This is used for recovery in case of a crash.
+ * It is set when a .blend file is loaded or when saving (manually or through autosave).
+ */
+ char filepath_last_blend[/*FILE_MAX*/ 1024];
+
+ /**
+ * Strings of recently opened files to show in the file menu.
+ * A list of #RecentFile read from #BLENDER_HISTORY_FILE.
+ */
+ ListBaseT<RecentFile> recent_files;
+
+ /**
+ * Set when Escape been pressed or `Ctrl-C` pressed in background mode.
+ * Used for render quit and some other background tasks such as baking.
+ */
+ bool is_break;
+
+ /**
+ * Blender is running without any Windows or OpenGLES context.
+ * Typically set by the `--background` command-line argument.
+ *
+ * Also enabled when build defines `WITH_PYTHON_MODULE` or `WITH_HEADLESS` are set
+ * (which use background mode by definition).
+ */
+ bool background;
+
+ /**
+ * Skip reading the startup file and user preferences.
+ * Also disable saving the preferences on exit (see #G_FLAG_USERPREF_NO_SAVE_ON_EXIT),
+ * see via the command line argument: `--factory-startup`.
+ */
+ bool factory_startup;
+
+ /**
+ * Set when the user is interactively moving (transforming) content.
+ * see: #G_TRANSFORM_OBJ and related flags.
+ */
+ short moving;
+
+ /** To indicate render is busy, prevent render-window events, animation playback etc. */
+ bool is_rendering;
+
+ /**
+ * Debug value, can be set from the UI and python, used for testing nonstandard features.
+ * DO NOT abuse it with generic checks like `if (G.debug_value > 0)`. Do not use it as bitflags.
+ * Only precise specific values should be checked for, to avoid unpredictable side-effects.
+ * Please document here the value(s) you are using (or a range of values reserved to some area):
+ * * -16384 and below: Reserved for python (add-ons) usage.
+ * * -1: Disable faster motion paths computation (since 08/2018).
+ * * 1 - 30: EEVEE debug/stats values (01/2018).
+ * * 31: Enable the Select Debug Engine. Only available with #WITH_DRAW_DEBUG (08/2021).
+ * * 101: Enable UI debug drawing of full-screen area's corner widget (10/2014).
+ * * 102: Enable extra items in string search UI (05/2022).
+ * * 666: Use quicker batch delete for outliners' delete hierarchy (01/2019).
+ * * 777: Enable UI node panel's sockets polling (11/2011).
+ * * 799: Enable some mysterious new depsgraph behavior (05/2015).
+ * * 1112: Disable new Cloth internal springs handling (09/2014).
+ * * 1234: Disable new dyntopo code fixing skinny faces generation (04/2015).
+ * * 3001: Enable additional Fluid modifier (Mantaflow) options (02/2020).
+ * * 4000: Line Art state output and debugging logs (03/2021).
+ * * 4001: Mesh topology information in the spreadsheet (01/2022).
+ * * 16384 and above: Reserved for python (add-ons) usage.
+ */
+ short debug_value;
+
+ /**
+ * Saved to the blend file as #FileGlobal.globalf
+ *
+ * \note Currently this is only used for runtime options, adding flags to #G_FLAG_ALL_READFILE
+ * will cause them to be written and read to files.
+ */
+ int f;
+
+ struct {
+ /**
+ * Logging vars (different loggers may use).
+ * Set via `--log-level` command line argument.
+ */
+ int level;
+ /**
+ * FILE handle or use `stderr` (we own this so close when done).
+ * Set via `--log-file` command line argument.
+ */
+ void *file;
+ } log;
+
+ /**
+ * Debug flag, #G_DEBUG, #G_DEBUG_PYTHON & friends, set via:
+ * - Command line arguments: `--debug`, `--debug-memory` ... etc.
+ * - Python API: `bpy.app.debug`, `bpy.app.debug_memory` ... etc.
+ */
+ int debug;
+
+ /**
+ * When true, various geometry processing algorithms randomize the order of elements (e.g.
+ * vertices or edges) in the output. In many cases, we don't make guarantees about the exact
+ * order of elements. So if users depend on the indices with e.g. geometry nodes, their file can
+ * break in a different Blender version. Explicitly turning on randomization can help protect
+ * oneself against such breakages.
+ */
+ bool randomize_geometry_element_order;
+
+ /**
+ * Control behavior of file reading/writing.
+ *
+ * This variable is written to / read from #FileGlobal.fileflags.
+ * See: #G_FILE_COMPRESS and related flags.
+ */
+ int fileflags;
+
+ /**
+ * Message to show when loading a `.blend` file attempts to execute
+ * a Python script or driver-expression when doing so is disallowed.
+ *
+ * Set when `(G.f & G_FLAG_SCRIPT_AUTOEXEC_FAIL) == 0`,
+ * so users can be alerted to the reason why the file may not be behaving as expected.
+ * Typically Python drivers.
+ */
+ char autoexec_fail[200];
+
+ /**
+ * Triggers a GPU capture if the name matches a DebugScope.
+ * Set using `--debug-gpu-scope-capture "debug_scope"`.
+ */
+ char gpu_debug_scope_name[100];
+
+ /**
+ * Save final shader string to disk.
+ * Set using `--debug-gpu-shader-source "shader_name"`.
+ */
+ char gpu_debug_shader_source_name[100];
+
+ bool profile_gpu;
+};
+
+/* **************** GLOBAL ********************* */
+
+/** #Global.f */
+enum {
+ G_FLAG_RENDER_VIEWPORT = (1 << 0),
+ G_FLAG_PICKSEL = (1 << 2),
+ /** Support simulating events (for testing). */
+ G_FLAG_EVENT_SIMULATE = (1 << 3),
+ G_FLAG_USERPREF_NO_SAVE_ON_EXIT = (1 << 4),
+
+ /**
+ * Internet access is allowed (offline mode when disabled).
+ *
+ * \note This setting doesn't prevent network access, rather it is a setting to
+ * disallow built-in utilities and 3rd party scripts from accessing the internet.
+ * While this isn't enforced, it is considered a bug when any script sends or receives
+ * data over the internet while this flag is set.
+ */
+ G_FLAG_INTERNET_ALLOW = (1 << 10),
+
+ /* NOTE: storing both online/offline override is needed so changing the preference
+ * can be disabled when launching Blender with `--offline-mode`.
+ * This means that users in a controlled environment can launch
+ * in offline-mode and the option can't be changed afterwards. */
+
+ /** Launched with `--offline-mode` (overrides #USER_INTERNET_ALLOW when set). */
+ G_FLAG_INTERNET_OVERRIDE_PREF_ONLINE = (1 << 11),
+ /** Launched with `--offline-mode` (overrides #USER_INTERNET_ALLOW when set). */
+ G_FLAG_INTERNET_OVERRIDE_PREF_OFFLINE = (1 << 12),
+
+ G_FLAG_SCRIPT_AUTOEXEC = (1 << 13),
+ /** When this flag is set ignore the preferences #USER_SCRIPT_AUTOEXEC_DISABLE. */
+ G_FLAG_SCRIPT_OVERRIDE_PREF = (1 << 14),
+ G_FLAG_SCRIPT_AUTOEXEC_FAIL = (1 << 15),
+ G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET = (1 << 16),
+
+ /** When this flag is set the active GPU Backend is different than the user wants to use. */
+ G_FLAG_GPU_BACKEND_FALLBACK = (1 << 17),
+ G_FLAG_GPU_BACKEND_FALLBACK_QUIET = (1 << 18),
+
+};
+
+#define G_FLAG_INTERNET_OVERRIDE_PREF_ANY \
+ (G_FLAG_INTERNET_OVERRIDE_PREF_ONLINE | G_FLAG_INTERNET_OVERRIDE_PREF_OFFLINE)
+
+/** Don't overwrite these flags when reading a file. */
+#define G_FLAG_ALL_RUNTIME \
+ (G_FLAG_SCRIPT_AUTOEXEC | G_FLAG_SCRIPT_OVERRIDE_PREF | G_FLAG_INTERNET_ALLOW | \
+ G_FLAG_INTERNET_OVERRIDE_PREF_ONLINE | G_FLAG_INTERNET_OVERRIDE_PREF_OFFLINE | \
+ G_FLAG_EVENT_SIMULATE | G_FLAG_USERPREF_NO_SAVE_ON_EXIT | G_FLAG_GPU_BACKEND_FALLBACK | \
+ G_FLAG_GPU_BACKEND_FALLBACK_QUIET | \
+\
+ /* #BPY_python_reset is responsible for resetting these flags on file load. */ \
+ G_FLAG_SCRIPT_AUTOEXEC_FAIL | G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET)
+
+/** Flags to read from blend file. */
+#define G_FLAG_ALL_READFILE 0
+
+/** #Global.debug */
+enum {
+ G_DEBUG = (1 << 0), /* general debug flag, print more info in unexpected cases */
+ G_DEBUG_PYTHON = (1 << 2), /* extra python info */
+ G_DEBUG_EVENTS = (1 << 3), /* input/window/screen events */
+ G_DEBUG_HANDLERS = (1 << 4), /* events handling */
+ G_DEBUG_WM = (1 << 5), /* operator, undo */
+ G_DEBUG_JOBS = (1 << 6), /* jobs time profiling */
+ G_DEBUG_FREESTYLE = (1 << 7), /* freestyle messages */
+ G_DEBUG_DEPSGRAPH_BUILD = (1 << 8), /* depsgraph construction messages */
+ G_DEBUG_DEPSGRAPH_EVAL = (1 << 9), /* depsgraph evaluation messages */
+ G_DEBUG_DEPSGRAPH_TAG = (1 << 10), /* depsgraph tagging messages */
+ G_DEBUG_DEPSGRAPH_TIME = (1 << 11), /* depsgraph timing statistics and messages */
+ G_DEBUG_DEPSGRAPH_NO_THREADS = (1 << 12), /* single threaded depsgraph */
+ G_DEBUG_DEPSGRAPH_PRETTY = (1 << 13), /* use pretty colors in depsgraph messages */
+ G_DEBUG_DEPSGRAPH_UID = (1 << 14), /* Verify validness of session-wide identifiers
+ * assigned to ID datablocks */
+ G_DEBUG_DEPSGRAPH = (G_DEBUG_DEPSGRAPH_BUILD | G_DEBUG_DEPSGRAPH_EVAL | G_DEBUG_DEPSGRAPH_TAG |
+ G_DEBUG_DEPSGRAPH_TIME | G_DEBUG_DEPSGRAPH_UID),
+ G_DEBUG_SIMDATA = (1 << 15), /* sim debug data display */
+ G_DEBUG_GPU = (1 << 16), /* gpu debug */
+ G_DEBUG_IO = (1 << 17), /* IO Debugging. */
+ G_DEBUG_GPU_FORCE_WORKAROUNDS = (1 << 18), /* Force GPU workarounds bypassing detection. */
+ G_DEBUG_GPU_FORCE_VULKAN_LOCAL_READ = (1 << 19), /* Force GPU dynamic rendering local read. */
+ G_DEBUG_GPU_COMPILE_SHADERS = (1 << 20), /* Compile all statically defined shaders. . */
+ G_DEBUG_GPU_RENDERDOC = (1 << 21), /* Enable RenderDoc integration. */
+ G_DEBUG_GPU_SHADER_DEBUG_INFO = (1 << 22), /* Enable the generation of shader debug info. */
+ G_DEBUG_GPU_NO_TEXTURE_POOL = (1 << 23), /* Disable memory aliasing in the texture pool. */
+ G_DEBUG_XR = (1 << 24), /* XR/OpenXR messages */
+ G_DEBUG_XR_TIME = (1 << 25), /* XR/OpenXR timing messages */
+
+ G_DEBUG_GHOST = (1 << 26), /* Debug GHOST module. */
+ G_DEBUG_WINTAB = (1 << 27), /* Debug Wintab. */
+
+ G_DEBUG_GPU_SHADER_NO_PREPROCESSOR = (1 << 28), /* Disable the preprocessor (implies NO_DCE). */
+ G_DEBUG_GPU_SHADER_NO_DCE = (1 << 29), /* Disable Dead Code Elimination. */
+};
+
+#define G_DEBUG_ALL \
+ (G_DEBUG | G_DEBUG_PYTHON | G_DEBUG_EVENTS | G_DEBUG_WM | G_DEBUG_JOBS | G_DEBUG_FREESTYLE | \
+ G_DEBUG_DEPSGRAPH | G_DEBUG_IO | G_DEBUG_GHOST | G_DEBUG_WINTAB)
+
+/** #Global.fileflags */
+enum {
+ G_FILE_AUTOPACK = (1 << 0),
+ G_FILE_COMPRESS = (1 << 1),
+
+ /**
+ * When in background mode, do not automatically build a depsgraph when loading a blend-file.
+ * Typically set by the `--disable-depsgraph-on-file-load` command-line argument.
+ *
+ * NOTE: This is a temporary option, it is intended to be removed in blender 5.0.
+ * The default behavior will then be changed to never automatically generate a depsgraph on
+ * file-load when in background mode.
+ */
+ G_BACKGROUND_NO_DEPSGRAPH = 1 << 2,
+
+ /**
+ * Do not perform automatic resync of library overrides on blend-file load.
+ *
+ * NOTE: runtime version of #UserDef_Experimental.no_override_auto_resync, both values are OR'ed
+ * together.
+ */
+ G_LIBOVERRIDE_NO_AUTO_RESYNC = 1 << 3,
+
+ // G_FILE_DEPRECATED_9 = (1 << 9),
+ G_FILE_NO_UI = (1 << 10),
+
+ /* Bits 11 to 22 (inclusive) are deprecated & need to be cleared */
+
+ /**
+ * On read, use #FileGlobal.filename instead of the real location on-disk,
+ * needed for recovering temp files so relative paths resolve.
+ *
+ * \note In some ways it would be nicer to make this an argument passed to file loading.
+ * In practice this means recover needs to be passed around to too many low level functions,
+ * so keep this as a flag.
+ */
+ G_FILE_RECOVER_READ = (1 << 23),
+ /**
+ * On write, assign use #FileGlobal.filename, otherwise leave it blank,
+ * needed so files can be recovered at their original locations.
+ *
+ * \note only #BLENDER_QUIT_FILE and auto-save files include recovery information.
+ * As users/developers may not want their paths exposed in publicly distributed files.
+ */
+ G_FILE_RECOVER_WRITE = (1 << 24),
+ /** BMesh option to save as older mesh format */
+ // #define G_FILE_MESH_COMPAT (1 << 26)
+ // #define G_FILE_GLSL_NO_ENV_LIGHTING (1 << 28) /* deprecated */
+ /**
+ * This file contains a single asset and its dependencies. Users may edit the asset through the
+ * UI and save the changes, at which point the file will be regenerated by the asset system to
+ * include the edits (API in #BKE_asset_edit.hh). Stored with an .asset.blend file extension.
+ */
+ G_FILE_ASSET_EDIT_FILE = (1 << 29),
+};
+
+/**
+ * Run-time only #G.fileflags which are never read or written to/from Blend files.
+ * This means we can change the values without worrying about do-versions.
+ */
+#define G_FILE_FLAG_ALL_RUNTIME \
+ (G_BACKGROUND_NO_DEPSGRAPH | G_LIBOVERRIDE_NO_AUTO_RESYNC | G_FILE_NO_UI | \
+ G_FILE_RECOVER_READ | G_FILE_RECOVER_WRITE)
+
+/** #Global.moving, signals drawing in (3d) window to denote transform */
+enum {
+ G_TRANSFORM_OBJ = (1 << 0),
+ G_TRANSFORM_EDIT = (1 << 1),
+ G_TRANSFORM_SEQ = (1 << 2),
+ G_TRANSFORM_FCURVES = (1 << 3),
+ /**
+ * Set while interactively transforming screen data (e.g. resizing areas & regions).
+ *
+ * \note Ideally this flag would also be used for resizing the window however that's handled
+ * outside by the windowing environment, so this is only used for internal windowing operations.
+ */
+ G_TRANSFORM_WM = (1 << 4),
+ /**
+ * Set when transforming the cursor itself.
+ * Used as a hint to draw the cursor (even when hidden).
+ * Otherwise it's not possible to see what's being transformed.
+ */
+ G_TRANSFORM_CURSOR = (1 << 5),
+};
+
+/** Defined in `blender.cc` */
+extern Global G;
+
+/**
+ * Stupid macro to hide the few *valid* usages of `G.main` (from startup/exit code e.g.),
+ * helps with cleanup task.
+ */
+#define G_MAIN (G).main
+
+} // namespace blender
diff --git a/compat/include/BKE_lib_id.hh b/compat/include/BKE_lib_id.hh
new file mode 100644
index 0000000..0b4dfef
--- /dev/null
+++ b/compat/include/BKE_lib_id.hh
@@ -0,0 +1,26 @@
+/* BUI seam: ID-name helpers used by search/templating drawing.
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#include "DNA_ID.h"
+
+#ifdef __cplusplus
+extern "C" {
+using blender::ID;
+#endif
+
+#ifndef MAX_ID_FULL_NAME_UI
+#define MAX_ID_FULL_NAME_UI (MAX_NAME + 23)
+#endif
+
+/* Stub implementation: copies the ID's name (no library prefix decoration)
+ * and reports zero prefix length. A real host can decorate linked-data names. */
+void BKE_id_full_name_ui_prefix_get(char name[MAX_ID_FULL_NAME_UI],
+ const ID *id,
+ bool add_lib_hint,
+ char separator_char,
+ int *r_prefix_len);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/compat/include/BKE_report.hh b/compat/include/BKE_report.hh
new file mode 100644
index 0000000..9fb8a79
--- /dev/null
+++ b/compat/include/BKE_report.hh
@@ -0,0 +1,161 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bke
+ */
+
+#include <cstdio>
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_enum_flags.hh"
+#include "BLI_mutex.hh"
+
+#include "DNA_listBase.h"
+
+struct CLG_LogRef;
+
+namespace blender {
+
+struct wmTimer;
+
+/**
+ * Reporting Information and Errors.
+ *
+ * These functions are thread-safe, unless otherwise specified.
+ *
+ * These functions also accept nullptr in case no error reporting is needed. The message are only
+ * printed to the console then.
+ */
+
+/** Keep in sync with 'rna_enum_wm_report_items' in `wm_rna.c`. */
+enum eReportType : uint16_t {
+ RPT_DEBUG = (1 << 0),
+ RPT_INFO = (1 << 1),
+ RPT_OPERATOR = (1 << 2),
+ RPT_PROPERTY = (1 << 3),
+ RPT_WARNING = (1 << 4),
+ RPT_ERROR = (1 << 5),
+ RPT_ERROR_INVALID_INPUT = (1 << 6),
+ RPT_ERROR_INVALID_CONTEXT = (1 << 7),
+ RPT_ERROR_OUT_OF_MEMORY = (1 << 8),
+};
+ENUM_OPERATORS(eReportType)
+
+#define RPT_DEBUG_ALL (RPT_DEBUG)
+#define RPT_INFO_ALL (RPT_INFO)
+#define RPT_OPERATOR_ALL (RPT_OPERATOR)
+#define RPT_PROPERTY_ALL (RPT_PROPERTY)
+#define RPT_WARNING_ALL (RPT_WARNING)
+#define RPT_ERROR_ALL \
+ (RPT_ERROR | RPT_ERROR_INVALID_INPUT | RPT_ERROR_INVALID_CONTEXT | RPT_ERROR_OUT_OF_MEMORY)
+
+enum ReportListFlags {
+ RPT_PRINT = (1 << 0),
+ RPT_STORE = (1 << 1),
+ RPT_FREE = (1 << 2),
+ RPT_OP_HOLD = (1 << 3), /* don't move them into the operator global list (caller will use) */
+ /** Don't print (the owner of the #ReportList will handle printing to the `stdout`). */
+ RPT_PRINT_HANDLED_BY_OWNER = (1 << 4),
+};
+
+struct Report {
+ Report *next, *prev;
+ /** eReportType. */
+ short type;
+ short flag;
+ /** `strlen(message)`, saves some time calculating the word wrap. */
+ int len;
+ const char *typestr;
+ const char *message;
+ /** Unique per-session identifier, assigned at creation. */
+ int session_uid;
+};
+
+struct ReportList {
+ ListBaseT<Report> list;
+ /** #eReportType. */
+ int printlevel;
+ /** #eReportType. */
+ int storelevel;
+ int flag;
+ char _pad[4];
+ wmTimer *reporttimer;
+
+ /** Mutex for thread-safety, runtime only. */
+ std::mutex *lock;
+};
+
+/* Report structures are stored in DNA. */
+
+/**
+ * Initialize a #ReportList struct.
+ *
+ * \note Not thread-safe, should only be called from the 'owner' thread of the report list.
+ */
+void BKE_reports_init(ReportList *reports, int flag);
+/**
+ * Fully release any internal resources used by this #ReportList, as acquired by #BKE_reports_init.
+ *
+ * Also calls #BKE_reports_clear. The given `reports` should not be used anymore unless it is
+ * re-initialized first.
+ *
+ * \note Not thread-safe, should only be called from the current owner of the report list, once
+ * no other concurrent access is possible.
+ */
+void BKE_reports_free(ReportList *reports);
+
+/**
+ * Only frees the list of reports in given \a reports. Use #BKE_reports_free to fully cleanup all
+ * allocated resources.
+ *
+ * To make displayed reports disappear, either remove window-manager reports
+ * (#wmWindowManager.reports, or #CTX_wm_reports()), or use #WM_report_banners_cancel().
+ */
+void BKE_reports_clear(ReportList *reports);
+
+/** Moves all reports from `reports_src` to `reports_dst`. */
+void BKE_reports_move_to_reports(ReportList *reports_dst, ReportList *reports_src);
+
+/** (Un)lock given `reports`, in case external code needs to access its data. */
+void BKE_reports_lock(ReportList *reports);
+void BKE_reports_unlock(ReportList *reports);
+
+void BKE_report(ReportList *reports, eReportType type, const char *message);
+void BKE_reportf(ReportList *reports, eReportType type, const char *format, ...)
+ ATTR_PRINTF_FORMAT(3, 4);
+
+void BKE_reports_prepend(ReportList *reports, const char *prepend);
+void BKE_reports_prependf(ReportList *reports, const char *prepend_format, ...)
+ ATTR_PRINTF_FORMAT(2, 3);
+
+eReportType BKE_report_print_level(ReportList *reports);
+void BKE_report_print_level_set(ReportList *reports, eReportType level);
+
+eReportType BKE_report_store_level(ReportList *reports);
+void BKE_report_store_level_set(ReportList *reports, eReportType level);
+
+char *BKE_reports_string(ReportList *reports, eReportType level);
+
+/**
+ * \return true when reports of this type will print to the `stdout`.
+ */
+bool BKE_reports_print_test(const ReportList *reports, eReportType type);
+void BKE_reports_print(ReportList *reports, eReportType level);
+
+void BKE_report_log(eReportType type, const char *message, CLG_LogRef *log);
+void BKE_reports_log(ReportList *reports, eReportType level, CLG_LogRef *log);
+
+Report *BKE_reports_last_displayable(ReportList *reports);
+
+bool BKE_reports_contain(ReportList *reports, eReportType level);
+
+const char *BKE_report_type_str(eReportType type);
+
+bool BKE_report_write_file_fp(FILE *fp, ReportList *reports, const char *header);
+bool BKE_report_write_file(const char *filepath, ReportList *reports, const char *header);
+
+} // namespace blender
diff --git a/compat/include/BKE_screen.hh b/compat/include/BKE_screen.hh
new file mode 100644
index 0000000..e69693a
--- /dev/null
+++ b/compat/include/BKE_screen.hh
@@ -0,0 +1,977 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+/** \file
+ * \ingroup bke
+ */
+
+#include <memory>
+#include <string>
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_enum_flags.hh"
+#include "BLI_map.hh"
+#include "BLI_math_vector_types.hh"
+#include "BLI_string_ref.hh"
+#include "BLI_vector.hh"
+
+#include "DNA_listBase.h"
+#include "DNA_space_types.h"
+#include "DNA_vec_types.h"
+
+#include "RNA_types.hh"
+
+#include "BKE_context.hh"
+
+namespace blender {
+namespace bke::id {
+class IDRemapper;
+}
+
+namespace asset_system {
+class AssetRepresentation;
+}
+
+namespace ui {
+struct Layout;
+struct Block;
+} // namespace ui
+
+struct ARegion;
+struct ARegionType;
+struct AssetShelfType;
+struct BlendDataReader;
+struct BlendLibReader;
+struct BlendWriter;
+struct Header;
+struct HeaderType;
+struct ID;
+struct LayoutPanelState;
+struct LibraryForeachIDData;
+struct Menu;
+struct Panel;
+struct PanelType;
+struct PanelCategoryDyn;
+struct RegionDrawCB;
+struct Scene;
+struct ScrArea;
+struct ScrAreaMap;
+struct ScrEdge;
+struct ScrVert;
+struct SpaceType;
+struct View3D;
+struct View3DShading;
+struct WorkSpace;
+struct bContext;
+struct bScreen;
+struct uiList;
+struct wmDrawBuffer;
+struct wmEventHandler;
+struct wmGizmoMap;
+struct wmKeyConfig;
+struct wmMsgBus;
+struct wmNotifier;
+struct wmTimer;
+struct wmWindow;
+struct wmWindowManager;
+struct RegionDrawCB;
+struct PanelType;
+struct HeaderType;
+struct ARegionType;
+struct wmEventHandler;
+struct PanelCategoryDyn;
+
+/* spacetype has everything stored to get an editor working, it gets initialized via
+ * #ED_spacetypes_init() in `editors/space_api/spacetypes.cc` */
+/* an editor in Blender is a combined ScrArea + SpaceType + SpaceData. */
+
+#define BKE_ST_MAXNAME 64
+
+struct wmSpaceTypeListenerParams {
+ wmWindow *window;
+ ScrArea *area;
+ const wmNotifier *notifier;
+ const Scene *scene;
+ const Main *bmain;
+};
+
+struct SpaceType {
+ /** For menus. */
+ char name[BKE_ST_MAXNAME];
+ /** Unique space identifier. */
+ int spaceid;
+ /** Icon lookup for menus. */
+ int iconid;
+
+ /**
+ * Initial allocation, after this WM will call init() too.
+ * Some editors need area and scene data (e.g. frame range) to set their initial scrolling.
+ */
+ SpaceLink *(*create)(const ScrArea *area, const Scene *scene);
+ /** Not free spacelink itself. */
+ void (*free)(SpaceLink *sl);
+
+ /** Init is to cope with file load, screen (size) changes, check handlers. */
+ void (*init)(wmWindowManager *wm, ScrArea *area);
+ /** Exit is called when the area is hidden or removed. */
+ void (*exit)(wmWindowManager *wm, ScrArea *area);
+ /** Listeners can react to bContext changes. */
+ void (*listener)(const wmSpaceTypeListenerParams *params);
+
+ /** Called when the mouse moves out of the area. */
+ void (*deactivate)(ScrArea *area);
+
+ /** Refresh context, called after file-reads, #ED_area_tag_refresh(). */
+ void (*refresh)(const bContext *C, ScrArea *area);
+
+ /** After a spacedata copy, an init should result in exact same situation. */
+ SpaceLink *(*duplicate)(SpaceLink *sl);
+
+ /** Register operator types on startup. */
+ void (*operatortypes)();
+ /** Add default items to WM keymap. */
+ void (*keymap)(wmKeyConfig *keyconf);
+ /** On startup, define dropboxes for spacetype+regions. */
+ void (*dropboxes)();
+
+ /** Initialize gizmo-map-types and gizmo-group-types with the region. */
+ void (*gizmos)();
+
+ /** Return context data. */
+ bContextDataCallback context;
+
+ /** Used when we want to replace an ID by another (or NULL). */
+ void (*id_remap)(ScrArea *area, SpaceLink *sl, const bke::id::IDRemapper &mappings);
+
+ /**
+ * foreach_id callback to process all ID pointers of the editor. Used indirectly by lib_query's
+ * #BKE_library_foreach_ID_link when #IDWALK_INCLUDE_UI bit-flag is set (through WM's foreach_id
+ * usage of #BKE_screen_foreach_id_screen_area).
+ */
+ void (*foreach_id)(SpaceLink *space_link, LibraryForeachIDData *data);
+
+ int (*space_subtype_get)(ScrArea *area);
+ void (*space_subtype_set)(ScrArea *area, int value);
+ void (*space_subtype_item_extend)(bContext *C, EnumPropertyItem **item, int *totitem);
+
+ /** Return a custom name, based on subtype or other reason. */
+ StringRefNull (*space_name_get)(const ScrArea *area);
+ /** Return a custom icon, based on subtype or other reason. */
+ int (*space_icon_get)(const ScrArea *area);
+
+ /**
+ * Update pointers for all structs directly owned by this space.
+ */
+ void (*blend_read_data)(BlendDataReader *reader, SpaceLink *space_link);
+
+ /**
+ * Update pointers to other id data blocks.
+ */
+ void (*blend_read_after_liblink)(BlendLibReader *reader, ID *parent_id, SpaceLink *space_link);
+
+ /**
+ * Write all structs that should be saved in a .blend file.
+ */
+ void (*blend_write)(BlendWriter *writer, SpaceLink *space_link);
+
+ /** Region type definitions. */
+ ListBaseT<ARegionType> regiontypes;
+
+ /* read and write... */
+
+ /** Default key-maps to add. */
+ int keymapflag;
+
+ ~SpaceType();
+};
+
+/* Region types are also defined using spacetypes_init, via a callback. */
+
+struct wmRegionListenerParams {
+ wmWindow *window;
+ /** Can be NULL when the region is not part of an area. */
+ ScrArea *area;
+ ARegion *region;
+ const wmNotifier *notifier;
+ const Scene *scene;
+};
+
+struct wmRegionMessageSubscribeParams {
+ const bContext *context;
+ wmMsgBus *message_bus;
+ WorkSpace *workspace;
+ Scene *scene;
+ bScreen *screen;
+ ScrArea *area;
+ ARegion *region;
+};
+
+struct RegionPollParams {
+ const bScreen *screen;
+ const ScrArea *area;
+ const ARegion *region;
+
+ /** Full context, if WM context above is not enough. */
+ const bContext *context;
+};
+
+enum class ARegionTypeFlag {
+ /**
+ * Use panel categories, where #PanelType.category and #ARegion.panels_category_active define
+ * which panels are visible. Available categories are collected during layout and cached in
+ * #ARegion.panels_category_active.
+ */
+ UsePanelCategories = (1 << 0),
+ /**
+ * Same as #UsePanelCategories, plus panel drawing will draw tabs for the categories in this
+ * region.
+ */
+ UsePanelCategoryTabs = (1 << 1),
+
+ /**
+ * When using panel categories, this hides the sidebar tab where there is only one category
+ * active.
+ */
+ HideSinglePanelCategories = (1 << 2),
+};
+ENUM_OPERATORS(ARegionTypeFlag)
+
+/* #ARegionType::lock */
+enum ARegionDrawLockFlags {
+ REGION_DRAW_LOCK_NONE = 0,
+ REGION_DRAW_LOCK_RENDER = (1 << 0),
+ REGION_DRAW_LOCK_BAKING = (1 << 1),
+ REGION_DRAW_LOCK_ALL = (REGION_DRAW_LOCK_RENDER | REGION_DRAW_LOCK_BAKING)
+};
+
+struct ARegionType {
+ ARegionType *next, *prev;
+ /** Unique identifier within this space, defines `RGN_TYPE_xxxx`. */
+ int regionid;
+
+ /** Add handlers, stuff you only do once or on area/region type/size changes. */
+ void (*init)(wmWindowManager *wm, ARegion *region);
+ /** Exit is called when the region is hidden or removed. */
+ void (*exit)(wmWindowManager *wm, ARegion *region);
+ /**
+ * Optional callback to decide whether the region should be treated as existing given the
+ * current context. When returning false, the region will be kept in storage, but is not
+ * available to the user in any way. Callbacks can assume that context has the owning area and
+ * space-data set.
+ */
+ bool (*poll)(const RegionPollParams *params);
+ /** Draw entirely, view changes should be handled here. */
+ void (*draw)(const bContext *C, ARegion *region);
+ /**
+ * Handler to draw overlays. This handler is called every draw loop.
+ *
+ * \note Some editors should return early if the interface is locked
+ * (check with #CTX_wm_interface_locked) to avoid accessing scene data
+ * that another thread may be modifying
+ */
+ void (*draw_overlay)(const bContext *C, ARegion *region);
+ /** Optional, compute button layout before drawing for dynamic size. */
+ void (*layout)(const bContext *C, ARegion *region);
+ /** Snap the size of the region (can be NULL for no snapping). */
+ int (*snap_size)(const ARegion *region, int size, int axis);
+ /** Contextual changes should be handled here. */
+ void (*listener)(const wmRegionListenerParams *params);
+ /** Optional callback to generate subscriptions. */
+ void (*message_subscribe)(const wmRegionMessageSubscribeParams *params);
+
+ void (*free)(ARegion *);
+
+ /** Split region, copy data optionally. */
+ void *(*duplicate)(void *poin);
+
+ /** Allows default cursor per region. */
+ void (*cursor)(wmWindow *win, ScrArea *area, ARegion *region);
+
+ /** Return context data. */
+ bContextDataCallback context;
+
+ /**
+ * Called on every frame in which the region's poll succeeds, regardless of visibility, before
+ * drawing, visibility evaluation and initialization. Allows the region to override visibility.
+ */
+ void (*on_poll_success)(const bContext *C, ARegion *region);
+
+ /**
+ * Called whenever the user changes the region's size. Not called when the size is changed
+ * through other means, like to adjust for a scaled down window.
+ */
+ void (*on_user_resize)(const ARegion *region);
+ /**
+ * Is called whenever the current visible View2D's region changes.
+ *
+ * Used from user code such as view navigation/zoom operators to inform region about changes.
+ * The goal is to support zoom-to-fit features which gets disabled when manual navigation is
+ * performed.
+ *
+ * This callback is not called on indirect changes of the current viewport (which could happen
+ * when the `v2d->tot` is changed and `cur` is adopted accordingly).
+ */
+ void (*on_view2d_changed)(const bContext *C, ARegion *region);
+
+ ARegionTypeFlag flag;
+
+ /** Custom drawing callbacks. */
+ ListBaseT<RegionDrawCB> drawcalls;
+
+ /** Panels type definitions. */
+ ListBaseT<PanelType> paneltypes;
+
+ /** Header type definitions. */
+ ListBaseT<HeaderType> headertypes;
+
+ /** Hardcoded constraints, smaller than these values region is not visible. */
+ int minsizex, minsizey;
+ /** When new region opens (region prefsizex/y are zero then. */
+ int prefsizex, prefsizey;
+ /** Default keymaps to add. */
+ int keymapflag;
+ /**
+ * Return without drawing.
+ * lock is set by region definition, and copied to do_lock by render.
+ * Set as bitflag value in #ARegionDrawLockFlags.
+ */
+ short do_lock, lock;
+ /** Don't handle gizmos events behind #ui::Block's with #BLOCK_CLIP_EVENTS flag set. */
+ bool clip_gizmo_events_by_ui;
+ /** Call cursor function on each move event. */
+ short event_cursor;
+};
+
+/* Panel types. */
+
+struct PanelType {
+ PanelType *next, *prev;
+
+ /** Unique name. */
+ char idname[BKE_ST_MAXNAME];
+ /** For panel header. */
+ char label[BKE_ST_MAXNAME];
+ /** For panel tooltip. */
+ const char *description;
+ int icon;
+ char translation_context[BKE_ST_MAXNAME];
+ /** For buttons window. */
+ char context[BKE_ST_MAXNAME];
+ /** For category tabs. */
+ char category[BKE_ST_MAXNAME];
+ /** For work-spaces to selectively show. */
+ char owner_id[128];
+ /** Parent idname for sub-panels. */
+ char parent_id[BKE_ST_MAXNAME];
+ /** Boolean property identifier of the panel custom data. Used to draw a highlighted border. */
+ char active_property[BKE_ST_MAXNAME];
+ char pin_to_last_property[BKE_ST_MAXNAME];
+ short space_type;
+ short region_type;
+ /** For popovers, 0 for default. */
+ int ui_units_x;
+ /**
+ * For popovers, position the popover at the given offset (multiplied by #UI_UNIT_X/#UI_UNIT_Y)
+ * relative to the top left corner, if it's not attached to a button.
+ */
+ float2 offset_units_xy;
+ int order;
+
+ int flag;
+
+ /** Verify if the panel should draw or not. */
+ bool (*poll)(const bContext *C, PanelType *pt);
+ /** Draw header (optional) */
+ void (*draw_header)(const bContext *C, Panel *panel);
+ /** Draw header preset (optional) */
+ void (*draw_header_preset)(const bContext *C, Panel *panel);
+ /** Draw entirely, view changes should be handled here. */
+ void (*draw)(const bContext *C, Panel *panel);
+ /**
+ * Listener to redraw the region this is contained in on changes. Only used for panels displayed
+ * in popover regions.
+ */
+ void (*listener)(const wmRegionListenerParams *params);
+
+ /* For instanced panels corresponding to a list: */
+
+ /** Reorder function, called when drag and drop finishes. */
+ void (*reorder)(bContext *C, Panel *pa, int new_index);
+ /**
+ * Get the panel and sub-panel's expansion state from the expansion flag in the corresponding
+ * data item. Called on draw updates.
+ * \note Sub-panels are indexed in depth first order,
+ * the visual order you would see if all panels were expanded.
+ */
+ short (*get_list_data_expand_flag)(const bContext *C, Panel *pa);
+ /**
+ * Set the expansion bit-field from the closed / open state of this panel and its sub-panels.
+ * Called when the expansion state of the panel changes with user input.
+ * \note Sub-panels are indexed in depth first order,
+ * the visual order you would see if all panels were expanded.
+ */
+ void (*set_list_data_expand_flag)(const bContext *C, Panel *pa, short expand_flag);
+
+ /** Sub panels. */
+ PanelType *parent;
+ ListBaseT<LinkData> children;
+ /** RNA integration. */
+ ExtensionRNA rna_ext;
+};
+
+/** #PanelType.flag */
+enum {
+ PANEL_TYPE_DEFAULT_CLOSED = (1 << 0),
+ PANEL_TYPE_NO_HEADER = (1 << 1),
+ /** Makes buttons in the header shrink/stretch to fill full layout width. */
+ PANEL_TYPE_HEADER_EXPAND = (1 << 2),
+ PANEL_TYPE_LAYOUT_VERT_BAR = (1 << 3),
+ /** This panel type represents data external to the UI. */
+ PANEL_TYPE_INSTANCED = (1 << 4),
+ /** Don't search panels with this type during property search. */
+ PANEL_TYPE_NO_SEARCH = (1 << 7),
+};
+
+struct LayoutPanelHeader {
+ float start_y;
+ float end_y;
+ PointerRNA open_owner_ptr;
+ std::string open_prop_name;
+};
+
+struct LayoutPanelBody {
+ float start_y;
+ float end_y;
+};
+
+/**
+ * "Layout Panels" are panels which are defined as part of the #ui::Layout. As such they
+ * have a specific place in the layout and can not be freely dragged around like top level panels.
+ *
+ * This struct gathers information about the layout panels created by layout code. This is then
+ * used for example drawing the backdrop of nested panels and to support opening and closing
+ * multiple panels with a single mouse gesture.
+ */
+struct LayoutPanels {
+ Vector<LayoutPanelHeader> headers;
+ Vector<LayoutPanelBody> bodies;
+
+ void clear()
+ {
+ this->headers.clear();
+ this->bodies.clear();
+ }
+};
+
+struct Panel_Runtime {
+ /** Applied to Panel.ofsx, but saved separately so we can track changes between redraws. */
+ int region_ofsx = 0;
+
+ /**
+ * Pointer for storing which data the panel corresponds to.
+ * Useful when there can be multiple instances of the same panel type.
+ *
+ * \note A panel and its sub-panels share the same custom data pointer.
+ * This avoids freeing the same pointer twice when panels are removed.
+ */
+ PointerRNA *custom_data_ptr = nullptr;
+
+ /**
+ * Pointer to the panel's block. Useful when changes to panel #ui::Blocks
+ * need some context from traversal of the panel "tree".
+ */
+ ui::Block *block = nullptr;
+
+ /** Non-owning pointer. The context is stored in the block. */
+ bContextStore *context = nullptr;
+
+ /** Information about nested layout panels generated in layout code. */
+ LayoutPanels layout_panels;
+
+ /**
+ * Custom storage for saving the open-close-state of layout panels created with
+ * `layout.panel(...)`. This precedes #Panel::layout_panel_states when storing layout panel
+ * state.
+ */
+ ListBaseT<LayoutPanelState> *layout_panel_states_storage = nullptr;
+};
+
+namespace bke {
+
+/** #ARegionRuntime.quadview_index */
+enum class ARegionQuadviewIndex : uint8_t {
+ None = 0,
+ BottomLeft = 1,
+ TopLeft = 2,
+ BottomRight = 3,
+ TopRight = 4,
+};
+
+struct ARegionRuntime {
+ /** Callbacks for this region type. */
+ struct ARegionType *type;
+
+ /** Runtime for partial redraw, same or smaller than #ARegion::winrct. */
+ rcti drawrct = {};
+
+ /**
+ * The visible part of the region, use with region overlap not to draw
+ * on top of the overlapping regions.
+ *
+ * Lazy initialize, zeroed when unset, relative to #ARegion.winrct x/y min.
+ */
+ rcti visible_rect = {};
+
+ /**
+ * The offset needed to not overlap with window scroll-bars.
+ * Only used by HUD regions for now.
+ */
+ int offset_x = 0;
+ int offset_y = 0;
+
+ /** Panel category to use between 'layout' and 'draw'. */
+ const char *category = nullptr;
+
+ /** Maps #ui::Block::name to ui::Block for faster lookups. */
+ Map<std::string, ui::Block *> block_name_map;
+ ListBaseT<ui::Block> uiblocks = {};
+
+ ListBaseT<wmEventHandler> handlers = {};
+
+ /** Use this string to draw info. */
+ char *headerstr = nullptr;
+
+ /** Gizmo-map of this region. */
+ wmGizmoMap *gizmo_map = nullptr;
+
+ /** Blend in/out. */
+ wmTimer *regiontimer = nullptr;
+
+ wmDrawBuffer *draw_buffer = nullptr;
+
+ /** Panel categories runtime. */
+ ListBaseT<PanelCategoryDyn> panels_category = {};
+
+ /** Region is currently visible on screen. */
+ short visible = 0;
+
+ /** Private, cached notifier events. */
+ short do_draw = 0;
+
+ /** Private, cached notifier events. */
+ short do_draw_paintcursor;
+
+ ARegionQuadviewIndex quadview_index = ARegionQuadviewIndex::None;
+
+ /** Dummy panel used in popups so they can support layout panels. */
+ Panel *popup_block_panel = nullptr;
+};
+
+} // namespace bke
+
+/* #uiList types. */
+
+/** Draw an item in the `ui_list`. */
+using uiListDrawItemFunc = void (*)(uiList *ui_list,
+ const bContext *C,
+ ui::Layout &layout,
+ PointerRNA *dataptr,
+ PointerRNA *itemptr,
+ int icon,
+ PointerRNA *active_dataptr,
+ const char *active_propname,
+ int index,
+ int flt_flag);
+
+/** Draw the filtering part of an uiList. */
+using uiListDrawFilterFunc = void (*)(uiList *ui_list, const bContext *C, ui::Layout &layout);
+
+/** Filter items of an uiList. */
+using uiListFilterItemsFunc = void (*)(uiList *ui_list,
+ const bContext *C,
+ PointerRNA *,
+ const char *propname);
+
+/** Listen to notifiers. Only for lists defined in C. */
+using uiListListener = void (*)(uiList *ui_list, wmRegionListenerParams *params);
+
+struct uiListType {
+ uiListType *next, *prev;
+
+ /** Unique name. */
+ char idname[BKE_ST_MAXNAME];
+
+ uiListDrawItemFunc draw_item;
+ uiListDrawFilterFunc draw_filter;
+ uiListFilterItemsFunc filter_items;
+
+ /** For lists defined in C only. */
+ uiListListener listener;
+
+ /** RNA integration. */
+ ExtensionRNA rna_ext;
+};
+
+/* Header types. */
+
+struct HeaderType {
+ HeaderType *next, *prev;
+ /** Unique name. */
+ char idname[BKE_ST_MAXNAME];
+ int space_type;
+ int region_type;
+
+ bool (*poll)(const bContext *C, HeaderType *ht);
+ /** Draw entirely, view changes should be handled here. */
+ void (*draw)(const bContext *C, Header *header);
+
+ /** RNA integration. */
+ ExtensionRNA rna_ext;
+};
+
+struct Header {
+ /** Runtime. */
+ HeaderType *type;
+ /** Runtime for drawing. */
+ ui::Layout *layout;
+};
+
+/* Menu types. */
+
+enum class MenuTypeFlag {
+ /**
+ * Whether the menu depends on data retrieved via #CTX_data_pointer_get. If it is context
+ * dependent, menu search has to scan it in different contexts.
+ */
+ ContextDependent = (1 << 0),
+ /**
+ * Automatically start searching in the menu when pressing a key.
+ */
+ SearchOnKeyPress = (1 << 1),
+};
+ENUM_OPERATORS(MenuTypeFlag)
+
+struct MenuType {
+ MenuType *next, *prev;
+
+ /** Unique name. */
+ char idname[BKE_ST_MAXNAME];
+ /** For button text. */
+ char label[BKE_ST_MAXNAME];
+ char translation_context[BKE_ST_MAXNAME];
+ /** Optional, see: #wmOwnerID. */
+ char owner_id[128];
+ const char *description;
+
+ /** Verify if the menu should draw or not. */
+ bool (*poll)(const bContext *C, MenuType *mt);
+ /** Draw entirely, view changes should be handled here. */
+ void (*draw)(const bContext *C, Menu *menu);
+ void (*listener)(const wmRegionListenerParams *params);
+
+ MenuTypeFlag flag;
+
+ /** RNA integration. */
+ ExtensionRNA rna_ext;
+};
+
+struct Menu {
+ /** Runtime. */
+ MenuType *type;
+ /** Runtime for drawing. */
+ ui::Layout *layout;
+};
+
+/* Asset shelf types. */
+
+/* #AssetShelfType.flag */
+enum AssetShelfTypeFlag {
+ /**
+ * Do not trigger asset dragging on drag events.
+ * Drag events can be overridden with custom keymap items then.
+ */
+ ASSET_SHELF_TYPE_FLAG_NO_ASSET_DRAG = (1 << 0),
+ ASSET_SHELF_TYPE_FLAG_DEFAULT_VISIBLE = (1 << 1),
+ ASSET_SHELF_TYPE_FLAG_STORE_CATALOGS_IN_PREFS = (1 << 2),
+ /**
+ * When spawning a context menu for an asset, activate the asset and call the activate operator
+ * (`bl_activate_operator`/#AssetShelfType.activate_operator) if present, rather than just
+ * highlighting the asset as active.
+ */
+ ASSET_SHELF_TYPE_FLAG_ACTIVATE_FOR_CONTEXT_MENU = (1 << 3),
+};
+ENUM_OPERATORS(AssetShelfTypeFlag);
+
+#define ASSET_SHELF_PREVIEW_SIZE_DEFAULT 48
+
+struct AssetShelfType {
+ /** Unique name. */
+ char idname[BKE_ST_MAXNAME];
+
+ int space_type;
+
+ /**
+ * `FILTER_ID_` bit-flags to pre-filter ID types to include in the asset shelf, as if
+ * #asset_poll() returned false for non-matching IDs. If this isn't set (== 0), no pre-filtering
+ * will be done.
+ *
+ * For bigger asset libraries, many assets can usually be excluded cheaply this way. Calling
+ * #asset_poll() on many assets isn't cheap, so doing the ID type check only in there can cause
+ * performance issues.
+ */
+ uint64_t id_types_prefilter; /* rna_enum_id_type_filter_items */
+
+ /** Operator to call when activating a grid view item. */
+ std::string activate_operator;
+ /** Operator to call when dragging a grid view item. */
+ std::string drag_operator;
+
+ AssetShelfTypeFlag flag;
+
+ short default_preview_size;
+
+ /** Determine if asset shelves of this type should be available in current context or not. */
+ bool (*poll)(const bContext *C, const AssetShelfType *shelf_type);
+
+ /**
+ * Determine if an individual asset should be visible or not.
+ * Don't use directly, use #ed::asset::shelf::type_asset_poll() (does additional
+ * pre-filtering based on the ID-type).
+ */
+ bool (*asset_poll)(const AssetShelfType *shelf_type,
+ const asset_system::AssetRepresentation *asset);
+
+ /** Asset shelves can define their own context menu via this layout definition callback. */
+ void (*draw_context_menu)(const bContext *C,
+ const AssetShelfType *shelf_type,
+ const asset_system::AssetRepresentation *asset,
+ ui::Layout &layout);
+
+ const AssetWeakReference *(*get_active_asset)(const AssetShelfType *shelf_type);
+
+ /** RNA integration. */
+ ExtensionRNA rna_ext;
+};
+
+/* Space-types. */
+
+SpaceType *BKE_spacetype_from_id(int spaceid);
+ARegionType *BKE_regiontype_from_id(const SpaceType *st, int regionid);
+Span<std::unique_ptr<SpaceType>> BKE_spacetypes_list();
+void BKE_spacetype_register(std::unique_ptr<SpaceType> st);
+bool BKE_spacetype_exists(int spaceid);
+/** Only for quitting blender. */
+void BKE_spacetypes_free();
+
+bool BKE_regiontype_uses_categories(const ARegionType *region_type);
+bool BKE_regiontype_uses_category_tabs(const ARegionType *region_type);
+
+/* Space-data. */
+
+void BKE_spacedata_freelist(ListBaseT<SpaceLink> *lb);
+/**
+ * \param lb_dst: should be empty (will be cleared).
+ */
+void BKE_spacedata_copylist(ListBaseT<SpaceLink> *lb_dst, ListBaseT<SpaceLink> *lb_src);
+
+/**
+ * Facility to set locks for drawing to survive (render) threads accessing drawing data.
+ *
+ * \note Should be replaced in future by better local data handling for threads.
+ * \note Effect of multiple calls to this function is not accumulative. The locking flags
+ * will be set to by the last call.
+ */
+void BKE_spacedata_draw_locks(ARegionDrawLockFlags lock_flags);
+
+/**
+ * Version of #BKE_area_find_region_type that also works if \a slink
+ * is not the active space of \a area.
+ */
+ARegion *BKE_spacedata_find_region_type(const SpaceLink *slink,
+ const ScrArea *area,
+ int region_type) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+
+void BKE_spacedata_callback_id_remap_set(
+ void (*func)(ScrArea *area, SpaceLink *sl, ID *old_id, ID *new_id));
+/**
+ * Currently unused!
+ */
+void BKE_spacedata_id_unref(ScrArea *area, SpaceLink *sl, ID *id);
+
+/* Area/regions. */
+
+ARegion *BKE_area_region_copy(const SpaceType *st, const ARegion *region);
+
+ARegion *BKE_area_region_new();
+
+/**
+ * Doesn't free the region itself.
+ */
+void BKE_area_region_free(SpaceType *st, ARegion *region);
+void BKE_area_region_panels_free(ListBaseT<Panel> *panels);
+/**
+ * Create and free panels.
+ */
+Panel *BKE_panel_new(PanelType *panel_type);
+void BKE_panel_free(Panel *panel);
+/**
+ * Doesn't free the area itself.
+ */
+void BKE_screen_area_free(ScrArea *area);
+/**
+ * Gizmo-maps of a region need to be freed with the region.
+ * Uses callback to avoid low-level call.
+ */
+void BKE_region_callback_free_gizmomap_set(void (*callback)(wmGizmoMap *));
+void BKE_region_callback_refresh_tag_gizmomap_set(void (*callback)(wmGizmoMap *));
+
+/**
+ * Get the layout panel state for the given idname. If it does not exist yet, initialize a new
+ * panel state with the given default value.
+ */
+LayoutPanelState *BKE_panel_layout_panel_state_ensure(Panel *panel,
+ StringRef idname,
+ bool default_closed);
+
+/**
+ * Find a region of type \a region_type in provided \a regionbase.
+ *
+ * \note this is useful for versioning where either the #Area or #SpaceLink regionbase are typical
+ * inputs
+ */
+ARegion *BKE_region_find_in_listbase_by_type(const ListBaseT<ARegion> *regionbase,
+ const int region_type);
+
+void BKE_area_copy(ScrArea *area_dst, ScrArea *area_src);
+
+/**
+ * Find a region of type \a region_type in the currently active space of \a area.
+ *
+ * \note This does _not_ work if the region to look up is not in the active space.
+ * Use #BKE_spacedata_find_region_type if that may be the case.
+ */
+ARegion *BKE_area_find_region_type(const ScrArea *area, int region_type);
+ARegion *BKE_area_find_region_active_win(const ScrArea *area);
+ARegion *BKE_area_find_region_xy(const ScrArea *area, int regiontype, const int xy[2])
+ ATTR_NONNULL(3);
+
+/**
+ * \note This is only for screen level regions (typically menus/popups).
+ */
+ARegion *BKE_screen_find_region_type(const bScreen *screen, int region_type) ATTR_NONNULL(1);
+/**
+ * \note This is only for screen level regions (typically menus/popups).
+ */
+ARegion *BKE_screen_find_region_xy(const bScreen *screen,
+ int regiontype,
+ const int xy[2]) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1, 3);
+
+ARegion *BKE_screen_find_main_region_at_xy(const bScreen *screen, int space_type, const int xy[2])
+ ATTR_NONNULL(1, 3);
+/**
+ * \note Ideally we can get the area from the context,
+ * there are a few places however where this isn't practical.
+ */
+ScrArea *BKE_screen_find_area_from_space(const bScreen *screen,
+ const SpaceLink *sl) ATTR_WARN_UNUSED_RESULT
+ ATTR_NONNULL(1, 2);
+ARegion *BKE_screen_find_region_in_space(const bScreen *screen,
+ const SpaceLink *sl,
+ int region_type) ATTR_WARN_UNUSED_RESULT
+ ATTR_NONNULL(1, 2);
+/**
+ * \note used to get proper RNA paths for spaces (editors).
+ */
+std::optional<std::string> BKE_screen_path_from_screen_to_space(const PointerRNA *ptr);
+std::optional<std::string> BKE_screen_path_from_screen_to_area(const PointerRNA *ptr);
+/**
+ * \note Using this function is generally a last resort, you really want to be
+ * using the context when you can - campbell
+ */
+ScrArea *BKE_screen_find_big_area(const bScreen *screen, int spacetype, short min);
+ScrArea *BKE_screen_area_map_find_area_xy(const ScrAreaMap *areamap,
+ int spacetype,
+ const int xy[2]) ATTR_NONNULL(1, 3);
+ScrArea *BKE_screen_find_area_xy(const bScreen *screen, int spacetype, const int xy[2])
+ ATTR_NONNULL(1, 3);
+
+void BKE_screen_gizmo_tag_refresh(bScreen *screen);
+
+/**
+ * Refresh any screen data that should be set on file-load
+ * with "Load UI" disabled.
+ */
+void BKE_screen_runtime_refresh_for_blendfile(bScreen *screen);
+
+void BKE_screen_view3d_sync(View3D *v3d, Scene *scene);
+void BKE_screen_view3d_scene_sync(bScreen *screen, Scene *scene);
+bool BKE_screen_is_fullscreen_area(const bScreen *screen) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+bool BKE_screen_is_used(const bScreen *screen) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+
+/* Zoom factor conversion. */
+
+float BKE_screen_view3d_zoom_to_fac(float camzoom);
+float BKE_screen_view3d_zoom_from_fac(float zoomfac);
+
+void BKE_screen_view3d_shading_init(View3DShading *shading);
+
+/* Screen. */
+
+/**
+ * Callback used by lib_query to walk over all ID usages
+ * (mimics `foreach_id` callback of #IDTypeInfo structure).
+ */
+void BKE_screen_foreach_id_screen_area(LibraryForeachIDData *data, ScrArea *area);
+
+/**
+ * Free (or release) any data used by this screen (does not free the screen itself).
+ */
+void BKE_screen_free_data(bScreen *screen);
+void BKE_screen_area_map_free(ScrAreaMap *area_map) ATTR_NONNULL();
+
+/**
+ * bScreen copying. Assumes that #screen_dst is cleared and can be fully overwritten.
+ */
+void BKE_screen_copy_data(bScreen *screen_dst, const bScreen *screen_src);
+
+ScrEdge *BKE_screen_find_edge(const bScreen *screen, ScrVert *v1, ScrVert *v2);
+void BKE_screen_sort_scrvert(ScrVert **v1, ScrVert **v2);
+void BKE_screen_remove_double_scrverts(bScreen *screen);
+void BKE_screen_remove_double_scredges(bScreen *screen);
+void BKE_screen_remove_unused_scredges(bScreen *screen);
+void BKE_screen_remove_unused_scrverts(bScreen *screen);
+
+void BKE_screen_header_alignment_reset(bScreen *screen);
+
+/* .blend file I/O */
+
+void BKE_screen_view3d_shading_blend_write(BlendWriter *writer, View3DShading *shading);
+void BKE_screen_view3d_shading_blend_read_data(BlendDataReader *reader, View3DShading *shading);
+
+void BKE_screen_area_map_blend_write(BlendWriter *writer, ScrAreaMap *area_map);
+/**
+ * \return false on error.
+ */
+bool BKE_screen_area_map_blend_read_data(BlendDataReader *reader, ScrAreaMap *area_map);
+/**
+ * And as patch for 2.48 and older.
+ * For the saved 2.50 files without `regiondata`.
+ */
+void BKE_screen_view3d_do_versions_250(View3D *v3d, ListBaseT<ARegion> *regions);
+
+/**
+ * Called after lib linking process is done, to perform some validation on the read data, or some
+ * complex specific reading process that requires the data to be fully read and ID pointers to be
+ * valid.
+ */
+void BKE_screen_area_blend_read_after_liblink(BlendLibReader *reader,
+ ID *parent_id,
+ ScrArea *area);
+/**
+ * Cannot use #IDTypeInfo callback yet, because of the return value.
+ */
+bool BKE_screen_blend_read_data(BlendDataReader *reader, bScreen *screen);
+
+} // namespace blender
diff --git a/compat/include/BKE_tracking.hh b/compat/include/BKE_tracking.hh
new file mode 100644
index 0000000..659b726
--- /dev/null
+++ b/compat/include/BKE_tracking.hh
@@ -0,0 +1,33 @@
+/* BUI seam: clip-tracking sample used by scope drawing only.
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#include "IMB_imbuf_types.hh"
+#include "DNA_tracking_types.h"
+
+#ifdef __cplusplus
+namespace blender {
+ImBuf *BKE_tracking_sample_pattern(int frame_width,
+ int frame_height,
+ const ImBuf *search_ib,
+ const struct MovieTrackingTrack *track,
+ const struct MovieTrackingMarker *marker,
+ bool from_anchor,
+ bool use_mask,
+ int num_samples_x,
+ int num_samples_y,
+ float pos[2]);
+} // namespace blender
+#else
+struct ImBuf;
+ImBuf *BKE_tracking_sample_pattern(int frame_width,
+ int frame_height,
+ const struct ImBuf *search_ib,
+ const struct MovieTrackingTrack *track,
+ const struct MovieTrackingMarker *marker,
+ bool from_anchor,
+ bool use_mask,
+ int num_samples_x,
+ int num_samples_y,
+ float pos[2]);
+#endif
diff --git a/compat/include/BKE_wm_runtime.hh b/compat/include/BKE_wm_runtime.hh
new file mode 100644
index 0000000..7d99da7
--- /dev/null
+++ b/compat/include/BKE_wm_runtime.hh
@@ -0,0 +1,198 @@
+/* SPDX-FileCopyrightText: 2024 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup bke
+ */
+
+#pragma once
+
+#include "BKE_report.hh"
+
+#include "DNA_windowmanager_types.h"
+
+#include "BLI_set.hh"
+
+namespace blender {
+
+struct UndoStack;
+struct wmMsgBus;
+struct wmKeyConfig;
+struct wmEvent;
+struct wmWindow;
+struct wmIMEData;
+struct wmGesture;
+struct wmJob;
+struct wmDrag;
+struct wmPaintCursor;
+struct WindowDrawCB;
+
+namespace bke {
+
+struct wmNotifierHashForQueue {
+ uint64_t operator()(const wmNotifier *note) const;
+};
+struct wmNotifierEqForQueue {
+ bool operator()(const wmNotifier *a, const wmNotifier *b) const;
+};
+using wmNotifierQueueSet = Set<const wmNotifier *,
+ 4,
+ DefaultProbingStrategy,
+ wmNotifierHashForQueue,
+ wmNotifierEqForQueue>;
+
+struct WindowManagerRuntime {
+ /** Separate active from drawable. */
+ wmWindow *windrawable = nullptr;
+ /**
+ * \note `CTX_wm_window(C)` is usually preferred.
+ * Avoid relying on this where possible as this may become NULL during when handling
+ * events that close or replace windows (e.g. opening a file).
+ * While this happens rarely in practice, it can cause difficult to reproduce bugs.
+ */
+ wmWindow *winactive = nullptr;
+
+ /** Indicates whether interface is locked for user interaction. */
+ bool is_interface_locked = false;
+
+ /** Indicates whether modified images should be saved when saving the blend file. */
+ char save_modified_images_when_file_is_saved = true;
+
+ /**
+ * Indicates the main loop (#WM_main()) to stop processing the event queue and move to the next
+ * step. The Remaining events will then be processed during the next iteration of the loop.
+ *
+ * This is used e.g. to avoid handling events immediately after an undo/redo action, when UI has
+ * not yet been updated.
+ */
+ bool break_events_handling = false;
+
+ /** Information and error reports. */
+ ReportList reports;
+
+ /**
+ * Refresh/redraw #wmNotifier structs.
+ * \note Once in the queue, notifiers should be considered read-only.
+ * With the exception of clearing notifiers for data which has been removed,
+ * see: #NOTE_CATEGORY_TAG_CLEARED.
+ */
+ ListBaseT<wmNotifier> notifier_queue = {nullptr, nullptr};
+ /**
+ * For duplicate detection.
+ * \note keep in sync with `notifier_queue` adding/removing elements must also update this set.
+ */
+ wmNotifierQueueSet notifier_queue_set;
+
+ /** The current notifier in the `notifier_queue` being handled (clear instead of freeing). */
+ const wmNotifier *notifier_current = nullptr;
+
+ /** Operator registry. */
+ ListBaseT<wmOperator> operators = {nullptr, nullptr};
+
+ /** Extra overlay cursors to draw, like circles. */
+ ListBaseT<wmPaintCursor> paintcursors = {nullptr, nullptr};
+
+ /**
+ * Known key configurations.
+ * This includes all the #wmKeyConfig members (`defaultconf`, `addonconf`, etc).
+ */
+ ListBaseT<wmKeyConfig> keyconfigs = {nullptr, nullptr};
+
+ /** Active timers. */
+ ListBaseT<wmTimer> timers = {nullptr, nullptr};
+
+ /** Threaded jobs manager. */
+ ListBaseT<wmJob> jobs = {nullptr, nullptr};
+
+ /** Active dragged items. */
+ ListBaseT<wmDrag> drags = {nullptr, nullptr};
+
+ /** Default configuration. */
+ wmKeyConfig *defaultconf = nullptr;
+
+ /** Addon configuration. */
+ wmKeyConfig *addonconf = nullptr;
+
+ /** User configuration. */
+ wmKeyConfig *userconf = nullptr;
+
+ /** All undo history. */
+ UndoStack *undo_stack = nullptr;
+
+ wmMsgBus *message_bus = nullptr;
+
+ WindowManagerRuntime();
+ ~WindowManagerRuntime();
+};
+
+struct WindowRuntime {
+ /** All events #wmEvent (ghost level events were handled). */
+ ListBaseT<wmEvent> event_queue = {nullptr, nullptr};
+
+ /**
+ * Input Method Editor data - complex character input (especially for Asian character input)
+ * Only used when `WITH_INPUT_IME` is defined.
+ */
+ wmIMEData *ime_data = nullptr;
+ bool ime_data_is_composing = false;
+
+ /** Don't want to include ghost.h stuff. */
+ void *ghostwin = nullptr;
+
+ /** Don't want to include gpu stuff. */
+ void *gpuctx = nullptr;
+
+ /** Window+screen handlers, handled last. */
+ ListBaseT<wmEventHandler> handlers = {nullptr, nullptr};
+
+ /** Priority handlers, handled first. */
+ ListBaseT<wmEventHandler> modalhandlers = {nullptr, nullptr};
+
+ /** Custom drawing callbacks. */
+ ListBaseT<WindowDrawCB> drawcalls = {nullptr, nullptr};
+
+ /** Gesture stuff. */
+ ListBaseT<wmGesture> gesture = {nullptr, nullptr};
+
+ /**
+ * Keep the last handled event in `event_queue` here (owned and must be freed).
+ *
+ * \warning This must only to be used for event queue logic.
+ * User interactions should use `eventstate` instead (if the event isn't passed to the function).
+ */
+ wmEvent *event_last_handled = nullptr;
+
+ /**
+ * Storage for event system.
+ *
+ * For the most part this is storage for `wmEvent.xy` & `wmEvent.modifiers`.
+ * newly added key/button events copy the cursor location and modifier state stored here.
+ *
+ * It's also convenient at times to be able to pass this as if it's a regular event.
+ *
+ * - This is not simply the current event being handled.
+ * The type and value is always set to the last press/release events
+ * otherwise cursor motion would always clear these values.
+ *
+ * - The value of `eventstate->modifiers` is set from the last pressed/released modifier key.
+ * This has the down side that the modifier value will be incorrect if users hold both
+ * left/right modifiers then release one. See note in #wm_event_add_ghostevent for details.
+ */
+ wmEvent *eventstate = nullptr;
+
+ /**
+ * The time when the key is pressed in milliseconds (see #GHOST_IEvent::getTime).
+ * Used to detect double-click events.
+ */
+ uint64_t eventstate_prev_press_time_ms = 0;
+
+ /** Private runtime info to show text in the status bar. */
+ void *cursor_keymap_status = nullptr;
+
+ WindowRuntime() = default;
+ ~WindowRuntime();
+};
+
+} // namespace bke
+} // namespace blender
diff --git a/compat/include/BLF_enums.hh b/compat/include/BLF_enums.hh
new file mode 100644
index 0000000..a209e63
--- /dev/null
+++ b/compat/include/BLF_enums.hh
@@ -0,0 +1,70 @@
+/* SPDX-FileCopyrightText: 2025 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup blf
+ */
+
+#pragma once
+
+#include "BLI_enum_flags.hh"
+
+namespace blender {
+
+enum class FontShadowType {
+ None = 0,
+ Blur3x3 = 3,
+ Blur5x5 = 5,
+ Outline = 6,
+};
+
+enum class BLFWrapMode : int {
+ /** Only on ASCII space and line feed. Legacy and invariant. */
+ Minimal = 0,
+ /** Multilingual, informed by Unicode Standard Annex #14. */
+ Typographical = 1 << 0,
+ /** Wrap on file path separators, space, underscores. */
+ Path = 1 << 1,
+ /** Line break at limit. */
+ HardLimit = 1 << 2,
+};
+ENUM_OPERATORS(BLFWrapMode);
+
+enum FontFlags {
+ BLF_NONE = 0,
+ BLF_ROTATION = 1 << 0,
+ BLF_CLIPPING = 1 << 1,
+ BLF_SHADOW = 1 << 2,
+ // BLF_FLAG_UNUSED_3 = 1 << 3, /* dirty */
+ // BLF_MATRIX = 1 << 4,
+ BLF_ASPECT = 1 << 5,
+ BLF_WORD_WRAP = 1 << 6,
+ /** No anti-aliasing. */
+ BLF_MONOCHROME = 1 << 7,
+ BLF_HINTING_NONE = 1 << 8,
+ BLF_HINTING_SLIGHT = 1 << 9,
+ BLF_HINTING_FULL = 1 << 10,
+ BLF_BOLD = 1 << 11,
+ BLF_ITALIC = 1 << 12,
+ /** Intended USE is monospaced, regardless of font type. */
+ BLF_MONOSPACED = 1 << 13,
+ /** A font within the default stack of fonts. */
+ BLF_DEFAULT = 1 << 14,
+ /** Must only be used as last font in the stack. */
+ BLF_LAST_RESORT = 1 << 15,
+ /** Failure to load this font. Don't try again. */
+ BLF_BAD_FONT = 1 << 16,
+ /**
+ * At small sizes glyphs are rendered at multiple sub-pixel positions.
+ *
+ * \note Can be checked without checking #BLF_MONOSPACED which can be assumed to be disabled.
+ */
+ BLF_RENDER_SUBPIXELAA = 1 << 18,
+
+ /** Do not look in other fonts when a glyph is not found in this font. */
+ BLF_NO_FALLBACK = 1 << 19,
+};
+ENUM_OPERATORS(FontFlags);
+
+} // namespace blender
diff --git a/compat/include/BLO_userdef_default.h b/compat/include/BLO_userdef_default.h
new file mode 100644
index 0000000..a490fb8
--- /dev/null
+++ b/compat/include/BLO_userdef_default.h
@@ -0,0 +1,22 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+#include "DNA_userdef_types.h"
+
+namespace blender {
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Default theme, see: `release/datafiles/userdef/userdef_default_theme.c`. */
+extern const bTheme U_theme_default;
+
+#ifdef __cplusplus
+}
+#endif
+
+} // namespace blender
diff --git a/compat/include/BLT_translation.hh b/compat/include/BLT_translation.hh
new file mode 100644
index 0000000..be0e334
--- /dev/null
+++ b/compat/include/BLT_translation.hh
@@ -0,0 +1,246 @@
+/* SPDX-FileCopyrightText: 2011 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup blt
+ */
+
+#pragma once
+
+#include "BLI_string_ref.hh"
+
+#define TEXT_DOMAIN_NAME "blender"
+
+namespace blender {
+
+bool BLT_is_default_context(StringRef msgctxt);
+const char *BLT_pgettext(const char *msgctxt, const char *msgid);
+StringRef BLT_pgettext(StringRef msgctxt, StringRef msgid);
+
+/* Translation */
+/* - iface includes buttons in the user interface: short labels displayed in windows, panels,
+ * menus.
+ * - tooltips only include the popup tooltips when hovering a button.
+ * - report is for longer, additional information displayed in the UI, such as error messages.
+ * - new_dataname is the actual user-created data such as objects, meshes, etc. */
+bool BLT_translate();
+bool BLT_translate_iface();
+bool BLT_translate_tooltips();
+bool BLT_translate_reports();
+bool BLT_translate_new_dataname();
+const char *BLT_translate_do(const char *msgctxt, const char *msgid);
+StringRef BLT_translate_do(StringRef msgctxt, StringRef msgid);
+const char *BLT_translate_do_iface(const char *msgctxt, const char *msgid);
+StringRef BLT_translate_do_iface(StringRef msgctxt, StringRef msgid);
+const char *BLT_translate_do_tooltip(const char *msgctxt, const char *msgid);
+StringRef BLT_translate_do_tooltip(StringRef msgctxt, StringRef msgid);
+const char *BLT_translate_do_report(const char *msgctxt, const char *msgid);
+StringRef BLT_translate_do_report(StringRef msgctxt, StringRef msgid);
+const char *BLT_translate_do_new_dataname(const char *msgctxt, const char *msgid);
+StringRef BLT_translate_do_new_dataname(StringRef msgctxt, StringRef msgid);
+
+/* The "translation-marker" macro. */
+#define N_(msgid) msgid
+#define CTX_N_(context, msgid) msgid
+
+/* These macros should be used everywhere in UI code. */
+/*# define _(msgid) BLT_gettext(msgid) */
+#define IFACE_(msgid) BLT_translate_do_iface(NULL, msgid)
+#define TIP_(msgid) BLT_translate_do_tooltip(NULL, msgid)
+#define RPT_(msgid) BLT_translate_do_report(NULL, msgid)
+#define DATA_(msgid) BLT_translate_do_new_dataname(NULL, msgid)
+#define CTX_IFACE_(context, msgid) BLT_translate_do_iface(context, msgid)
+#define CTX_TIP_(context, msgid) BLT_translate_do_tooltip(context, msgid)
+#define CTX_RPT_(context, msgid) BLT_translate_do_report(context, msgid)
+#define CTX_DATA_(context, msgid) BLT_translate_do_new_dataname(context, msgid)
+
+/* Helper macro, when we want to define a same msgid for multiple msgctxt...
+ * Does nothing in C, but is "parsed" by our i18n py tools.
+ * XXX Currently limited to at most 16 contexts at once
+ * (but you can call it several times with the same msgid, should you need more contexts!).
+ */
+#define BLT_I18N_MSGID_MULTI_CTXT(msgid, ...)
+
+/******************************************************************************
+ * All i18n contexts must be defined here.
+ * This is a nice way to be sure not to use a context twice for different
+ * things, and limit the number of existing contexts!
+ * WARNING! Contexts should not be longer than BKE_ST_MAXNAME - 1!
+ */
+
+/* Default, void context.
+ * WARNING! The "" context is not the same as no (NULL) context at mo/boost::locale level!
+ * NOTE: We translate BLT_I18NCONTEXT_DEFAULT as BLT_I18NCONTEXT_DEFAULT_BPY in Python,
+ * as we can't use "natural" None value in rna string properties... :/
+ * The void string "" is also interpreted as BLT_I18NCONTEXT_DEFAULT.
+ * For performance reason, we only use the first char to detect this context,
+ * so other contexts should never start with the same char!
+ */
+#define BLT_I18NCONTEXT_DEFAULT NULL
+#define BLT_I18NCONTEXT_DEFAULT_BPYRNA "*"
+
+/* Default context for operator names/labels. */
+#define BLT_I18NCONTEXT_OPERATOR_DEFAULT "Operator"
+
+/* Context for events/keymaps (necessary, since those often use one or two letters,
+ * easy to get collisions with other areas...). */
+#define BLT_I18NCONTEXT_UI_EVENTS "UI_Events_KeyMaps"
+
+/* Mark the msgid applies to several elements
+ * (needed in some cases, as English adjectives have no plural mark :( ). */
+#define BLT_I18NCONTEXT_PLURAL "Plural"
+
+/* Some words can be either countable or uncountable in English, but translate to different words
+ * in other languages. An example is "Amount", which can refer to "a number of things", countable,
+ * or "a quantity or volume", uncountable. */
+#define BLT_I18NCONTEXT_COUNTABLE "Countable"
+
+/* Special cases when translation cannot be avoided, for example in an interface where some props
+ * are built-in (translatable) and others are user-defined (non-translatable), but we don't know
+ * which ones in advance.
+ * It allows specifying explicitly that translation should not occur for user data when building
+ * the UI. */
+#define BLT_I18NCONTEXT_NO_TRANSLATION "Do not translate"
+
+/* ID-types contexts. */
+/* WARNING! Keep it in sync with ID-types in `blenkernel/intern/idtype.cc`. */
+#define BLT_I18NCONTEXT_ID_ACTION "Action"
+#define BLT_I18NCONTEXT_ID_ANIMATION "Animation"
+#define BLT_I18NCONTEXT_ID_ARMATURE "Armature"
+#define BLT_I18NCONTEXT_ID_BRUSH "Brush"
+#define BLT_I18NCONTEXT_ID_CACHEFILE "CacheFile"
+#define BLT_I18NCONTEXT_ID_CAMERA "Camera"
+#define BLT_I18NCONTEXT_ID_COLLECTION "Collection"
+#define BLT_I18NCONTEXT_ID_CURVES "Curves"
+#define BLT_I18NCONTEXT_ID_CURVE_LEGACY "Curve"
+#define BLT_I18NCONTEXT_ID_FREESTYLELINESTYLE "FreestyleLineStyle"
+#define BLT_I18NCONTEXT_ID_GPENCIL "GPencil"
+#define BLT_I18NCONTEXT_ID_ID "ID"
+#define BLT_I18NCONTEXT_ID_IMAGE "Image"
+// #define BLT_I18NCONTEXT_ID_IPO "Ipo" /* DEPRECATED */
+#define BLT_I18NCONTEXT_ID_LATTICE "Lattice"
+#define BLT_I18NCONTEXT_ID_LIBRARY "Library"
+#define BLT_I18NCONTEXT_ID_LIGHT "Light"
+#define BLT_I18NCONTEXT_ID_LIGHTPROBE "LightProbe"
+#define BLT_I18NCONTEXT_ID_MASK "Mask"
+#define BLT_I18NCONTEXT_ID_MATERIAL "Material"
+#define BLT_I18NCONTEXT_ID_MESH "Mesh"
+#define BLT_I18NCONTEXT_ID_METABALL "Metaball"
+#define BLT_I18NCONTEXT_ID_MOVIECLIP "MovieClip"
+#define BLT_I18NCONTEXT_ID_NODETREE "NodeTree"
+#define BLT_I18NCONTEXT_ID_OBJECT "Object"
+#define BLT_I18NCONTEXT_ID_PAINTCURVE "PaintCurve"
+#define BLT_I18NCONTEXT_ID_PALETTE "Palette"
+#define BLT_I18NCONTEXT_ID_PARTICLESETTINGS "ParticleSettings"
+#define BLT_I18NCONTEXT_ID_POINTCLOUD "PointCloud"
+#define BLT_I18NCONTEXT_ID_SCENE "Scene"
+#define BLT_I18NCONTEXT_ID_SCREEN "Screen"
+#define BLT_I18NCONTEXT_ID_SEQUENCE "Sequence"
+#define BLT_I18NCONTEXT_ID_SHAPEKEY "Key"
+#define BLT_I18NCONTEXT_ID_SIMULATION "Simulation"
+#define BLT_I18NCONTEXT_ID_SOUND "Sound"
+#define BLT_I18NCONTEXT_ID_SPEAKER "Speaker"
+#define BLT_I18NCONTEXT_ID_TEXT "Text"
+#define BLT_I18NCONTEXT_ID_TEXTURE "Texture"
+#define BLT_I18NCONTEXT_ID_VFONT "VFont"
+#define BLT_I18NCONTEXT_ID_VOLUME "Volume"
+#define BLT_I18NCONTEXT_ID_WINDOWMANAGER "WindowManager"
+#define BLT_I18NCONTEXT_ID_WORKSPACE "WorkSpace"
+#define BLT_I18NCONTEXT_ID_WORLD "World"
+
+/* Editors-types contexts. */
+#define BLT_I18NCONTEXT_EDITOR_FILEBROWSER "File browser"
+#define BLT_I18NCONTEXT_EDITOR_PREFERENCES "Preferences"
+#define BLT_I18NCONTEXT_EDITOR_PYTHON_CONSOLE "Python console"
+#define BLT_I18NCONTEXT_EDITOR_VIEW3D "View3D"
+
+/* Generic contexts. */
+#define BLT_I18NCONTEXT_AMOUNT "Amount"
+#define BLT_I18NCONTEXT_COLOR "Color"
+#define BLT_I18NCONTEXT_CONSTRAINT "Constraint"
+#define BLT_I18NCONTEXT_MODIFIER "Modifier"
+#define BLT_I18NCONTEXT_NAVIGATION "Navigation"
+#define BLT_I18NCONTEXT_RENDER_LAYER "Render Layer"
+#define BLT_I18NCONTEXT_TIME "Time"
+#define BLT_I18NCONTEXT_UNIT "Unit"
+
+/* Helper for bpy.app.i18n object... */
+struct BLT_i18n_contexts_descriptor {
+ const char *c_id;
+ const char *py_id;
+ const char *value;
+};
+
+#define BLT_I18NCONTEXTS_ITEM(ctxt_id, py_id) {#ctxt_id, py_id, ctxt_id}
+
+#define BLT_I18NCONTEXTS_DESC \
+ { \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_DEFAULT, "default_real"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_DEFAULT_BPYRNA, "default"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "operator_default"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_UI_EVENTS, "ui_events_keymaps"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_PLURAL, "plural"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_COUNTABLE, "countable"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_ACTION, "id_action"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_ARMATURE, "id_armature"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_NO_TRANSLATION, "no_translation"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_BRUSH, "id_brush"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_CACHEFILE, "id_cachefile"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_CAMERA, "id_camera"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_COLLECTION, "id_collection"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_CURVES, "id_curves"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_CURVE_LEGACY, "id_curve"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_FREESTYLELINESTYLE, "id_fs_linestyle"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_GPENCIL, "id_gpencil"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_ID, "id_id"), \
+ BLT_I18NCONTEXTS_ITEM( \
+ BLT_I18NCONTEXT_ID_IMAGE, \
+ "id_image"), /* BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_IPO, "id_ipo"), */ \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_LATTICE, "id_lattice"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_LIBRARY, "id_library"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_LIGHT, "id_light"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_LIGHTPROBE, "id_lightprobe"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_MASK, "id_mask"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_MATERIAL, "id_material"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_MESH, "id_mesh"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_METABALL, "id_metaball"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_MOVIECLIP, "id_movieclip"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_NODETREE, "id_nodetree"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_OBJECT, "id_object"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_PAINTCURVE, "id_paintcurve"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_PALETTE, "id_palette"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_PARTICLESETTINGS, "id_particlesettings"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_POINTCLOUD, "id_pointcloud"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_SCENE, "id_scene"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_SCREEN, "id_screen"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_SEQUENCE, "id_sequence"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_SHAPEKEY, "id_shapekey"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_SIMULATION, "id_simulation"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_SOUND, "id_sound"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_SPEAKER, "id_speaker"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_TEXT, "id_text"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_TEXTURE, "id_texture"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_VFONT, "id_vfont"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_VOLUME, "id_volume"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_WINDOWMANAGER, "id_windowmanager"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_WORKSPACE, "id_workspace"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_ID_WORLD, "id_world"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_EDITOR_FILEBROWSER, "editor_filebrowser"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_EDITOR_PYTHON_CONSOLE, "editor_python_console"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_EDITOR_PREFERENCES, "editor_preferences"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_EDITOR_VIEW3D, "editor_view3d"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_AMOUNT, "amount"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_COLOR, "color"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_CONSTRAINT, "constraint"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_MODIFIER, "modifier"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_NAVIGATION, "navigation"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_RENDER_LAYER, "render_layer"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_TIME, "time"), \
+ BLT_I18NCONTEXTS_ITEM(BLT_I18NCONTEXT_UNIT, "unit"), \
+ { \
+ NULL, NULL, NULL \
+ } \
+ }
+
+} // namespace blender
diff --git a/compat/include/CLG_log.h b/compat/include/CLG_log.h
new file mode 100644
index 0000000..181984c
--- /dev/null
+++ b/compat/include/CLG_log.h
@@ -0,0 +1,206 @@
+/* SPDX-FileCopyrightText: 2018-2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup intern_clog
+ *
+ * C Logging Library (clog)
+ * ========================
+ *
+ * Usage
+ * -----
+ *
+ * - `CLG_LOGREF_DECLARE_GLOBAL` macro to declare #CLG_LogRef pointers.
+ * - `CLOG_` prefixed macros for logging.
+ *
+ * Identifiers
+ * -----------
+ *
+ * #CLG_LogRef holds an identifier which defines the category of the logger.
+ *
+ * You can define and use identifiers as needed, logging will lazily initialize them.
+ *
+ * By convention lower case dot separated identifiers are used, eg:
+ * `module.sub_module`, this allows filtering by `module.*`,
+ * see #CLG_type_filter_include, #CLG_type_filter_exclude
+ *
+ * There is currently no functionality to remove a category once it's created.
+ */
+
+#pragma once
+
+#ifdef __GNUC__
+# define _CLOG_ATTR_NONNULL(args...) __attribute__((nonnull(args)))
+#else
+# define _CLOG_ATTR_NONNULL(...)
+#endif
+
+#ifdef __GNUC__
+# define _CLOG_ATTR_PRINTF_FORMAT(format_param, dots_param) \
+ __attribute__((format(printf, format_param, dots_param)))
+#else
+# define _CLOG_ATTR_PRINTF_FORMAT(format_param, dots_param)
+#endif
+
+#define STRINGIFY_ARG(x) "" #x
+#define STRINGIFY_APPEND(a, b) "" a #b
+#define STRINGIFY(x) STRINGIFY_APPEND("", x)
+
+struct CLogContext;
+
+enum CLG_Level {
+ /* Similar to assert. This logs the message, then a stack trace and abort. */
+ CLG_LEVEL_FATAL = 0,
+ /* An error we can recover from, should not happen. */
+ CLG_LEVEL_ERROR = 1,
+ /* General warnings (which aren't necessary to show to users). */
+ CLG_LEVEL_WARN = 2,
+ /* Information about devices, files, configuration, user operations. */
+ CLG_LEVEL_INFO = 3,
+ /* Debugging information for developers. */
+ CLG_LEVEL_DEBUG = 4,
+ /* Very verbose code execution tracing. */
+ CLG_LEVEL_TRACE = 5,
+};
+#define CLG_LEVEL_LEN (CLG_LEVEL_TRACE + 1)
+
+/* Each logger ID has one of these. */
+struct CLG_LogType {
+ struct CLG_LogType *next;
+ char identifier[64];
+ /** FILE output. */
+ struct CLogContext *ctx;
+ /** Control behavior. */
+ CLG_Level level;
+};
+
+struct CLG_LogRef {
+ CLG_LogRef(const char *identifier);
+
+ const char *identifier;
+ CLG_LogType *type;
+ struct CLG_LogRef *next;
+};
+
+void CLG_log_str(const CLG_LogType *lg,
+ enum CLG_Level level,
+ const char *file_line,
+ const char *fn,
+ const char *message) _CLOG_ATTR_NONNULL(1, 3, 4, 5);
+void CLG_logf(const CLG_LogType *lg,
+ enum CLG_Level level,
+ const char *file_line,
+ const char *fn,
+ const char *format,
+ ...) _CLOG_ATTR_NONNULL(1, 3, 4, 5) _CLOG_ATTR_PRINTF_FORMAT(5, 6);
+void CLG_log_raw(const CLG_LogType *lg, const char *message);
+
+/* Main initializer and destructor (per session, not logger). */
+void CLG_init();
+void CLG_exit();
+
+void CLG_output_set(void *file_handle);
+void CLG_output_use_source_set(int value);
+void CLG_output_use_basename_set(int value);
+void CLG_output_use_timestamp_set(int value);
+void CLG_output_use_memory_set(int value);
+void CLG_error_fn_set(void (*error_fn)(void *file_handle));
+void CLG_fatal_fn_set(void (*fatal_fn)(void *file_handle));
+void CLG_backtrace_fn_set(void (*fatal_fn)(void *file_handle));
+
+void CLG_type_filter_include(const char *type_match, int type_match_len);
+void CLG_type_filter_exclude(const char *type_match, int type_match_len);
+
+void CLG_level_set(CLG_Level level);
+
+void CLG_logref_init(CLG_LogRef *clg_ref);
+
+void CLG_logref_register(CLG_LogRef *clg_ref);
+void CLG_logref_list_all(void (*callback)(const char *identifier, void *user_data),
+ void *user_data);
+
+int CLG_color_support_get(CLG_LogRef *clg_ref);
+
+/* When true, quiet any NOCHECK logs that would otherwise be printed regardless of log filters
+ * and levels. This is used so command line tools can control output without unnecessary noise.
+ *
+ * Note this does not silence log filters and levels that have been explicitly enabled. */
+void CLG_quiet_set(bool quiet);
+bool CLG_quiet_get();
+
+inline CLG_LogRef::CLG_LogRef(const char *identifier)
+ : identifier(identifier), type(nullptr), next(nullptr)
+{
+ CLG_logref_register(this);
+}
+
+/** Declare outside function, declare as extern in header. */
+#define CLG_LOGREF_DECLARE_GLOBAL(var, id) \
+ static CLG_LogRef _static_##var = {id}; \
+ CLG_LogRef *var = &_static_##var
+
+/** Initialize struct once. */
+#define CLOG_ENSURE(clg_ref) \
+ ((clg_ref)->type ? (clg_ref)->type : (CLG_logref_init(clg_ref), (clg_ref)->type))
+
+#define CLOG_CHECK(clg_ref, verbose_level, ...) \
+ ((void)CLOG_ENSURE(clg_ref), ((clg_ref)->type->level >= verbose_level))
+
+#define CLOG_AT_LEVEL(clg_ref, verbose_level, ...) \
+ { \
+ const CLG_LogType *_lg_ty = CLOG_ENSURE(clg_ref); \
+ if (_lg_ty->level >= verbose_level) { \
+ CLG_logf(_lg_ty, verbose_level, __FILE__ ":" STRINGIFY(__LINE__), __func__, __VA_ARGS__); \
+ } \
+ } \
+ ((void)0)
+
+#define CLOG_AT_LEVEL_NOCHECK(clg_ref, verbose_level, ...) \
+ { \
+ const CLG_LogType *_lg_ty = CLOG_ENSURE(clg_ref); \
+ if (!CLG_quiet_get() || _lg_ty->level >= verbose_level) { \
+ CLG_logf(_lg_ty, verbose_level, __FILE__ ":" STRINGIFY(__LINE__), __func__, __VA_ARGS__); \
+ } \
+ } \
+ ((void)0)
+
+#define CLOG_STR_AT_LEVEL(clg_ref, verbose_level, str) \
+ { \
+ const CLG_LogType *_lg_ty = CLOG_ENSURE(clg_ref); \
+ if (_lg_ty->level >= verbose_level) { \
+ CLG_log_str(_lg_ty, verbose_level, __FILE__ ":" STRINGIFY(__LINE__), __func__, str); \
+ } \
+ } \
+ ((void)0)
+
+#define CLOG_STR_AT_LEVEL_NOCHECK(clg_ref, verbose_level, str) \
+ { \
+ const CLG_LogType *_lg_ty = CLOG_ENSURE(clg_ref); \
+ if (!CLG_quiet_get() || _lg_ty->level >= verbose_level) { \
+ CLG_log_str(_lg_ty, verbose_level, __FILE__ ":" STRINGIFY(__LINE__), __func__, str); \
+ } \
+ } \
+ ((void)0)
+
+/* Log with format string. */
+#define CLOG_FATAL(clg_ref, ...) CLOG_AT_LEVEL(clg_ref, CLG_LEVEL_FATAL, __VA_ARGS__)
+#define CLOG_ERROR(clg_ref, ...) CLOG_AT_LEVEL(clg_ref, CLG_LEVEL_ERROR, __VA_ARGS__)
+#define CLOG_WARN(clg_ref, ...) CLOG_AT_LEVEL(clg_ref, CLG_LEVEL_WARN, __VA_ARGS__)
+#define CLOG_INFO(clg_ref, ...) CLOG_AT_LEVEL(clg_ref, CLG_LEVEL_INFO, __VA_ARGS__)
+#define CLOG_DEBUG(clg_ref, ...) CLOG_AT_LEVEL(clg_ref, CLG_LEVEL_DEBUG, __VA_ARGS__)
+#define CLOG_TRACE(clg_ref, ...) CLOG_AT_LEVEL(clg_ref, CLG_LEVEL_TRACE, __VA_ARGS__)
+
+/* Log single string. */
+#define CLOG_STR_FATAL(clg_ref, str) CLOG_STR_AT_LEVEL(clg_ref, CLG_LEVEL_FATAL, str)
+#define CLOG_STR_ERROR(clg_ref, str) CLOG_STR_AT_LEVEL(clg_ref, CLG_LEVEL_ERROR, str)
+#define CLOG_STR_WARN(clg_ref, str) CLOG_STR_AT_LEVEL(clg_ref, CLG_LEVEL_WARN, str)
+#define CLOG_STR_INFO(clg_ref, str) CLOG_STR_AT_LEVEL(clg_ref, CLG_LEVEL_INFO, str)
+#define CLOG_STR_DEBUG(clg_ref, str) CLOG_STR_AT_LEVEL(clg_ref, CLG_LEVEL_DEBUG, str)
+#define CLOG_STR_TRACE(clg_ref, str) CLOG_STR_AT_LEVEL(clg_ref, CLG_LEVEL_TRACE, str)
+
+/* Log regardless of filters and levels, for a few important messages like blend save and load.
+ * Only #CLG_quiet_set will silence these. */
+#define CLOG_INFO_NOCHECK(clg_ref, format, ...) \
+ CLOG_AT_LEVEL_NOCHECK(clg_ref, CLG_LEVEL_INFO, format, __VA_ARGS__)
+#define CLOG_STR_INFO_NOCHECK(clg_ref, str) CLOG_STR_AT_LEVEL_NOCHECK(clg_ref, CLG_LEVEL_INFO, str)
diff --git a/compat/include/ED_asset.hh b/compat/include/ED_asset.hh
new file mode 100644
index 0000000..801f271
--- /dev/null
+++ b/compat/include/ED_asset.hh
@@ -0,0 +1,3 @@
+/* BUI seam: minimal stand-in. SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
diff --git a/compat/include/ED_buttons.hh b/compat/include/ED_buttons.hh
new file mode 100644
index 0000000..57b80ec
--- /dev/null
+++ b/compat/include/ED_buttons.hh
@@ -0,0 +1,49 @@
+/* SPDX-FileCopyrightText: 2013 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup editors
+ */
+
+#pragma once
+
+#include "BLI_vector.hh"
+
+#include "DNA_space_types.h"
+
+namespace blender {
+
+struct ScrArea;
+struct SpaceProperties;
+struct bContext;
+struct PointerRNA;
+
+namespace ui {
+struct Layout;
+} // namespace ui
+
+/**
+ * Fills an array with the tab context values for the properties editor. -1 signals a separator.
+ *
+ * \return The total number of items in the array returned.
+ */
+Vector<eSpaceButtons_Context> ED_buttons_tabs_list(const SpaceProperties *sbuts,
+ bool apply_filter = true);
+void ED_buttons_visible_tabs_menu(bContext *C, ui::Layout *layout, void * /*arg*/);
+void ED_buttons_navbar_menu(bContext *C, ui::Layout *layout, void * /*arg*/);
+bool ED_buttons_tab_has_search_result(SpaceProperties *sbuts, int index);
+
+void ED_buttons_search_string_set(SpaceProperties *sbuts, const char *value);
+int ED_buttons_search_string_length(SpaceProperties *sbuts);
+const char *ED_buttons_search_string_get(SpaceProperties *sbuts);
+
+bool ED_buttons_should_sync_with_outliner(const bContext *C,
+ const SpaceProperties *sbuts,
+ ScrArea *area);
+void ED_buttons_set_context(const bContext *C,
+ SpaceProperties *sbuts,
+ PointerRNA *ptr,
+ int context);
+
+} // namespace blender
diff --git a/compat/include/ED_node.hh b/compat/include/ED_node.hh
new file mode 100644
index 0000000..6477a5f
--- /dev/null
+++ b/compat/include/ED_node.hh
@@ -0,0 +1,20 @@
+/* BUI seam: node-socket drawing entry points used by the widget cache.
+ * A host (or the node editor add-on) can provide real implementations; the
+ * stubs draw nothing with the null renderer.
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#include "DNA_node_types.h"
+#include "DNA_vec_types.h"
+
+namespace blender::ed::space_node {
+
+void node_socket_draw(bNodeSocket *sock, const rcti *rect, const float color[4], float scale);
+void node_draw_nodesocket(const rctf *rect,
+ const float color_inner[4],
+ const float color_outline[4],
+ float outline_thickness,
+ int shape,
+ float aspect);
+
+} // namespace blender::ed::space_node
diff --git a/compat/include/ED_screen.hh b/compat/include/ED_screen.hh
new file mode 100644
index 0000000..d8e140d
--- /dev/null
+++ b/compat/include/ED_screen.hh
@@ -0,0 +1,794 @@
+/* SPDX-FileCopyrightText: 2008 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup editors
+ */
+
+#pragma once
+
+#include "DNA_screen_types.h"
+#include "DNA_space_types.h"
+#include "DNA_userdef_types.h"
+#include "DNA_workspace_types.h"
+
+#include "ED_screen_types.hh"
+
+#include "WM_types.hh"
+
+#include "BLI_compiler_attrs.h"
+
+namespace blender {
+
+struct ARegion;
+struct AZone;
+struct Depsgraph;
+struct IDProperty;
+struct Main;
+struct MenuType;
+struct Scene;
+struct SpaceLink;
+struct WorkSpace;
+struct WorkSpaceInstanceHook;
+struct bContext;
+struct bScreen;
+struct rcti;
+struct wmKeyConfig;
+struct wmMsgSubscribeKey;
+struct wmMsgSubscribeValue;
+struct wmNotifier;
+struct wmOperatorType;
+struct wmRegionListenerParams;
+struct wmRegionMessageSubscribeParams;
+struct wmSpaceTypeListenerParams;
+struct wmWindow;
+struct wmWindowManager;
+
+namespace ui {
+struct Layout;
+struct Block;
+enum class ButtonSectionsAlign : int8_t;
+} // namespace ui
+
+/* regions */
+/** Only exported for WM. */
+void ED_region_do_listen(wmRegionListenerParams *params);
+/** Only exported for WM. */
+void ED_region_do_layout(bContext *C, ARegion *region);
+/** Only exported for WM. */
+void ED_region_do_draw(bContext *C, ARegion *region);
+void ED_region_exit(bContext *C, ARegion *region);
+/**
+ * Utility to exit and free an area-region. Screen level regions (menus/popups) need to be treated
+ * slightly differently, see #ui::region_temp_remove().
+ */
+void ED_region_remove(bContext *C, ScrArea *area, ARegion *region);
+void ED_region_pixelspace(const ARegion *region);
+/**
+ * Call to move a popup window (keep OpenGL context free!)
+ */
+void ED_region_update_rect(ARegion *region);
+/**
+ * Externally called for floating regions like menus.
+ */
+void ED_region_floating_init(ARegion *region);
+void ED_region_tag_redraw(ARegion *region);
+void ED_region_tag_redraw_partial(ARegion *region, const rcti *rct, bool rebuild);
+void ED_region_tag_redraw_cursor(ARegion *region);
+void ED_region_tag_redraw_no_rebuild(ARegion *region);
+void ED_region_tag_refresh_ui(ARegion *region);
+/**
+ * Tag editor overlays to be redrawn. If in doubt about which parts need to be redrawn (partial
+ * clipping rectangle set), redraw everything.
+ */
+void ED_region_tag_redraw_editor_overlays(ARegion *region);
+
+/**
+ * If the region has tag RGN_FLAG_INDICATE_OVERFLOW then draw
+ * a line or gradient on edges if there is content overflowing.
+ */
+void ED_region_draw_overflow_indication(const ScrArea *area,
+ const ARegion *region,
+ const rcti *mask = nullptr);
+
+/**
+ * Set the temporary update flag for property search.
+ */
+void ED_region_search_filter_update(const ScrArea *area, ARegion *region);
+/**
+ * Returns the search string if the space type and region type support property search.
+ */
+const char *ED_area_region_search_filter_get(const ScrArea *area, const ARegion *region);
+/**
+ * Returns the maximum size a region can grow to so it still fits in the area.
+ */
+int ED_area_max_regionsize(const ScrArea *area, const ARegion *scale_region, const AZEdge edge);
+
+void ED_region_panels_init(wmWindowManager *wm, ARegion *region);
+void ED_region_panels_ex(const bContext *C,
+ ARegion *region,
+ wm::OpCallContext op_context,
+ const char *contexts[]);
+void ED_region_panels(const bContext *C, ARegion *region);
+/**
+ * \param contexts: A NULL terminated array of context strings to match against.
+ * Matching against any of these strings will draw the panel.
+ * Can be NULL to skip context checks.
+ */
+void ED_region_panels_layout_ex(const bContext *C,
+ ARegion *region,
+ ListBaseT<PanelType> *paneltypes,
+ wm::OpCallContext op_context,
+ const char *contexts[],
+ const char *category_override);
+/**
+ * Build the same panel list as #ED_region_panels_layout_ex and checks whether any
+ * of the panels contain a search result based on the area / region's search filter.
+ */
+bool ED_region_property_search(const bContext *C,
+ ARegion *region,
+ ListBaseT<PanelType> *paneltypes,
+ const char *contexts[],
+ const char *category_override);
+
+void ED_region_panels_layout(const bContext *C, ARegion *region);
+void ED_region_panels_draw(const bContext *C, ARegion *region);
+
+void ED_region_header_init(ARegion *region);
+void ED_region_header(const bContext *C, ARegion *region);
+void ED_region_header_layout(const bContext *C, ARegion *region);
+void ED_region_header_draw(const bContext *C, ARegion *region);
+
+/** Version of #ED_region_header() that draws with button sections. */
+void ED_region_header_with_button_sections(const bContext *C,
+ ARegion *region,
+ ui::ButtonSectionsAlign align);
+/** Version of #ED_region_header_draw() that draws with button sections. */
+void ED_region_header_draw_with_button_sections(const bContext *C,
+ const ARegion *region,
+ ui::ButtonSectionsAlign align);
+
+void ED_region_cursor_set(wmWindow *win, ScrArea *area, ARegion *region);
+/**
+ * Exported to all editors, uses fading default.
+ */
+void ED_region_toggle_hidden(bContext *C, ARegion *region);
+/**
+ * For use after changing visibility of regions.
+ */
+void ED_region_visibility_change_update_ex(
+ bContext *C, ScrArea *area, ARegion *region, bool is_hidden, bool do_init);
+void ED_region_visibility_change_update(bContext *C, ScrArea *area, ARegion *region);
+/* `screen_ops.cc` */
+
+/**
+ * \note Assumes that \a region itself is not a split version from previous region.
+ */
+void ED_region_visibility_change_update_animated(bContext *C, ScrArea *area, ARegion *region);
+
+void ED_region_clear(const bContext *C, const ARegion *region, int /*ThemeColorID*/ colorid);
+
+void ED_region_info_draw(ARegion *region,
+ const char *text,
+ const float fill_color[4],
+ bool full_redraw);
+void ED_region_info_draw_multiline(ARegion *region,
+ const char *text_array[],
+ const float fill_color[4],
+ bool full_redraw);
+void ED_region_image_metadata_panel_draw(ImBuf *ibuf, ui::Layout *layout);
+void ED_region_grid_draw(ARegion *region, float zoomx, float zoomy, float x0, float y0);
+float ED_region_blend_alpha(ARegion *region);
+const rcti *ED_region_visible_rect(ARegion *region);
+/**
+ * Overlapping regions only in the following restricted cases.
+ */
+bool ED_region_is_overlap(int spacetype, int regiontype);
+
+int ED_region_snap_size_test(const ARegion *region);
+bool ED_region_snap_size_apply(ARegion *region, int snap_flag);
+
+/* message_bus callbacks */
+void ED_region_do_msg_notify_tag_redraw(bContext *C,
+ wmMsgSubscribeKey *msg_key,
+ wmMsgSubscribeValue *msg_val);
+void ED_area_do_msg_notify_tag_refresh(bContext *C,
+ wmMsgSubscribeKey *msg_key,
+ wmMsgSubscribeValue *msg_val);
+
+/**
+ * Follow #ARegionType.message_subscribe.
+ */
+void ED_area_do_mgs_subscribe_for_tool_header(const wmRegionMessageSubscribeParams *params);
+void ED_area_do_mgs_subscribe_for_tool_ui(const wmRegionMessageSubscribeParams *params);
+
+/* message bus */
+
+/**
+ * Generate subscriptions for this region.
+ */
+void ED_region_message_subscribe(wmRegionMessageSubscribeParams *params);
+
+/* spaces */
+
+/**
+ * \note Keymap definitions are registered only once per WM initialize,
+ * usually on file read, using the keymap the actual areas/regions add the handlers.
+ * \note Called in `wm.cc`. */
+void ED_spacetypes_keymap(wmKeyConfig *keyconf);
+/**
+ * Returns offset for next button in header.
+ */
+int ED_area_header_switchbutton(const bContext *C, ui::Block *block, int yco);
+
+/* areas */
+/**
+ * Ensure #ScrArea.type and #ARegion.type are set and valid.
+ */
+void ED_area_and_region_types_init(ScrArea *area);
+/**
+ * Called in screen_refresh, or screens_init, also area size changes.
+ */
+void ED_area_init(bContext *C, const wmWindow *win, ScrArea *area);
+void ED_area_exit(bContext *C, ScrArea *area);
+StringRefNull ED_area_name(const ScrArea *area);
+int ED_area_icon(const ScrArea *area);
+int ED_screen_area_active(const bContext *C);
+void ED_screen_global_areas_refresh(wmWindow *win);
+void ED_screen_global_areas_sync(wmWindow *win);
+/** Only exported for WM. */
+void ED_area_do_listen(wmSpaceTypeListenerParams *params);
+void ED_area_tag_redraw(ScrArea *area);
+void ED_area_tag_redraw_no_rebuild(ScrArea *area);
+void ED_area_tag_redraw_regiontype(ScrArea *area, int regiontype);
+void ED_area_tag_refresh(ScrArea *area);
+/**
+ * For regions that change the region size in their #ARegionType.layout() callback: Mark the area
+ * as having a changed region size, requiring refitting of regions within the area.
+ */
+void ED_area_tag_region_size_update(ScrArea *area, ARegion *changed_region);
+/**
+ * Only exported for WM.
+ */
+void ED_area_do_refresh(bContext *C, ScrArea *area);
+AZone *ED_area_azones_update(ScrArea *area, const int mouse_xy[2]);
+/**
+ * Show the given text in the area's header, instead of its regular contents.
+ * Use NULL to disable this and show the regular header contents again.
+ */
+void ED_area_status_text(ScrArea *area, const char *str);
+/**
+ * \param skip_region_exit: Skip calling area exit callback. Set for opening temp spaces.
+ */
+void ED_area_newspace(bContext *C, ScrArea *area, int type, bool skip_region_exit);
+void ED_area_prevspace(bContext *C, ScrArea *area);
+void ED_area_swapspace(bContext *C, ScrArea *sa1, ScrArea *sa2);
+int ED_area_headersize();
+int ED_area_footersize();
+/**
+ * \return the final height of a global \a area, accounting for DPI.
+ */
+int ED_area_global_size_y(const ScrArea *area);
+int ED_area_global_min_size_y(const ScrArea *area);
+int ED_area_global_max_size_y(const ScrArea *area);
+bool ED_area_is_global(const ScrArea *area);
+/**
+ * For now we just assume all global areas are made up out of horizontal bars
+ * with the same size. A fixed size could be stored in ARegion instead if needed.
+ *
+ * \return the DPI aware height of a single bar/region in global areas.
+ */
+int ED_region_global_size_y();
+void ED_area_update_region_sizes(wmWindowManager *wm, wmWindow *win, ScrArea *area);
+bool ED_area_has_shared_border(ScrArea *a, ScrArea *b);
+ScrArea *ED_area_offscreen_create(wmWindow *win, eSpace_Type space_type);
+void ED_area_offscreen_free(wmWindowManager *wm, wmWindow *win, ScrArea *area);
+
+/**
+ * Search all screens, even non-active or overlapping (multiple windows), return the most-likely
+ * area of interest. xy is relative to active window, like all similar functions.
+ */
+ScrArea *ED_area_find_under_cursor(const bContext *C, int spacetype, const int event_xy[2]);
+
+ScrArea *ED_screen_areas_iter_first(const wmWindow *win, const bScreen *screen);
+ScrArea *ED_screen_areas_iter_next(const bScreen *screen, const ScrArea *area);
+/**
+ * Iterate over all areas visible in the screen (screen as in everything
+ * visible in the window, not just bScreen).
+ * \note Skips global areas with flag GLOBAL_AREA_IS_HIDDEN.
+ */
+#define ED_screen_areas_iter(win, screen, area_name) \
+ for (ScrArea *area_name = ED_screen_areas_iter_first(win, screen); area_name != NULL; \
+ area_name = ED_screen_areas_iter_next(screen, area_name))
+#define ED_screen_verts_iter(win, screen, vert_name) \
+ for (ScrVert *vert_name = (win)->global_areas.vertbase.first ? \
+ (ScrVert *)(win)->global_areas.vertbase.first : \
+ (ScrVert *)(screen)->vertbase.first; \
+ vert_name != NULL; \
+ vert_name = (vert_name == (win)->global_areas.vertbase.last) ? \
+ (ScrVert *)(screen)->vertbase.first : \
+ vert_name->next)
+
+/**
+ * Update all areas that are supposed to follow the timeline current-frame indicator.
+ */
+void ED_areas_do_frame_follow(bContext *C, bool center_view);
+
+/* screens */
+
+/**
+ * File read, set all screens, ....
+ */
+void ED_screens_init(bContext *C, Main *bmain, wmWindowManager *wm);
+/**
+ * Only for edge lines between areas.
+ */
+void ED_screen_draw_edges(wmWindow *win);
+
+/**
+ * Make this screen usable.
+ * for file read and first use, for scaling window, area moves.
+ */
+void ED_screen_refresh(bContext *C, wmWindowManager *wm, wmWindow *win);
+void ED_screen_ensure_updated(bContext *C, wmWindowManager *wm, wmWindow *win);
+void ED_screen_do_listen(bContext *C, const wmNotifier *note);
+/**
+ * \brief Change the active screen.
+ *
+ * Operator call, WM + Window + screen already existed before
+ *
+ * \warning Do NOT call in area/region queues!
+ * \returns if screen changing was successful.
+ */
+bool ED_screen_change(bContext *C, bScreen *screen);
+void ED_screen_scene_change(bContext *C, wmWindow *win, Scene *scene, bool refresh_toolsystem);
+/**
+ * Called in `wm_event_system.cc`. sets state vars in screen, cursors.
+ * event type is mouse move.
+ */
+void ED_screen_set_active_region(bContext *C, wmWindow *win, const int xy[2]);
+void ED_screen_exit(bContext *C, wmWindow *window, bScreen *screen);
+/**
+ * redraws: uses defines from `stime->redraws`
+ * \param enable: 1 - forward on, -1 - backwards on, 0 - off.
+ */
+void ED_screen_animation_timer(
+ bContext *C, Scene *scene, ViewLayer *view_layer, int redraws, int sync, int enable);
+void ED_screen_animation_timer_update(bScreen *screen, int redraws);
+void ED_screen_restore_temp_type(bContext *C, ScrArea *area);
+ScrArea *ED_screen_full_newspace(bContext *C, ScrArea *area, int type);
+/**
+ * \a was_prev_temp for the case previous space was a temporary full-screen as well
+ */
+void ED_screen_full_prevspace(bContext *C, ScrArea *area);
+/**
+ * Restore a screen / area back to default operation, after temp full-screen modes.
+ */
+void ED_screen_full_restore(bContext *C, ScrArea *area);
+/**
+ * Create a new temporary screen with a maximized, empty area.
+ * This can be closed with #ED_screen_state_toggle().
+ *
+ * Use this to just create a new maximized screen/area, rather than maximizing an existing one.
+ * Otherwise, maximize with #ED_screen_state_toggle().
+ */
+bScreen *ED_screen_state_maximized_create(bContext *C);
+/**
+ * This function toggles: if area is maximized/full then the parent will be restored.
+ *
+ * Use #ED_screen_state_maximized_create() if you do not want the toggle behavior when changing to
+ * a maximized area. I.e. if you just want to open a new maximized screen/area, not maximize a
+ * specific area. In the former case, space data of the maximized and non-maximized area should be
+ * independent, in the latter it should be the same.
+ *
+ * \warning \a area may be freed.
+ */
+ScrArea *ED_screen_state_toggle(bContext *C, wmWindow *win, ScrArea *area, short state);
+/**
+ * Wrapper to open a temporary space either as full-screen space, or as separate window,
+ * as defined by \a display_type.
+ *
+ * \param title: Title to set for the window, if a window is spawned.
+ * \param rect_unscaled: Position & size of the window, if a window is spawned.
+ */
+ScrArea *ED_screen_temp_space_open(bContext *C,
+ const char *title,
+ eSpace_Type space_type,
+ int display_type,
+ bool dialog) ATTR_NONNULL(1);
+void ED_screens_header_tools_menu_create(bContext *C, ui::Layout *layout, void *arg);
+void ED_screens_footer_tools_menu_create(bContext *C, ui::Layout *layout, void *arg);
+void ED_screens_region_flip_menu_create(bContext *C, ui::Layout *layout, void *arg);
+/**
+ * \return true if any active area requires to see in 3D.
+ */
+bool ED_screen_stereo3d_required(const bScreen *screen, const Scene *scene);
+Scene *ED_screen_scene_find(const bScreen *screen, const wmWindowManager *wm);
+/**
+ * Find the scene displayed in \a screen.
+ * \note Assumes \a screen to be visible/active!
+ */
+Scene *ED_screen_scene_find_with_window(const bScreen *screen,
+ const wmWindowManager *wm,
+ wmWindow **r_window);
+ScrArea *ED_screen_area_find_with_spacedata(const bScreen *screen,
+ const SpaceLink *sl,
+ bool only_visible);
+wmWindow *ED_screen_window_find(const bScreen *screen, const wmWindowManager *wm);
+
+/* workspaces */
+
+WorkSpace *ED_workspace_add(Main *bmain, const char *name) ATTR_NONNULL();
+/**
+ * \brief Change the active workspace.
+ *
+ * Operator call, WM + Window + screen already existed before
+ * Pretty similar to #ED_screen_change since changing workspace also changes screen.
+ *
+ * \warning Do NOT call in area/region queues!
+ * \returns if workspace changing was successful.
+ */
+bool ED_workspace_change(WorkSpace *workspace_new, bContext *C, wmWindowManager *wm, wmWindow *win)
+ ATTR_NONNULL();
+/**
+ * Duplicate a workspace including its layouts. Does not activate the workspace, but
+ * it stores the screen-layout to be activated (BKE_workspace_temp_layout_store)
+ */
+WorkSpace *ED_workspace_duplicate(WorkSpace *workspace_old, Main *bmain, wmWindow *win);
+/**
+ * \return if succeeded.
+ */
+bool ED_workspace_delete(WorkSpace *workspace, Main *bmain, bContext *C, wmWindowManager *wm)
+ ATTR_NONNULL();
+/**
+ * Some editor data may need to be synced with scene data (3D View camera and layers).
+ * This function ensures data is synced for editors in active layout of \a workspace.
+ */
+void ED_workspace_scene_data_sync(WorkSpaceInstanceHook *hook, Scene *scene) ATTR_NONNULL();
+/**
+ * Make sure there is a non-full-screen layout to switch to that isn't used yet by an other window.
+ * Needed for workspace or screen switching to ensure valid screens.
+ *
+ * \param layout_fallback_base: As last resort, this layout is duplicated and returned.
+ */
+WorkSpaceLayout *ED_workspace_screen_change_ensure_unused_layout(
+ Main *bmain,
+ WorkSpace *workspace,
+ WorkSpaceLayout *layout_new,
+ const WorkSpaceLayout *layout_fallback_base,
+ wmWindow *win) ATTR_NONNULL();
+/**
+ * Empty screen, with 1 dummy area without space-data. Uses window size.
+ */
+WorkSpaceLayout *ED_workspace_layout_add(Main *bmain,
+ WorkSpace *workspace,
+ wmWindow *win,
+ const char *name) ATTR_NONNULL();
+WorkSpaceLayout *ED_workspace_layout_duplicate(Main *bmain,
+ WorkSpace *workspace,
+ const WorkSpaceLayout *layout_old,
+ wmWindow *win) ATTR_NONNULL();
+/**
+ * \warning Only call outside of area/region loops!
+ * \return true if succeeded.
+ */
+bool ED_workspace_layout_delete(WorkSpace *workspace, WorkSpaceLayout *layout_old, bContext *C)
+ ATTR_NONNULL();
+bool ED_workspace_layout_cycle(WorkSpace *workspace, short direction, bContext *C) ATTR_NONNULL();
+
+void ED_workspace_status_text(bContext *C, const char *str);
+
+class WorkspaceStatus {
+ WorkSpace *workspace_;
+ wmWindowManager *wm_;
+
+ public:
+ WorkspaceStatus(bContext *C);
+
+ /**
+ * Add a static status entry and up to two icons.
+ *
+ * Example:
+ * [LMB][Enter] Confirm
+ */
+ void item(std::string text, int icon1, int icon2 = 0);
+
+ /**
+ * Add extra (or negative) space between items.
+ */
+ void separator(float factor = 1.0f);
+
+ /**
+ * Add a dynamic status entry with up to two icons that change appearance.
+ * Example:
+ * [CTRL] Tweak
+ */
+ void item_bool(std::string text, bool inverted, int icon1, int icon2 = 0);
+
+ /**
+ * Add a static status entry showing two icons separated by a dash.
+ * Example:
+ * [A]-[Z] Search
+ */
+ void range(std::string text, int icon1, int icon2);
+
+ /**
+ * Add a dynamic status entry for a given property in an operator's keymap.
+ * Example:
+ * [V] X-Ray
+ */
+ void opmodal(std::string text, const wmOperatorType *ot, int propvalue, bool inverted = false);
+};
+
+void ED_workspace_do_listen(bContext *C, const wmNotifier *note);
+
+/* anim */
+/**
+ * Results in fully updated anim system.
+ */
+void ED_update_for_newframe(Main *bmain, Depsgraph *depsgraph);
+
+/**
+ * Toggle operator.
+ */
+void ED_reset_audio_device(bContext *C);
+wmOperatorStatus ED_screen_animation_play(bContext *C, int sync, int mode);
+/**
+ * Find window that owns the animation timer.
+ */
+wmWindow *ED_window_animation_playing_no_scrub(const wmWindowManager *wm);
+bScreen *ED_screen_animation_playing(const wmWindowManager *wm);
+bScreen *ED_screen_animation_no_scrub(const wmWindowManager *wm);
+
+/**
+ * Find the scene that is currently playing in a window/screen.
+ */
+Scene *ED_screen_find_playing_scene(const bScreen *screen, bool scrub = false);
+
+/* screen keymaps */
+/* called in `spacetypes.cc`. */
+void ED_operatortypes_screen();
+/* called in `spacetypes.cc`. */
+void ED_keymap_screen(wmKeyConfig *keyconf);
+/**
+ * Workspace key-maps.
+ */
+void ED_operatortypes_workspace();
+
+/* operators; context poll callbacks */
+
+bool ED_operator_screenactive(bContext *C);
+bool ED_operator_active_screen_and_scene(bContext *C);
+bool ED_operator_screenactive_nobackground(bContext *C);
+/**
+ * When mouse is over area-edge.
+ */
+bool ED_operator_screen_mainwinactive(bContext *C);
+bool ED_operator_areaactive(bContext *C);
+bool ED_operator_regionactive(bContext *C);
+
+bool ED_operator_scene(bContext *C);
+bool ED_operator_scene_editable(bContext *C);
+bool ED_operator_sequencer_scene(bContext *C);
+bool ED_operator_sequencer_scene_editable(bContext *C);
+
+bool ED_operator_objectmode(bContext *C);
+/**
+ * Same as #ED_operator_objectmode() but additionally sets a "disabled hint". That is, a message
+ * to be displayed to the user explaining why the operator can't be used in current context.
+ */
+bool ED_operator_objectmode_poll_msg(bContext *C);
+bool ED_operator_objectmode_with_view3d_poll_msg(bContext *C);
+
+bool ED_operator_view3d_active(bContext *C);
+bool ED_operator_region_view3d_active(bContext *C);
+bool ED_operator_region_gizmo_active(bContext *C);
+
+/**
+ * Generic for any view2d which uses anim_ops.
+ */
+bool ED_operator_animview_active(bContext *C);
+bool ED_operator_outliner_active(bContext *C);
+bool ED_operator_region_outliner_active(bContext *C);
+bool ED_operator_outliner_active_no_editobject(bContext *C);
+/**
+ * \note Will return true for file spaces in either file or asset browsing mode! See
+ * #ED_operator_file_browsing_active() (file browsing only) and
+ * #ED_operator_asset_browsing_active() (asset browsing only).
+ */
+bool ED_operator_file_active(bContext *C);
+/**
+ * \note Will only return true if the file space is in file browsing mode, not asset browsing! See
+ * #ED_operator_file_active() (file or asset browsing) and
+ * #ED_operator_asset_browsing_active() (asset browsing only).
+ */
+bool ED_operator_file_browsing_active(bContext *C);
+bool ED_operator_asset_browsing_active(bContext *C);
+bool ED_operator_spreadsheet_active(bContext *C);
+bool ED_operator_action_active(bContext *C);
+bool ED_operator_buttons_active(bContext *C);
+bool ED_operator_node_active(bContext *C);
+bool ED_operator_node_editable(bContext *C);
+bool ED_operator_graphedit_active(bContext *C);
+bool ED_operator_sequencer_active(bContext *C);
+bool ED_operator_sequencer_active_editable(bContext *C);
+bool ED_operator_image_active(bContext *C);
+bool ED_operator_nla_active(bContext *C);
+bool ED_operator_info_active(bContext *C);
+bool ED_operator_console_active(bContext *C);
+bool ED_operator_preferences_active(bContext *C);
+
+/** Only check there is an active object (no visibility check). */
+bool ED_operator_object_active_only(bContext *C);
+bool ED_operator_object_active(bContext *C);
+bool ED_operator_object_active_editable_ex(bContext *C, const Object *ob);
+bool ED_operator_object_active_editable(bContext *C);
+/**
+ * Object must be editable and fully local (i.e. not an override).
+ */
+bool ED_operator_object_active_local_editable_ex(bContext *C, const Object *ob);
+bool ED_operator_object_active_local_editable(bContext *C);
+bool ED_operator_object_active_editable_mesh(bContext *C);
+bool ED_operator_object_active_editable_font(bContext *C);
+bool ED_operator_editable_mesh(bContext *C);
+bool ED_operator_editmesh(bContext *C);
+bool ED_operator_editmesh_view3d(bContext *C);
+bool ED_operator_editmesh_region_view3d(bContext *C);
+bool ED_operator_editarmature(bContext *C);
+bool ED_operator_editcurve(bContext *C);
+bool ED_operator_editcurve_3d(bContext *C);
+bool ED_operator_editsurf(bContext *C);
+bool ED_operator_editsurfcurve(bContext *C);
+bool ED_operator_editsurfcurve_region_view3d(bContext *C);
+bool ED_operator_editfont(bContext *C);
+bool ED_operator_editlattice(bContext *C);
+bool ED_operator_editmball(bContext *C);
+/**
+ * Wrapper for #ED_space_image_show_uvedit.
+ */
+bool ED_operator_uvedit(bContext *C);
+bool ED_operator_uvedit_space_image(bContext *C);
+bool ED_operator_uvmap(bContext *C);
+bool ED_operator_posemode_exclusive(bContext *C);
+/**
+ * Object must be editable, fully local (i.e. not an override), and exclusively in Pose mode.
+ */
+bool ED_operator_object_active_local_editable_posemode_exclusive(bContext *C);
+/**
+ * Allows for pinned pose objects to be used in the object buttons
+ * and the non-active pose object to be used in the 3D view.
+ */
+bool ED_operator_posemode_context(bContext *C);
+bool ED_operator_posemode(bContext *C);
+bool ED_operator_posemode_local(bContext *C);
+bool ED_operator_camera_poll(bContext *C);
+
+/* `screen_user_menu.cc` */
+
+bUserMenu **ED_screen_user_menus_find(const bContext *C, uint *r_len);
+bUserMenu *ED_screen_user_menu_ensure(bContext *C);
+
+/**
+ * Finds a menu item associated with an operator in user menus (aka Quick Favorites)
+ *
+ * \param op_prop_enum: name of an operator property when the operator is called with an enum (to
+ * be an empty string otherwise)
+ */
+bUserMenuItem_Op *ED_screen_user_menu_item_find_operator(ListBaseT<bUserMenuItem> *lb,
+ const wmOperatorType *ot,
+ IDProperty *prop,
+ const char *op_prop_enum,
+ wm::OpCallContext opcontext);
+bUserMenuItem_Menu *ED_screen_user_menu_item_find_menu(ListBaseT<bUserMenuItem> *lb,
+ const MenuType *mt);
+bUserMenuItem_Prop *ED_screen_user_menu_item_find_prop(ListBaseT<bUserMenuItem> *lb,
+ const char *context_data_path,
+ const char *prop_id,
+ int prop_index);
+
+void ED_screen_user_menu_item_add_operator(ListBaseT<bUserMenuItem> *lb,
+ const char *ui_name,
+ const wmOperatorType *ot,
+ const IDProperty *prop,
+ const char *op_prop_enum,
+ wm::OpCallContext opcontext);
+void ED_screen_user_menu_item_add_menu(ListBaseT<bUserMenuItem> *lb,
+ const char *ui_name,
+ const MenuType *mt);
+void ED_screen_user_menu_item_add_prop(ListBaseT<bUserMenuItem> *lb,
+ const char *ui_name,
+ const char *context_data_path,
+ const char *prop_id,
+ int prop_index);
+
+void ED_screen_user_menu_item_remove(ListBaseT<bUserMenuItem> *lb, bUserMenuItem *umi);
+void ED_screen_user_menu_register();
+
+/* Cache display helpers */
+
+void ED_region_cache_draw_background(ARegion *region);
+void ED_region_cache_draw_curfra_label(int framenr, float x, float y);
+void ED_region_cache_draw_cached_segments(
+ ARegion *region, int num_segments, const int *points, int sfra, int efra);
+
+/* `area_utils.cc` */
+
+/**
+ * Callback for #ARegionType.message_subscribe
+ */
+void ED_region_generic_tools_region_message_subscribe(
+ const wmRegionMessageSubscribeParams *params);
+/**
+ * Callback for #ARegionType.snap_size
+ */
+int ED_region_generic_tools_region_snap_size(const ARegion *region, int size, int axis);
+int ED_region_generic_panel_region_snap_size(const ARegion *region, int size, int axis);
+
+/* `area_query.cc` */
+
+bool ED_region_overlap_isect_x(const ARegion *region, int event_x);
+bool ED_region_overlap_isect_y(const ARegion *region, int event_y);
+bool ED_region_overlap_isect_xy(const ARegion *region, const int event_xy[2]);
+bool ED_region_overlap_isect_any_xy(const ScrArea *area, const int event_xy[2]);
+bool ED_region_overlap_isect_x_with_margin(const ARegion *region, int event_x, int margin);
+bool ED_region_overlap_isect_y_with_margin(const ARegion *region, int event_y, int margin);
+bool ED_region_overlap_isect_xy_with_margin(const ARegion *region,
+ const int event_xy[2],
+ int margin);
+
+bool ED_region_panel_category_gutter_calc_rect(const ARegion *region, rcti *r_region_gutter);
+bool ED_region_panel_category_gutter_isect_xy(const ARegion *region, const int event_xy[2]);
+
+/**
+ * \note This may return true for multiple overlapping regions.
+ * If it matters, check overlapped regions first (#ARegion.overlap).
+ */
+bool ED_region_contains_xy(const ARegion *region, const int event_xy[2]);
+/**
+ * Similar to #BKE_area_find_region_xy() but when \a event_xy intersects an overlapping region,
+ * this returns the region that is visually under the cursor. E.g. when over the
+ * transparent part of the region, it returns the region underneath.
+ *
+ * The overlapping region is determined using the #ED_region_contains_xy() query.
+ */
+ARegion *ED_area_find_region_xy_visual(const ScrArea *area, int regiontype, const int event_xy[2]);
+
+/* `interface_region_hud.cc` */
+
+namespace ui {
+ARegionType *ED_area_type_hud(int space_type);
+void ED_area_type_hud_clear(wmWindowManager *wm, ScrArea *area_keep);
+void ED_area_type_hud_ensure(bContext *C, ScrArea *area);
+/**
+ * Lookup the region the operation was executed in, and which should be used to redo the
+ * operation. The lookup is based on the region type, so it can return a different region when the
+ * same region type is present multiple times.
+ */
+ARegion *ED_area_type_hud_redo_region_find(const ScrArea *area, const ARegion *hud_region);
+} // namespace ui
+
+/**
+ * Default key-maps, bit-flags (matches order of evaluation).
+ */
+enum {
+ ED_KEYMAP_UI = (1 << 1),
+ ED_KEYMAP_GIZMO = (1 << 2),
+ ED_KEYMAP_TOOL = (1 << 3),
+ ED_KEYMAP_VIEW2D = (1 << 4),
+ ED_KEYMAP_ANIMATION = (1 << 6),
+ ED_KEYMAP_FRAMES = (1 << 7),
+ ED_KEYMAP_HEADER = (1 << 8),
+ ED_KEYMAP_FOOTER = (1 << 9),
+ ED_KEYMAP_GPENCIL = (1 << 10),
+ ED_KEYMAP_NAVBAR = (1 << 11),
+ ED_KEYMAP_ASSET_SHELF = (1 << 12),
+};
+
+/** #SCREEN_OT_space_context_cycle direction. */
+enum eScreenCycle {
+ SPACE_CONTEXT_CYCLE_PREV,
+ SPACE_CONTEXT_CYCLE_NEXT,
+};
+
+} // namespace blender
diff --git a/compat/include/ED_screen_types.hh b/compat/include/ED_screen_types.hh
new file mode 100644
index 0000000..5c8ad9e
--- /dev/null
+++ b/compat/include/ED_screen_types.hh
@@ -0,0 +1,133 @@
+/* SPDX-FileCopyrightText: 2008 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup editors
+ */
+
+#pragma once
+
+#include "DNA_vec_types.h"
+
+namespace blender {
+
+struct ARegion;
+struct Scene;
+struct ViewLayer;
+
+/* ----------------------------------------------------- */
+
+/**
+ * For animation playback operator, stored in #bScreen.animtimer.customdata.
+ */
+struct ScreenAnimData {
+ /** Do not read from this, only for comparing if region exists. */
+ ARegion *region;
+
+ /* The Scene and the View Layer that the animation timer is playing. */
+ Scene *scene;
+ ViewLayer *view_layer;
+ /* For sequencer scenes, account for scene syncing during playback. */
+ bool do_scene_syncing;
+
+ short redraws;
+ /** Flags for playback */
+ short flag;
+ /** Frame that playback was started from */
+ int sfra;
+ /** Next frame to go to (when ANIMPLAY_FLAG_USE_NEXT_FRAME is set) */
+ int nextfra;
+ /** Used for frame dropping */
+ double lagging_frame_count;
+ /** Playback was invoked from animation editor */
+ bool from_anim_edit;
+};
+
+/** #ScreenAnimData.flag */
+enum {
+ /** User-setting - frame range is played backwards. */
+ ANIMPLAY_FLAG_REVERSE = (1 << 0),
+ /** Temporary - playback just jumped to the start/end. */
+ ANIMPLAY_FLAG_JUMPED = (1 << 1),
+ /** Drop frames as needed to maintain frame-rate. */
+ ANIMPLAY_FLAG_SYNC = (1 << 2),
+ /** Don't drop frames (and ignore #SCE_FRAME_DROP flag). */
+ ANIMPLAY_FLAG_NO_SYNC = (1 << 3),
+ /** Use #ScreenAnimData::nextfra at next timer update. */
+ ANIMPLAY_FLAG_USE_NEXT_FRAME = (1 << 4),
+};
+
+/* ----------------------------------------------------- */
+
+/** Enum for Action Zone Edges. Which edge of area is action zone. */
+enum AZEdge {
+ /** Region located on the left, _right_ edge is action zone.
+ * Region minimized to the top left */
+ AE_RIGHT_TO_TOPLEFT,
+ /** Region located on the right, _left_ edge is action zone.
+ * Region minimized to the top right */
+ AE_LEFT_TO_TOPRIGHT,
+ /** Region located at the bottom, _top_ edge is action zone.
+ * Region minimized to the bottom right */
+ AE_TOP_TO_BOTTOMRIGHT,
+ /** Region located at the top, _bottom_ edge is action zone.
+ * Region minimized to the top left */
+ AE_BOTTOM_TO_TOPLEFT,
+};
+
+enum AZScrollDirection {
+ AZ_SCROLL_VERT,
+ AZ_SCROLL_HOR,
+};
+
+/** For editing areas/regions. */
+struct AZone {
+ AZone *next, *prev;
+ ARegion *region;
+ int type;
+
+ union {
+ /** Region-AZone, which of the edges (only for #AZONE_REGION). */
+ AZEdge edge;
+ AZScrollDirection direction;
+ };
+ /** For drawing. */
+ short x1, y1, x2, y2;
+ /** For clip. */
+ rcti rect;
+ /** For fade in/out. */
+ float alpha;
+};
+
+/** Action-Zone Type: #AZone.type */
+enum {
+ /**
+ * Corner widgets for:
+ * - Splitting areas.
+ * - Swapping areas (Ctrl).
+ * - Copying the area into a new window (Shift).
+ */
+ AZONE_AREA = 1,
+ /**
+ * Use for region show/hide state:
+ * - When a region is collapsed, draw a handle to expose.
+ * - When a region is expanded, use the action zone to resize the region.
+ */
+ AZONE_REGION,
+ /**
+ * Widget at the very center of the 3D Viewport Quad View for resizing.
+ */
+ AZONE_REGION_QUAD,
+ /**
+ * Used when in editor full-screen draw a corner to return to normal mode.
+ */
+ AZONE_FULLSCREEN,
+ /**
+ * Hot-spot #AZone around scroll-bars to show/hide them.
+ * Only show the scroll-bars when the cursor is close.
+ */
+ AZONE_REGION_SCROLL,
+};
+
+} // namespace blender
diff --git a/compat/include/ED_space_api.hh b/compat/include/ED_space_api.hh
new file mode 100644
index 0000000..93d62bd
--- /dev/null
+++ b/compat/include/ED_space_api.hh
@@ -0,0 +1,81 @@
+/* SPDX-FileCopyrightText: 2008 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup editors
+ */
+
+#pragma once
+
+namespace blender {
+
+struct ARegion;
+struct ARegionType;
+struct bContext;
+
+/* Only called once on startup. storage is global in BKE kernel listbase. */
+void ED_spacetypes_init();
+void ED_spacemacros_init();
+
+/* The plugin-able API for export to editors. */
+
+/* -------------------------------------------------------------------- */
+/** \name Calls for registering default spaces
+ *
+ * Calls for registering default spaces, only called once, from #ED_spacetypes_init
+ * \{ */
+
+void ED_spacetype_outliner();
+void ED_spacetype_view3d();
+void ED_spacetype_ipo();
+void ED_spacetype_image();
+void ED_spacetype_node();
+void ED_spacetype_buttons();
+void ED_spacetype_info();
+void ED_spacetype_file();
+void ED_spacetype_action();
+void ED_spacetype_nla();
+void ED_spacetype_script();
+void ED_spacetype_text();
+void ED_spacetype_console();
+void ED_spacetype_userpref();
+void ED_spacetype_clip();
+void ED_spacetype_statusbar();
+void ED_spacetype_topbar();
+
+namespace ed::vse {
+void ED_spacetype_sequencer();
+}
+
+namespace ed::spreadsheet {
+void register_spacetype();
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Space-type Static Data
+ * Calls for instancing and freeing space-type static data called in #WM_init_exit
+ * \{ */
+
+void ED_file_init();
+void ED_file_exit();
+
+/** \} */
+
+#define REGION_DRAW_POST_VIEW 0
+#define REGION_DRAW_POST_PIXEL 1
+#define REGION_DRAW_PRE_VIEW 2
+#define REGION_DRAW_BACKDROP 3
+
+void *ED_region_draw_cb_activate(ARegionType *art,
+ void (*draw)(const bContext *, ARegion *, void *),
+ void *customdata,
+ int type);
+void ED_region_draw_cb_draw(const bContext *C, ARegion *region, int type);
+void ED_region_surface_draw_cb_draw(const bContext *C, ARegionType *art, int type);
+bool ED_region_draw_cb_exit(ARegionType *art, void *handle);
+void ED_region_draw_cb_remove_by_type(ARegionType *art, void *draw_fn, void (*free)(void *));
+
+} // namespace blender
diff --git a/compat/include/GPU_texture.hh b/compat/include/GPU_texture.hh
new file mode 100644
index 0000000..bdd0b6a
--- /dev/null
+++ b/compat/include/GPU_texture.hh
@@ -0,0 +1,11 @@
+/* BUI GPU seam: textures (minimal).
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#ifdef __cplusplus
+namespace blender::gpu {
+class Texture;
+enum class TextureFormat : unsigned char;
+} // namespace blender::gpu
+using GPUTexture = blender::gpu::Texture;
+#endif
diff --git a/compat/include/IMB_colormanagement.hh b/compat/include/IMB_colormanagement.hh
new file mode 100644
index 0000000..92f1d7e
--- /dev/null
+++ b/compat/include/IMB_colormanagement.hh
@@ -0,0 +1,41 @@
+/* BUI seam: minimal colormanagement surface used by the toolkit.
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#include "BLI_sys_types.h"
+#include "DNA_vec_types.h"
+
+#ifdef __cplusplus
+#include "OCIO_scope.hh"
+#endif
+
+#ifdef __cplusplus
+namespace blender {
+struct ColorManagedDisplaySettings;
+namespace ocio {
+class Display;
+} // namespace ocio
+using ColorManagedDisplay = ocio::Display;
+} // namespace blender
+#endif
+
+float IMB_colormanagement_get_luminance(const float rgb[3]);
+
+#ifdef __cplusplus
+/* Returns an empty scope description; wire a real processor later. */
+blender::ocio::ScopeInfo IMB_colormanagement_get_scope_info(
+ const blender::ColorManagedDisplaySettings *display_settings, const char *view_name);
+
+/* Display-space conversion used by color widgets. Null-op with the stub
+ * color management (scene-linear == display space). */
+void IMB_colormanagement_scene_linear_to_display_v3(float pixel[3],
+ const blender::ColorManagedDisplay *display);
+void IMB_colormanagement_display_to_scene_linear_v3(float pixel[3],
+ const blender::ColorManagedDisplay *display);
+
+/* Color-picking space (stub: identity). */
+void IMB_colormanagement_scene_linear_to_color_picking_v3(float color_picking[3],
+ const float scene_linear[3]);
+void IMB_colormanagement_color_picking_to_scene_linear_v3(float scene_linear[3],
+ const float color_picking[3]);
+#endif
diff --git a/compat/include/IMB_imbuf.hh b/compat/include/IMB_imbuf.hh
new file mode 100644
index 0000000..16a1e03
--- /dev/null
+++ b/compat/include/IMB_imbuf.hh
@@ -0,0 +1,718 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ * SPDX-FileCopyrightText: 2025 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup imbuf
+ */
+
+#pragma once
+
+#include "GPU_texture.hh"
+
+#include "BLI_enum_flags.hh"
+#include "BLI_math_matrix_types.hh"
+#include "BLI_span.hh"
+
+#include "IMB_imbuf_types.hh"
+
+namespace blender {
+
+struct ImBuf;
+struct rctf;
+struct rcti;
+
+struct ImageFormatData;
+struct Stereo3dFormat;
+
+/**
+ * Module init/exit.
+ */
+void IMB_init();
+void IMB_exit();
+
+/**
+ * Module GPU context management.
+ */
+void IMB_ensure_gpu_context();
+void IMB_activate_gpu_context();
+void IMB_deactivate_gpu_context();
+
+/**
+ * Load image.
+ */
+ImBuf *IMB_load_image_from_memory(const unsigned char *mem,
+ size_t size,
+ int flags,
+ const char *descr,
+ const char *filepath = nullptr,
+ char r_colorspace[IM_MAX_SPACE] = nullptr);
+
+ImBuf *IMB_load_image_from_file_descriptor(int file,
+ int flags,
+ const char *filepath = nullptr,
+ char r_colorspace[IM_MAX_SPACE] = nullptr);
+
+ImBuf *IMB_load_image_from_filepath(const char *filepath,
+ int flags,
+ char r_colorspace[IM_MAX_SPACE] = nullptr);
+
+/**
+ * Save image.
+ */
+bool IMB_save_image(ImBuf *ibuf, const char *filepath, int flags);
+
+/**
+ * Test image file.
+ */
+bool IMB_test_image(const char *filepath);
+bool IMB_test_image_type_matches(const char *filepath, eImbFileType filetype);
+eImbFileType IMB_test_image_type_from_memory(const unsigned char *buf, size_t buf_size);
+eImbFileType IMB_test_image_type(const char *filepath);
+
+/**
+ * Return true if the file type is supported (compiled in).
+ */
+bool IMB_ftype_is_supported(eImbFileType ftype);
+
+/**
+ * Return the string identifier for a file type, or nullptr if not found.
+ */
+const char *IMB_ftype_to_id(eImbFileType ftype);
+
+/**
+ * Return the file type enum value for a string identifier, or #IMB_FTYPE_NONE if not found.
+ */
+eImbFileType IMB_ftype_from_id(const char *id);
+
+/**
+ * Return the null-terminated list of extensions for a file type, or nullptr if not found.
+ */
+const char **IMB_ftype_file_extensions(eImbFileType ftype);
+
+/**
+ * Return the read capability flags for a file type.
+ */
+eImFileTypeCapability IMB_ftype_capability_read(eImbFileType ftype);
+
+/**
+ * Return the write capability flags for a file type.
+ */
+eImFileTypeCapability IMB_ftype_capability_write(eImbFileType ftype);
+
+/**
+ * Load thumbnail image.
+ */
+enum class IMBThumbLoadFlags {
+ Zero = 0,
+ /** Normally files larger than 100MB are not loaded for thumbnails, except when this flag is set.
+ */
+ LoadLargeFiles = (1 << 0),
+};
+ENUM_OPERATORS(IMBThumbLoadFlags);
+
+ImBuf *IMB_thumb_load_image(const char *filepath,
+ size_t max_thumb_size,
+ char colorspace[IM_MAX_SPACE],
+ IMBThumbLoadFlags load_flags = IMBThumbLoadFlags::Zero);
+
+/**
+ * Allocate and free image buffer.
+ */
+ImBuf *IMB_allocImBuf(unsigned int x, unsigned int y, unsigned char planes, unsigned int flags);
+void IMB_freeImBuf(ImBuf *ibuf);
+
+/**
+ * Initialize given ImBuf.
+ *
+ * Use in cases when temporary image buffer is allocated on stack.
+ */
+bool IMB_initImBuf(
+ ImBuf *ibuf, unsigned int x, unsigned int y, unsigned char planes, unsigned int flags);
+
+/**
+ * Create a copy of a pixel buffer and wrap it to a new ImBuf
+ * (transferring ownership to the in imbuf).
+ */
+ImBuf *IMB_allocFromBufferOwn(uint8_t *byte_buffer,
+ float *float_buffer,
+ unsigned int w,
+ unsigned int h,
+ unsigned int channels);
+
+/**
+ * Create a copy of a pixel buffer and wrap it to a new ImBuf
+ */
+ImBuf *IMB_allocFromBuffer(const uint8_t *byte_buffer,
+ const float *float_buffer,
+ unsigned int w,
+ unsigned int h,
+ unsigned int channels);
+
+/**
+ * Assign the content of the corresponding buffer with the given data and ownership.
+ * The current content of the buffer is released corresponding to its ownership configuration.
+ *
+ * \note Does not modify the topology (width, height, number of channels).
+ */
+void IMB_assign_byte_buffer(ImBuf *ibuf, uint8_t *buffer_data, ImBufOwnership ownership);
+void IMB_assign_float_buffer(ImBuf *ibuf, float *buffer_data, ImBufOwnership ownership);
+
+/**
+ * Assign the GPU texture of the buffer to the given texture. The current GPU texture is released.
+ *
+ * \note Does not modify the topology (width, height, number of channels).
+ */
+void IMB_assign_gpu_texture(ImBuf *ibuf, gpu::Texture *texture);
+
+/**
+ * Reads the GPU data texture of the image buffer if it exists and assigns the data to the float
+ * buffer. This is only done if the buffer has the IB_HOST_BUFFER_INVALID flag is set, which is
+ * then reset after the function executes.
+ *
+ * \warning Not thread-safe, so callee should worry about thread locks.
+ */
+void IMB_ensure_host_buffer(ImBuf *ibuf);
+
+/**
+ * Assign the content and the color space of the corresponding buffer the data from the given
+ * buffer.
+ *
+ * \note Does not modify the topology (width, height, number of channels).
+ *
+ * \note The ownership of the data in the source buffer is ignored.
+ */
+void IMB_assign_byte_buffer(ImBuf *ibuf, const ImBufByteBuffer &buffer, ImBufOwnership ownership);
+void IMB_assign_float_buffer(ImBuf *ibuf,
+ const ImBufFloatBuffer &buffer,
+ ImBufOwnership ownership);
+void IMB_assign_dds_data(ImBuf *ibuf, const DDSData &data, ImBufOwnership ownership);
+
+/**
+ * Make corresponding buffers available for modification.
+ * Is achieved by ensuring that the given ImBuf is the only owner of the underlying buffer data.
+ */
+void IMB_make_writable_byte_buffer(ImBuf *ibuf);
+void IMB_make_writable_float_buffer(ImBuf *ibuf);
+
+/**
+ * Steal the buffer data pointer: the ImBuf is no longer an owner of this data.
+ * \note If the ImBuf does not own the data the behavior is undefined.
+ * \note Stealing encoded buffer resets the encoded size.
+ */
+uint8_t *IMB_steal_byte_buffer(ImBuf *ibuf);
+float *IMB_steal_float_buffer(ImBuf *ibuf);
+uint8_t *IMB_steal_encoded_buffer(ImBuf *ibuf);
+
+/**
+ * Increase reference count to imbuf
+ * (to delete an imbuf you have to call freeImBuf as many times as it
+ * is referenced)
+ */
+
+void IMB_refImBuf(ImBuf *ibuf);
+ImBuf *IMB_makeSingleUser(ImBuf *ibuf);
+
+ImBuf *IMB_dupImBuf(const ImBuf *ibuf1);
+
+/**
+ * Approximate size of ImBuf in memory
+ */
+size_t IMB_get_size_in_memory(const ImBuf *ibuf);
+
+/**
+ * \brief Get the length of the data of the given image buffer in pixels.
+ *
+ * This is the width * the height of the image buffer.
+ * This function is preferred over `ibuf->x * ibuf->y` due to 32 bit int overflow
+ * issues when working with very large resolution images.
+ */
+size_t IMB_get_pixel_count(const ImBuf *ibuf);
+
+enum IMB_BlendMode {
+ IMB_BLEND_MIX = 0,
+ IMB_BLEND_ADD = 1,
+ IMB_BLEND_SUB = 2,
+ IMB_BLEND_MUL = 3,
+ IMB_BLEND_LIGHTEN = 4,
+ IMB_BLEND_DARKEN = 5,
+ IMB_BLEND_ERASE_ALPHA = 6,
+ IMB_BLEND_ADD_ALPHA = 7,
+ IMB_BLEND_OVERLAY = 8,
+ IMB_BLEND_HARDLIGHT = 9,
+ IMB_BLEND_COLORBURN = 10,
+ IMB_BLEND_LINEARBURN = 11,
+ IMB_BLEND_COLORDODGE = 12,
+ IMB_BLEND_SCREEN = 13,
+ IMB_BLEND_SOFTLIGHT = 14,
+ IMB_BLEND_PINLIGHT = 15,
+ IMB_BLEND_VIVIDLIGHT = 16,
+ IMB_BLEND_LINEARLIGHT = 17,
+ IMB_BLEND_DIFFERENCE = 18,
+ IMB_BLEND_EXCLUSION = 19,
+ IMB_BLEND_HUE = 20,
+ IMB_BLEND_SATURATION = 21,
+ IMB_BLEND_LUMINOSITY = 22,
+ IMB_BLEND_COLOR = 23,
+ IMB_BLEND_INTERPOLATE = 24,
+
+ IMB_BLEND_COPY_RGB = 1001,
+ IMB_BLEND_COPY_ALPHA = 1002,
+};
+
+void IMB_blend_color_byte(unsigned char dst[4],
+ const unsigned char src1[4],
+ const unsigned char src2[4],
+ IMB_BlendMode mode);
+void IMB_blend_color_float(float dst[4],
+ const float src1[4],
+ const float src2[4],
+ IMB_BlendMode mode);
+void IMB_blend_color_float(MutableSpan<float4> dst,
+ Span<float4> src1,
+ Span<float4> src2,
+ IMB_BlendMode mode);
+
+/**
+ * Copy a rectangle of pixel data from one image buffer to another. The source and destination
+ * buffers are described by the pointers and corresponding 2D sizes. They must not reference the
+ * same memory.
+ */
+void IMB_copy_rect(float *dst,
+ const int2 &dst_size,
+ const float *src,
+ const int2 &src_size,
+ int channels,
+ const int2 &src_rect_pos,
+ const int2 &dst_rect_pos,
+ const int2 &rect_size);
+void IMB_copy_rect(uchar *dst,
+ const int2 &dst_size,
+ const uchar *src,
+ const int2 &src_size,
+ const int2 &src_rect_pos,
+ const int2 &dst_rect_pos,
+ const int2 &rect_size);
+
+/**
+ * In-place image crop. `rect` is *inclusive*.
+ */
+void IMB_crop(ImBuf *ibuf, const int2 &rect_pos, const int2 &rect_size);
+
+/**
+ * Copy a rectangle of pixel data from one image buffer to another. Data outside of the destination
+ * rectangle is not written to.
+ */
+void IMB_copy_rect(ImBuf *dst,
+ const ImBuf *src,
+ const int2 &src_rect_pos,
+ const int2 &dst_rect_pos,
+ const int2 &rect_size);
+
+/**
+ * In-place size setting (caller must fill in buffer contents).
+ */
+void IMB_rect_size_set(ImBuf *ibuf, const uint size[2]);
+
+void IMB_rectclip(ImBuf *dbuf,
+ const ImBuf *sbuf,
+ int *destx,
+ int *desty,
+ int *srcx,
+ int *srcy,
+ int *width,
+ int *height);
+void IMB_rectblend(ImBuf *dbuf,
+ const ImBuf *obuf,
+ const ImBuf *sbuf,
+ unsigned short *dmask,
+ const unsigned short *curvemask,
+ const unsigned short *texmask,
+ float mask_max,
+ int destx,
+ int desty,
+ int origx,
+ int origy,
+ int srcx,
+ int srcy,
+ int width,
+ int height,
+ IMB_BlendMode mode,
+ bool accumulate);
+void IMB_rectblend_threaded(ImBuf *dbuf,
+ const ImBuf *obuf,
+ const ImBuf *sbuf,
+ unsigned short *dmask,
+ const unsigned short *curvemask,
+ const unsigned short *texmask,
+ float mask_max,
+ int destx,
+ int desty,
+ int origx,
+ int origy,
+ int srcx,
+ int srcy,
+ int width,
+ int height,
+ IMB_BlendMode mode,
+ bool accumulate);
+
+enum eIMBInterpolationFilterMode {
+ IMB_FILTER_NEAREST,
+ IMB_FILTER_BILINEAR,
+ IMB_FILTER_CUBIC_BSPLINE,
+ IMB_FILTER_CUBIC_MITCHELL,
+ IMB_FILTER_BOX,
+};
+
+#define FILTER_MASK_NULL 0
+#define FILTER_MASK_MARGIN 1
+#define FILTER_MASK_USED 2
+
+void IMB_mask_filter_extend(char *mask, int width, int height);
+void IMB_mask_clear(ImBuf *ibuf, const char *mask, int val);
+/**
+ * If alpha is zero, it checks surrounding pixels and averages color. sets new alphas to 1.0
+ * When a mask is given, the mask will be used instead of the alpha channel, where only
+ * pixels with a mask value of 0 will be written to, and only pixels with a mask value of 1
+ * will be used for the average. The mask will be set to one for the pixels which were written.
+ */
+void IMB_filter_extend(ImBuf *ibuf, char *mask, int filter);
+
+void IMB_filtery(ImBuf *ibuf);
+
+/** Interpolation filter used by `IMB_scale`. */
+enum class IMBScaleFilter {
+ /** No filtering (point sampling). This is fastest but lowest quality. */
+ Nearest,
+ /**
+ * Bilinear filter: each pixel in result image interpolates between 2x2 pixels of source image.
+ */
+ Bilinear,
+ /**
+ * Box filter. Behaves exactly like Bilinear when scaling up,
+ * better results when scaling down by more than 2x.
+ */
+ Box,
+};
+
+/**
+ * Scale/resize image to new dimensions.
+ * Return true if \a ibuf is modified.
+ */
+bool IMB_scale(ImBuf *ibuf, int2 new_size, IMBScaleFilter filter, bool threaded = true);
+inline bool IMB_scale(
+ ImBuf *ibuf, unsigned int newx, unsigned int newy, IMBScaleFilter filter, bool threaded = true)
+{
+ return IMB_scale(ibuf, int2(newx, newy), filter, threaded);
+}
+
+/**
+ * Scale/resize image to new dimensions, into a newly created result image.
+ * Metadata of input image (if any) is copied into the result image.
+ */
+ImBuf *IMB_scale_into_new(const ImBuf *ibuf,
+ int2 new_size,
+ IMBScaleFilter filter,
+ bool threaded = true);
+inline ImBuf *IMB_scale_into_new(const ImBuf *ibuf,
+ unsigned int newx,
+ unsigned int newy,
+ IMBScaleFilter filter,
+ bool threaded = true)
+{
+ return IMB_scale_into_new(ibuf, int2(newx, newy), filter, threaded);
+}
+
+/**
+ * Test if color-space conversions of pixels in buffer need to take into account alpha.
+ */
+bool IMB_alpha_affects_rgb(const ImBuf *ibuf);
+
+/**
+ * Create char buffer, color corrected if necessary, for ImBufs that lack one.
+ */
+void IMB_byte_from_float(ImBuf *ibuf);
+void IMB_float_from_byte_ex(ImBuf *dst, const ImBuf *src, const rcti *region_to_update);
+void IMB_float_from_byte(ImBuf *ibuf);
+/**
+ * No profile conversion.
+ */
+void IMB_color_to_bw(ImBuf *ibuf);
+void IMB_saturation(ImBuf *ibuf, float sat);
+
+/* Converting pixel buffers. */
+
+/**
+ * Float to byte pixels, output 4-channel RGBA.
+ */
+void IMB_buffer_byte_from_float(unsigned char *rect_to,
+ const float *rect_from,
+ int channels_from,
+ float dither,
+ int profile_to,
+ int profile_from,
+ bool predivide,
+ int width,
+ int height,
+ int stride_to,
+ int stride_from,
+ int start_y = 0);
+/**
+ * Float to byte pixels, output 4-channel RGBA.
+ */
+void IMB_buffer_byte_from_float_mask(unsigned char *rect_to,
+ const float *rect_from,
+ int channels_from,
+ float dither,
+ bool predivide,
+ int width,
+ int height,
+ int stride_to,
+ int stride_from,
+ char *mask);
+/**
+ * Byte to float pixels, input and output 4-channel RGBA.
+ */
+void IMB_buffer_float_from_byte(float *rect_to,
+ const unsigned char *rect_from,
+ int profile_to,
+ int profile_from,
+ bool predivide,
+ int width,
+ int height,
+ int stride_to,
+ int stride_from);
+/**
+ * Float to float pixels, output 4-channel RGBA.
+ */
+void IMB_buffer_float_from_float(float *rect_to,
+ const float *rect_from,
+ int channels_from,
+ int profile_to,
+ int profile_from,
+ bool predivide,
+ int width,
+ int height,
+ int stride_to,
+ int stride_from);
+void IMB_buffer_float_from_float_threaded(float *rect_to,
+ const float *rect_from,
+ int channels_from,
+ int profile_to,
+ int profile_from,
+ bool predivide,
+ int width,
+ int height,
+ int stride_to,
+ int stride_from);
+/**
+ * Float to float pixels, output 4-channel RGBA.
+ */
+void IMB_buffer_float_from_float_mask(float *rect_to,
+ const float *rect_from,
+ int channels_from,
+ int width,
+ int height,
+ int stride_to,
+ int stride_from,
+ char *mask);
+/**
+ * Byte to byte pixels, input and output 4-channel RGBA.
+ */
+void IMB_buffer_byte_from_byte(unsigned char *rect_to,
+ const unsigned char *rect_from,
+ int profile_to,
+ int profile_from,
+ bool predivide,
+ int width,
+ int height,
+ int stride_to,
+ int stride_from);
+
+void IMB_alpha_under_color_float(float *rect_float, int x, int y, float backcol[3]);
+void IMB_alpha_under_color_byte(unsigned char *rect, int x, int y, const float backcol[3]);
+
+void IMB_flipx(ImBuf *ibuf);
+void IMB_flipy(ImBuf *ibuf);
+
+/** Rotate by 90 degree increments. Returns true if the ImBuf is altered. */
+bool IMB_rotate_orthogonal(ImBuf *ibuf, int degrees);
+
+/* Pre-multiply alpha. */
+
+void IMB_premultiply_alpha(ImBuf *ibuf);
+void IMB_unpremultiply_alpha(ImBuf *ibuf);
+
+/**
+ * Replace pixels of entire image with solid color.
+ * \param drect: An image to be filled with color. It must be 4 channel image.
+ * \param col: RGBA color, which is assigned directly to both byte (via scaling) and float buffers.
+ */
+void IMB_rectfill(ImBuf *drect, const float col[4]);
+/**
+ * Blend pixels of image area with solid color.
+ *
+ * \param ibuf: an image to be filled with color. It must be 4 channel image.
+ * \param scene_linear_color: RGBA color in scene linear colorspace. For byte buffers, this is
+ * converted to the byte buffer colorspace.
+ * \param x1, y1, x2, y2: (x1, y1) defines starting point
+ * of the rectangular area to be filled, (x2, y2) is the end point. Note that values are allowed to
+ * be loosely ordered, which means that x2 is allowed to be lower than x1, as well as y2 is allowed
+ * to be lower than y1. No matter the order the area between x1 and x2, and y1 and y2 is filled.
+ * \param colorspace: color-space reference for display space.
+ */
+void IMB_rectfill_area(
+ ImBuf *ibuf, const float scene_linear_color[4], int x1, int y1, int x2, int y2);
+void IMB_rectfill_alpha(ImBuf *ibuf, float value);
+
+/**
+ * Exported for image tools in blender, to quickly allocate 32 bits rect.
+ */
+void *imb_alloc_pixels(unsigned int x,
+ unsigned int y,
+ unsigned int channels,
+ size_t typesize,
+ bool initialize_pixels,
+ const char *alloc_name);
+
+/**
+ * Allocate storage for byte type pixels.
+ * If the image already contains byte data storage, it is freed first.
+ */
+bool IMB_alloc_byte_pixels(ImBuf *ibuf, bool initialize_pixels = true);
+
+/**
+ * Deallocate image byte storage.
+ */
+void IMB_free_byte_pixels(ImBuf *ibuf);
+
+/**
+ * Allocate storage for float type pixels.
+ * If the image already contains float data storage, it is freed first.
+ */
+bool IMB_alloc_float_pixels(ImBuf *ibuf, unsigned int channels, bool initialize_pixels = true);
+/**
+ * Deallocate image float storage.
+ */
+void IMB_free_float_pixels(ImBuf *ibuf);
+
+/** Deallocate all CPU side data storage (byte, float, encoded). */
+void IMB_free_all_data(ImBuf *ibuf);
+
+/**
+ * Free the GPU textures of the given image buffer, leaving the CPU buffers unchanged.
+ * The ibuf can be nullptr, in which case the function does nothing.
+ */
+void IMB_free_gpu_textures(ImBuf *ibuf);
+
+/**
+ * \brief Transform modes to use for IMB_transform function.
+ *
+ * These are not flags as the combination of cropping and repeat can lead to different expectation.
+ */
+enum eIMBTransformMode {
+ /** \brief Do not crop or repeat. */
+ IMB_TRANSFORM_MODE_REGULAR = 0,
+ /** \brief Crop the source buffer. */
+ IMB_TRANSFORM_MODE_CROP_SRC = 1,
+ /** \brief Wrap repeat the source buffer. Only supported in with nearest filtering. */
+ IMB_TRANSFORM_MODE_WRAP_REPEAT = 2,
+};
+
+/**
+ * \brief Transform source image buffer onto destination image buffer using a transform matrix.
+ *
+ * \param src: Image buffer to read from.
+ * \param dst: Image buffer to write to. rect or rect_float must already be initialized.
+ * - dst buffer must be a 4 channel buffers.
+ * - Only one data type buffer will be used (rect_float has priority over rect)
+ * \param mode: Cropping/Wrap repeat effect to apply during transformation.
+ * \param filter: Interpolation to use during sampling.
+ * \param transform_matrix: Transformation matrix to use.
+ * The given matrix should transform between dst pixel space to src pixel space.
+ * One unit is one pixel.
+ * \param src_crop: Cropping region how to crop the source buffer. Should only be passed when mode
+ * is set to #IMB_TRANSFORM_MODE_CROP_SRC. For any other mode this should be empty.
+ *
+ * During transformation no data/color conversion will happens.
+ * When transforming between float images the number of channels of the source buffer may be
+ * between 1 and 4. When source buffer has one channel the data will be read as a gray scale value.
+ */
+void IMB_transform(const ImBuf *src,
+ ImBuf *dst,
+ eIMBTransformMode mode,
+ eIMBInterpolationFilterMode filter,
+ const float3x3 &transform_matrix,
+ const rctf *src_crop);
+
+/* Creates a GPU texture from the given image buffer and name. If use_high_bitdepth is true, float
+ * image buffers will be stored in full float textures, otherwise, they will be stored in half
+ * float textures. If use_premult is true, the image buffer data will be stored premultiplied. If
+ * limit_size is true, the texture will be scaled down to match the maximum size allowed by the
+ * U.glreslimit user preferences setting. */
+gpu::Texture *IMB_create_gpu_texture(const char *name,
+ ImBuf *ibuf,
+ bool use_high_bitdepth,
+ bool use_premult,
+ const bool limit_size);
+
+gpu::TextureFormat IMB_gpu_get_texture_format(const ImBuf *ibuf,
+ bool high_bitdepth,
+ bool use_grayscale);
+
+bool IMB_gpu_get_compressed_format(const ImBuf *ibuf, gpu::TextureFormat *r_texture_format);
+
+/**
+ * Ensures that values stored in the float rect can safely loaded into half float gpu textures.
+ *
+ * Does nothing when given image_buffer doesn't contain a float rect.
+ */
+void IMB_gpu_clamp_half_float(ImBuf *image_buffer);
+
+/**
+ * The `ibuf` is only here to detect the storage type. The produced texture will have undefined
+ * content. It will need to be populated by using #IMB_update_gpu_texture_sub().
+ */
+gpu::Texture *IMB_touch_gpu_texture(const char *name,
+ ImBuf *ibuf,
+ int w,
+ int h,
+ int layers,
+ bool use_high_bitdepth,
+ bool use_grayscale);
+
+/**
+ * Will update a #gpu::Texture using the content of the #ImBuf. Only one layer will be
+ * updated. Will resize the ibuf if needed. Z is the layer to update. Unused if the texture is 2D.
+ */
+void IMB_update_gpu_texture_sub(gpu::Texture *tex,
+ ImBuf *ibuf,
+ int x,
+ int y,
+ int z,
+ int w,
+ int h,
+ bool use_high_bitdepth,
+ bool use_grayscale,
+ bool use_premult);
+
+void IMB_stereo3d_write_dimensions(
+ char mode, bool is_squeezed, size_t width, size_t height, size_t *r_width, size_t *r_height);
+void IMB_stereo3d_read_dimensions(
+ char mode, bool is_squeezed, size_t width, size_t height, size_t *r_width, size_t *r_height);
+/**
+ * Left/right are always float.
+ */
+ImBuf *IMB_stereo3d_ImBuf(const ImageFormatData *im_format, ImBuf *ibuf_left, ImBuf *ibuf_right);
+/**
+ * Reading a stereo encoded ibuf (*left) and generating two ibufs from it (*left and *right).
+ */
+void IMB_ImBufFromStereo3d(const Stereo3dFormat *s3d,
+ ImBuf *ibuf_stereo3d,
+ ImBuf **r_ibuf_left,
+ ImBuf **r_ibuf_right);
+
+} // namespace blender
+
diff --git a/compat/include/IMB_imbuf_enums.h b/compat/include/IMB_imbuf_enums.h
new file mode 100644
index 0000000..c425497
--- /dev/null
+++ b/compat/include/IMB_imbuf_enums.h
@@ -0,0 +1,64 @@
+/* SPDX-FileCopyrightText: 2024 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+#include "BLI_enum_flags.hh"
+
+/** \file
+ * \ingroup imbuf
+ */
+
+namespace blender {
+
+#define IM_MAX_SPACE 64
+
+/** #ImBuf.ftype: main image types. */
+enum eImbFileType : int8_t {
+ IMB_FTYPE_NONE = 0,
+ IMB_FTYPE_PNG = 1,
+ IMB_FTYPE_TGA = 2,
+ IMB_FTYPE_JPG = 3,
+ IMB_FTYPE_BMP = 4,
+ IMB_FTYPE_OPENEXR = 5,
+ IMB_FTYPE_IRIS = 6,
+ IMB_FTYPE_PSD = 7,
+#ifdef WITH_IMAGE_OPENJPEG
+ IMB_FTYPE_JP2 = 8,
+#endif
+ IMB_FTYPE_RADHDR = 9,
+ IMB_FTYPE_TIF = 10,
+#ifdef WITH_IMAGE_CINEON
+ IMB_FTYPE_CINEON = 11,
+ IMB_FTYPE_DPX = 12,
+#endif
+
+ IMB_FTYPE_DDS = 13,
+#ifdef WITH_IMAGE_WEBP
+ IMB_FTYPE_WEBP = 14,
+#endif
+ IMB_FTYPE_AVIF = 15,
+};
+#define IMB_FTYPE_LAST IMB_FTYPE_AVIF
+
+/** Flags for #ImFileType.capability_read and #ImFileType.capability_write. */
+enum class eImFileTypeCapability : uint8_t {
+ Zero = 0,
+ File = (1 << 0),
+ Memory = (1 << 1),
+};
+ENUM_OPERATORS(eImFileTypeCapability);
+
+/** NOTE: Keep in sync with #MovieClipProxy.build_size_flag */
+enum IMB_Proxy_Size {
+ IMB_PROXY_NONE = 0,
+ IMB_PROXY_25 = 1,
+ IMB_PROXY_50 = 2,
+ IMB_PROXY_75 = 4,
+ IMB_PROXY_100 = 8,
+ IMB_PROXY_MAX_SLOT = 4,
+};
+ENUM_OPERATORS(IMB_Proxy_Size);
+
+} // namespace blender
diff --git a/compat/include/IMB_imbuf_types.hh b/compat/include/IMB_imbuf_types.hh
new file mode 100644
index 0000000..c3ea6f5
--- /dev/null
+++ b/compat/include/IMB_imbuf_types.hh
@@ -0,0 +1,407 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ * SPDX-FileCopyrightText: 2025 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup imbuf
+ *
+ * Image buffer types.
+ */
+
+#include "DNA_vec_types.h" /* for rcti */
+
+#include "IMB_imbuf_enums.h"
+
+#include <string>
+
+namespace blender {
+
+struct ColormanageCache;
+struct ExrHandle;
+namespace gpu {
+class Texture;
+}
+struct IDProperty;
+
+namespace ocio {
+class ColorSpace;
+}
+using ColorSpace = ocio::ColorSpace;
+
+/**
+ * \ingroup imbuf
+ * This is the abstraction of an image. ImBuf is the basic type used for all imbuf operations.
+ *
+ * Also; add new variables to the end to save pain!
+ */
+
+/**
+ * #ImBuf::foptions.flag, type specific options.
+ * Some formats include compression rations on some bits.
+ */
+
+#define OPENEXR_HALF (1 << 8)
+#define OPENEXR_MULTIPART (1 << 9)
+/* Lowest bits of foptions.flag / exr_codec contain actual codec enum. */
+#define OPENEXR_CODEC_MASK (0xF)
+
+#ifdef WITH_IMAGE_CINEON
+# define CINEON_LOG (1 << 8)
+# define CINEON_16BIT (1 << 7)
+# define CINEON_12BIT (1 << 6)
+# define CINEON_10BIT (1 << 5)
+#endif
+
+#ifdef WITH_IMAGE_OPENJPEG
+# define JP2_12BIT (1 << 9)
+# define JP2_16BIT (1 << 8)
+# define JP2_YCC (1 << 7)
+# define JP2_CINE (1 << 6)
+# define JP2_CINE_48FPS (1 << 5)
+# define JP2_JP2 (1 << 4)
+# define JP2_J2K (1 << 3)
+#endif
+
+#define PNG_16BIT (1 << 10)
+
+#define RAWTGA 1
+
+#define TIF_16BIT (1 << 8)
+#define TIF_COMPRESS_NONE (1 << 7)
+#define TIF_COMPRESS_DEFLATE (1 << 6)
+#define TIF_COMPRESS_LZW (1 << 5)
+#define TIF_COMPRESS_PACKBITS (1 << 4)
+
+#define AVIF_10BIT (1 << 8)
+#define AVIF_12BIT (1 << 9)
+
+struct ImbFormatOptions {
+ short flag = 0;
+ /** Quality for JPEG, WebP, AVIF. */
+ char quality = 90;
+ /* Compression amount for PNG.
+ * Default to low compression ratio that is not time consuming. */
+ char compress = 15;
+};
+
+/* -------------------------------------------------------------------- */
+/** \name ImBuf Component flags
+ * \brief These flags determine the components of an ImBuf struct.
+ * \{ */
+
+enum eImBufFlags {
+ /** Image has byte data (unsigned 0..1 range in a byte, always 4 channels). */
+ IB_byte_data = 1 << 0,
+ IB_test = 1 << 1,
+ IB_mem = 1 << 4,
+ /** Image has float data (usually 1..4 channels, 32 bit float per channel). */
+ IB_float_data = 1 << 5,
+ IB_multilayer = 1 << 7,
+ IB_metadata = 1 << 8,
+ IB_animdeinterlace = 1 << 9,
+ /** Do not clear image pixel buffer to zero. Without this flag, allocating
+ * a new ImBuf does clear the pixel data to zero (transparent black). If
+ * whole pixel data is overwritten after allocation, then this flag can be
+ * faster since it avoids a memory clear. */
+ IB_uninitialized_pixels = 1 << 10,
+
+ /** Indicates whether image on disk have pre-multiplied alpha. */
+ IB_alphamode_premul = 1 << 12,
+ /** If this flag is set, alpha mode would be guessed from file. */
+ IB_alphamode_detect = 1 << 13,
+ /** Alpha channel is unrelated to RGB and should not affect it. */
+ IB_alphamode_channel_packed = 1 << 14,
+ /** Ignore alpha on load and substitute it with 1.0f. */
+ IB_alphamode_ignore = 1 << 15,
+ IB_thumbnail = 1 << 16,
+ /**
+ * The image contains display window information. See ImbBuf.display_size and other members for
+ * more information. */
+ IB_has_display_window = 1 << 17,
+
+ /** Perform no color space conversions when reading, leave the image in the file colorspace. */
+ IB_no_colorspace_convert = 1 << 18,
+};
+ENUM_OPERATORS(eImBufFlags);
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name ImBuf buffer storage
+ * \{ */
+
+/**
+ * Specialization of an ownership whenever a bare pointer is provided to the ImBuf buffers
+ * assignment API.
+ */
+enum ImBufOwnership {
+ /**
+ * The ImBuf simply shares pointer with data owned by someone else, and will not perform any
+ * memory management when the ImBuf frees the buffer.
+ */
+ IB_DO_NOT_TAKE_OWNERSHIP = 0,
+
+ /**
+ * The ImBuf takes ownership of the buffer data, and will use MEM_delete() to free this memory
+ * when the ImBuf needs to free the data.
+ */
+ IB_TAKE_OWNERSHIP = 1,
+};
+
+struct DDSData {
+ /** DDS fourcc info */
+ unsigned int fourcc = 0;
+ /** The number of mipmaps in the dds file */
+ unsigned int nummipmaps = 0;
+ /** The compressed image data */
+ unsigned char *data = nullptr;
+ /** The size of the compressed data */
+ unsigned int size = 0;
+ /** Who owns the data buffer. */
+ ImBufOwnership ownership = IB_DO_NOT_TAKE_OWNERSHIP;
+};
+
+/* Different storage specialization.
+ *
+ * NOTE: Avoid direct access. Use the buffer utilities from the IMB_imbuf.hh instead
+ */
+
+struct ImBufByteBuffer {
+ uint8_t *data = nullptr;
+ ImBufOwnership ownership = IB_DO_NOT_TAKE_OWNERSHIP;
+
+ const ColorSpace *colorspace = nullptr;
+};
+
+struct ImBufFloatBuffer {
+ float *data = nullptr;
+ ImBufOwnership ownership = IB_DO_NOT_TAKE_OWNERSHIP;
+
+ const ColorSpace *colorspace = nullptr;
+};
+
+struct ImBufGPU {
+ /**
+ * Texture which corresponds to the state of the ImBug on the GPU.
+ *
+ * Allocation is supposed to happen outside of the ImBug module from a proper GPU context.
+ * De-referencing the ImBuf or its GPU texture can happen from any state.
+ *
+ * TODO(@sergey): This should become a list of textures, to support having high-res ImBuf on GPU
+ * without hitting hardware limitations.
+ */
+ gpu::Texture *texture = nullptr;
+};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Image Buffer
+ * \{ */
+
+struct ImBuf {
+ /* dimensions */
+ /** Width and Height of our image buffer.
+ * Should be 'unsigned int' since most formats use this.
+ * but this is problematic with texture math in `imagetexture.c`
+ * avoid problems and use int. - campbell */
+ int x = 0;
+ int y = 0;
+
+ /**
+ * Stores the Data and Display Window information. Those are only initialized if the image buffer
+ * has the IB_has_display_window flag active, otherwise, they should be ignored as the image has
+ * no display window.
+ *
+ * The data size is already stored in the x and y members. The data_offset member stores the
+ * offset from the display window to the data window, if positive, then only part of the display
+ * window has data, while if negative, it means the image has over-scan.
+ * The display_offset member is the offset from the origin,
+ * can can be interpreted as a global translation.
+ */
+ int display_size[2];
+ int data_offset[2];
+ int display_offset[2];
+
+ /** Active amount of bits/bit-planes. */
+ unsigned char planes = 0;
+ /** Number of channels in `rect_float` (0 = 4 channel default) */
+ int channels = 0;
+
+ /* flags */
+ /** Controls which components should exist. */
+ int flags = 0;
+
+ /* pixels */
+
+ /**
+ * Image pixel buffer (8bit representation):
+ * - color space defaults to `sRGB`.
+ * - alpha defaults to 'straight'.
+ */
+ ImBufByteBuffer byte_buffer;
+
+ /**
+ * Image pixel buffer (float representation):
+ * - color space defaults to 'linear' (`rec709`).
+ * - alpha defaults to 'premul'.
+ * \note May need gamma correction to `sRGB` when generating 8bit representations.
+ * \note Formats that support higher more than 8 but channels load as floats.
+ */
+ ImBufFloatBuffer float_buffer;
+
+ /** Image buffer on the GPU. */
+ ImBufGPU gpu;
+
+ /** Resolution in pixels per meter. Multiply by `0.0254` for DPI. */
+ double ppm[2] = {0.0, 0.0};
+
+ /** Amount of dithering to apply, when converting float -> byte. */
+ float dither = 0.0f;
+
+ /* externally used data */
+ /** reference index for ImBuf lists */
+ int index = 0;
+ /** used to set imbuf to dirty and other stuff */
+ int userflags = 0;
+ /** image metadata */
+ IDProperty *metadata = nullptr;
+ /** OpenEXR handle. */
+ ExrHandle *exrhandle = nullptr;
+
+ /* file information */
+ /** file type we are going to save as */
+ eImbFileType ftype = IMB_FTYPE_NONE;
+ /** file format specific flags */
+ ImbFormatOptions foptions;
+ /** The absolute file path associated with this image. */
+ std::string filepath;
+ /** For movie files, the frame number loaded from the file. */
+ int fileframe = 0;
+
+ /** reference counter for multiple users */
+ int32_t refcounter = 0;
+
+ /* some parameters to pass along for packing images */
+ /** Compressed image only used with PNG and EXR currently. */
+ ImBufByteBuffer encoded_buffer;
+ /** Size of data written to `encoded_buffer`. */
+ unsigned int encoded_size = 0;
+ /** Size of `encoded_buffer` */
+ unsigned int encoded_buffer_size = 0;
+
+ /* color management */
+ /** array of per-display display buffers dirty flags */
+ unsigned int *display_buffer_flags = nullptr;
+ /** cache used by color management */
+ ColormanageCache *colormanage_cache = nullptr;
+ int colormanage_flag = 0;
+ rcti invalid_rect;
+
+ /** Information for compressed textures. */
+ DDSData dds_data;
+
+ const uint8_t *byte_data() const;
+ uint8_t *byte_data_for_write();
+
+ const float *float_data() const;
+ float *float_data_for_write();
+};
+
+/**
+ * \brief userflags: Flags used internally by blender for image-buffers.
+ */
+enum {
+ /** image needs to be saved is not the same as filename */
+ IB_BITMAPDIRTY = (1 << 1),
+ /** float buffer changed, needs recreation of byte rect */
+ IB_RECT_INVALID = (1 << 3),
+ /** either float or byte buffer changed, need to re-calculate display buffers */
+ IB_DISPLAY_BUFFER_INVALID = (1 << 4),
+ /** image buffer is persistent in the memory and should never be removed from the cache */
+ IB_PERSISTENT = (1 << 5),
+ /** The image buffer is backed by a GPU texture storage but the host buffers either do not exist
+ * or are out-dated and needs to read from the GPU texture. */
+ IB_HOST_BUFFER_INVALID = (1 << 6),
+};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name ImBuf Preset Profile Tags
+ *
+ * \brief Some predefined color space profiles that 8 bit imbufs can represent.
+ * \{ */
+
+#define IB_PROFILE_NONE 0
+#define IB_PROFILE_LINEAR_RGB 1
+#define IB_PROFILE_SRGB 2
+#define IB_PROFILE_CUSTOM 3
+
+/** \} */
+
+/* dds */
+#ifndef DDS_MAKEFOURCC
+# define DDS_MAKEFOURCC(ch0, ch1, ch2, ch3) \
+ ((unsigned long)(unsigned char)(ch0) | ((unsigned long)(unsigned char)(ch1) << 8) | \
+ ((unsigned long)(unsigned char)(ch2) << 16) | ((unsigned long)(unsigned char)(ch3) << 24))
+#endif /* DDS_MAKEFOURCC */
+
+/*
+ * FOURCC codes for DX compressed-texture pixel formats.
+ */
+
+#define FOURCC_DDS (DDS_MAKEFOURCC('D', 'D', 'S', ' '))
+#define FOURCC_DX10 (DDS_MAKEFOURCC('D', 'X', '1', '0'))
+#define FOURCC_DXT1 (DDS_MAKEFOURCC('D', 'X', 'T', '1'))
+#define FOURCC_DXT2 (DDS_MAKEFOURCC('D', 'X', 'T', '2'))
+#define FOURCC_DXT3 (DDS_MAKEFOURCC('D', 'X', 'T', '3'))
+#define FOURCC_DXT4 (DDS_MAKEFOURCC('D', 'X', 'T', '4'))
+#define FOURCC_DXT5 (DDS_MAKEFOURCC('D', 'X', 'T', '5'))
+
+/**
+ * Known image extensions, in most cases these match values
+ * for images which Blender creates, there are some exceptions to this.
+ *
+ * See #BKE_image_path_ext_from_imformat which also stores known extensions.
+ */
+extern const char *imb_ext_image[];
+extern const char *imb_ext_movie[];
+extern const char *imb_ext_audio[];
+
+/* -------------------------------------------------------------------- */
+/** \name ImBuf Color Management Flag
+ *
+ * \brief Used with #ImBuf.colormanage_flag
+ * \{ */
+
+enum {
+ IMB_COLORMANAGE_IS_DATA = (1 << 0),
+};
+
+/** \} */
+
+inline const uint8_t *ImBuf::byte_data() const
+{
+ return this->byte_buffer.data;
+}
+
+inline uint8_t *ImBuf::byte_data_for_write()
+{
+ return this->byte_buffer.data;
+}
+
+inline const float *ImBuf::float_data() const
+{
+ return this->float_buffer.data;
+}
+
+inline float *ImBuf::float_data_for_write()
+{
+ return this->float_buffer.data;
+}
+
+} // namespace blender
diff --git a/compat/include/OCIO_scope.hh b/compat/include/OCIO_scope.hh
new file mode 100644
index 0000000..e20a341
--- /dev/null
+++ b/compat/include/OCIO_scope.hh
@@ -0,0 +1,46 @@
+/* SPDX-FileCopyrightText: 2026 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+#include "BLI_math_matrix_types.hh"
+#include "BLI_math_vector_types.hh"
+#include "BLI_vector.hh"
+
+namespace blender::ocio {
+
+/**
+ * Grid line for waveform/parade scopes: a display code value with a
+ * pre-formatted label string.
+ */
+struct ScopeGraticule {
+ float value = 0.0f;
+ char label[16] = "";
+};
+
+/**
+ * Information for drawing scopes (waveform/parade/vectorscope).
+ */
+struct ScopeInfo {
+ /** Graticules. */
+ Vector<ScopeGraticule> graticules;
+ /** Display code value corresponding to 100 nits (SDR reference white).
+ * 1.0 for SDR displays, less than 1.0 for HDR displays. */
+ float sdr_white_level = 1.0f;
+ /** Max luminance in nits from the view transform, 0 if unknown. */
+ int view_transform_max_nits = 0;
+ /** Display code value corresponding to #view_transform_max_nits. */
+ float view_transform_max_nits_value = 1.0f;
+
+ /** Is the scope HDR? */
+ bool is_hdr = false;
+ /** Gamut mapping from scope display space to Rec.709 linear. */
+ blender::float3x3 scope_gamut_to_rec709 = blender::float3x3::identity();
+ /** Luminance coefficients to use for scope evaluation (default Rec.709). */
+ blender::float3 luma_coefficients = blender::float3(0.2126f, 0.7152f, 0.0722f);
+ /** RGB to YCbCr matrix for the vectorscope. */
+ blender::float3x3 yuv_matrix = blender::float3x3::identity();
+};
+
+} // namespace blender::ocio
diff --git a/compat/include/OCIO_view.hh b/compat/include/OCIO_view.hh
new file mode 100644
index 0000000..801f271
--- /dev/null
+++ b/compat/include/OCIO_view.hh
@@ -0,0 +1,3 @@
+/* BUI seam: minimal stand-in. SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
diff --git a/compat/include/RNA_define.hh b/compat/include/RNA_define.hh
new file mode 100644
index 0000000..faa56a8
--- /dev/null
+++ b/compat/include/RNA_define.hh
@@ -0,0 +1,751 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup RNA
+ *
+ * Functions used during preprocess and runtime, for defining the RNA.
+ */
+
+#include <float.h>
+#include <inttypes.h>
+#include <limits.h>
+
+#include "DNA_listBase.h"
+
+#include "RNA_types.hh"
+
+namespace blender {
+
+#ifdef UNIT_TEST
+# define RNA_MAX_ARRAY_LENGTH 64
+#else
+# define RNA_MAX_ARRAY_LENGTH 64
+#endif
+
+#define RNA_MAX_ARRAY_DIMENSION 3
+
+/* Blender RNA */
+
+struct Scene;
+
+BlenderRNA *RNA_create();
+/**
+ * Create a container for RNA types that are defined at runtime (in contrast to the main global
+ * #BlenderRNA which contains RNA types defined at startup from static data).
+ */
+BlenderRNA *RNA_create_runtime();
+void RNA_define_free(BlenderRNA *brna);
+void RNA_free(BlenderRNA *brna);
+
+/**
+ * Tell the RNA maker to check whether the property exists in the matching DNA structure,
+ *
+ * When in DNA, RNA generates automatically the accessors code. Otherwise, you
+ * have to give it explicit getters/setters/etc. By default, the RNA maker will
+ * error if it cannot find the corresponding DNA properties; this is what can be
+ * turned off with this function.
+ *
+ * This is used to generate RNA structs that do not (directly) match any DNA
+ * data, passing `false` as parameter at the beginning of the struct definition,
+ * and then calling it again at the end with `true` to restore default 'check
+ * DNA' behavior.
+ */
+void RNA_define_verify_sdna(bool verify);
+void RNA_define_animate_sdna(bool animate);
+void RNA_define_fallback_property_update(int noteflag, const char *updatefunc);
+/**
+ * Properties defined when this is enabled are lib-overridable by default
+ * (except for Pointer ones).
+ */
+void RNA_define_lib_overridable(bool make_overridable);
+
+void RNA_init();
+void RNA_bpy_exit();
+void RNA_exit();
+
+/* Struct */
+
+/**
+ * Struct Definition.
+ */
+StructRNA *RNA_def_struct_ptr(BlenderRNA *brna, const char *identifier, StructRNA *srnafrom);
+StructRNA *RNA_def_struct(BlenderRNA *brna, const char *identifier, const char *from);
+void RNA_def_struct_sdna(StructRNA *srna, const char *structname);
+void RNA_def_struct_sdna_from(StructRNA *srna, const char *structname, const char *propname);
+/**
+ * Define the struct's String property used to retrieve the name of a PointerRNA of that type.
+ * Used e.g. in several UI widget displaying content of RNA collections.
+ *
+ * \param allow_replace If true, allow replacing an already defined struct name property.
+ */
+void RNA_def_struct_name_property(StructRNA *srna, PropertyRNA *prop, bool allow_replace = false);
+void RNA_def_struct_nested(BlenderRNA *brna, StructRNA *srna, const char *structname);
+void RNA_def_struct_flag(StructRNA *srna, int flag);
+void RNA_def_struct_clear_flag(StructRNA *srna, int flag);
+void RNA_def_struct_property_tags(StructRNA *srna, const EnumPropertyItem *prop_tag_defines);
+void RNA_def_struct_refine_func(StructRNA *srna, const char *refine);
+void RNA_def_struct_idprops_func(StructRNA *srna, const char *idproperties);
+/**
+ * Define the callback to access the struct's system IDProperty root.
+ */
+void RNA_def_struct_system_idprops_func(StructRNA *srna, const char *system_idproperties);
+void RNA_def_struct_register_funcs(StructRNA *srna,
+ const char *reg,
+ const char *unreg,
+ const char *instance);
+/**
+ * Return an allocated string for the RNA data-path:
+ *
+ * - Double quotes must be used for string access, e.g: `collection["%s"]`.
+ * - Strings containing arbitrary characters must be escaped using #BLI_str_escape.
+ *
+ * Paths must be compatible with #RNA_path_resolve & related functions.
+ */
+void RNA_def_struct_path_func(StructRNA *srna, const char *path);
+void RNA_def_struct_path_func_runtime(StructRNA *srna, StructPathFunc path_fn);
+/**
+ * Only used in one case when we name the struct for the purpose of useful error messages.
+ */
+void RNA_def_struct_identifier_no_struct_map(StructRNA *srna, const char *identifier);
+void RNA_def_struct_identifier(BlenderRNA *brna, StructRNA *srna, const char *identifier);
+void RNA_def_struct_ui_text(StructRNA *srna, const char *name, const char *description);
+void RNA_def_struct_ui_icon(StructRNA *srna, int icon);
+void RNA_struct_free_extension(StructRNA *srna, ExtensionRNA *rna_ext);
+void RNA_struct_free(BlenderRNA *brna, StructRNA *srna);
+
+void RNA_def_struct_translation_context(StructRNA *srna, const char *context);
+
+/* Compact Property Definitions */
+
+typedef void StructOrFunctionRNA;
+
+PropertyRNA *RNA_def_boolean(StructOrFunctionRNA *cont,
+ const char *identifier,
+ bool default_value,
+ const char *ui_name,
+ const char *ui_description);
+PropertyRNA *RNA_def_boolean_array(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int len,
+ const bool *default_value,
+ const char *ui_name,
+ const char *ui_description);
+PropertyRNA *RNA_def_boolean_layer(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int len,
+ const bool *default_value,
+ const char *ui_name,
+ const char *ui_description);
+PropertyRNA *RNA_def_boolean_layer_member(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int len,
+ const bool *default_value,
+ const char *ui_name,
+ const char *ui_description);
+PropertyRNA *RNA_def_boolean_vector(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int len,
+ const bool *default_value,
+ const char *ui_name,
+ const char *ui_description);
+
+PropertyRNA *RNA_def_int(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int default_value,
+ int hardmin,
+ int hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ int softmin,
+ int softmax);
+PropertyRNA *RNA_def_int_vector(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int len,
+ const int *default_value,
+ int hardmin,
+ int hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ int softmin,
+ int softmax);
+PropertyRNA *RNA_def_int_array(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int len,
+ const int *default_value,
+ int hardmin,
+ int hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ int softmin,
+ int softmax);
+
+PropertyRNA *RNA_def_string(StructOrFunctionRNA *cont,
+ const char *identifier,
+ const char *default_value,
+ int maxlen,
+ const char *ui_name,
+ const char *ui_description);
+PropertyRNA *RNA_def_string_file_path(StructOrFunctionRNA *cont,
+ const char *identifier,
+ const char *default_value,
+ int maxlen,
+ const char *ui_name,
+ const char *ui_description);
+PropertyRNA *RNA_def_string_dir_path(StructOrFunctionRNA *cont,
+ const char *identifier,
+ const char *default_value,
+ int maxlen,
+ const char *ui_name,
+ const char *ui_description);
+PropertyRNA *RNA_def_string_file_name(StructOrFunctionRNA *cont,
+ const char *identifier,
+ const char *default_value,
+ int maxlen,
+ const char *ui_name,
+ const char *ui_description);
+
+PropertyRNA *RNA_def_enum(StructOrFunctionRNA *cont,
+ const char *identifier,
+ const EnumPropertyItem *items,
+ int default_value,
+ const char *ui_name,
+ const char *ui_description);
+/**
+ * Same as #RNA_def_enum but sets #PROP_ENUM_FLAG before setting the default value.
+ */
+PropertyRNA *RNA_def_enum_flag(StructOrFunctionRNA *cont,
+ const char *identifier,
+ const EnumPropertyItem *items,
+ int default_value,
+ const char *ui_name,
+ const char *ui_description);
+void RNA_def_enum_funcs(PropertyRNA *prop, EnumPropertyItemFunc itemfunc);
+
+PropertyRNA *RNA_def_float(StructOrFunctionRNA *cont,
+ const char *identifier,
+ float default_value,
+ float hardmin,
+ float hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ float softmin,
+ float softmax);
+PropertyRNA *RNA_def_float_vector(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int len,
+ const float *default_value,
+ float hardmin,
+ float hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ float softmin,
+ float softmax);
+PropertyRNA *RNA_def_float_vector_xyz(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int len,
+ const float *default_value,
+ float hardmin,
+ float hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ float softmin,
+ float softmax);
+PropertyRNA *RNA_def_float_color(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int len,
+ const float *default_value,
+ float hardmin,
+ float hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ float softmin,
+ float softmax);
+PropertyRNA *RNA_def_float_matrix(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int rows,
+ int columns,
+ const float *default_value,
+ float hardmin,
+ float hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ float softmin,
+ float softmax);
+PropertyRNA *RNA_def_float_translation(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int len,
+ const float *default_value,
+ float hardmin,
+ float hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ float softmin,
+ float softmax);
+PropertyRNA *RNA_def_float_rotation(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int len,
+ const float *default_value,
+ float hardmin,
+ float hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ float softmin,
+ float softmax);
+PropertyRNA *RNA_def_float_distance(StructOrFunctionRNA *cont,
+ const char *identifier,
+ float default_value,
+ float hardmin,
+ float hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ float softmin,
+ float softmax);
+PropertyRNA *RNA_def_float_array(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int len,
+ const float *default_value,
+ float hardmin,
+ float hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ float softmin,
+ float softmax);
+
+#if 0
+PropertyRNA *RNA_def_float_dynamic_array(StructOrFunctionRNA *cont,
+ const char *identifier,
+ float hardmin,
+ float hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ float softmin,
+ float softmax,
+ unsigned int dimension,
+ unsigned short dim_size[]);
+#endif
+
+PropertyRNA *RNA_def_float_percentage(StructOrFunctionRNA *cont,
+ const char *identifier,
+ float default_value,
+ float hardmin,
+ float hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ float softmin,
+ float softmax);
+PropertyRNA *RNA_def_float_factor(StructOrFunctionRNA *cont,
+ const char *identifier,
+ float default_value,
+ float hardmin,
+ float hardmax,
+ const char *ui_name,
+ const char *ui_description,
+ float softmin,
+ float softmax);
+
+PropertyRNA *RNA_def_pointer(StructOrFunctionRNA *cont,
+ const char *identifier,
+ const char *type,
+ const char *ui_name,
+ const char *ui_description);
+PropertyRNA *RNA_def_pointer_runtime(StructOrFunctionRNA *cont,
+ const char *identifier,
+ StructRNA *type,
+ const char *ui_name,
+ const char *ui_description);
+
+PropertyRNA *RNA_def_collection(StructOrFunctionRNA *cont,
+ const char *identifier,
+ const char *type,
+ const char *ui_name,
+ const char *ui_description);
+PropertyRNA *RNA_def_collection_runtime(StructOrFunctionRNA *cont,
+ const char *identifier,
+ StructRNA *type,
+ const char *ui_name,
+ const char *ui_description);
+
+/* Extended Property Definitions */
+
+PropertyRNA *RNA_def_property(StructOrFunctionRNA *cont,
+ const char *identifier,
+ int type,
+ int subtype);
+
+/**
+ * Define a boolean property controlling one or more bitflags in the DNA member.
+ *
+ * \note This can be combined to a call to #RNA_def_property_array on the same property, in case
+ * the wrapped DNA member is an array of integers. Do not confuse it with defining a RNA boolean
+ * array property using a single DNA member as a bitset (use
+ * #RNA_def_property_boolean_bitset_array_sdna for this).
+ */
+void RNA_def_property_boolean_sdna(PropertyRNA *prop,
+ const char *structname,
+ const char *propname,
+ int64_t booleanbit);
+void RNA_def_property_boolean_negative_sdna(PropertyRNA *prop,
+ const char *structname,
+ const char *propname,
+ int64_t booleanbit);
+/**
+ * Used to define an array of boolean values using a single int/char/etc. member of a DNA struct
+ * (aka 'bitset array').
+ *
+ * The #booleanbit value should strictly have a single bit enabled (so typically come from a
+ * bit-shift expression like `1 << 0`), and be strictly positive (i.e. the left-most bit in the
+ * valid range should not be used). Multi-bit values are not valid. It will be used as first bit
+ * for the `0`-indexed item of the array.
+ *
+ * The maximum #len depends on the type of the DNA member, and the #booleanbit value. The left-most
+ * bit is not usable (because bit-shift operations over signed negative values are typically
+ * 'arithmetic', and not 'bitwise', in C++). So e.g. `31` for an `int32_t` with a `booleanbit`
+ * value of `1 << 0`, and so on.
+ */
+void RNA_def_property_boolean_bitset_array_sdna(
+ PropertyRNA *prop, const char *structname, const char *propname, int64_t booleanbit, int len);
+void RNA_def_property_int_sdna(PropertyRNA *prop, const char *structname, const char *propname);
+void RNA_def_property_float_sdna(PropertyRNA *prop, const char *structname, const char *propname);
+void RNA_def_property_string_sdna(PropertyRNA *prop, const char *structname, const char *propname);
+/**
+ * Define a regular, non-bitflags-aware enum property.
+ *
+ * The key aspect of using this call is that when setting the property, the whole underlying DNA
+ * property will be overwritten.
+ *
+ * This should typically be used for:
+ * - Non-bitflags enums.
+ * - Bitflags enums using a callback function to define their items.
+ *
+ * \note This behavior is the only one available for runtime-defined enum properties. C++-defined
+ * runtime properties can work around this limitation by defining their own setter to handle the
+ * bitmasking.
+ *
+ * \note This is not related to the #PROP_ENUM_FLAG property option.
+ */
+void RNA_def_property_enum_sdna(PropertyRNA *prop, const char *structname, const char *propname);
+/**
+ * Define a bitflags-aware enum property.
+ *
+ * The key aspect of using this call is that when setting the property, a bitmask is used to avoid
+ * overwriting unrelated bits in the underlying DNA property.
+ *
+ * The bitmask is computed from the values defined in the static 'items' array defined by
+ * `RNA_def_property_enum_items`, so it won't be valid in case an `items` callback function is
+ * defined, that may use bitflags outside of that statically computed bitmask.
+ *
+ * This should typically be used for bitflags enums. It is especially critical when several
+ * bitflags enums and/or bitflag booleans (defined with `RNA_def_property_boolean_sdna` or
+ * `RNA_def_property_boolean_negative_sdna`) share the same DNA variable. Otherwise, setting one
+ * RNA property may affect unrelated bitflags.
+ *
+ * \note This is not related to the #PROP_ENUM_FLAG property option.
+ */
+void RNA_def_property_enum_bitflag_sdna(PropertyRNA *prop,
+ const char *structname,
+ const char *propname);
+void RNA_def_property_pointer_sdna(PropertyRNA *prop,
+ const char *structname,
+ const char *propname);
+void RNA_def_property_collection_sdna(PropertyRNA *prop,
+ const char *structname,
+ const char *propname,
+ const char *lengthpropname);
+
+void RNA_def_property_flag(PropertyRNA *prop, PropertyFlag flag);
+void RNA_def_property_clear_flag(PropertyRNA *prop, PropertyFlag flag);
+void RNA_def_property_override_flag(PropertyRNA *prop, PropertyOverrideFlag flag);
+void RNA_def_property_override_clear_flag(PropertyRNA *prop, PropertyOverrideFlag flag);
+
+/**
+ * In some cases showing properties in the outliner crashes.
+ * It's a bug that occurs when accessing a value re-allocates
+ * memory which may already be referenced by other RNA.
+ * See: #145877.
+ */
+void RNA_def_property_flag_hide_from_ui_workaround(PropertyRNA *prop);
+
+/**
+ * Add the property-tags passed as \a tags to \a prop (if valid).
+ *
+ * \note Multiple tags can be set by passing them within \a tags (using bit-flags).
+ * \note Doesn't do any type-checking with the tags defined in the parent #StructRNA
+ * of \a prop. This should be done before (e.g. see #WM_operatortype_prop_tag).
+ */
+void RNA_def_property_tags(PropertyRNA *prop, int tags);
+void RNA_def_property_subtype(PropertyRNA *prop, PropertySubType subtype);
+void RNA_def_property_array(PropertyRNA *prop, int length);
+void RNA_def_property_multi_array(PropertyRNA *prop, int dimension, const int length[]);
+void RNA_def_property_range(PropertyRNA *prop, double min, double max);
+
+/**
+ * \param item: An array of enum properties terminated by null members.
+ * \warning take care not to reference stack memory as the reference to `item` is held by `prop`.
+ */
+void RNA_def_property_enum_items(PropertyRNA *prop, const EnumPropertyItem *item);
+void RNA_def_property_enum_native_type(PropertyRNA *prop, const char *native_enum_type);
+void RNA_def_property_string_maxlength(PropertyRNA *prop, int maxlength);
+void RNA_def_property_struct_type(PropertyRNA *prop, const char *type);
+void RNA_def_property_struct_runtime(StructOrFunctionRNA *cont,
+ PropertyRNA *prop,
+ StructRNA *type);
+
+void RNA_def_property_boolean_default(PropertyRNA *prop, bool value);
+void RNA_def_property_boolean_array_default(PropertyRNA *prop, const bool *array);
+void RNA_def_property_int_default(PropertyRNA *prop, int value);
+void RNA_def_property_int_array_default(PropertyRNA *prop, const int *array);
+void RNA_def_property_float_default(PropertyRNA *prop, float value);
+/**
+ * Array must remain valid after this function finishes.
+ */
+void RNA_def_property_float_array_default(PropertyRNA *prop, const float *array);
+void RNA_def_property_enum_default(PropertyRNA *prop, int value);
+void RNA_def_property_string_default(PropertyRNA *prop, const char *value);
+
+void RNA_def_property_ui_text(PropertyRNA *prop, const char *name, const char *description);
+void RNA_def_property_ui_name_func(PropertyRNA *prop, const char *name_func);
+void RNA_def_property_ui_description_func(PropertyRNA *prop, const char *description_func);
+
+void RNA_def_property_deprecated(PropertyRNA *prop,
+ const char *note,
+ short version,
+ short removal_version);
+
+/**
+ * The values hare are a little confusing:
+ *
+ * \param step: Used as the value to increase/decrease when clicking on number buttons,
+ * as well as scaling mouse input for click-dragging number buttons.
+ * For floats this is (step * UI_PRECISION_FLOAT_SCALE), why? - nobody knows.
+ * For ints, whole values are used.
+ *
+ * \param precision: The number of zeros to show
+ * (as a whole number - common range is 1 - 6), see UI_PRECISION_FLOAT_MAX
+ */
+void RNA_def_property_ui_range(
+ PropertyRNA *prop, double min, double max, double step, int precision);
+void RNA_def_property_ui_scale_type(PropertyRNA *prop, PropertyScaleType ui_scale_type);
+void RNA_def_property_ui_icon(PropertyRNA *prop, int icon, int consecutive);
+
+void RNA_def_property_update(PropertyRNA *prop, int noteflag, const char *updatefunc);
+void RNA_def_property_editable_func(PropertyRNA *prop, const char *editable);
+void RNA_def_property_editable_array_func(PropertyRNA *prop, const char *editable);
+
+/**
+ * Set custom callbacks for override operations handling.
+ *
+ * \note \a diff callback will also be used by RNA comparison/equality functions.
+ */
+void RNA_def_property_override_funcs(PropertyRNA *prop,
+ const char *diff,
+ const char *store,
+ const char *apply);
+
+using RNAPropertyUpdateFunc = void (*)(Main *, Scene *, PointerRNA *);
+using RNAPropertyUpdateFuncWithContextAndProperty = void (*)(bContext *C,
+ PointerRNA *ptr,
+ PropertyRNA *prop);
+
+void RNA_def_property_update_runtime(PropertyRNA *prop, RNAPropertyUpdateFunc func);
+void RNA_def_property_update_runtime_with_context_and_property(
+ PropertyRNA *prop, RNAPropertyUpdateFuncWithContextAndProperty func);
+void RNA_def_property_update_notifier(PropertyRNA *prop, int noteflag);
+void RNA_def_property_poll_runtime(PropertyRNA *prop, const void *func);
+
+void RNA_def_property_dynamic_array_funcs(PropertyRNA *prop, const char *getlength);
+void RNA_def_property_boolean_funcs(PropertyRNA *prop, const char *get, const char *set);
+void RNA_def_property_int_funcs(PropertyRNA *prop,
+ const char *get,
+ const char *set,
+ const char *range);
+void RNA_def_property_float_funcs(PropertyRNA *prop,
+ const char *get,
+ const char *set,
+ const char *range);
+void RNA_def_property_enum_funcs(PropertyRNA *prop,
+ const char *get,
+ const char *set,
+ const char *item);
+void RNA_def_property_string_funcs(PropertyRNA *prop,
+ const char *get,
+ const char *length,
+ const char *set);
+void RNA_def_property_string_search_func(PropertyRNA *prop,
+ const char *search,
+ eStringPropertySearchFlag search_flag);
+void RNA_def_property_string_filepath_filter_func(PropertyRNA *prop, const char *filter);
+void RNA_def_property_pointer_funcs(
+ PropertyRNA *prop, const char *get, const char *set, const char *type_fn, const char *poll);
+void RNA_def_property_collection_funcs(PropertyRNA *prop,
+ const char *begin,
+ const char *next,
+ const char *end,
+ const char *get,
+ const char *length,
+ const char *lookupint,
+ const char *lookupstring,
+ const char *assignint);
+
+void RNA_def_property_float_default_func(PropertyRNA *prop, const char *get_default);
+void RNA_def_property_int_default_func(PropertyRNA *prop, const char *get_default);
+void RNA_def_property_boolean_default_func(PropertyRNA *prop, const char *get_default);
+void RNA_def_property_enum_default_func(PropertyRNA *prop, const char *get_default);
+void RNA_def_property_string_default_func(PropertyRNA *prop, const char *get_default);
+
+void RNA_def_property_srna(PropertyRNA *prop, const char *type);
+void RNA_def_py_data(PropertyRNA *prop, void *py_data);
+
+/* API to define callbacks for runtime-defined properties (mainly for Operators, and from the
+ * Python `bpy.props` API).
+ *
+ * These expect 'extended' versions of the callbacks, with both the StructRNA owner and the
+ * PropertyRNA as first arguments.
+ *
+ * The 'Transform' ones allow to add a transform step (applied after getting, or before setting the
+ * value), which only modifies the value, but does not handle actual storage. Currently only used
+ * by `bpy`, more details in the documentation of #BPyPropStore.
+ */
+void RNA_def_property_boolean_funcs_runtime(PropertyRNA *prop,
+ BooleanPropertyGetFunc getfunc,
+ BooleanPropertySetFunc setfunc,
+ BooleanPropertyGetTransformFunc get_transform_fn,
+ BooleanPropertySetTransformFunc set_transform_fn);
+void RNA_def_property_boolean_array_funcs_runtime(
+ PropertyRNA *prop,
+ BooleanArrayPropertyGetFunc getfunc,
+ BooleanArrayPropertySetFunc setfunc,
+ BooleanArrayPropertyGetTransformFunc get_transform_fn,
+ BooleanArrayPropertySetTransformFunc set_transform_fn);
+void RNA_def_property_int_funcs_runtime(PropertyRNA *prop,
+ IntPropertyGetFunc getfunc,
+ IntPropertySetFunc setfunc,
+ IntPropertyRangeFunc rangefunc,
+ IntPropertyGetTransformFunc get_transform_fn,
+ IntPropertySetTransformFunc set_transform_fn);
+void RNA_def_property_int_array_funcs_runtime(PropertyRNA *prop,
+ IntArrayPropertyGetFunc getfunc,
+ IntArrayPropertySetFunc setfunc,
+ IntPropertyRangeFunc rangefunc,
+ IntArrayPropertyGetTransformFunc get_transform_fn,
+ IntArrayPropertySetTransformFunc set_transform_fn);
+void RNA_def_property_float_funcs_runtime(PropertyRNA *prop,
+ FloatPropertyGetFunc getfunc,
+ FloatPropertySetFunc setfunc,
+ FloatPropertyRangeFunc rangefunc,
+ FloatPropertyGetTransformFunc get_transform_fn,
+ FloatPropertySetTransformFunc set_transform_fn);
+void RNA_def_property_float_array_funcs_runtime(
+ PropertyRNA *prop,
+ FloatArrayPropertyGetFunc getfunc,
+ FloatArrayPropertySetFunc setfunc,
+ FloatPropertyRangeFunc rangefunc,
+ FloatArrayPropertyGetTransformFunc get_transform_fn,
+ FloatArrayPropertySetTransformFunc set_transform_fn);
+void RNA_def_property_enum_funcs_runtime(PropertyRNA *prop,
+ EnumPropertyGetFunc getfunc,
+ EnumPropertySetFunc setfunc,
+ EnumPropertyItemFunc itemfunc,
+ EnumPropertyGetTransformFunc get_transform_fn,
+ EnumPropertySetTransformFunc set_transform_fn);
+void RNA_def_property_string_funcs_runtime(PropertyRNA *prop,
+ StringPropertyGetFunc getfunc,
+ StringPropertyLengthFunc lengthfunc,
+ StringPropertySetFunc setfunc,
+ StringPropertyGetTransformFunc get_transform_fn,
+ StringPropertySetTransformFunc set_transform_fn);
+void RNA_def_property_string_search_func_runtime(PropertyRNA *prop,
+ StringPropertySearchFunc search_fn,
+ eStringPropertySearchFlag search_flag);
+void RNA_def_property_pointer_funcs_runtime(PropertyRNA *prop,
+ PointerPropertyGetFunc getfunc,
+ PointerPropertySetFunc setfunc,
+ PointerPropertyTypeFunc typefunc);
+
+void RNA_def_property_translation_context(PropertyRNA *prop, const char *context);
+
+/* Function */
+
+FunctionRNA *RNA_def_function(StructRNA *srna, const char *identifier, const char *call);
+FunctionRNA *RNA_def_function_runtime(StructRNA *srna, const char *identifier, CallFunc call);
+/**
+ * C return value only! multiple RNA returns can be done with #RNA_def_function_output.
+ */
+void RNA_def_function_return(FunctionRNA *func, PropertyRNA *ret);
+void RNA_def_function_output(FunctionRNA *func, PropertyRNA *ret);
+void RNA_def_function_flag(FunctionRNA *func, int flag);
+void RNA_def_function_ui_description(FunctionRNA *func, const char *description);
+
+void RNA_def_parameter_flags(PropertyRNA *prop,
+ PropertyFlag flag_property,
+ ParameterFlag flag_parameter);
+void RNA_def_parameter_clear_flags(PropertyRNA *prop,
+ PropertyFlag flag_property,
+ ParameterFlag flag_parameter);
+void RNA_def_property_path_template_type(PropertyRNA *prop,
+ PropertyPathTemplateType path_template_type);
+
+/* Dynamic Enums
+ * strings are not freed, assumed pointing to static location. */
+
+void RNA_enum_item_add(EnumPropertyItem **items, int *totitem, const EnumPropertyItem *item);
+void RNA_enum_item_add_separator(EnumPropertyItem **items, int *totitem);
+void RNA_enum_items_add(EnumPropertyItem **items, int *totitem, const EnumPropertyItem *item);
+void RNA_enum_items_add_value(EnumPropertyItem **items,
+ int *totitem,
+ const EnumPropertyItem *item,
+ int value);
+void RNA_enum_item_end(EnumPropertyItem **items, int *totitem);
+
+/* Memory management */
+
+void RNA_def_struct_duplicate_pointers(BlenderRNA *brna, StructRNA *srna);
+void RNA_def_struct_free_pointers(BlenderRNA *brna, StructRNA *srna);
+void RNA_def_func_duplicate_pointers(FunctionRNA *func);
+void RNA_def_func_free_pointers(FunctionRNA *func);
+void RNA_def_property_duplicate_pointers(StructOrFunctionRNA *cont_, PropertyRNA *prop);
+void RNA_def_property_free_pointers(PropertyRNA *prop);
+int RNA_def_property_free_identifier(StructOrFunctionRNA *cont_, const char *identifier);
+
+int RNA_def_property_free_identifier_deferred_prepare(StructOrFunctionRNA *cont_,
+ const char *identifier,
+ void **handle);
+void RNA_def_property_free_identifier_deferred_finish(StructOrFunctionRNA *cont_, void *handle);
+
+void RNA_def_property_free_pointers_set_py_data_callback(
+ void (*py_data_clear_fn)(PropertyRNA *prop));
+
+/* Utilities. */
+
+const char *RNA_property_typename(PropertyType type);
+#define IS_DNATYPE_FLOAT_COMPAT(_str) (strcmp(_str, "float") == 0 || strcmp(_str, "double") == 0)
+#define IS_DNATYPE_INT_COMPAT(_str) \
+ (strcmp(_str, "int") == 0 || strcmp(_str, "short") == 0 || strcmp(_str, "char") == 0 || \
+ strcmp(_str, "uchar") == 0 || strcmp(_str, "ushort") == 0 || strcmp(_str, "int8_t") == 0)
+#define IS_DNATYPE_BOOLEAN_COMPAT(_str) \
+ (IS_DNATYPE_INT_COMPAT(_str) || strcmp(_str, "int64_t") == 0 || strcmp(_str, "uint64_t") == 0)
+
+bool RNA_validate_identifier(const char *identifier,
+ bool is_property,
+ const char **r_error = nullptr);
+void RNA_identifier_sanitize(char *identifier, bool is_property);
+
+/* Common arguments for length. */
+
+extern const int rna_matrix_dimsize_3x3[];
+extern const int rna_matrix_dimsize_4x4[];
+extern const int rna_matrix_dimsize_4x2[];
+
+/* Common arguments for defaults. */
+
+extern const float rna_default_axis_angle[4];
+extern const float rna_default_quaternion[4];
+extern const float rna_default_scale_3d[3];
+
+/** Maximum size for dynamic defined type descriptors, this value is arbitrary. */
+#define RNA_DYN_DESCR_MAX 1024
+
+} // namespace blender
diff --git a/compat/include/RNA_prototypes.hh b/compat/include/RNA_prototypes.hh
new file mode 100644
index 0000000..4c27873
--- /dev/null
+++ b/compat/include/RNA_prototypes.hh
@@ -0,0 +1,18 @@
+/* BUI seam: stand-in for the generated RNA prototypes. Only symbols actually
+ * referenced by the toolkit are declared here.
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#ifndef __cplusplus
+#error "RNA prototypes are C++-only in BUI"
+#endif
+
+#include "RNA_types.hh"
+
+namespace blender {
+extern StructRNA *const RNA_NodeTree;
+extern StructRNA *const RNA_ActionSlot;
+} // namespace blender
+
+using blender::RNA_NodeTree;
+using blender::RNA_ActionSlot;
diff --git a/compat/include/RNA_types.hh b/compat/include/RNA_types.hh
index 4e1ca4b..983eda7 100644
--- a/compat/include/RNA_types.hh
+++ b/compat/include/RNA_types.hh
@@ -10,13 +10,15 @@
#ifndef __RNA_TYPES_H__
#define __RNA_TYPES_H__
+#include "DNA_listBase.h"
+
#include <optional>
#include <string>
-#include "../blenlib/BLI_enum_flags.hh"
-#include "../blenlib/BLI_function_ref.hh"
-#include "../blenlib/BLI_sys_types.h"
-#include "../blenlib/BLI_vector.hh"
+#include "BLI_enum_flags.hh"
+#include "BLI_function_ref.hh"
+#include "BLI_sys_types.h"
+#include "BLI_vector.hh"
namespace blender {
@@ -577,7 +579,6 @@ enum ParameterFlag {
ENUM_OPERATORS(ParameterFlag)
struct CollectionPropertyIterator;
-struct Link;
using IteratorSkipFunc = bool (*)(CollectionPropertyIterator *iter, void *data);
struct ListBaseIterator {
@@ -1088,3 +1089,4 @@ struct PrimitiveBooleanRNA {
} // namespace blender
#endif /* __RNA_TYPES_H__ */
+
diff --git a/compat/include/WM_api.hh b/compat/include/WM_api.hh
new file mode 100644
index 0000000..4105319
--- /dev/null
+++ b/compat/include/WM_api.hh
@@ -0,0 +1,2418 @@
+/* SPDX-FileCopyrightText: 2007 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+/** \file
+ * \ingroup wm
+ *
+ * \page wmpage windowmanager
+ * \section wmabout About windowmanager
+ * \ref wm handles events received from \ref GHOST and manages
+ * the screens, areas and input for Blender
+ * \section wmnote NOTE
+ * \todo document
+ */
+
+#include <functional>
+#include <optional>
+#include <string>
+
+#include "DNA_windowmanager_types.h"
+
+#include "BLI_array.hh"
+#include "BLI_bounds_types.hh"
+#include "BLI_compiler_attrs.h"
+#include "BLI_enum_flags.hh"
+#include "BLI_function_ref.hh"
+#include "BLI_math_vector_types.hh"
+#include "BLI_set.hh"
+#include "BLI_sys_types.h"
+
+#include "WM_keymap.hh"
+#include "WM_types.hh"
+
+class GHOST_IContext;
+
+namespace blender {
+
+struct ARegion;
+struct GPUViewport;
+struct ID;
+struct IDProperty;
+struct ImBuf;
+struct ImageFormatData;
+struct Main;
+struct MenuType;
+struct PointerRNA;
+struct PropertyRNA;
+struct ScrArea;
+struct View3D;
+struct ViewLayer;
+struct bContext;
+struct rcti;
+struct uiListType;
+struct WorkSpace;
+struct WorkSpaceLayout;
+struct wmDrag;
+struct wmDropBox;
+struct wmEvent;
+struct wmEventHandler;
+struct wmEventHandler_Dropbox;
+struct wmEventHandler_Keymap;
+struct wmEventHandler_Op;
+struct wmEventHandler_UI;
+struct wmGenericUserData;
+struct wmGesture;
+struct wmJob;
+struct wmJobWorkerStatus;
+struct wmOperator;
+struct wmOperatorType;
+struct wmPaintCursor;
+struct wmTabletData;
+
+#ifdef WITH_INPUT_NDOF
+struct wmNDOFMotionData;
+#endif
+
+#ifdef WITH_XR_OPENXR
+struct wmXrRuntimeData;
+struct wmXrSessionState;
+#endif
+
+namespace bke::id {
+class IDRemapper;
+}
+
+namespace asset_system {
+class AssetRepresentation;
+}
+
+namespace ui {
+enum class AlertIcon : int8_t;
+}
+
+/* General API. */
+
+/**
+ * Used for setting app-template from the command line:
+ * - non-empty string: overrides.
+ * - empty string: override, using no app template.
+ * - NULL: clears override.
+ */
+void WM_init_state_app_template_set(const char *app_template);
+const char *WM_init_state_app_template_get();
+
+/**
+ * Called when no ghost system was initialized.
+ */
+void WM_init_state_size_set(int stax, int stay, int sizx, int sizy);
+/**
+ * For border-less and border windows set from command-line.
+ */
+void WM_init_state_fullscreen_set();
+void WM_init_state_normal_set();
+void WM_init_state_maximized_set();
+void WM_init_state_start_with_console_set(bool value);
+void WM_init_window_focus_set(bool do_it);
+bool WM_init_window_frame_get();
+void WM_init_window_frame_set(bool do_it);
+void WM_init_native_pixels(bool do_it);
+void WM_init_input_devices();
+
+/**
+ * Initialize Blender and load the startup file & preferences
+ * (only called once).
+ */
+void WM_init(bContext *C, int argc, const char **argv);
+/**
+ * Main exit function (implementation).
+ *
+ * \note Unlike #WM_exit this does not call `exit()`,
+ * the caller is responsible for this.
+ *
+ * \param C: The context or null, a null context implies `do_user_exit_actions == false` &
+ * prevents some editor-exit operations from running.
+ * \param do_python_exit: Exit the Python interpreter (unless `WITH_PYTHON_MODULE` is enabled).
+ * \param do_user_exit_actions: When enabled perform actions associated with a user
+ * having been using Blender then exiting. Actions such as writing the auto-save
+ * and writing any changes to preferences.
+ * Set to false in background mode or when exiting because of failed command line argument parsing.
+ * In general automated actions where the user isn't making changes should pass in false too.
+ */
+void WM_exit_ex(bContext *C, bool do_python_exit, bool do_user_exit_actions);
+
+/**
+ * Main exit function to close Blender ordinarily.
+ *
+ * \note Use #wm_exit_schedule_delayed() to close Blender from an operator.
+ * Might leak memory otherwise.
+ *
+ * \param exit_code: Passed to #exit, typically #EXIT_SUCCESS or #EXIT_FAILURE should be used.
+ * With failure being used for an early exit when parsing command line arguments fails.
+ * Note that any exit-code besides #EXIT_SUCCESS calls #WM_exit_ex with its `do_user_exit_actions`
+ * argument set to false.
+ */
+void WM_exit(bContext *C, int exit_code) ATTR_NORETURN;
+
+void WM_main(bContext *C) ATTR_NORETURN;
+
+/**
+ * Show the splash screen as needed on startup.
+ *
+ * The splash may not show depending on a file being loaded and user preferences.
+ */
+void WM_init_splash_on_startup(bContext *C);
+/**
+ * Show the splash screen.
+ */
+void WM_init_splash(bContext *C);
+
+void WM_init_gpu();
+
+/**
+ * Return an identifier for the underlying GHOST implementation.
+ * \warning Use of this function should be limited & never for compatibility checks.
+ * see: #GHOST_ISystem::getSystemBackend for details.
+ */
+const char *WM_ghost_backend();
+
+enum eWM_CapabilitiesFlag {
+ /** Ability to warp the cursor (set its location). */
+ WM_CAPABILITY_CURSOR_WARP = (1 << 0),
+ /**
+ * Window position access, support for the following.
+ * - Getting window positions.
+ * - Setting window positions.
+ * - Setting positions for new windows.
+ *
+ * Currently there is no need to distinguish between these different cases
+ * so a single flag is used.
+ *
+ * When omitted, it isn't possible to know where windows are located in relation to each other.
+ * Operations such as applying events from one window to another or detecting the non-active
+ * window under the cursor are not supported.
+ */
+ WM_CAPABILITY_WINDOW_POSITION = (1 << 1),
+ /**
+ * The windowing system supports a separate primary clipboard
+ * (typically set when interactively selecting text).
+ */
+ WM_CAPABILITY_CLIPBOARD_PRIMARY = (1 << 2),
+ /**
+ * Reading from the back-buffer is supported.
+ */
+ WM_CAPABILITY_GPU_FRONT_BUFFER_READ = (1 << 3),
+ /** Ability to copy/paste system clipboard images. */
+ WM_CAPABILITY_CLIPBOARD_IMAGE = (1 << 4),
+ /** Ability to sample a color outside of Blender windows. */
+ WM_CAPABILITY_DESKTOP_SAMPLE = (1 << 5),
+ /** Support for IME input methods. */
+ WM_CAPABILITY_INPUT_IME = (1 << 6),
+ /** Trackpad physical scroll detection. */
+ WM_CAPABILITY_TRACKPAD_PHYSICAL_DIRECTION = (1 << 7),
+ /** Support for window decoration styles. */
+ WM_CAPABILITY_WINDOW_DECORATION_STYLES = (1 << 8),
+ /** Support for the "Hyper" modifier key. */
+ WM_CAPABILITY_KEYBOARD_HYPER_KEY = (1 << 9),
+ /** Support for RGBA Cursors. */
+ WM_CAPABILITY_CURSOR_RGBA = (1 << 10),
+ /** Support on demand cursor generation. */
+ WM_CAPABILITY_CURSOR_GENERATOR = (1 << 11),
+ /** Ability to save/restore windows among multiple monitors. */
+ WM_CAPABILITY_MULTIMONITOR_PLACEMENT = (1 << 12),
+ /** Support for the window to show a file-path (otherwise include in the title text). */
+ WM_CAPABILITY_WINDOW_PATH = (1 << 13),
+ /** Support for window server side decorations (SSD). */
+ WM_CAPABILITY_WINDOW_DECORATION_SERVER_SIDE = (1 << 14),
+ /** The initial value, indicates the value needs to be set by inspecting GHOST. */
+ WM_CAPABILITY_INITIALIZED = (1u << 31),
+};
+ENUM_OPERATORS(eWM_CapabilitiesFlag)
+
+/**
+ * Return the capabilities of the windowing system.
+ *
+ * \note Some callers need to check `G.background == false` before this function.
+ * See inline code-comments for details.
+ */
+eWM_CapabilitiesFlag WM_capabilities_flag();
+
+void WM_check(bContext *C);
+void WM_reinit_gizmomap_all(Main *bmain);
+
+/**
+ * Needed for cases when operators are re-registered
+ * (when operator type pointers are stored).
+ */
+void WM_script_tag_reload();
+
+wmWindow *WM_window_find_under_cursor(wmWindow *win,
+ const int event_xy[2],
+ int r_event_xy_other[2]);
+
+/**
+ * Knowing the area, return its screen.
+ * \note This should typically be avoided, only use when the context is not available.
+ */
+wmWindow *WM_window_find_by_area(wmWindowManager *wm, const ScrArea *area);
+
+/**
+ * Return the color of the pixel at the current mouse cursor position on the desktop, whether in a
+ * Blender window or not. Returns false on failure or if not supported by the platform.
+ */
+bool WM_desktop_cursor_sample_read(float r_col[3]);
+
+/**
+ * Read pixels from the front-buffer (fast).
+ *
+ * \note Internally this depends on the front-buffer state,
+ * for a slower but more reliable method of reading pixels,
+ * use #WM_window_pixels_read_from_offscreen.
+ * Fast pixel access may be preferred for file-save thumbnails.
+ *
+ * \warning Drawing (swap-buffers) immediately before calling this function causes
+ * the front-buffer state to be invalid under some EGL configurations.
+ */
+uint8_t *WM_window_pixels_read_from_frontbuffer(const wmWindowManager *wm,
+ const wmWindow *win,
+ int r_size[2]);
+/** A version of #WM_window_pixels_read_from_frontbuffer that samples a pixel at `pos`. */
+void WM_window_pixels_read_sample_from_frontbuffer(const wmWindowManager *wm,
+ const wmWindow *win,
+ const int pos[2],
+ float r_col[3]);
+
+/**
+ * Draw the window & read pixels from an off-screen buffer
+ * (slower than #WM_window_pixels_read_from_frontbuffer).
+ *
+ * \note This is needed because the state of the front-buffer may be damaged
+ * (see in-line code comments for details).
+ */
+uint8_t *WM_window_pixels_read_from_offscreen(bContext *C, wmWindow *win, int r_size[2]);
+/** A version of #WM_window_pixels_read_from_offscreen that samples a pixel at `pos`. */
+bool WM_window_pixels_read_sample_from_offscreen(bContext *C,
+ wmWindow *win,
+ const int pos[2],
+ float r_col[3]);
+
+/**
+ * Read from the screen.
+ *
+ * \note Use off-screen drawing when front-buffer reading is not supported.
+ */
+uint8_t *WM_window_pixels_read(bContext *C, wmWindow *win, int r_size[2]);
+/**
+ * Read a single pixel from the screen.
+ *
+ * \note Use off-screen drawing when front-buffer reading is not supported.
+ */
+bool WM_window_pixels_read_sample(bContext *C, wmWindow *win, const int pos[2], float r_col[3]);
+
+/**
+ * Support for native pixel size
+ *
+ * \note macOS retina opens window in size X, but it has up to 2 x more pixels.
+ *
+ * \warning This includes CSD (Client-Side Decoration) area such as the title-bar.
+ * Use #WM_window_rect_calc to get the usable content bounds.
+ */
+int WM_window_native_pixel_x(const wmWindow *win);
+int WM_window_native_pixel_y(const wmWindow *win);
+
+int2 WM_window_native_pixel_size(const wmWindow *win);
+
+void WM_window_native_pixel_coords(const wmWindow *win, int *x, int *y);
+/**
+ * Return non-nil if the CSD is used.
+ */
+bool WM_window_is_csd(const wmWindow *win);
+/**
+ * Calculate the window content sub-region when CSD is used.
+ */
+void WM_window_csd_rect_calc(const wmWindow *win, rcti *r_rect);
+/**
+ * Get boundaries usable by all window contents, including global areas.
+ */
+void WM_window_rect_calc(const wmWindow *win, rcti *r_rect);
+/**
+ * Get boundaries usable by screen-layouts, excluding global areas.
+ * \note Depends on #UI_SCALE_FAC. Should that be outdated, call #WM_window_dpi_set_userdef first.
+ */
+void WM_window_screen_rect_calc(const wmWindow *win, rcti *r_rect);
+bool WM_window_is_main_top_level(const wmWindow *win);
+bool WM_window_is_fullscreen(const wmWindow *win);
+bool WM_window_is_maximized(const wmWindow *win);
+
+/**
+ * Support for wide gamut and HDR colors.
+ */
+bool WM_window_support_hdr_color(const wmWindow *win);
+
+/**
+ * Some editor data may need to be synced with scene data (3D View camera and layers).
+ * This function ensures data is synced for editors
+ * in visible work-spaces and their visible layouts.
+ */
+void WM_windows_scene_data_sync(const ListBaseT<wmWindow> *win_lb, Scene *scene) ATTR_NONNULL();
+Scene *WM_windows_scene_get_from_screen(const wmWindowManager *wm, const bScreen *screen)
+ ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT;
+ViewLayer *WM_windows_view_layer_get_from_screen(const wmWindowManager *wm, const bScreen *screen)
+ ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT;
+WorkSpace *WM_windows_workspace_get_from_screen(const wmWindowManager *wm, const bScreen *screen)
+ ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT;
+
+Scene *WM_window_get_active_scene(const wmWindow *win) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT;
+/**
+ * \warning Only call outside of area/region loops.
+ */
+void WM_window_set_active_scene(Main *bmain, bContext *C, wmWindow *win, Scene *scene)
+ ATTR_NONNULL();
+WorkSpace *WM_window_get_active_workspace(const wmWindow *win)
+ ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT;
+void WM_window_set_active_workspace(bContext *C, wmWindow *win, WorkSpace *workspace)
+ ATTR_NONNULL(1);
+WorkSpaceLayout *WM_window_get_active_layout(const wmWindow *win)
+ ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT;
+void WM_window_set_active_layout(wmWindow *win, WorkSpace *workspace, WorkSpaceLayout *layout)
+ ATTR_NONNULL(1);
+/**
+ * Get the active screen of the active workspace in \a win.
+ */
+bScreen *WM_window_get_active_screen(const wmWindow *win) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT;
+void WM_window_set_active_screen(wmWindow *win, WorkSpace *workspace, bScreen *screen)
+ ATTR_NONNULL(1);
+
+ViewLayer *WM_window_get_active_view_layer(const wmWindow *win)
+ ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT;
+void WM_window_set_active_view_layer(wmWindow *win, ViewLayer *view_layer) ATTR_NONNULL(1);
+void WM_window_ensure_active_view_layer(wmWindow *win) ATTR_NONNULL(1);
+
+bool WM_window_is_temp_screen(const wmWindow *win) ATTR_WARN_UNUSED_RESULT;
+
+GHOST_IContext *WM_system_gpu_context_create();
+void WM_system_gpu_context_dispose(GHOST_IContext *context);
+void WM_system_gpu_context_activate(GHOST_IContext *context);
+void WM_system_gpu_context_release(GHOST_IContext *context);
+
+/** #WM_window_open alignment. */
+enum eWindowAlignment {
+ WIN_ALIGN_ABSOLUTE = 0,
+ WIN_ALIGN_LOCATION_CENTER,
+ WIN_ALIGN_PARENT_CENTER,
+};
+
+/**
+ * \param rect: Position & size of the window.
+ * \param space_type: #SPACE_VIEW3D, #SPACE_INFO, ... (#eSpace_Type).
+ * \param toplevel: Not a child owned by other windows. A peer of main window.
+ * \param dialog: whether this should be made as a dialog-style window
+ * \param temp: whether this is considered a short-lived window
+ * \param alignment: how this window is positioned relative to its parent
+ * \param area_setup_fn: An optional callback which can be used to initialize the area
+ * before it's initialized. When set, `space_type` should be #SPACE_EMTPY,
+ * so the setup function can take a blank area and initialize it.
+ * \param area_setup_user_data: User data argument passed to `area_setup_fn`.
+ * \return the window or NULL in case of failure.
+ */
+wmWindow *WM_window_open(bContext *C,
+ const char *title,
+ const rcti *rect_unscaled,
+ int space_type,
+ bool toplevel,
+ bool dialog,
+ bool temp,
+ eWindowAlignment alignment,
+ void (*area_setup_fn)(bScreen *screen, ScrArea *area, void *user_data),
+ void *area_setup_user_data) ATTR_NONNULL(1, 3);
+
+wmWindow *WM_window_open_temp(bContext *C, const char *title, int space_type, bool dialog);
+
+void WM_window_dpi_set_userdef(const wmWindow *win);
+/**
+ * Return the windows DPI as a scale, bypassing UI scale preference.
+ *
+ * \note Use for calculating cursor size which doesn't use the UI scale.
+ */
+float WM_window_dpi_get_scale(const wmWindow *win);
+
+/**
+ * Give a title to a window. With "Title" unspecified or nullptr, it is generated
+ * automatically from window settings and areas. Only use custom title when really needed.
+ */
+void WM_window_title_set(wmWindow *win, const char *title);
+/**
+ * Generate a window title automatically from window settings and areas.
+ *
+ * Also refresh the modified-state (for main windows).
+ */
+void WM_window_title_refresh(wmWindowManager *wm, wmWindow *win);
+
+/**
+ * Update the parameters for CSD.
+ */
+void WM_window_csd_params_update();
+
+bool WM_stereo3d_enabled(wmWindow *win, bool skip_stereo3d_check);
+
+/* Window Decoration Styles. */
+
+/**
+ * Flags for #WM_window_decoration_set_style().
+ *
+ * \note To be kept in sync with #GHOST_TWindowDecorationFlags.
+ */
+enum eWM_WindowDecorationStyleFlag {
+ /** No decoration styling. */
+ WM_WINDOW_DECORATION_STYLE_NONE = 0,
+ /** Colored TitleBar. */
+ WM_WINDOW_DECORATION_STYLE_COLORED_TITLEBAR = (1 << 0),
+};
+ENUM_OPERATORS(eWM_WindowDecorationStyleFlag)
+
+/**
+ * Get the window decoration style flags.
+ */
+eWM_WindowDecorationStyleFlag WM_window_decoration_style_flags_get(const wmWindow *win);
+/**
+ * Set window decoration style flags.
+ * Use before calling #WM_window_decoration_style_apply.
+ */
+void WM_window_decoration_style_flags_set(const wmWindow *win,
+ eWM_WindowDecorationStyleFlag style_flags);
+/**
+ * Apply the window decoration style using the current style flags and by parsing style
+ * settings from the current Blender theme.
+ * The screen parameter is optional, and can be passed for enhanced theme parsing.
+ *
+ * \note Avoid calling this function directly, prefer sending an #NC_WINDOW
+ * notification when #WM_CAPABILITY_WINDOW_DECORATION_STYLES is supported instead.
+ */
+void WM_window_decoration_style_apply(const wmWindow *win, const bScreen *screen = nullptr);
+
+/* `wm_files.cc`. */
+
+void WM_file_autoexec_init(const char *filepath);
+/**
+ * \param use_scripts_autoexec_check: When true, script auto-execution checks excluded directories.
+ * Note that this is passed in as an argument because `filepath` may reference a path to recover.
+ * In this case the file-path used for exclusion is the recovery path which is only known once
+ * the file has been loaded.
+ */
+bool WM_file_read(bContext *C,
+ const char *filepath,
+ const bool use_scripts_autoexec_check,
+ ReportList *reports);
+void WM_file_autosave_init(wmWindowManager *wm);
+bool WM_file_recover_last_session(bContext *C,
+ const bool use_scripts_autoexec_check,
+ ReportList *reports);
+void WM_file_tag_modified();
+
+/**
+ * \note `scene` (and related `view_layer` and `v3d`) pointers may be NULL,
+ * in which case no instantiation of linked objects, collections etc. will be performed.
+ */
+ID *WM_file_link_datablock(Main *bmain,
+ Scene *scene,
+ ViewLayer *view_layer,
+ View3D *v3d,
+ const char *filepath,
+ short id_code,
+ const char *id_name,
+ int flag,
+ ReportList *reports = nullptr);
+/**
+ * \note `scene` (and related `view_layer` and `v3d`) pointers may be NULL,
+ * in which case no instantiation of appended objects, collections etc. will be performed.
+ */
+ID *WM_file_append_datablock(Main *bmain,
+ Scene *scene,
+ ViewLayer *view_layer,
+ View3D *v3d,
+ const char *filepath,
+ short id_code,
+ const char *id_name,
+ int flag,
+ ReportList *reports = nullptr);
+void WM_lib_reload(Library *lib, bContext *C, ReportList *reports);
+
+/* Mouse cursors. */
+
+void WM_cursor_set(wmWindow *win, int curs);
+bool WM_cursor_set_from_tool(wmWindow *win, const ScrArea *area, const ARegion *region);
+/**
+ * Check the cursor isn't set elsewhere.
+ * When false setting the modal cursor can be done but may overwrite an existing cursor.
+ *
+ * Use this check for modal navigation operators that may be activated while other modal operators
+ * are running.
+ *
+ * \note A cursor "stack" would remove the need for this.
+ */
+bool WM_cursor_modal_is_set_ok(const wmWindow *win);
+void WM_cursor_modal_set(wmWindow *win, int val);
+void WM_cursor_modal_restore(wmWindow *win);
+/**
+ * To allow usage all over, we do entire WM.
+ */
+void WM_cursor_wait(bool val);
+/**
+ * Enable cursor grabbing, optionally hiding the cursor and wrapping cursor-motion
+ * within a sub-region of the window.
+ *
+ * \param wrap: an enum (#WM_CURSOR_WRAP_NONE, #WM_CURSOR_WRAP_XY... etc).
+ * \param wrap_region: Window-relative region for cursor wrapping (when `wrap` is
+ * #WM_CURSOR_WRAP_XY). When NULL, the window bounds are used for wrapping.
+ *
+ * \note The current grab state can be accessed by #wmWindowManager.grabcursor although.
+ */
+void WM_cursor_grab_enable(wmWindow *win,
+ eWM_CursorWrapAxis wrap,
+ const rcti *wrap_region,
+ bool hide);
+void WM_cursor_grab_disable(wmWindow *win, const int mouse_ungrab_xy[2]);
+/**
+ * After this you can call restore too.
+ */
+void WM_cursor_time(wmWindow *win, int nr);
+
+/**
+ * Show progress in the cursor (0.0..1.0 when complete).
+ */
+void WM_cursor_progress(wmWindow *win, float progress_factor);
+
+wmPaintCursor *WM_paint_cursor_activate(short space_type,
+ short region_type,
+ bool (*poll)(bContext *C),
+ wmPaintCursorDraw draw,
+ void *customdata);
+
+bool WM_paint_cursor_end(wmPaintCursor *handle);
+void WM_paint_cursor_remove_by_type(wmWindowManager *wm, void *draw_fn, void (*free)(void *));
+void WM_paint_cursor_tag_redraw(wmWindow *win, ARegion *region);
+
+/**
+ * Set the cursor location in window coordinates (compatible with #wmEvent.xy).
+ *
+ * \note Some platforms don't support this, check: #WM_CAPABILITY_WINDOW_POSITION
+ * before relying on this functionality.
+ */
+void WM_cursor_warp(wmWindow *win, int x, int y);
+
+/**
+ * The default size of a cursor without any DPI scaling.
+ */
+#define WM_CURSOR_DEFAULT_LOGICAL_SIZE 24
+
+/**
+ * \return the preferred logical size for the cursor
+ * (before DPI/Hi-DPI scaling is applied).
+ */
+uint WM_cursor_preferred_logical_size();
+
+/* Handlers. */
+
+enum eWM_EventHandlerFlag {
+ /** After this handler all others are ignored. */
+ WM_HANDLER_BLOCKING = (1 << 0),
+ /** Handler accepts double key press events. */
+ WM_HANDLER_ACCEPT_DBL_CLICK = (1 << 1),
+
+ /* Internal. */
+ /** Handler tagged to be freed in #wm_handlers_do(). */
+ WM_HANDLER_DO_FREE = (1 << 7),
+};
+ENUM_OPERATORS(eWM_EventHandlerFlag)
+
+using EventHandlerPoll = bool (*)(const wmWindow *win,
+ const ScrArea *area,
+ const ARegion *region,
+ const wmEvent *event);
+wmEventHandler_Keymap *WM_event_add_keymap_handler(ListBaseT<wmEventHandler> *handlers,
+ wmKeyMap *keymap);
+wmEventHandler_Keymap *WM_event_add_keymap_handler_poll(ListBaseT<wmEventHandler> *handlers,
+ wmKeyMap *keymap,
+ EventHandlerPoll poll);
+
+/**
+ * \return true when the `event` should be handled by the 2D views masked region.
+ *
+ * \note uses the #EventHandlerPoll signature.
+ */
+bool WM_event_handler_region_v2d_mask_poll(const wmWindow *win,
+ const ScrArea *area,
+ const ARegion *region,
+ const wmEvent *event);
+/**
+ * \return true when the `event` is inside the marker region.
+ *
+ * \note There are no checks that markers are displayed.
+ */
+bool WM_event_handler_region_marker_poll(const wmWindow *win,
+ const ScrArea *area,
+ const ARegion *region,
+ const wmEvent *event);
+
+/**
+ * A version of #WM_event_handler_region_v2d_mask_poll which excludes events
+ * (returning false) in the marker region.
+ *
+ * \note uses the #EventHandlerPoll signature.
+ */
+bool WM_event_handler_region_v2d_mask_no_marker_poll(const wmWindow *win,
+ const ScrArea *area,
+ const ARegion *region,
+ const wmEvent *event);
+
+wmEventHandler_Keymap *WM_event_add_keymap_handler_v2d_mask(ListBaseT<wmEventHandler> *handlers,
+ wmKeyMap *keymap);
+/**
+ * \note Priorities not implemented yet, for time being just insert in begin of list.
+ */
+wmEventHandler_Keymap *WM_event_add_keymap_handler_priority(ListBaseT<wmEventHandler> *handlers,
+ wmKeyMap *keymap,
+ int priority);
+
+struct wmEventHandler_KeymapResult {
+ wmKeyMap *keymaps[3];
+ int keymaps_len;
+};
+
+using wmEventHandler_KeymapDynamicFn = void (*)(wmWindowManager *wm,
+ wmWindow *win,
+ wmEventHandler_Keymap *handler,
+ wmEventHandler_KeymapResult *km_result);
+
+void WM_event_get_keymap_from_toolsystem_with_gizmos(wmWindowManager *wm,
+ wmWindow *win,
+ wmEventHandler_Keymap *handler,
+ wmEventHandler_KeymapResult *km_result);
+void WM_event_get_keymap_from_toolsystem(wmWindowManager *wm,
+ wmWindow *win,
+ wmEventHandler_Keymap *handler,
+ wmEventHandler_KeymapResult *km_result);
+
+wmEventHandler_Keymap *WM_event_add_keymap_handler_dynamic(
+ ListBaseT<wmEventHandler> *handlers,
+ wmEventHandler_KeymapDynamicFn keymap_fn,
+ void *user_data);
+
+void WM_event_remove_keymap_handler(ListBaseT<wmEventHandler> *handlers, wmKeyMap *keymap);
+
+void WM_event_set_keymap_handler_post_callback(wmEventHandler_Keymap *handler,
+ void(keymap_tag)(wmKeyMap *keymap,
+ wmKeyMapItem *kmi,
+ void *user_data),
+ void *user_data);
+void WM_event_get_keymaps_from_handler(wmWindowManager *wm,
+ wmWindow *win,
+ wmEventHandler_Keymap *handler,
+ wmEventHandler_KeymapResult *km_result);
+
+wmKeyMapItem *WM_event_match_keymap_item(bContext *C, wmKeyMap *keymap, const wmEvent *event);
+
+wmKeyMapItem *WM_event_match_keymap_item_from_handlers(bContext *C,
+ wmWindowManager *wm,
+ wmWindow *win,
+ ListBaseT<wmEventHandler> *handlers,
+ const wmEvent *event);
+
+bool WM_event_match(const wmEvent *winevent, const wmKeyMapItem *kmi);
+
+using wmUIHandlerFunc = int (*)(bContext *C, const wmEvent *event, void *userdata);
+using wmUIHandlerRemoveFunc = void (*)(bContext *C, void *userdata);
+
+wmEventHandler_UI *WM_event_add_ui_handler(const bContext *C,
+ ListBaseT<wmEventHandler> *handlers,
+ wmUIHandlerFunc handle_fn,
+ wmUIHandlerRemoveFunc remove_fn,
+ void *user_data,
+ eWM_EventHandlerFlag flag);
+
+/**
+ * Return the first modal operator of type \a ot or NULL.
+ */
+wmOperator *WM_operator_find_modal_by_type(wmWindow *win, const wmOperatorType *ot);
+
+/**
+ * \param postpone: Enable for `win->modalhandlers`,
+ * this is in a running for () loop in wm_handlers_do().
+ */
+void WM_event_remove_ui_handler(ListBaseT<wmEventHandler> *handlers,
+ wmUIHandlerFunc handle_fn,
+ wmUIHandlerRemoveFunc remove_fn,
+ void *user_data,
+ bool postpone);
+void WM_event_remove_handlers_by_area(ListBaseT<wmEventHandler> *handlers, const ScrArea *area);
+void WM_event_free_ui_handler_all(bContext *C,
+ ListBaseT<wmEventHandler> *handlers,
+ wmUIHandlerFunc handle_fn,
+ wmUIHandlerRemoveFunc remove_fn);
+
+/**
+ * Add a modal handler to `win`, `area` and `region` may optionally be NULL.
+ */
+wmEventHandler_Op *WM_event_add_modal_handler_ex(wmWindow *win,
+ ScrArea *area,
+ ARegion *region,
+ wmOperator *op) ATTR_NONNULL(1, 4);
+wmEventHandler_Op *WM_event_add_modal_handler(bContext *C, wmOperator *op) ATTR_NONNULL(1, 2);
+void WM_event_remove_modal_handler(ListBaseT<wmEventHandler> *handlers,
+ const wmOperator *op,
+ bool postpone) ATTR_NONNULL(1, 2);
+
+void WM_event_remove_modal_handler_all(const wmOperator *op, bool postpone) ATTR_NONNULL(1);
+
+/**
+ * Modal handlers store a pointer to an area which might be freed while the handler runs.
+ * Use this function to NULL all handler pointers to \a old_area.
+ */
+void WM_event_modal_handler_area_replace(wmWindow *win,
+ const ScrArea *old_area,
+ ScrArea *new_area);
+/**
+ * Modal handlers store a pointer to a region which might be freed while the handler runs.
+ * Use this function to NULL all handler pointers to \a old_region.
+ */
+void WM_event_modal_handler_region_replace(wmWindow *win,
+ const ARegion *old_region,
+ ARegion *new_region);
+void WM_event_ui_handler_region_popup_replace(wmWindow *win,
+ const ARegion *old_region,
+ ARegion *new_region);
+
+/**
+ * Called on exit or remove area, only here call cancel callback.
+ */
+void WM_event_remove_handlers(bContext *C, ListBaseT<wmEventHandler> *handlers);
+
+wmEventHandler_Dropbox *WM_event_add_dropbox_handler(ListBaseT<wmEventHandler> *handlers,
+ ListBaseT<wmDropBox> *dropboxes);
+
+/* Mouse. */
+void WM_event_add_mousemove(wmWindow *win);
+
+#ifdef WITH_INPUT_NDOF
+/* 3D mouse. */
+void WM_ndof_deadzone_set(float deadzone);
+#endif
+
+/**
+ * Mark the current event queue to break its current processing, and delay handling of remaining
+ * events to the next main event loop iteration in `WM_main()`.
+ *
+ * Used e.g. by undo/redo code to ensure that a redraw has been done before processing further
+ * events.
+ */
+void WM_event_handling_break(const bContext &C);
+
+/* Notifiers. */
+void WM_event_add_notifier_ex(wmWindowManager *wm,
+ const wmWindow *win,
+ unsigned int type,
+ void *reference);
+void WM_event_add_notifier(const bContext *C, unsigned int type, void *reference);
+void WM_main_add_notifier(unsigned int type, void *reference);
+/**
+ * Clear notifiers by reference, Used so listeners don't act on freed data.
+ */
+void WM_main_remove_notifier_reference(const void *reference);
+void WM_main_remap_editor_id_reference(const bke::id::IDRemapper &mappings);
+
+/* Reports. */
+
+/**
+ * Show the report in the info header.
+ * \param win: When NULL, a best-guess is used.
+ */
+void WM_report_banner_show(wmWindowManager *wm, wmWindow *win) ATTR_NONNULL(1);
+/**
+ * Hide all currently displayed banners and abort their timer.
+ */
+void WM_report_banners_cancel(Main *bmain);
+/**
+ * Move a whole list of reports to the WM ReportList, and show the banner.
+ *
+ * \note In case the given \a reports is a `nullptr`, or has its #RPT_OP_HOLD flag set, this
+ * function does nothing.
+ *
+ * \note The list of reports from given \a reports is moved into the list of WM's reports, so the
+ * given \a reports will be empty after calling this function. The \a reports #ReportList data
+ * itself is not freed or cleared though, and remains fully usable after this call.
+ *
+ * \params reports The #ReportList from which to move reports to the WM one, may be `nullptr`.
+ * \params wm the WindowManager to add given \a reports to. If `nullptr`, the first WM of current
+ * #G_MAIN will be used.
+ */
+void WM_reports_from_reports_move(wmWindowManager *wm, ReportList *reports);
+
+/**
+ * Report directly to the window manager without any context.
+ *
+ * \warning This function should almost always be avoided in favor of #BKE_report,
+ * if this isn't possible, a code-comment must be included explaining why.
+ *
+ * Global reports are bad practice because the caller can't handle or suppress them.
+ * This means for example, if an automated tasks/scripts can generate many reports
+ * that are shown to the user without any way to control error handling.
+ *
+ * When used in operators it prevents the Python script from raising an exception
+ * form the error as it should do, showing a popup instead.
+ */
+void WM_global_report(eReportType type, const char *message);
+/**
+ * Report directly to the window manager without any context.
+ *
+ * \warning This function should almost always be avoided in favor of #BKE_reportf,
+ * if this isn't possible, a code-comment must be included explaining why.
+ *
+ * See #WM_global_report for details.
+ */
+void WM_global_reportf(eReportType type, const char *format, ...) ATTR_PRINTF_FORMAT(2, 3);
+
+wmEvent *WM_event_add(wmWindow *win, const wmEvent *event_to_add) ATTR_NONNULL(1, 2);
+
+void wm_event_init_from_window(wmWindow *win, wmEvent *event);
+
+/**
+ * At maximum, every time_step seconds it triggers `event_type` events.
+ */
+wmTimer *WM_event_timer_add(wmWindowManager *wm,
+ wmWindow *win,
+ wmEventType event_type,
+ double time_step);
+wmTimer *WM_event_timer_add_notifier(wmWindowManager *wm,
+ wmWindow *win,
+ unsigned int type,
+ double time_step);
+
+void WM_event_timer_free_data(wmTimer *timer);
+
+/**
+ * Mark the given `timer` to be removed, actual removal and deletion is deferred and handled
+ * internally by the window manager code.
+ */
+void WM_event_timer_remove(wmWindowManager *wm, wmWindow *win, wmTimer *timer);
+void WM_event_timer_remove_notifier(wmWindowManager *wm, wmWindow *win, wmTimer *timer);
+/**
+ * To (de)activate running timers temporary.
+ */
+void WM_event_timer_sleep(wmWindowManager *wm, wmWindow *win, wmTimer *timer, bool do_sleep);
+
+/* Operator API, default callbacks. */
+
+/**
+ * Helper to get select and tweak-transform to work conflict free and as desired. See
+ * #WM_operator_properties_generic_select() for details.
+ *
+ * To be used together with #WM_generic_select_invoke() and
+ * #WM_operator_properties_generic_select().
+ */
+wmOperatorStatus WM_generic_select_modal(bContext *C, wmOperator *op, const wmEvent *event);
+/**
+ * Helper to get select and tweak-transform to work conflict free and as desired. See
+ * #WM_operator_properties_generic_select() for details.
+ *
+ * To be used together with #WM_generic_select_modal() and
+ * #WM_operator_properties_generic_select().
+ */
+wmOperatorStatus WM_generic_select_invoke(bContext *C, wmOperator *op, const wmEvent *event);
+void WM_operator_view3d_unit_defaults(bContext *C, wmOperator *op);
+int WM_operator_smooth_viewtx_get(const wmOperator *op);
+/**
+ * Invoke callback, uses enum property named "type".
+ */
+wmOperatorStatus WM_menu_invoke_ex(bContext *C, wmOperator *op, wm::OpCallContext opcontext);
+wmOperatorStatus WM_menu_invoke(bContext *C, wmOperator *op, const wmEvent *event);
+/**
+ * Call an existent menu. The menu can be created in C or Python.
+ */
+void WM_menu_name_call(bContext *C, const char *menu_name, wm::OpCallContext context);
+
+wmOperatorStatus WM_enum_search_invoke(bContext *C, wmOperator *op, const wmEvent *event);
+
+/**
+ * Invoke callback, confirm menu + exec.
+ */
+wmOperatorStatus WM_operator_confirm(bContext *C, wmOperator *op, const wmEvent *event);
+wmOperatorStatus WM_operator_confirm_or_exec(bContext *C, wmOperator *op, const wmEvent *event);
+
+/**
+ * Like WM_operator_confirm, but with more options and can't be used as an invoke directly.
+ */
+wmOperatorStatus WM_operator_confirm_ex(bContext *C,
+ wmOperator *op,
+ const char *title,
+ const char *message,
+ const char *confirm_text,
+ ui::AlertIcon icon,
+ bool cancel_default = false);
+
+/**
+ * Invoke callback, file selector "filepath" unset + exec.
+ *
+ * #wmOperatorType.invoke, opens file-select if path property not set, otherwise executes.
+ */
+wmOperatorStatus WM_operator_filesel(bContext *C, wmOperator *op, const wmEvent *event);
+bool WM_operator_filesel_ensure_ext_imtype(wmOperator *op, const ImageFormatData *im_format);
+/** Callback for #wmOperatorType.poll. */
+bool WM_operator_winactive(bContext *C);
+/**
+ * Invoke callback, exec + redo popup.
+ *
+ * Same as #WM_operator_props_popup but don't use operator redo.
+ * just wraps #WM_operator_props_dialog_popup.
+ */
+wmOperatorStatus WM_operator_props_popup_confirm(bContext *C,
+ wmOperator *op,
+ const wmEvent *event);
+
+wmOperatorStatus WM_operator_props_popup_confirm_ex(
+ bContext *C,
+ wmOperator *op,
+ const wmEvent *event,
+ std::optional<std::string> title = std::nullopt,
+ std::optional<std::string> confirm_text = std::nullopt,
+ bool cancel_default = false,
+ std::optional<std::string> message = std::nullopt);
+
+/**
+ * Same as #WM_operator_props_popup but call the operator first,
+ * This way - the button values correspond to the result of the operator.
+ * Without this, first access to a button will make the result jump, see #32452.
+ */
+wmOperatorStatus WM_operator_props_popup_call(bContext *C, wmOperator *op, const wmEvent *event);
+wmOperatorStatus WM_operator_props_popup(bContext *C, wmOperator *op, const wmEvent *event);
+
+wmOperatorStatus WM_operator_props_dialog_popup(
+ bContext *C,
+ wmOperator *op,
+ int width,
+ std::optional<std::string> title = std::nullopt,
+ std::optional<std::string> confirm_text = std::nullopt,
+ bool cancel_default = false,
+ std::optional<std::string> message = std::nullopt);
+
+wmOperatorStatus WM_operator_redo_popup(bContext *C, wmOperator *op);
+wmOperatorStatus WM_operator_ui_popup(bContext *C, wmOperator *op, int width);
+
+/**
+ * Can't be used as an invoke directly, needs message arg (can be NULL).
+ */
+wmOperatorStatus WM_operator_confirm_message_ex(bContext *C,
+ wmOperator *op,
+ const char *title,
+ int icon,
+ const char *message,
+ wm::OpCallContext opcontext);
+wmOperatorStatus WM_operator_confirm_message(bContext *C, wmOperator *op, const char *message);
+
+/* Operator API. */
+
+void WM_operator_free(wmOperator *op);
+void WM_operator_free_all_after(wmWindowManager *wm, wmOperator *op);
+/**
+ * Use with extreme care!
+ * Properties, custom-data etc - must be compatible.
+ *
+ * \param op: Operator to assign the type to.
+ * \param ot: Operator type to assign.
+ */
+void WM_operator_type_set(wmOperator *op, wmOperatorType *ot);
+void WM_operator_stack_clear(wmWindowManager *wm);
+void WM_operator_stack_clear(wmWindowManager *wm, const Set<wmOperatorType *> &types);
+/**
+ * This function is needed in the case when an addon id disabled
+ * while a modal operator it defined is running.
+ */
+void WM_operator_handlers_clear(wmWindowManager *wm, wmOperatorType *ot);
+void WM_operator_handlers_clear(wmWindowManager *wm, const Set<wmOperatorType *> &types);
+
+bool WM_operator_poll(bContext *C, wmOperatorType *ot);
+bool WM_operator_poll_context(bContext *C, wmOperatorType *ot, wm::OpCallContext context);
+
+/**
+ * Check poll succeeds or returns false & report an error.
+ *
+ * This can be used from #wmOperatorType::exec for operators that use the file-selector.
+ * It's needed in this case because the context can be changed once the file-selector
+ * has been activated.
+ *
+ * \return true or false & report an error.
+ *
+ * \note It's best practice that `ot->poll` sets the "poll message",
+ * otherwise a generic (unhelpful) error will be used.
+ */
+bool WM_operator_poll_or_report_error(bContext *C, wmOperatorType *ot, ReportList *reports);
+
+/**
+ * For running operators with frozen context (modal handlers, menus).
+ *
+ * \param store: Store properties for re-use when an operator has finished
+ * (unless #PROP_SKIP_SAVE is set).
+ *
+ * \warning do not use this within an operator to call itself! #29537.
+ */
+wmOperatorStatus WM_operator_call_ex(bContext *C, wmOperator *op, bool store);
+wmOperatorStatus WM_operator_call(bContext *C, wmOperator *op);
+/**
+ * This is intended to be used when an invoke operator wants to call exec on itself
+ * and is basically like running op->type->exec() directly, no poll checks no freeing,
+ * since we assume whoever called invoke will take care of that
+ */
+wmOperatorStatus WM_operator_call_notest(bContext *C, wmOperator *op);
+/**
+ * Execute this operator again, put here so it can share above code
+ */
+wmOperatorStatus WM_operator_repeat(bContext *C, wmOperator *op);
+wmOperatorStatus WM_operator_repeat_last(bContext *C, wmOperator *op);
+/**
+ * \return true if #WM_operator_repeat can run.
+ * Simple check for now but may become more involved.
+ * To be sure the operator can run call `WM_operator_poll(C, op->type)` also, since this call
+ * checks if #WM_operator_repeat() can run at all, not that it WILL run at any time.
+ */
+bool WM_operator_repeat_check(const bContext *C, wmOperator *op);
+bool WM_operator_is_repeat(const bContext *C, const wmOperator *op);
+
+bool WM_operator_name_poll(bContext *C, const char *opstring);
+/**
+ * Invokes operator in context.
+ *
+ * \param event: Optionally pass in an event to use when context uses one of the
+ * `WM_OP_INVOKE_*` values. When left unset the #wmWindow.eventstate will be used,
+ * this can cause problems for operators that read the events type - for example,
+ * storing the key that was pressed so as to be able to detect its release.
+ * In these cases it's necessary to forward the current event being handled.
+ */
+wmOperatorStatus WM_operator_name_call_ptr(bContext *C,
+ wmOperatorType *ot,
+ wm::OpCallContext context,
+ PointerRNA *properties,
+ const wmEvent *event);
+/** See #WM_operator_name_call_ptr. */
+wmOperatorStatus WM_operator_name_call(bContext *C,
+ const char *opstring,
+ wm::OpCallContext context,
+ PointerRNA *properties,
+ const wmEvent *event);
+wmOperatorStatus WM_operator_name_call_with_properties(bContext *C,
+ const char *opstring,
+ wm::OpCallContext context,
+ IDProperty *properties,
+ const wmEvent *event);
+/**
+ * Similar to #WM_operator_name_call called with #wm::OpCallContext::ExecDefault
+ * context.
+ *
+ * - #wmOperatorType is used instead of operator name since python already has the operator type.
+ * - `poll()` must be called by python before this runs.
+ * - reports can be passed to this function (so python can report them as exceptions).
+ */
+wmOperatorStatus WM_operator_call_py(bContext *C,
+ wmOperatorType *ot,
+ wm::OpCallContext context,
+ PointerRNA *properties,
+ ReportList *reports,
+ bool is_undo);
+
+void WM_operator_name_call_ptr_with_depends_on_cursor(bContext *C,
+ wmOperatorType *ot,
+ wm::OpCallContext opcontext,
+ PointerRNA *properties,
+ const wmEvent *event,
+ StringRef drawstr);
+
+/**
+ * Similar to the function above except its uses ID properties used for key-maps and macros.
+ */
+void WM_operator_properties_alloc(PointerRNA **ptr, IDProperty **properties, const char *opstring);
+
+/**
+ * Make props context sensitive or not.
+ */
+void WM_operator_properties_sanitize(PointerRNA *ptr, bool no_context);
+
+/**
+ * Set all props to their default.
+ *
+ * \param do_update: Only update un-initialized props.
+ *
+ * \note There's nothing specific to operators here.
+ * This could be made a general function.
+ */
+bool WM_operator_properties_default(PointerRNA *ptr, bool do_update);
+/**
+ * Remove all props without #PROP_SKIP_SAVE or #PROP_SKIP_PRESET.
+ */
+void WM_operator_properties_reset(wmOperator *op);
+PointerRNA WM_operator_properties_create(const char *opstring);
+PointerRNA WM_operator_properties_create_ptr(wmOperatorType *ot);
+void WM_operator_properties_clear(PointerRNA *ptr);
+void WM_operator_properties_free(PointerRNA *ptr);
+
+bool WM_operator_ui_poll(wmOperatorType *ot, PointerRNA *ptr);
+/**
+ * Return false, if the UI should be disabled.
+ */
+bool WM_operator_check_ui_enabled(const bContext *C, const char *idname);
+
+IDProperty *WM_operator_last_properties_ensure_idprops(wmOperatorType *ot);
+void WM_operator_last_properties_ensure(wmOperatorType *ot, PointerRNA *ptr);
+wmOperator *WM_operator_last_redo(const bContext *C);
+/**
+ * Use for drag & drop a path or name with operators invoke() function.
+ * Returns null if no operator property is set to identify the file or ID to use.
+ */
+ID *WM_operator_drop_load_path(bContext *C, wmOperator *op, short idcode);
+
+bool WM_operator_last_properties_init(wmOperator *op);
+bool WM_operator_last_properties_store(wmOperator *op);
+
+/* `wm_operator_props.cc` */
+
+void WM_operator_properties_confirm_or_exec(wmOperatorType *ot);
+
+/** Flags for #WM_operator_properties_filesel. */
+enum eFileSel_Flag {
+ WM_FILESEL_RELPATH = 1 << 0,
+ WM_FILESEL_DIRECTORY = 1 << 1,
+ WM_FILESEL_FILENAME = 1 << 2,
+ WM_FILESEL_FILEPATH = 1 << 3,
+ WM_FILESEL_FILES = 1 << 4,
+ /** Show the properties sidebar by default. */
+ WM_FILESEL_SHOW_PROPS = 1 << 5,
+};
+ENUM_OPERATORS(eFileSel_Flag)
+
+/** Action for #WM_operator_properties_filesel. */
+enum eFileSel_Action {
+ FILE_OPENFILE = 0,
+ FILE_SAVE = 1,
+};
+
+/**
+ * Default properties for file-select.
+ */
+void WM_operator_properties_filesel(wmOperatorType *ot,
+ int filter,
+ short type,
+ eFileSel_Action action,
+ eFileSel_Flag flag,
+ short display,
+ short sort);
+
+/**
+ * Tries to pass \a id to an operator via either a "session_uid" or a "name" property defined in
+ * the properties of \a ptr. The former is preferred, since it works properly with linking and
+ * library overrides (which may both result in multiple IDs with the same name and type).
+ *
+ * Also see #WM_operator_properties_id_lookup() and
+ * #WM_operator_properties_id_lookup_from_name_or_session_uid()
+ */
+void WM_operator_properties_id_lookup_set_from_id(PointerRNA *ptr, const ID *id);
+/**
+ * Tries to find an ID in \a bmain. There needs to be either a "session_uid" int or "name" string
+ * property defined and set. The former has priority. See #WM_operator_properties_id_lookup() for a
+ * helper to add the properties.
+ */
+ID *WM_operator_properties_id_lookup_from_name_or_session_uid(Main *bmain,
+ PointerRNA *ptr,
+ enum ID_Type type);
+/**
+ * Check if either the "session_uid" or "name" property is set inside \a ptr. If this is the case
+ * the ID can be looked up by #WM_operator_properties_id_lookup_from_name_or_session_uid().
+ */
+bool WM_operator_properties_id_lookup_is_set(PointerRNA *ptr);
+/**
+ * Adds "name" and "session_uid" properties so the caller can tell the operator which ID to act
+ * on. See #WM_operator_properties_id_lookup_from_name_or_session_uid(). Both properties will be
+ * hidden in the UI and not be saved over consecutive operator calls.
+ *
+ * \note New operators should probably use "session_uid" only (set \a add_name_prop to #false),
+ * since this works properly with linked data and/or library overrides (in both cases, multiple IDs
+ * with the same name and type may be present). The "name" property is only kept to not break
+ * compatibility with old scripts using some previously existing operators.
+ */
+void WM_operator_properties_id_lookup(wmOperatorType *ot, const bool add_name_prop);
+
+/**
+ * Disable using cursor position,
+ * use when view operators are initialized from buttons.
+ */
+void WM_operator_properties_use_cursor_init(wmOperatorType *ot);
+void WM_operator_properties_border(wmOperatorType *ot);
+void WM_operator_properties_border_to_rcti(wmOperator *op, rcti *r_rect);
+void WM_operator_properties_border_to_rctf(wmOperator *op, rctf *r_rect);
+Bounds<int2> WM_operator_properties_border_to_bounds(wmOperator *op);
+/**
+ * Use with #WM_gesture_box_invoke
+ */
+void WM_operator_properties_gesture_box_ex(wmOperatorType *ot, bool deselect, bool extend);
+void WM_operator_properties_gesture_box(wmOperatorType *ot);
+void WM_operator_properties_gesture_box_select(wmOperatorType *ot);
+void WM_operator_properties_gesture_box_zoom(wmOperatorType *ot);
+/**
+ * Use with #WM_gesture_lasso_invoke
+ */
+void WM_operator_properties_gesture_lasso(wmOperatorType *ot);
+/**
+ * Use with #WM_gesture_polyline_invoke
+ */
+void WM_operator_properties_gesture_polyline(wmOperatorType *ot);
+/**
+ * Use with #WM_gesture_straightline_invoke
+ */
+void WM_operator_properties_gesture_straightline(wmOperatorType *ot, int cursor);
+/**
+ * Use with #WM_gesture_circle_invoke
+ */
+void WM_operator_properties_gesture_circle(wmOperatorType *ot);
+/**
+ * See #ED_select_pick_params_from_operator to initialize parameters defined here.
+ */
+void WM_operator_properties_mouse_select(wmOperatorType *ot);
+void WM_operator_properties_select_all(wmOperatorType *ot);
+void WM_operator_properties_select_action(wmOperatorType *ot, int default_action, bool hide_gui);
+/**
+ * Only for select/de-select.
+ */
+void WM_operator_properties_select_action_simple(wmOperatorType *ot,
+ int default_action,
+ bool hide_gui);
+/**
+ * Use for all select random operators.
+ * Adds properties: percent, seed, action.
+ */
+void WM_operator_properties_select_random(wmOperatorType *ot);
+int WM_operator_properties_select_random_seed_increment_get(wmOperator *op);
+void WM_operator_properties_select_operation(wmOperatorType *ot);
+/**
+ * \note Some tools don't support XOR/AND.
+ */
+void WM_operator_properties_select_operation_simple(wmOperatorType *ot);
+void WM_operator_properties_select_walk_direction(wmOperatorType *ot);
+/**
+ * Selecting and tweaking items are overlapping operations. Getting both to work without conflicts
+ * requires special care. See
+ * https://wiki.blender.org/wiki/Human_Interface_Guidelines/Selection#Select-tweaking for the
+ * desired behavior.
+ *
+ * For default click selection (with no modifier keys held), the select operators can do the
+ * following:
+ * - On a mouse press on an unselected item, change selection and finish immediately after.
+ * This sends an undo push and allows transform to take over should a click-drag event be caught.
+ * - On a mouse press on a selected item, don't change selection state, but start modal execution
+ * of the operator. Idea is that we wait with deselecting other items until we know that the
+ * intention wasn't to tweak (mouse press+drag) all selected items.
+ * - If a click-drag is recognized before the release event happens, cancel the operator,
+ * so that transform can take over and no undo-push is sent.
+ * - If the release event occurs rather than a click-drag one,
+ * deselect all items but the one under the cursor, and finish the modal operator.
+ *
+ * This utility, together with #WM_generic_select_invoke() and #WM_generic_select_modal() should
+ * help getting the wanted behavior to work. Most generic logic should be handled in these, so that
+ * the select operators only have to care for the case dependent handling.
+ *
+ * Every select operator has slightly different requirements, e.g. sequencer strip selection
+ * also needs to account for handle selection. This should be the baseline behavior though.
+ */
+void WM_operator_properties_generic_select(wmOperatorType *ot);
+
+struct CheckerIntervalParams {
+ /** Bypass when set to zero. */
+ int nth;
+ int skip;
+ int offset;
+};
+/**
+ * \param nth_can_disable: Enable if we want to be able to select no interval at all.
+ */
+void WM_operator_properties_checker_interval(wmOperatorType *ot, bool nth_can_disable);
+void WM_operator_properties_checker_interval_from_op(wmOperator *op,
+ CheckerIntervalParams *op_params);
+bool WM_operator_properties_checker_interval_test(const CheckerIntervalParams *op_params,
+ int depth);
+
+/**
+ * Operator as a Python command.
+ *
+ * Return a string representation of the operator,
+ * with the arguments that it runs so Python can run it again.
+ *
+ * When calling from an existing #wmOperator, better to use simple version:
+ * `WM_operator_pystring(C, op);`
+ *
+ * \note Both \a op and \a opptr may be `NULL` (\a op is only used for macro operators).
+ */
+std::string WM_operator_pystring_ex(bContext *C,
+ wmOperator *op,
+ bool all_args,
+ bool macro_args,
+ wmOperatorType *ot,
+ PointerRNA *opptr);
+std::string WM_operator_pystring(bContext *C, wmOperator *op, bool all_args, bool macro_args);
+
+std::string WM_operator_pystring_abbreviate(std::string str, int str_len_max);
+
+std::optional<std::string> WM_prop_pystring_assign(bContext *C,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ int index);
+/**
+ * Convert: `some.op` -> `SOME_OT_op` or leave as-is.
+ * \return the length of `dst`.
+ */
+size_t WM_operator_bl_idname(char *dst, const char *src) ATTR_NONNULL(1, 2);
+/**
+ * Convert: `SOME_OT_op` -> `some.op` or leave as-is.
+ * \return the length of `dst`.
+ */
+size_t WM_operator_py_idname(char *dst, const char *src) ATTR_NONNULL(1, 2);
+/**
+ * Sanity check to ensure #WM_operator_bl_idname won't fail.
+ * \returns true when there are no problems with \a idname, otherwise report an error.
+ */
+bool WM_operator_py_idname_ok_or_report(ReportList *reports,
+ const char *classname,
+ const char *idname);
+bool WM_operator_idname_ok_or_report(ReportList *reports, const char *idname);
+/**
+ * Return true when an operators name follows the `SOME_OT_op` naming convention.
+ */
+bool WM_operator_bl_idname_is_valid(const char *idname);
+
+/**
+ * Calculate the path to `ptr` from context `C`, or return NULL if it can't be calculated.
+ */
+std::optional<std::string> WM_context_path_resolve_property_full(const bContext *C,
+ const PointerRNA *ptr,
+ PropertyRNA *prop,
+ int index);
+std::optional<std::string> WM_context_path_resolve_full(bContext *C, const PointerRNA *ptr);
+
+/* `wm_operator_type.cc` */
+
+wmOperatorType *WM_operatortype_find(const char *idname, bool quiet);
+Span<wmOperatorType *> WM_operatortypes_registered_get();
+void WM_operatortype_append(void (*opfunc)(wmOperatorType *ot));
+void WM_operatortype_append_ptr(void (*opfunc)(wmOperatorType *ot, void *userdata),
+ void *userdata);
+void WM_operatortype_append_macro_ptr(void (*opfunc)(wmOperatorType *ot, void *userdata),
+ void *userdata);
+/**
+ * Called on initialize WM_exit().
+ */
+void WM_operatortype_remove_ptr(wmOperatorType *ot);
+bool WM_operatortype_remove(const char *idname);
+/**
+ * Remove memory of all previously executed tools.
+ */
+void WM_operatortype_last_properties_clear_all();
+
+void WM_operatortype_idname_visit_for_search(
+ const bContext *C,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ const char *edit_text,
+ FunctionRef<void(StringPropertySearchVisitParams)> visit_fn);
+
+/**
+ * Tag all operator-properties of \a ot defined after calling this, until
+ * the next #WM_operatortype_props_advanced_end call (if available), with
+ * #OP_PROP_TAG_ADVANCED. Previously defined ones properties not touched.
+ *
+ * Calling this multiple times without a call to #WM_operatortype_props_advanced_end,
+ * all calls after the first one are ignored. Meaning all proprieties defined after the
+ * first call are tagged as advanced.
+ *
+ * This doesn't do the actual tagging, #WM_operatortype_props_advanced_end does which is
+ * called for all operators during registration (see #wm_operatortype_append__end).
+ */
+void WM_operatortype_props_advanced_begin(wmOperatorType *ot);
+/**
+ * Tags all operator-properties of \a ot defined since the first
+ * #WM_operatortype_props_advanced_begin call,
+ * or the last #WM_operatortype_props_advanced_end call, with #OP_PROP_TAG_ADVANCED.
+ *
+ * \note This is called for all operators during registration (see #wm_operatortype_append__end).
+ * So it does not need to be explicitly called in operator-type definition.
+ */
+void WM_operatortype_props_advanced_end(wmOperatorType *ot);
+
+#define WM_operatortype_prop_tag(property, tags) \
+ { \
+ CHECK_TYPE(tags, eOperatorPropTags); \
+ RNA_def_property_tags(prop, tags); \
+ } \
+ (void)0
+
+/**
+ * \note Names have to be static for now.
+ */
+wmOperatorType *WM_operatortype_append_macro(const char *idname,
+ const char *name,
+ const char *description,
+ int flag);
+wmOperatorTypeMacro *WM_operatortype_macro_define(wmOperatorType *ot, const char *idname);
+
+std::string WM_operatortype_name(wmOperatorType *ot, PointerRNA *properties);
+std::string WM_operatortype_description(bContext *C, wmOperatorType *ot, PointerRNA *properties);
+/**
+ * Use when we want a label, preferring the description.
+ */
+std::string WM_operatortype_description_or_name(bContext *C,
+ wmOperatorType *ot,
+ PointerRNA *properties);
+
+/** Check the #OPTYPE_DEPENDS_ON_CURSOR flag and the callback. */
+bool WM_operator_depends_on_cursor(bContext &C, wmOperatorType &ot, PointerRNA *properties);
+
+/* `wm_operator_utils.cc` */
+
+/**
+ * Allow an operator with only and execute function to run modally,
+ * re-doing the action, using vertex coordinate store/restore instead of operator undo.
+ */
+void WM_operator_type_modal_from_exec_for_object_edit_coords(wmOperatorType *ot);
+
+/* `wm_uilist_type.cc` */
+
+/**
+ * Called on initialize #WM_init()
+ */
+void WM_uilisttype_init();
+uiListType *WM_uilisttype_find(StringRef idname, bool quiet);
+bool WM_uilisttype_add(uiListType *ult);
+void WM_uilisttype_remove_ptr(Main *bmain, uiListType *ult);
+void WM_uilisttype_free();
+
+/**
+ * The "full" list-ID is an internal name used for storing and identifying a list. It is built like
+ * this:
+ * `{uiListType.idname}_{list_id}`, whereby `list_id` is an optional parameter passed to
+ * `ui::Layout.template_uilist()`. If it is not set, the full list-ID is just
+ * `{uiListType.idname}_`.
+ *
+ * Note that whenever the Python API refers to the list-ID, it's the short, "non-full" one it
+ * passed to `ui::Layout.template_list()`. C code can query that through
+ * #WM_uilisttype_list_id_get().
+ */
+void WM_uilisttype_to_full_list_id(const uiListType *ult,
+ const char *list_id,
+ char r_full_list_id[]);
+/**
+ * Get the "non-full" list-ID, see #WM_uilisttype_to_full_list_id() for details.
+ *
+ * \note Assumes `uiList.list_id` was set using #WM_uilisttype_to_full_list_id()!
+ */
+const char *WM_uilisttype_list_id_get(const uiListType *ult, uiList *list);
+
+/* `wm_menu_type.cc` */
+
+/**
+ * \note Called on initialize #WM_init().
+ */
+void WM_menutype_init();
+MenuType *WM_menutype_find(StringRef idname, bool quiet);
+Span<MenuType *> WM_menutypes_registered_get();
+bool WM_menutype_add(MenuType *mt);
+void WM_menutype_freelink(MenuType *mt);
+void WM_menutype_free();
+bool WM_menutype_poll(bContext *C, MenuType *mt);
+
+void WM_menutype_idname_visit_for_search(
+ const bContext *C,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ const char *edit_text,
+ FunctionRef<void(StringPropertySearchVisitParams)> visit_fn);
+
+/* `wm_panel_type.cc` */
+
+/**
+ * Called on initialize #WM_init().
+ */
+void WM_paneltype_init();
+void WM_paneltype_clear();
+PanelType *WM_paneltype_find(StringRef idname, bool quiet);
+bool WM_paneltype_add(PanelType *pt);
+void WM_paneltype_remove(PanelType *pt);
+
+void WM_paneltype_idname_visit_for_search(
+ const bContext *C,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ const char *edit_text,
+ FunctionRef<void(StringPropertySearchVisitParams)> visit_fn);
+
+/* `wm_gesture_ops.cc` */
+
+wmOperatorStatus WM_gesture_box_invoke(bContext *C, wmOperator *op, const wmEvent *event);
+wmOperatorStatus WM_gesture_box_modal(bContext *C, wmOperator *op, const wmEvent *event);
+void WM_gesture_box_cancel(bContext *C, wmOperator *op);
+wmOperatorStatus WM_gesture_circle_invoke(bContext *C, wmOperator *op, const wmEvent *event);
+wmOperatorStatus WM_gesture_circle_modal(bContext *C, wmOperator *op, const wmEvent *event);
+void WM_gesture_circle_cancel(bContext *C, wmOperator *op);
+wmOperatorStatus WM_gesture_lines_invoke(bContext *C, wmOperator *op, const wmEvent *event);
+wmOperatorStatus WM_gesture_lines_modal(bContext *C, wmOperator *op, const wmEvent *event);
+void WM_gesture_lines_cancel(bContext *C, wmOperator *op);
+wmOperatorStatus WM_gesture_lasso_invoke(bContext *C, wmOperator *op, const wmEvent *event);
+wmOperatorStatus WM_gesture_lasso_modal(bContext *C, wmOperator *op, const wmEvent *event);
+void WM_gesture_lasso_cancel(bContext *C, wmOperator *op);
+wmOperatorStatus WM_gesture_polyline_invoke(bContext *C, wmOperator *op, const wmEvent *event);
+wmOperatorStatus WM_gesture_polyline_modal(bContext *C, wmOperator *op, const wmEvent *event);
+void WM_gesture_polyline_cancel(bContext *C, wmOperator *op);
+/**
+ * helper function, we may want to add options for conversion to view space
+ */
+Array<int2> WM_gesture_lasso_path_to_array(bContext *C, wmOperator *op);
+
+wmOperatorStatus WM_gesture_straightline_invoke(bContext *C, wmOperator *op, const wmEvent *event);
+/**
+ * This invoke callback starts the straight-line gesture with a viewport preview to the right side
+ * of the line.
+ */
+wmOperatorStatus WM_gesture_straightline_active_side_invoke(bContext *C,
+ wmOperator *op,
+ const wmEvent *event);
+/**
+ * This modal callback calls exec once per mouse move event while the gesture is active with the
+ * updated line start and end values, so it can be used for tools that have a real time preview
+ * (like a gradient updating in real time over the mesh).
+ */
+wmOperatorStatus WM_gesture_straightline_modal(bContext *C, wmOperator *op, const wmEvent *event);
+/**
+ * This modal one-shot callback only calls exec once after the gesture finishes without any updates
+ * during the gesture execution. Should be used for operations that are intended to be applied once
+ * without real time preview (like a trimming tool that only applies the bisect operation once
+ * after finishing the gesture as the bisect operation is too heavy to be computed in real time for
+ * a preview).
+ */
+wmOperatorStatus WM_gesture_straightline_oneshot_modal(bContext *C,
+ wmOperator *op,
+ const wmEvent *event);
+void WM_gesture_straightline_cancel(bContext *C, wmOperator *op);
+
+/* Gesture manager API. */
+
+/**
+ * Context checked on having screen, window and area.
+ */
+wmGesture *WM_gesture_new(wmWindow *window, const ARegion *region, const wmEvent *event, int type);
+void WM_gesture_end(wmWindow *win, wmGesture *gesture);
+void WM_gestures_remove(wmWindow *win);
+void WM_gestures_free_all(wmWindow *win);
+bool WM_gesture_is_modal_first(const wmGesture *gesture);
+
+/* File-selecting support. */
+
+/**
+ * The idea here is to keep a handler alive on window queue, owning the operator.
+ * The file window can send event to make it execute, thus ensuring
+ * executing happens outside of lower level queues, with UI refreshed.
+ * Should also allow multi-window solutions.
+ */
+void WM_event_add_fileselect(bContext *C, wmOperator *op);
+void WM_event_fileselect_event(wmWindowManager *wm, void *ophandle, int eventval);
+
+/* Event consecutive data. */
+
+/** Return a borrowed reference to the custom-data. */
+void *WM_event_consecutive_data_get(wmWindow *win, const char *id);
+/** Set the custom-data (and own the pointer), free with #MEM_delete_void. */
+void WM_event_consecutive_data_set(wmWindow *win, const char *id, void *custom_data);
+/** Clear and free the consecutive custom-data. */
+void WM_event_consecutive_data_free(wmWindow *win);
+
+/**
+ * Sets the active region for this space from the context.
+ *
+ * \see #BKE_area_find_region_active_win
+ */
+void WM_operator_region_active_win_set(bContext *C);
+
+/**
+ * Indented for use in a selection (picking) operators #wmOperatorType::invoke callback
+ * to implement click-drag, where the initial click selects and the drag action
+ * grabs or performs box-select (for example).
+ *
+ * - In this case, returning `OPERATOR_FINISHED` causes the PRESS event
+ * to be handled and prevents further CLICK (on release) or DRAG (on cursor motion)
+ * from being generated & handled.
+ *
+ * - Returning `OPERATOR_FINISHED | OPERATOR_PASS_THROUGH` allows for CLICK/DRAG but only makes
+ * sense if the event's value is PRESS. If the operator was already mapped to a CLICK/DRAG event,
+ * a single CLICK/DRAG could invoke multiple operators.
+ *
+ * This function handles the details of checking the operator return value,
+ * clearing #OPERATOR_PASS_THROUGH when the #wmEvent::val is not #KM_PRESS.
+ *
+ * \note Combining selection with other actions should only be used
+ * in situations where selecting doesn't change the visibility of other items.
+ * Since it means for example click-drag to box select could hide-show elements the user
+ * intended to box-select. In this case it's preferred to select on CLICK instead of PRESS
+ * (see the Outliner use of click-drag).
+ */
+wmOperatorStatus WM_operator_flag_only_pass_through_on_press(wmOperatorStatus retval,
+ const wmEvent *event);
+
+/* Drag and drop. */
+
+/**
+ * Start dragging immediately with the given data.
+ * Note that \a poin should be valid allocated and not on stack.
+ */
+void WM_event_start_drag(
+ bContext *C, int icon, eWM_DragDataType type, void *poin, unsigned int flags);
+/**
+ * Create and fill the dragging data, but don't start dragging just yet (unlike
+ * #WM_event_start_drag()). Must be followed up by #WM_event_start_prepared_drag(), otherwise the
+ * returned pointer will leak memory.
+ *
+ * Note that \a poin should be valid allocated and not on stack.
+ */
+wmDrag *WM_drag_data_create(
+ bContext *C, int icon, eWM_DragDataType type, void *poin, unsigned int flags);
+/**
+ * Invoke dragging using the given \a drag data.
+ */
+void WM_event_start_prepared_drag(bContext *C, wmDrag *drag);
+void WM_event_drag_image(wmDrag *drag, const ImBuf *imb, float scale);
+/**
+ * Overrides the `drag.poin` event to include all selected files in the space file where the event
+ * started.
+ */
+void WM_event_drag_path_override_poin_data_with_space_file_paths(const bContext *, wmDrag *drag);
+void WM_event_drag_preview_icon(wmDrag *drag, int icon_id);
+void WM_drag_free(wmDrag *drag);
+void WM_drag_data_free(eWM_DragDataType dragtype, void *poin);
+void WM_drag_free_list(ListBaseT<wmDrag> *lb);
+wmDropBox *WM_dropbox_add(ListBaseT<wmDropBox> *lb,
+ const char *idname,
+ bool (*poll)(bContext *C, wmDrag *drag, const wmEvent *event),
+ void (*copy)(bContext *C, wmDrag *drag, wmDropBox *drop),
+ void (*cancel)(Main *bmain, wmDrag *drag, wmDropBox *drop),
+ WMDropboxTooltipFunc tooltip);
+/**
+ * Register a "prefetch" handler that gets triggered whenever dragging starts, independent of which
+ * drop handlers are available or will be used in the end.
+ *
+ * #wmDropBox::on_drag_start() is similar, but it will only be executed for drop-boxes visible in a
+ * window. For example, sequencer drop-boxes pre-fetch information about dragged media files this
+ * way, but this should only be done if a sequencer is visible somewhere.
+ *
+ * Contrary to the #wmDropBox::on_drag_start() prefetch handlers, the "global" prefetch handlers
+ * here always trigger for the given data type.
+ */
+void WM_drag_global_prefetch_handler_add(
+ const eWM_DragDataType drag_type,
+ const std::function<void(bContext &C, wmDrag &drag)> on_drag_start);
+/**
+ * Ensure operator pointers & properties are valid after operators have been added/removed.
+ */
+void WM_dropbox_update_ot();
+
+void WM_drag_draw_item_name_fn(bContext *C, wmWindow *win, wmDrag *drag, const int xy[2]);
+void WM_drag_draw_default_fn(bContext *C, wmWindow *win, wmDrag *drag, const int xy[2]);
+/**
+ * `spaceid` / `regionid` are zero for window drop maps.
+ */
+ListBaseT<wmDropBox> *WM_dropboxmap_find(const char *idname, int spaceid, int regionid);
+
+/* ID drag and drop. */
+
+/**
+ * \note This can return null! Importing can fail if the asset was deleted or moved since the asset
+ * library was loaded.
+ *
+ * \param flag_extra: Additional linking flags (from #eFileSel_Params_Flag).
+ */
+ID *WM_drag_asset_id_import(const bContext *C, wmDragAsset *asset_drag, int flag_extra);
+bool WM_drag_asset_will_import_linked(const wmDrag *drag);
+bool WM_drag_asset_will_import_packed(const wmDrag *drag);
+void WM_drag_add_local_ID(wmDrag *drag, ID *id, ID *from_parent);
+ID *WM_drag_get_local_ID(const wmDrag *drag, short idcode);
+ID *WM_drag_get_local_ID_from_event(const wmEvent *event, short idcode);
+/**
+ * Check if the drag data is either a local ID or an external ID asset of type \a idcode.
+ */
+bool WM_drag_is_ID_type(const wmDrag *drag, int idcode);
+
+/**
+ * \note Does not store \a asset in any way, so it's fine to pass a temporary.
+ */
+wmDragAsset *WM_drag_create_asset_data(const asset_system::AssetRepresentation *asset,
+ const AssetImportSettings &import_settings);
+
+wmDragAsset *WM_drag_get_asset_data(const wmDrag *drag, int idcode);
+AssetMetaData *WM_drag_get_asset_meta_data(const wmDrag *drag, int idcode);
+/**
+ * When dragging a local ID, return that. Otherwise, if dragging an asset-handle, link or append
+ * that depending on what was chosen by the drag-box (currently append only in fact).
+ *
+ * Use #WM_drag_free_imported_drag_ID() as cancel callback of the drop-box, so that the asset
+ * import is rolled back if the drop operator fails.
+ */
+ID *WM_drag_get_local_ID_or_import_from_asset(const bContext *C, const wmDrag *drag, int idcode);
+
+/**
+ * \brief Free asset ID imported for canceled drop.
+ *
+ * If the asset was imported (linked/appended) using #WM_drag_get_local_ID_or_import_from_asset()`
+ * (typically via a #wmDropBox.copy() callback), we want the ID to be removed again if the drop
+ * operator cancels.
+ * This is for use as #wmDropBox.cancel() callback.
+ */
+void WM_drag_free_imported_drag_ID(Main *bmain, wmDrag *drag, wmDropBox *drop);
+
+wmDragAssetCatalog *WM_drag_get_asset_catalog_data(const wmDrag *drag);
+
+/**
+ * \note Does not store \a asset in any way, so it's fine to pass a temporary.
+ */
+void WM_drag_add_asset_list_item(wmDrag *drag, const asset_system::AssetRepresentation *asset);
+
+const ListBaseT<wmDragAssetListItem> *WM_drag_asset_list_get(const wmDrag *drag);
+
+const std::string WM_drag_get_item_name(wmDrag *drag);
+
+/* Paths drag and drop. */
+/**
+ * \param paths: The paths to drag. Values will be copied into the drag data so the passed strings
+ * may be destructed.
+ */
+wmDragPath *WM_drag_create_path_data(Span<const char *> paths);
+/**
+ * If `drag` contains path data, returns the first path int he path list.
+ */
+const char *WM_drag_get_single_path(const wmDrag *drag);
+/**
+ * If `drag` contains path data, returns the first path in the path list that matches a
+ * a `file_type`.
+ *
+ * \param drag: The drag that could contain drag path data.
+ * \param file_type: #eFileSel_File_Types bit flag.
+ */
+const char *WM_drag_get_single_path(const wmDrag *drag, int file_type);
+Span<std::string> WM_drag_get_paths(const wmDrag *drag);
+/**
+ * If `drag` contains path data, returns if any file path match a `file_type`.
+ *
+ * \param drag: The drag that could contain drag path data.
+ * \param file_type: #eFileSel_File_Types bit flag.
+ */
+bool WM_drag_has_path_file_type(const wmDrag *drag, int file_type);
+/**
+ * Note that even though the enum return type uses bit-flags, this should never have multiple
+ * type-bits set, so `ELEM()` like comparison is possible. To check all paths or to do a bit-flag
+ * check use `WM_drag_has_path_file_type(drag, file_type)` instead.
+ */
+int /*eFileSel_File_Types*/ WM_drag_get_path_file_type(const wmDrag *drag);
+
+const std::string &WM_drag_get_string(const wmDrag *drag);
+std::string WM_drag_get_string_firstline(const wmDrag *drag);
+
+/* Set OpenGL viewport and scissor. */
+void wmViewport(const rcti *winrct);
+void wmPartialViewport(rcti *drawrct, const rcti *winrct, const rcti *partialrct);
+void wmWindowViewport(const wmWindow *win);
+void wmWindowViewport_ex(const wmWindow *win, float offset);
+
+/* Closely related to #wmWindowViewport but for drawing the title-bar. */
+void wmWindowViewportTitle_ex(const rcti &rect, float offset);
+void wmWindowViewportTitle(const rcti &rect);
+
+/* OpenGL utilities with safety check. */
+void wmOrtho2(float x1, float x2, float y1, float y2);
+/* Use for conventions (avoid hard-coded offsets all over). */
+
+/**
+ * Default pixel alignment for regions.
+ */
+void wmOrtho2_region_pixelspace(const ARegion *region);
+void wmOrtho2_pixelspace(float x, float y);
+void wmGetProjectionMatrix(float mat[4][4], const rcti *winrct);
+
+/* Threaded Jobs Manager. */
+enum eWM_JobFlag {
+ WM_JOB_PRIORITY = (1 << 0),
+ /**
+ * Only one render job can run at a time, this tags them a such. New jobs with this flag will
+ * wait on previous ones to finish then.
+ */
+ WM_JOB_EXCL_RENDER = (1 << 1),
+ WM_JOB_PROGRESS = (1 << 2),
+};
+ENUM_OPERATORS(eWM_JobFlag);
+
+/**
+ * Identifying jobs by owner alone is unreliable, this isn't saved, order can change.
+ */
+enum eWM_JobType {
+ /** Not a real type, use for querying any type. */
+ WM_JOB_TYPE_ANY = 0,
+
+ WM_JOB_TYPE_COMPOSITE,
+ WM_JOB_TYPE_RENDER,
+ WM_JOB_TYPE_RENDER_PREVIEW, /* UI preview. */
+ /** Job for the UI to load previews from the file system (uses OS thumbnail cache). */
+ WM_JOB_TYPE_LOAD_PREVIEW, /* UI preview. */
+ WM_JOB_TYPE_OBJECT_SIM_OCEAN,
+ WM_JOB_TYPE_OBJECT_SIM_FLUID,
+ WM_JOB_TYPE_OBJECT_BAKE_TEXTURE,
+ WM_JOB_TYPE_OBJECT_BAKE,
+ WM_JOB_TYPE_FILESEL_READDIR,
+ WM_JOB_TYPE_ASSET_LIBRARY_LOAD,
+ /** For the global asset list storage (#ED_asset_list.hh). Use a different job type from
+ * #WM_JOB_TYPE_ASSET_LIBRARY_LOAD (used by the asset browser) so the global storage loading can
+ * happen independently of the asset browser loading. They would block each other if the type was
+ * the same. */
+ WM_JOB_TYPE_ASSET_LIBRARY_GLOBAL_LISTING_LOAD,
+ WM_JOB_TYPE_CLIP_BUILD_PROXY,
+ WM_JOB_TYPE_CLIP_TRACK_MARKERS,
+ WM_JOB_TYPE_CLIP_SOLVE_CAMERA,
+ WM_JOB_TYPE_CLIP_PREFETCH,
+ WM_JOB_TYPE_SEQ_BUILD_PROXY,
+ WM_JOB_TYPE_SEQ_BUILD_PREVIEW,
+ WM_JOB_TYPE_POINTCACHE,
+ WM_JOB_TYPE_DPAINT_BAKE,
+ WM_JOB_TYPE_ALEMBIC_IMPORT,
+ WM_JOB_TYPE_ALEMBIC_EXPORT,
+ WM_JOB_TYPE_USD_IMPORT,
+ WM_JOB_TYPE_USD_EXPORT,
+ WM_JOB_TYPE_SHADER_COMPILATION,
+ WM_JOB_TYPE_STUDIOLIGHT,
+ WM_JOB_TYPE_LIGHT_BAKE,
+ WM_JOB_TYPE_FSMENU_BOOKMARK_VALIDATE,
+ WM_JOB_TYPE_QUADRIFLOW_REMESH,
+ WM_JOB_TYPE_TRACE_IMAGE,
+ WM_JOB_TYPE_LINEART,
+ WM_JOB_TYPE_SEQ_DRAW_THUMBNAIL,
+ WM_JOB_TYPE_SEQ_DRAG_DROP_PREVIEW,
+ WM_JOB_TYPE_CALCULATE_SIMULATION_NODES,
+ WM_JOB_TYPE_BAKE_GEOMETRY_NODES,
+ WM_JOB_TYPE_UV_PACK,
+ WM_JOB_TYPE_GENERATE_TEXTURE_CACHE,
+ WM_JOB_TYPE_SOUND_MIXDOWN,
+ /* Add as needed, bake, seq proxy build
+ * if having hard coded values is a problem. */
+};
+
+/**
+ * \return current job or adds new job, but doesn't run it.
+ *
+ * \note every owner only gets a single running job of the same \a job_type (or with the
+ * #WM_JOB_EXCL_RENDER flag). Adding a new one will wait for the running job to finish.
+ */
+wmJob *WM_jobs_get(wmWindowManager *wm,
+ wmWindow *win,
+ const void *owner,
+ const char *name,
+ eWM_JobFlag flag,
+ eWM_JobType job_type);
+
+/**
+ * Returns true if job runs, for UI (progress) indicators.
+ */
+bool WM_jobs_test(const wmWindowManager *wm, const void *owner, int job_type);
+float WM_jobs_progress(const wmWindowManager *wm, const void *owner);
+const char *WM_jobs_name(const wmWindowManager *wm, const void *owner);
+/**
+ * Time that job started.
+ */
+double WM_jobs_starttime(const wmWindowManager *wm, const void *owner);
+void *WM_jobs_customdata_from_type(wmWindowManager *wm, const void *owner, int job_type);
+
+bool WM_jobs_is_running(const wmJob *wm_job);
+bool WM_jobs_is_stopped(const wmWindowManager *wm, const void *owner);
+void *WM_jobs_customdata_get(wmJob *wm_job);
+void WM_jobs_customdata_set(wmJob *wm_job, void *customdata, void (*free)(void *));
+void WM_jobs_timer(wmJob *wm_job,
+ double time_step,
+ unsigned int note,
+ unsigned int endnote,
+ void (*timer_step)(void *) = nullptr);
+void WM_jobs_delay_start(wmJob *wm_job, double delay_time);
+
+using wm_jobs_start_callback = void (*)(void *custom_data, wmJobWorkerStatus *worker_status);
+void WM_jobs_callbacks(wmJob *wm_job,
+ wm_jobs_start_callback startjob,
+ void (*initjob)(void *),
+ void (*update)(void *),
+ void (*endjob)(void *));
+
+void WM_jobs_callbacks_ex(wmJob *wm_job,
+ wm_jobs_start_callback startjob,
+ void (*initjob)(void *),
+ void (*update)(void *),
+ void (*endjob)(void *),
+ void (*completed)(void *),
+ void (*canceled)(void *));
+
+/**
+ * Register the given \a wm_job and try to start it immediately.
+ *
+ * The new \a wm_job will not start immediately and wait for other blocking jobs
+ * to end in some way if:
+ * - the new job is flagged with #WM_JOB_EXCL_RENDER and another job with the same flag is already
+ * running (blocks it), or...
+ * - the new job is __not__ flagged with #WM_JOB_EXCL_RENDER and a job of the same #eWM_JobType is
+ * already running (blocks it).
+ *
+ * If the new \a wm_job is flagged with #WM_JOB_PRIORITY, it will request other blocking jobs to
+ * stop (using #WM_jobs_stop(), so this doesn't take immediate effect) rather than finish its work.
+ * Additionally, it will hint the operating system to use performance cores on hybrid CPUs.
+ */
+void WM_jobs_start(wmWindowManager *wm, wmJob *wm_job);
+/**
+ * Signal all jobs of this type and owner (if non-null) to stop, timer is required to get
+ * handled.
+ *
+ * Don't pass #WM_JOB_TYPE_ANY as \a job_type. Use #WM_jobs_stop_all_from_owner() instead.
+ */
+void WM_jobs_stop_type(wmWindowManager *wm, const void *owner, eWM_JobType job_type);
+/**
+ * Signal all jobs from this owner to stop, timer is required to get handled.
+ *
+ * Beware of the impact of calling this. For example passing the scene will stop **all** jobs
+ * having the scene as owner, even otherwise unrelated jobs.
+ */
+void WM_jobs_stop_all_from_owner(wmWindowManager *wm, const void *owner) ATTR_NONNULL();
+/**
+ * Wait until every job ended.
+ */
+void WM_jobs_kill_all(wmWindowManager *wm);
+/**
+ * Wait until every job ended, except for one owner (used in undo to keep screen job alive).
+ */
+void WM_jobs_kill_all_except(wmWindowManager *wm, const void *owner);
+/**
+ * Terminate thread and timer of all jobs of this type and owner (if non-null).
+ *
+ * Don't pass #WM_JOB_TYPE_ANY as \a job_type. Use #WM_jobs_kill_all_from_owner() instead.
+ */
+void WM_jobs_kill_type(wmWindowManager *wm, const void *owner, int job_type);
+/**
+ * Terminate thread and timer of all jobs from this owner.
+ *
+ * Beware of the impact of calling this. For example passing the scene will kill **all** jobs
+ * having the scene as owner, even otherwise unrelated jobs.
+ */
+void WM_jobs_kill_all_from_owner(wmWindowManager *wm, const void *owner) ATTR_NONNULL();
+
+bool WM_jobs_has_running(const wmWindowManager *wm);
+bool WM_jobs_has_running_type(const wmWindowManager *wm, int job_type);
+
+void WM_job_main_thread_lock_acquire(wmJob *wm_job);
+void WM_job_main_thread_lock_release(wmJob *wm_job);
+
+/* Clipboard. */
+
+/**
+ * Return text from the clipboard.
+ * \param selection: Use the "primary" clipboard, see: #WM_CAPABILITY_CLIPBOARD_PRIMARY.
+ * \param ensure_utf8: Ensure the resulting string does not contain invalid UTF8 encoding.
+ */
+char *WM_clipboard_text_get(bool selection, bool ensure_utf8, int *r_len);
+/**
+ * Convenience function for pasting to areas of Blender which don't support newlines.
+ */
+char *WM_clipboard_text_get_firstline(bool selection, bool ensure_utf8, int *r_len);
+
+void WM_clipboard_text_set(const char *buf, bool selection);
+
+/**
+ * Returns true if the clipboard contains an image.
+ */
+bool WM_clipboard_image_available();
+
+/**
+ * Get image data from the clipboard.
+ * \return The image or null when not found. Caller must free.
+ */
+ImBuf *WM_clipboard_image_get();
+
+/**
+ * Put image data to the clipboard.
+ *
+ * \param ibuf: the image to set the clipboard to.
+ */
+bool WM_clipboard_image_set_byte_buffer(ImBuf *ibuf) ATTR_NONNULL(1);
+
+/* Progress. */
+
+void WM_progress_set(wmWindow *win, float progress);
+void WM_progress_clear(wmWindow *win);
+
+/* Draw (for screenshot). */
+
+void *WM_draw_cb_activate(wmWindow *win,
+ void (*draw)(const wmWindow *win, void *customdata),
+ void *customdata);
+void WM_draw_cb_exit(wmWindow *win, void *handle);
+/**
+ * High level function to redraw windows.
+ *
+ * \warning this should be avoided by operators and low-level IO functionality
+ * because drawing relies on the event system & depsgraph preparing data for display.
+ * An explicit call to draw is error prone since it may attempt to show stale data.
+ *
+ * With some rare exceptions which require a redraw (e.g. screen-shot & sample screen color)
+ * explicitly redrawing should be avoided, see: #92704, #93950, #97627 & #98462.
+ */
+void WM_redraw_windows(bContext *C);
+
+void WM_draw_region_viewport_ensure(Scene *scene, ARegion *region, short space_type);
+void WM_draw_region_viewport_bind(ARegion *region);
+void WM_draw_region_viewport_unbind(ARegion *region);
+
+/* Region drawing. */
+
+void WM_draw_region_free(ARegion *region);
+GPUViewport *WM_draw_region_get_viewport(ARegion *region);
+GPUViewport *WM_draw_region_get_bound_viewport(ARegion *region);
+
+int WM_main_playanim(int argc, const char **argv);
+
+/**
+ * Debugging only, convenience function to write on crash.
+ * Convenient to save a blend file from a debugger.
+ */
+bool write_crash_blend();
+
+bool WM_autosave_is_scheduled(wmWindowManager *wm);
+/** Flushes all changes from edit modes and stores the auto-save file. */
+void WM_autosave_write(wmWindowManager *wm, Main *bmain);
+
+/**
+ * Lock the interface for any communication.
+ * For #WM_locked_interface_set_with_flags, #lock_flags is #ARegionDrawLockFlags
+ */
+void WM_locked_interface_set(wmWindowManager *wm, bool lock);
+void WM_locked_interface_set_with_flags(wmWindowManager *wm, short lock_flags);
+
+void WM_event_tablet_data_default_set(wmTabletData *tablet_data);
+
+/**
+ * For testing only, see #G_FLAG_EVENT_SIMULATE.
+ */
+wmEvent *WM_event_add_simulate(wmWindow *win, const wmEvent *event_to_add);
+
+const char *WM_window_cursor_keymap_status_get(const wmWindow *win,
+ int button_index,
+ int type_index);
+void WM_window_cursor_keymap_status_refresh(bContext *C, wmWindow *win);
+void WM_window_cursor_keymap_status_free(wmWindow *win);
+
+void WM_window_status_area_tag_redraw(wmWindow *win);
+/**
+ * Similar to #BKE_screen_area_map_find_area_xy and related functions,
+ * use here since the area is stored in the window manager.
+ */
+ScrArea *WM_window_status_area_find(wmWindow *win, bScreen *screen);
+bool WM_window_modal_keymap_status_draw(bContext *C, wmWindow *win, ui::Layout &layout);
+
+/* `wm_event_query.cc` */
+
+/**
+ * For debugging only, getting inspecting events manually is tedious.
+ */
+void WM_event_print(const wmEvent *event);
+
+/**
+ * For modal callbacks, check configuration for how to interpret exit when dragging.
+ */
+bool WM_event_is_modal_drag_exit(const wmEvent *event,
+ short init_event_type,
+ short init_event_val);
+bool WM_event_is_mouse_drag(const wmEvent *event);
+bool WM_event_is_mouse_drag_or_press(const wmEvent *event);
+int WM_event_drag_direction(const wmEvent *event);
+char WM_event_utf8_to_ascii(const wmEvent *event) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT;
+
+/**
+ * Detect motion between selection (callers should only use this for selection picking),
+ * typically mouse press/click events.
+ *
+ * \param mval: Region relative coordinates, call with (-1, -1) resets the last cursor location.
+ * \returns True when there was motion since last called.
+ *
+ * NOTE(@ideasman42): The logic used here isn't foolproof.
+ * It's possible that users move the cursor past #WM_EVENT_CURSOR_MOTION_THRESHOLD then back to
+ * a position within the threshold (between mouse clicks).
+ * In practice users never reported this since the threshold is very small (a few pixels).
+ * To prevent the unlikely case of values matching from another region,
+ * changing regions resets this value to (-1, -1).
+ */
+bool WM_cursor_test_motion_and_update(const int mval[2]) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT;
+
+/**
+ * Return true if this event type is a candidate for being flagged as consecutive.
+ *
+ * See: #WM_EVENT_IS_CONSECUTIVE doc-string.
+ */
+bool WM_event_consecutive_gesture_test(const wmEvent *event);
+/**
+ * Return true if this event should break the chain of consecutive gestures.
+ * Practically all intentional user input should, key presses or button clicks.
+ */
+bool WM_event_consecutive_gesture_test_break(const wmWindow *win, const wmEvent *event);
+
+int WM_event_drag_threshold(const wmEvent *event);
+bool WM_event_drag_test(const wmEvent *event, const int prev_xy[2]);
+bool WM_event_drag_test_with_delta(const wmEvent *event, const int drag_delta[2]);
+void WM_event_drag_start_mval(const wmEvent *event, const ARegion *region, int r_mval[2]);
+void WM_event_drag_start_mval_fl(const wmEvent *event, const ARegion *region, float r_mval[2]);
+void WM_event_drag_start_xy(const wmEvent *event, int r_xy[2]);
+
+/**
+ * Event map that takes preferences into account.
+ */
+int WM_userdef_event_map(int kmitype);
+/**
+ * Use so we can check if 'wmEvent.type' is released in modal operators.
+ *
+ * An alternative would be to add a 'wmEvent.type_nokeymap'... or similar.
+ */
+int WM_userdef_event_type_from_keymap_type(int kmitype);
+
+#ifdef WITH_INPUT_NDOF
+float3 WM_event_ndof_translation_get_for_navigation(const wmNDOFMotionData &ndof);
+float3 WM_event_ndof_rotation_get_for_navigation(const wmNDOFMotionData &ndof);
+float WM_event_ndof_rotation_get_axis_angle_for_navigation(const wmNDOFMotionData &ndof,
+ float axis[3]);
+
+float3 WM_event_ndof_translation_get(const wmNDOFMotionData &ndof);
+float3 WM_event_ndof_rotation_get(const wmNDOFMotionData &ndof);
+float WM_event_ndof_rotation_get_axis_angle(const wmNDOFMotionData &ndof, float axis[3]);
+
+bool WM_event_ndof_translation_has_pan(const wmNDOFMotionData &ndof);
+bool WM_event_ndof_translation_has_zoom(const wmNDOFMotionData &ndof);
+
+#endif /* WITH_INPUT_NDOF */
+
+#ifdef WITH_XR_OPENXR
+bool WM_event_is_xr(const wmEvent *event);
+#endif
+
+/**
+ * If this is a tablet event, return tablet pressure and set `*pen_flip`
+ * to 1 if the eraser tool is being used, 0 otherwise.
+ */
+float WM_event_tablet_data(const wmEvent *event, bool *r_pen_flip, float r_tilt[2]);
+bool WM_event_is_tablet(const wmEvent *event);
+
+int WM_event_absolute_delta_x(const wmEvent *event);
+int WM_event_absolute_delta_y(const wmEvent *event);
+
+#ifdef WITH_INPUT_IME
+bool WM_event_is_ime_switch(const wmEvent *event);
+#endif
+
+/* `wm_tooltip.cc` */
+
+using wmTooltipInitFn = ARegion *(*)(bContext * C,
+ ARegion *region,
+ int *pass,
+ double *r_pass_delay,
+ bool *r_exit_on_event);
+
+void WM_tooltip_immediate_init(
+ bContext *C, wmWindow *win, ScrArea *area, ARegion *region, wmTooltipInitFn init);
+void WM_tooltip_timer_init_ex(bContext *C,
+ wmWindow *win,
+ ScrArea *area,
+ ARegion *region,
+ wmTooltipInitFn init,
+ double delay);
+void WM_tooltip_timer_init(
+ bContext *C, wmWindow *win, ScrArea *area, ARegion *region, wmTooltipInitFn init);
+void WM_tooltip_timer_clear(bContext *C, wmWindow *win);
+void WM_tooltip_clear(bContext *C, wmWindow *win);
+void WM_tooltip_init(bContext *C, wmWindow *win);
+void WM_tooltip_refresh(bContext *C, wmWindow *win);
+double WM_tooltip_time_closed();
+
+/* `wm_utils.cc` */
+
+wmGenericCallback *WM_generic_callback_steal(wmGenericCallback *callback);
+void WM_generic_callback_free(wmGenericCallback *callback);
+
+void WM_generic_user_data_free(wmGenericUserData *wm_userdata);
+
+bool WM_region_use_viewport(ScrArea *area, ARegion *region);
+
+/* `wm_platform.cc` */
+
+/**
+ * \return Success.
+ */
+bool WM_platform_associate_set(bool do_register, bool all_users, char **r_error_msg);
+
+#ifdef WITH_XR_OPENXR
+/* `wm_xr_session.cc` */
+
+/**
+ * Check if the XR-Session was triggered.
+ * If an error happened while trying to start a session, this returns false too.
+ */
+bool WM_xr_session_exists(const wmXrData *xr);
+/**
+ * Check if the session is running, according to the OpenXR definition.
+ */
+bool WM_xr_session_is_ready(const wmXrData *xr);
+wmXrSessionState *WM_xr_session_state_handle_get(const wmXrData *xr);
+
+bContext *WM_xr_session_context_get(const wmXrData *xr);
+bContext *WM_xr_session_context_ensure(wmXrData *xr, const wmWindowManager *wm);
+
+void WM_xr_session_base_pose_reset(wmXrData *xr);
+bool WM_xr_session_state_viewer_pose_location_get(const wmXrData *xr, float r_location[3]);
+bool WM_xr_session_state_viewer_pose_rotation_get(const wmXrData *xr, float r_rotation[4]);
+bool WM_xr_session_state_viewer_pose_matrix_info_get(const wmXrData *xr,
+ float r_viewmat[4][4],
+ float *r_focal_len);
+bool WM_xr_session_state_controller_grip_location_get(const wmXrData *xr,
+ unsigned int subaction_idx,
+ float r_location[3]);
+bool WM_xr_session_state_controller_grip_rotation_get(const wmXrData *xr,
+ unsigned int subaction_idx,
+ float r_rotation[4]);
+bool WM_xr_session_state_controller_aim_location_get(const wmXrData *xr,
+ unsigned int subaction_idx,
+ float r_location[3]);
+bool WM_xr_session_state_controller_aim_rotation_get(const wmXrData *xr,
+ unsigned int subaction_idx,
+ float r_rotation[4]);
+bool WM_xr_session_state_nav_location_get(const wmXrData *xr, float r_location[3]);
+void WM_xr_session_state_nav_location_set(wmXrData *xr, const float location[3]);
+bool WM_xr_session_state_nav_rotation_get(const wmXrData *xr, float r_rotation[4]);
+void WM_xr_session_state_nav_rotation_set(wmXrData *xr, const float rotation[4]);
+bool WM_xr_session_state_nav_scale_get(const wmXrData *xr, float *r_scale);
+void WM_xr_session_state_nav_scale_set(wmXrData *xr, float scale);
+bool WM_xr_session_state_viewer_scale_get(const wmXrData *xr, float *r_scale);
+void WM_xr_session_state_navigation_reset(wmXrSessionState *state);
+void WM_xr_session_state_vignette_activate(wmXrData *xr);
+void WM_xr_session_state_vignette_update(wmXrSessionState *state);
+
+ARegionType *WM_xr_surface_controller_region_type_get();
+
+/* `wm_xr_actions.cc`. */
+
+/* XR action functions to be called pre-XR session start.
+ * NOTE: The "destroy" functions can also be called post-session start. */
+
+bool WM_xr_action_set_create(wmXrData *xr, const char *action_set_name);
+void WM_xr_action_set_destroy(wmXrData *xr, const char *action_set_name);
+bool WM_xr_action_create(wmXrData *xr,
+ const char *action_set_name,
+ const char *action_name,
+ eXrActionType type,
+ const ListBaseT<XrUserPath> *user_paths,
+ wmOperatorType *ot,
+ IDProperty *op_properties,
+ const char *haptic_name,
+ const int64_t *haptic_duration,
+ const float *haptic_frequency,
+ const float *haptic_amplitude,
+ eXrOpFlag op_flag,
+ eXrActionFlag action_flag,
+ eXrHapticFlag haptic_flag);
+void WM_xr_action_destroy(wmXrData *xr, const char *action_set_name, const char *action_name);
+bool WM_xr_action_binding_create(wmXrData *xr,
+ const char *action_set_name,
+ const char *action_name,
+ const char *profile_path,
+ const ListBaseT<XrUserPath> *user_paths,
+ const ListBaseT<XrComponentPath> *component_paths,
+ const float *float_thresholds,
+ const eXrAxisFlag *axis_flags,
+ const wmXrPose *poses);
+void WM_xr_action_binding_destroy(wmXrData *xr,
+ const char *action_set_name,
+ const char *action_name,
+ const char *profile_path);
+
+/**
+ * If action_set_name is NULL, then all action sets will be treated as active.
+ */
+bool WM_xr_active_action_set_set(wmXrData *xr, const char *action_set_name, bool delayed);
+
+bool WM_xr_controller_pose_actions_set(wmXrData *xr,
+ const char *action_set_name,
+ const char *grip_action_name,
+ const char *aim_action_name);
+
+/**
+ * XR action functions to be called post-XR session start.
+ */
+bool WM_xr_action_state_get(const wmXrData *xr,
+ const char *action_set_name,
+ const char *action_name,
+ const char *subaction_path,
+ wmXrActionState *r_state);
+bool WM_xr_haptic_action_apply(wmXrData *xr,
+ const char *action_set_name,
+ const char *action_name,
+ const char *subaction_path,
+ const int64_t *duration,
+ const float *frequency,
+ const float *amplitude);
+void WM_xr_haptic_action_stop(wmXrData *xr,
+ const char *action_set_name,
+ const char *action_name,
+ const char *subaction_path);
+
+/* `wm_xr_actionmap.cc` */
+
+XrActionMap *WM_xr_actionmap_new(wmXrRuntimeData *runtime,
+ const char *name,
+ bool replace_existing);
+/**
+ * Ensure unique name among all action maps.
+ */
+void WM_xr_actionmap_ensure_unique(wmXrRuntimeData *runtime, XrActionMap *actionmap);
+XrActionMap *WM_xr_actionmap_add_copy(wmXrRuntimeData *runtime, XrActionMap *am_src);
+bool WM_xr_actionmap_remove(wmXrRuntimeData *runtime, XrActionMap *actionmap);
+XrActionMap *WM_xr_actionmap_find(wmXrRuntimeData *runtime, const char *name);
+void WM_xr_actionmap_clear(XrActionMap *actionmap);
+void WM_xr_actionmaps_clear(wmXrRuntimeData *runtime);
+ListBaseT<XrActionMap> *WM_xr_actionmaps_get(wmXrRuntimeData *runtime);
+short WM_xr_actionmap_active_index_get(const wmXrRuntimeData *runtime);
+void WM_xr_actionmap_active_index_set(wmXrRuntimeData *runtime, short idx);
+short WM_xr_actionmap_selected_index_get(const wmXrRuntimeData *runtime);
+void WM_xr_actionmap_selected_index_set(wmXrRuntimeData *runtime, short idx);
+
+XrActionMapItem *WM_xr_actionmap_item_new(XrActionMap *actionmap,
+ const char *name,
+ bool replace_existing);
+/**
+ * Ensure unique name among all action map items.
+ */
+void WM_xr_actionmap_item_ensure_unique(XrActionMap *actionmap, XrActionMapItem *ami);
+XrActionMapItem *WM_xr_actionmap_item_add_copy(XrActionMap *actionmap, XrActionMapItem *ami_src);
+bool WM_xr_actionmap_item_remove(XrActionMap *actionmap, XrActionMapItem *ami);
+XrActionMapItem *WM_xr_actionmap_item_find(XrActionMap *actionmap, const char *name);
+/**
+ * Similar to #wm_xr_actionmap_item_properties_set()
+ * but checks for the #eXrActionType and #wmOperatorType having changed.
+ */
+void WM_xr_actionmap_item_properties_update_ot(XrActionMapItem *ami);
+
+XrActionMapBinding *WM_xr_actionmap_binding_new(XrActionMapItem *ami,
+ const char *name,
+ bool replace_existing);
+/**
+ * Ensure unique name among all action map bindings.
+ */
+void WM_xr_actionmap_binding_ensure_unique(XrActionMapItem *ami, XrActionMapBinding *amb);
+XrActionMapBinding *WM_xr_actionmap_binding_add_copy(XrActionMapItem *ami,
+ XrActionMapBinding *amb_src);
+bool WM_xr_actionmap_binding_remove(XrActionMapItem *ami, XrActionMapBinding *amb);
+XrActionMapBinding *WM_xr_actionmap_binding_find(XrActionMapItem *ami, const char *name);
+#endif /* WITH_XR_OPENXR */
+
+} // namespace blender
diff --git a/compat/include/WM_gizmo_api.hh b/compat/include/WM_gizmo_api.hh
new file mode 100644
index 0000000..1d88655
--- /dev/null
+++ b/compat/include/WM_gizmo_api.hh
@@ -0,0 +1,479 @@
+/* SPDX-FileCopyrightText: 2016 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup wm
+ *
+ * \name Gizmo API
+ * \brief API for external use of wmGizmo types.
+ *
+ * Only included in WM_api.hh
+ */
+
+#pragma once
+
+#include "WM_gizmo_types.hh"
+#include "wm_gizmo_fn.hh"
+
+#include "BLI_string_ref.hh"
+
+#include "DNA_listBase.h"
+
+namespace blender {
+
+struct ARegion;
+struct bContext;
+struct IDProperty;
+struct Main;
+struct PointerRNA;
+struct PropertyRNA;
+struct ScrArea;
+struct bToolRef;
+struct wmGizmo;
+struct wmGizmoGroup;
+struct wmGizmoGroupType;
+struct wmGizmoGroupTypeRef;
+struct wmGizmoMap;
+struct wmGizmoMapType;
+struct wmGizmoMapType_Params;
+struct wmGizmoOpElem;
+struct wmGizmoProperty;
+struct wmGizmoPropertyType;
+struct wmGizmoType;
+struct wmKeyConfig;
+struct wmMsgSubscribeKey;
+struct wmMsgSubscribeValue;
+struct wmOperatorType;
+struct wmWindow;
+struct wmWindowManager;
+
+/* -------------------------------------------------------------------- */
+/* #wmGizmo. */
+
+wmGizmo *WM_gizmo_new_ptr(const wmGizmoType *gzt, wmGizmoGroup *gzgroup, PointerRNA *properties);
+/**
+ * \param idname: Must be a valid gizmo type name,
+ * if you need to check it exists use #WM_gizmo_new_ptr
+ * because callers of this function don't NULL check the return value.
+ */
+wmGizmo *WM_gizmo_new(StringRef idname, wmGizmoGroup *gzgroup, PointerRNA *properties);
+/**
+ * \warning this doesn't check #wmGizmoMap (highlight, selection etc).
+ * Typical use is when freeing the windowing data,
+ * where caller can manage clearing selection, highlight... etc.
+ */
+void WM_gizmo_free(wmGizmo *gz);
+/**
+ * Free \a gizmo and unlink from \a gizmolist.
+ * \a gizmolist is allowed to be NULL.
+ */
+void WM_gizmo_unlink(ListBaseT<wmGizmo> *gizmolist, wmGizmoMap *gzmap, wmGizmo *gz, bContext *C);
+
+/**
+ * Remove from selection array without running callbacks.
+ */
+bool WM_gizmo_select_unlink(wmGizmoMap *gzmap, wmGizmo *gz);
+bool WM_gizmo_select_set(wmGizmoMap *gzmap, wmGizmo *gz, bool select);
+bool WM_gizmo_highlight_set(wmGizmoMap *gzmap, wmGizmo *gz);
+
+/**
+ * Special function to run from setup so gizmos start out interactive.
+ *
+ * We could do this when linking them,
+ * but this complicates things since the window update code needs to run first.
+ */
+void WM_gizmo_modal_set_from_setup(
+ wmGizmoMap *gzmap, bContext *C, wmGizmo *gz, int part_index, const wmEvent *event);
+
+/**
+ * Replaces the current gizmo modal.
+ * The substitute gizmo start out interactive.
+ * It is similar to #WM_gizmo_modal_set_from_setup but without operator initialization.
+ */
+void WM_gizmo_modal_set_while_modal(wmGizmoMap *gzmap,
+ bContext *C,
+ wmGizmo *gz,
+ const wmEvent *event);
+
+wmGizmoOpElem *WM_gizmo_operator_get(wmGizmo *gz, int part_index);
+PointerRNA *WM_gizmo_operator_set(wmGizmo *gz,
+ int part_index,
+ wmOperatorType *ot,
+ IDProperty *properties);
+wmOperatorStatus WM_gizmo_operator_invoke(bContext *C,
+ wmGizmo *gz,
+ wmGizmoOpElem *gzop,
+ const wmEvent *event);
+
+/* Callbacks. */
+
+void WM_gizmo_set_fn_custom_modal(wmGizmo *gz, wmGizmoFnModal fn);
+
+void WM_gizmo_set_matrix_location(wmGizmo *gz, const float origin[3]);
+/**
+ * #wmGizmo.matrix utility, set the orientation by its Z axis.
+ */
+void WM_gizmo_set_matrix_rotation_from_z_axis(wmGizmo *gz, const float z_axis[3]);
+/**
+ * #wmGizmo.matrix utility, set the orientation by its Y/Z axis.
+ */
+void WM_gizmo_set_matrix_rotation_from_yz_axis(wmGizmo *gz,
+ const float y_axis[3],
+ const float z_axis[3]);
+
+void WM_gizmo_set_matrix_offset_location(wmGizmo *gz, const float offset[3]);
+/**
+ * #wmGizmo.matrix_offset utility, set the orientation by its Z axis.
+ */
+void WM_gizmo_set_matrix_offset_rotation_from_z_axis(wmGizmo *gz, const float z_axis[3]);
+/**
+ * #wmGizmo.matrix_offset utility, set the orientation by its Y/Z axis.
+ */
+void WM_gizmo_set_matrix_offset_rotation_from_yz_axis(wmGizmo *gz,
+ const float y_axis[3],
+ const float z_axis[3]);
+
+void WM_gizmo_set_flag(wmGizmo *gz, int flag, bool enable);
+void WM_gizmo_set_scale(wmGizmo *gz, float scale);
+void WM_gizmo_set_line_width(wmGizmo *gz, float line_width);
+
+void WM_gizmo_get_color(const wmGizmo *gz, float color[4]);
+void WM_gizmo_set_color(wmGizmo *gz, const float color[4]);
+void WM_gizmo_get_color_highlight(const wmGizmo *gz, float color_hi[4]);
+void WM_gizmo_set_color_highlight(wmGizmo *gz, const float color_hi[4]);
+
+/**
+ * Leaving values NULL use values from #wmGizmo.
+ */
+struct wmGizmoMatrixParams {
+ const float (*matrix_space)[4];
+ const float (*matrix_basis)[4];
+ const float (*matrix_offset)[4];
+ const float *scale_final;
+};
+
+void WM_gizmo_calc_matrix_final_params(const wmGizmo *gz,
+ const wmGizmoMatrixParams *params,
+ float r_mat[4][4]);
+void WM_gizmo_calc_matrix_final_no_offset(const wmGizmo *gz, float r_mat[4][4]);
+
+void WM_gizmo_calc_matrix_final(const wmGizmo *gz, float r_mat[4][4]);
+
+/* Properties. */
+
+void WM_gizmo_properties_create_ptr(PointerRNA *ptr, wmGizmoType *gzt);
+void WM_gizmo_properties_create(PointerRNA *ptr, StringRef gtstring);
+/**
+ * Similar to #WM_gizmo_properties_create
+ * except its uses ID properties used for key-maps and macros.
+ */
+void WM_gizmo_properties_alloc(PointerRNA **ptr, IDProperty **properties, StringRef gtstring);
+void WM_gizmo_properties_sanitize(PointerRNA *ptr, bool no_context);
+/**
+ * Set all props to their default.
+ *
+ * \param do_update: Only update un-initialized props.
+ *
+ * \note There's nothing specific to gizmos here.
+ * This could be made a general function.
+ */
+bool WM_gizmo_properties_default(PointerRNA *ptr, bool do_update);
+/**
+ * Remove all props without #PROP_SKIP_SAVE.
+ */
+void WM_gizmo_properties_reset(wmGizmo *gz);
+void WM_gizmo_properties_clear(PointerRNA *ptr);
+void WM_gizmo_properties_free(PointerRNA *ptr);
+
+/* `wm_gizmo_type.cc` */
+
+const wmGizmoType *WM_gizmotype_find(StringRef idname, bool quiet);
+void WM_gizmotype_append(void (*gtfunc)(wmGizmoType *));
+void WM_gizmotype_append_ptr(void (*gtfunc)(wmGizmoType *, void *), void *userdata);
+bool WM_gizmotype_remove(bContext *C, Main *bmain, StringRef idname);
+void WM_gizmotype_remove_ptr(bContext *C, Main *bmain, wmGizmoType *gzt);
+/**
+ * Free but don't remove from the global list.
+ */
+void WM_gizmotype_free_ptr(wmGizmoType *gzt);
+
+/* `wm_gizmo_group_type.cc` */
+
+wmGizmoGroupType *WM_gizmogrouptype_find(StringRef idname, bool quiet);
+wmGizmoGroupType *WM_gizmogrouptype_append(void (*wtfunc)(wmGizmoGroupType *));
+wmGizmoGroupType *WM_gizmogrouptype_append_ptr(void (*wtfunc)(wmGizmoGroupType *, void *),
+ void *userdata);
+
+/**
+ * Append and insert into a gizmo type-map.
+ * This is most common for C gizmos which are enabled by default.
+ */
+wmGizmoGroupTypeRef *WM_gizmogrouptype_append_and_link(wmGizmoMapType *gzmap_type,
+ void (*wtfunc)(wmGizmoGroupType *));
+
+/* `wm_gizmo_map.cc` */
+
+/* Dynamic Updates (for RNA runtime registration). */
+void WM_gizmoconfig_update_tag_group_type_init(wmGizmoMapType *gzmap_type, wmGizmoGroupType *gzgt);
+void WM_gizmoconfig_update_tag_group_type_remove(wmGizmoMapType *gzmap_type,
+ wmGizmoGroupType *gzgt);
+/**
+ * Run in case new types have been added (runs often, early exit where possible).
+ * Follows #WM_keyconfig_update conventions.
+ */
+void WM_gizmoconfig_update(Main *bmain);
+
+void WM_gizmoconfig_update_tag_group_remove(wmGizmoMap *gzmap);
+
+void WM_gizmoconfig_update_tag_reinit_all();
+
+/* `wm_gizmo_target_props.cc`. */
+
+wmGizmoProperty *WM_gizmo_target_property_find(wmGizmo *gz, const char *idname);
+
+void WM_gizmo_target_property_def_rna_ptr(wmGizmo *gz,
+ const wmGizmoPropertyType *gz_prop_type,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ int index);
+void WM_gizmo_target_property_def_rna(
+ wmGizmo *gz, const char *idname, PointerRNA *ptr, const char *propname, int index);
+
+void WM_gizmo_target_property_def_func_ptr(wmGizmo *gz,
+ const wmGizmoPropertyType *gz_prop_type,
+ const wmGizmoPropertyFnParams *params);
+void WM_gizmo_target_property_def_func(wmGizmo *gz,
+ const char *idname,
+ const wmGizmoPropertyFnParams *params);
+
+void WM_gizmo_target_property_clear_rna_ptr(wmGizmo *gz, const wmGizmoPropertyType *gz_prop_type);
+void WM_gizmo_target_property_clear_rna(wmGizmo *gz, const char *idname);
+
+bool WM_gizmo_target_property_is_valid_any(const wmGizmo *gz);
+bool WM_gizmo_target_property_is_valid(const wmGizmoProperty *gz_prop);
+float WM_gizmo_target_property_float_get(const wmGizmo *gz, wmGizmoProperty *gz_prop);
+void WM_gizmo_target_property_float_set(bContext *C,
+ const wmGizmo *gz,
+ wmGizmoProperty *gz_prop,
+ float value);
+
+void WM_gizmo_target_property_float_get_array(const wmGizmo *gz,
+ wmGizmoProperty *gz_prop,
+ float *value);
+void WM_gizmo_target_property_float_set_array(bContext *C,
+ const wmGizmo *gz,
+ wmGizmoProperty *gz_prop,
+ const float *value);
+
+bool WM_gizmo_target_property_float_range_get(const wmGizmo *gz,
+ wmGizmoProperty *gz_prop,
+ float range[2]);
+
+int WM_gizmo_target_property_array_length(const wmGizmo *gz, wmGizmoProperty *gz_prop);
+
+/* Definitions. */
+
+const wmGizmoPropertyType *WM_gizmotype_target_property_find(const wmGizmoType *gzt,
+ const char *idname);
+void WM_gizmotype_target_property_def(wmGizmoType *gzt,
+ const char *idname,
+ int data_type,
+ int array_length);
+
+/* Utilities. */
+
+void WM_gizmo_do_msg_notify_tag_refresh(bContext *C,
+ wmMsgSubscribeKey *msg_key,
+ wmMsgSubscribeValue *msg_val);
+/**
+ * Runs on the "prepare draw" pass, drawing the region clears.
+ */
+void WM_gizmo_target_property_subscribe_all(wmGizmo *gz, wmMsgBus *mbus, ARegion *region);
+
+/**
+ * Auto-key function if auto-key is enabled.
+ */
+void WM_gizmo_target_property_anim_autokey(bContext *C,
+ const wmGizmo *gz,
+ wmGizmoProperty *gz_prop);
+
+/* -------------------------------------------------------------------- */
+/* #wmGizmoGroup. */
+
+/* Callbacks for #wmGizmoGroupType::setup_keymap. */
+wmKeyMap *WM_gizmogroup_setup_keymap_generic(const wmGizmoGroupType *gzgt, wmKeyConfig *kc);
+wmKeyMap *WM_gizmogroup_setup_keymap_generic_select(const wmGizmoGroupType *gzgt, wmKeyConfig *kc);
+wmKeyMap *WM_gizmogroup_setup_keymap_generic_drag(const wmGizmoGroupType *gzgt, wmKeyConfig *kc);
+wmKeyMap *WM_gizmogroup_setup_keymap_generic_maybe_drag(const wmGizmoGroupType *gzgt,
+ wmKeyConfig *kc);
+
+/* Utility functions (not callbacks). */
+
+wmKeyMap *WM_gizmo_keymap_generic_with_keyconfig(wmKeyConfig *kc);
+wmKeyMap *WM_gizmo_keymap_generic(wmWindowManager *wm);
+
+wmKeyMap *WM_gizmo_keymap_generic_select_with_keyconfig(wmKeyConfig *kc);
+wmKeyMap *WM_gizmo_keymap_generic_select(wmWindowManager *wm);
+
+wmKeyMap *WM_gizmo_keymap_generic_drag_with_keyconfig(wmKeyConfig *kc);
+wmKeyMap *WM_gizmo_keymap_generic_drag(wmWindowManager *wm);
+
+wmKeyMap *WM_gizmo_keymap_generic_press_drag_with_keyconfig(wmKeyConfig *kc);
+wmKeyMap *WM_gizmo_keymap_generic_press_drag(wmWindowManager *wm);
+
+/**
+ * Drag or press depending on preference.
+ */
+wmKeyMap *WM_gizmo_keymap_generic_maybe_drag_with_keyconfig(wmKeyConfig *kc);
+wmKeyMap *WM_gizmo_keymap_generic_maybe_drag(wmWindowManager *wm);
+
+void WM_gizmogroup_ensure_init(const bContext *C, wmGizmoGroup *gzgroup);
+
+/* Sort utilities for use with `BLI_listbase_sort`. */
+
+int WM_gizmo_cmp_temp_fl(const void *gz_a_ptr, const void *gz_b_ptr);
+int WM_gizmo_cmp_temp_fl_reverse(const void *gz_a_ptr, const void *gz_b_ptr);
+
+/* -------------------------------------------------------------------- */
+/* #wmGizmoMap. */
+
+/**
+ * Creates a gizmo-map with all registered gizmos for that type
+ */
+wmGizmoMap *WM_gizmomap_new_from_type(const wmGizmoMapType_Params *gzmap_params);
+/**
+ * Re-create the gizmos (use when changing theme settings).
+ */
+void WM_gizmomap_reinit(wmGizmoMap *gzmap);
+const ListBaseT<wmGizmoGroup> *WM_gizmomap_group_list(wmGizmoMap *gzmap);
+wmGizmoGroup *WM_gizmomap_group_find(wmGizmoMap *gzmap, const char *idname);
+wmGizmoGroup *WM_gizmomap_group_find_ptr(wmGizmoMap *gzmap, const wmGizmoGroupType *gzgt);
+
+eWM_GizmoFlagMapDrawStep WM_gizmomap_drawstep_from_gizmo_group(const wmGizmoGroup *gzgroup);
+void WM_gizmomap_tag_refresh_drawstep(wmGizmoMap *gzmap, eWM_GizmoFlagMapDrawStep drawstep);
+void WM_gizmomap_tag_refresh(wmGizmoMap *gzmap);
+
+bool WM_gizmomap_tag_delay_refresh_for_tweak_check(wmGizmoMap *gzmap);
+
+void WM_gizmomap_draw(wmGizmoMap *gzmap, const bContext *C, eWM_GizmoFlagMapDrawStep drawstep);
+void WM_gizmomap_add_handlers(ARegion *region, wmGizmoMap *gzmap);
+/**
+ * Select/Deselect all selectable gizmos in \a gzmap.
+ * \return if selection has changed.
+ *
+ * TODO: select all by type.
+ */
+bool WM_gizmomap_select_all(bContext *C, wmGizmoMap *gzmap, int action);
+bool WM_gizmomap_cursor_set(const wmGizmoMap *gzmap, wmWindow *win);
+void WM_gizmomap_message_subscribe(const bContext *C,
+ wmGizmoMap *gzmap,
+ ARegion *region,
+ wmMsgBus *mbus);
+bool WM_gizmomap_is_any_selected(const wmGizmoMap *gzmap);
+wmGizmo *WM_gizmomap_get_modal(const wmGizmoMap *gzmap);
+
+/**
+ * \note We could use a callback to define bounds, for now just use matrix location.
+ */
+bool WM_gizmomap_minmax(
+ const wmGizmoMap *gzmap, bool use_hidden, bool use_select, float r_min[3], float r_max[3]);
+
+ARegion *WM_gizmomap_tooltip_init(
+ bContext *C, ARegion *region, int *pass, double *pass_delay, bool *r_exit_on_event);
+
+/* -------------------------------------------------------------------- */
+/* #wmGizmoMapType. */
+
+wmGizmoMapType *WM_gizmomaptype_find(const wmGizmoMapType_Params *gzmap_params);
+wmGizmoMapType *WM_gizmomaptype_ensure(const wmGizmoMapType_Params *gzmap_params);
+
+wmGizmoGroupTypeRef *WM_gizmomaptype_group_find(wmGizmoMapType *gzmap_type, StringRef idname);
+wmGizmoGroupTypeRef *WM_gizmomaptype_group_find_ptr(wmGizmoMapType *gzmap_type,
+ const wmGizmoGroupType *gzgt);
+/**
+ * Use this for registering gizmos on startup.
+ * For runtime, use #WM_gizmomaptype_group_link_runtime.
+ */
+wmGizmoGroupTypeRef *WM_gizmomaptype_group_link(wmGizmoMapType *gzmap_type, StringRef idname);
+wmGizmoGroupTypeRef *WM_gizmomaptype_group_link_ptr(wmGizmoMapType *gzmap_type,
+ wmGizmoGroupType *gzgt);
+
+void WM_gizmomaptype_group_init_runtime_keymap(const Main *bmain, wmGizmoGroupType *gzgt);
+void WM_gizmomaptype_group_init_runtime(const Main *bmain,
+ wmGizmoMapType *gzmap_type,
+ wmGizmoGroupType *gzgt);
+wmGizmoGroup *WM_gizmomaptype_group_init_runtime_with_region(wmGizmoMapType *gzmap_type,
+ wmGizmoGroupType *gzgt,
+ ARegion *region);
+void WM_gizmomaptype_group_unlink(bContext *C,
+ Main *bmain,
+ wmGizmoMapType *gzmap_type,
+ const wmGizmoGroupType *gzgt);
+
+/**
+ * Unlike #WM_gizmomaptype_group_unlink this doesn't maintain correct state, simply free.
+ */
+void WM_gizmomaptype_group_free(wmGizmoGroupTypeRef *gzgt_ref);
+
+/* -------------------------------------------------------------------- */
+/* #GizmoGroup. */
+
+/* Add/Ensure/Remove (High level API). */
+
+void WM_gizmo_group_type_add_ptr_ex(wmGizmoGroupType *gzgt, wmGizmoMapType *gzmap_type);
+void WM_gizmo_group_type_add_ptr(wmGizmoGroupType *gzgt);
+void WM_gizmo_group_type_add(StringRef idname);
+
+bool WM_gizmo_group_type_ensure_ptr_ex(wmGizmoGroupType *gzgt, wmGizmoMapType *gzmap_type);
+bool WM_gizmo_group_type_ensure_ptr(wmGizmoGroupType *gzgt);
+bool WM_gizmo_group_type_ensure(StringRef idname);
+
+/**
+ * Call #WM_gizmo_group_type_free_ptr after to remove & free.
+ */
+void WM_gizmo_group_type_remove_ptr_ex(Main *bmain,
+ wmGizmoGroupType *gzgt,
+ wmGizmoMapType *gzmap_type);
+void WM_gizmo_group_type_remove_ptr(Main *bmain, wmGizmoGroupType *gzgt);
+void WM_gizmo_group_type_remove(Main *bmain, StringRef idname);
+
+void WM_gizmo_group_type_unlink_delayed_ptr_ex(wmGizmoGroupType *gzgt, wmGizmoMapType *gzmap_type);
+void WM_gizmo_group_type_unlink_delayed_ptr(wmGizmoGroupType *gzgt);
+void WM_gizmo_group_type_unlink_delayed(StringRef idname);
+
+void WM_gizmo_group_unlink_delayed_ptr_from_space(wmGizmoGroupType *gzgt,
+ wmGizmoMapType *gzmap_type,
+ ScrArea *area);
+
+void WM_gizmo_group_type_free_ptr(wmGizmoGroupType *gzgt);
+bool WM_gizmo_group_type_free(StringRef idname);
+
+/**
+ * Has the result of unlinking and linking (re-initializes gizmo's).
+ */
+void WM_gizmo_group_type_reinit_ptr_ex(Main *bmain,
+ wmGizmoGroupType *gzgt,
+ wmGizmoMapType *gzmap_type);
+void WM_gizmo_group_type_reinit_ptr(Main *bmain, wmGizmoGroupType *gzgt);
+void WM_gizmo_group_type_reinit(Main *bmain, StringRef idname);
+
+/* Utilities. */
+
+bool WM_gizmo_group_is_modal(const wmGizmoGroup *gzgroup);
+
+bool WM_gizmo_context_check_drawstep(const bContext *C, eWM_GizmoFlagMapDrawStep step);
+
+void WM_gizmo_group_remove_by_tool(bContext *C,
+ Main *bmain,
+ const wmGizmoGroupType *gzgt,
+ const bToolRef *tref);
+
+void WM_gizmo_group_tag_remove(wmGizmoGroup *gzgroup);
+
+/* Wrap Group Type Callbacks. */
+
+bool WM_gizmo_group_type_poll(const bContext *C, const wmGizmoGroupType *gzgt);
+void WM_gizmo_group_refresh(const bContext *C, wmGizmoGroup *gzgroup);
+
+} // namespace blender
diff --git a/compat/include/WM_gizmo_types.hh b/compat/include/WM_gizmo_types.hh
new file mode 100644
index 0000000..dd1a13a
--- /dev/null
+++ b/compat/include/WM_gizmo_types.hh
@@ -0,0 +1,535 @@
+/* SPDX-FileCopyrightText: 2016 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup wm
+ *
+ * \name Gizmo Types
+ * \brief Gizmo defines for external use.
+ *
+ * Only included in WM_types.hh and lower level files.
+ */
+
+#pragma once
+
+#include "BLI_enum_flags.hh"
+#include "BLI_vector.hh"
+
+#include "DNA_listBase.h"
+
+#include "RNA_types.hh"
+
+namespace blender {
+
+struct IDProperty;
+struct wmGizmo;
+struct wmGizmoType;
+struct wmGizmoGroup;
+struct wmGizmoGroupType;
+struct wmGizmoMap;
+struct wmGizmoMapType;
+struct wmGizmoProperty;
+struct wmGizmoPropertyType;
+struct wmKeyConfig;
+struct wmOperatorType;
+
+/* -------------------------------------------------------------------- */
+/* Enum Typedef's. */
+
+/**
+ * #wmGizmo.state
+ */
+enum eWM_GizmoFlagState {
+ /** While hovered. */
+ WM_GIZMO_STATE_HIGHLIGHT = (1 << 0),
+ /** While dragging. */
+ WM_GIZMO_STATE_MODAL = (1 << 1),
+ WM_GIZMO_STATE_SELECT = (1 << 2),
+};
+ENUM_OPERATORS(eWM_GizmoFlagState)
+
+/**
+ * #wmGizmo.flag
+ * Flags for individual gizmos.
+ */
+enum eWM_GizmoFlag {
+ /** Draw *only* while hovering. */
+ WM_GIZMO_DRAW_HOVER = (1 << 0),
+ /** Draw while dragging. */
+ WM_GIZMO_DRAW_MODAL = (1 << 1),
+ /** Draw an indicator for the current value while dragging. */
+ WM_GIZMO_DRAW_VALUE = (1 << 2),
+ WM_GIZMO_HIDDEN = (1 << 3),
+ WM_GIZMO_HIDDEN_SELECT = (1 << 4),
+ /** Ignore the key-map for this gizmo. */
+ WM_GIZMO_HIDDEN_KEYMAP = (1 << 5),
+ /**
+ * When set 'scale_final' value also scales the offset.
+ * Use when offset is to avoid screen-space overlap instead of absolute positioning. */
+ WM_GIZMO_DRAW_OFFSET_SCALE = (1 << 6),
+ /**
+ * User should still use 'scale_final' for any handles and UI elements.
+ * This simply skips scale when calculating the final matrix.
+ * Needed when the gizmo needs to align with the interface underneath it. */
+ WM_GIZMO_DRAW_NO_SCALE = (1 << 7),
+ /**
+ * Hide the cursor and lock its position while interacting with this gizmo.
+ */
+ WM_GIZMO_MOVE_CURSOR = (1 << 8),
+ /** Don't write into the depth buffer when selecting. */
+ WM_GIZMO_SELECT_BACKGROUND = (1 << 9),
+
+ /** Use the active tools operator properties when running as an operator. */
+ WM_GIZMO_OPERATOR_TOOL_INIT = (1 << 10),
+
+ /** Don't pass through events to other handlers
+ * (allows click/drag not to have its events stolen by press events in other keymaps). */
+ WM_GIZMO_EVENT_HANDLE_ALL = (1 << 11),
+
+ /** Don't use tool-tips for this gizmo (can be distracting). */
+ WM_GIZMO_NO_TOOLTIP = (1 << 12),
+ /** Push an undo step after each use of the gizmo. */
+ WM_GIZMO_NEEDS_UNDO = (1 << 13),
+
+ /** This gizmo should be visually distinct and not shown grouped with other gizmos. */
+ WM_GIZMO_NO_GROUPING = (1 << 14),
+};
+ENUM_OPERATORS(eWM_GizmoFlag);
+
+/**
+ * #wmGizmoGroupType.flag
+ * Flags that influence the behavior of all gizmos in the group.
+ */
+enum eWM_GizmoFlagGroupTypeFlag {
+ /** Mark gizmo-group as being 3D. */
+ WM_GIZMOGROUPTYPE_3D = (1 << 0),
+ /** Scale gizmos as 3D object that respects zoom (otherwise zoom independent draw size).
+ * NOTE: currently only for 3D views, 2D support needs adding. */
+ WM_GIZMOGROUPTYPE_SCALE = (1 << 1),
+ /** Gizmos can be depth culled with scene objects (covered by other geometry - TODO). */
+ WM_GIZMOGROUPTYPE_DEPTH_3D = (1 << 2),
+ /** Gizmos can be selected. */
+ WM_GIZMOGROUPTYPE_SELECT = (1 << 3),
+ /** The gizmo group is to be kept (not removed on loading a new file for eg). */
+ WM_GIZMOGROUPTYPE_PERSISTENT = (1 << 4),
+ /**
+ * Show all other gizmos when interacting.
+ * Also show this group when another group is being interacted with.
+ */
+ WM_GIZMOGROUPTYPE_DRAW_MODAL_ALL = (1 << 5),
+
+ /** Don't draw this gizmo group when it is modal. */
+ WM_GIZMOGROUPTYPE_DRAW_MODAL_EXCLUDE = (1 << 6),
+
+ /**
+ * When used with tool, only run when activating the tool,
+ * instead of linking the gizmo while the tool is active.
+ *
+ * \warning this option has some limitations, we might even re-implement this differently.
+ * Currently it's quite minimal so we can see how it works out.
+ * The main issue is controlling how a gizmo is activated with a tool
+ * when a tool can activate multiple operators based on the key-map.
+ * We could even move the options into the key-map item.
+ * ~ campbell. */
+ WM_GIZMOGROUPTYPE_TOOL_INIT = (1 << 7),
+
+ /**
+ * This gizmo type supports using the fall back tools keymap.
+ * #wmGizmoGroup.use_tool_fallback will need to be set too.
+ *
+ * Often useful in combination with #WM_GIZMOGROUPTYPE_DELAY_REFRESH_FOR_TWEAK
+ */
+ WM_GIZMOGROUPTYPE_TOOL_FALLBACK_KEYMAP = (1 << 8),
+
+ /**
+ * Use this from a gizmos refresh callback so we can postpone the refresh operation
+ * until the tweak operation is finished.
+ * Only do this when the group doesn't have a highlighted gizmo.
+ *
+ * The result for the user is tweak events delay the gizmo from flashing under the users cursor,
+ * for selection operations. This means gizmos that use this check don't interfere
+ * with click-drag events by popping up under the cursor and catching the drag-drag event.
+ */
+ WM_GIZMOGROUPTYPE_DELAY_REFRESH_FOR_TWEAK = (1 << 9),
+
+ /**
+ * Cause continuous redraws, i.e. set the region redraw flag on every main loop iteration. This
+ * should really be avoided by using proper region redraw tagging, notifiers and the message-bus,
+ * however for VR it's sometimes needed.
+ */
+ WM_GIZMOGROUPTYPE_VR_REDRAWS = (1 << 10),
+};
+
+ENUM_OPERATORS(eWM_GizmoFlagGroupTypeFlag);
+
+/**
+ * #wmGizmoGroup.init_flag
+ */
+enum eWM_GizmoFlagGroupInitFlag {
+ /** Gizmo-group has been initialized. */
+ WM_GIZMOGROUP_INIT_SETUP = (1 << 0),
+ WM_GIZMOGROUP_INIT_REFRESH = (1 << 1),
+};
+ENUM_OPERATORS(eWM_GizmoFlagGroupInitFlag)
+
+/**
+ * #wmGizmoMapType.type_update_flag
+ * Gizmo-map type update flag
+ */
+enum eWM_GizmoFlagMapTypeUpdateFlag {
+ /** A new type has been added, needs to be initialized for all views. */
+ WM_GIZMOMAPTYPE_UPDATE_INIT = (1 << 0),
+ WM_GIZMOMAPTYPE_UPDATE_REMOVE = (1 << 1),
+
+ /** Needed because keymap may be registered before and after window initialization.
+ * So we need to keep track of keymap initialization separately. */
+ WM_GIZMOMAPTYPE_KEYMAP_INIT = (1 << 2),
+};
+ENUM_OPERATORS(eWM_GizmoFlagMapTypeUpdateFlag)
+
+/* -------------------------------------------------------------------- */
+/* #wmGizmo. */
+
+/**
+ * \brief Gizmo tweak flag.
+ * Bit-flag passed to gizmo while tweaking.
+ *
+ * \note Gizmos are responsible for handling this #wmGizmo.modal callback.
+ */
+enum eWM_GizmoFlagTweak {
+ /** Drag with extra precision (Shift). */
+ WM_GIZMO_TWEAK_PRECISE = (1 << 0),
+ /** Drag with snap enabled (Control). */
+ WM_GIZMO_TWEAK_SNAP = (1 << 1),
+};
+
+} // namespace blender
+
+#include "wm_gizmo_fn.hh"
+
+namespace blender {
+
+struct wmGizmoOpElem {
+ wmOperatorType *type = nullptr;
+ /** Operator properties if gizmo spawns and controls an operator,
+ * or owner pointer if gizmo spawns and controls a property. */
+ PointerRNA ptr = {};
+
+ bool is_redo = false;
+};
+
+/** Gizmos are set per region by registering them on gizmo-maps. */
+struct wmGizmo {
+ wmGizmo *next, *prev;
+
+ /** While we don't have a real type, use this to put type-like vars. */
+ const wmGizmoType *type;
+
+ /** Overrides 'type->modal' when set.
+ * Note that this is a workaround, remove if we can. */
+ wmGizmoFnModal custom_modal;
+
+ /** Pointer back to group this gizmo is in (just for quick access). */
+ wmGizmoGroup *parent_gzgroup;
+
+ /** Optional keymap to use for this gizmo (overrides #wmGizmoGroupType.keymap). */
+ wmKeyMap *keymap;
+
+ void *py_instance;
+
+ /** Rna pointer to access properties. */
+ PointerRNA *ptr;
+
+ /** Flags that influence the behavior or how the gizmos are drawn. */
+ eWM_GizmoFlag flag;
+ /** State flags (active, highlighted, selected). */
+ eWM_GizmoFlagState state;
+
+ /** Optional ID for highlighting different parts of this gizmo.
+ * -1 when unset, otherwise a valid index. (Used as index to 'op_data'). */
+ int highlight_part;
+
+ /**
+ * For gizmos that differentiate between click & drag,
+ * use a different part for any drag events, -1 when unused.
+ */
+ int drag_part;
+
+ /** Distance to bias this gizmo above others when picking
+ * (in world-space, scaled by the gizmo scale - when used). */
+ float select_bias;
+
+ /* Transformation of the gizmo in 2d or 3d space.
+ * - Matrix axis are expected to be unit length (scale is applied after).
+ * - Behavior when axis aren't orthogonal depends on each gizmo.
+ * - Typically the +Z is the primary axis for gizmos to use.
+ * - 'matrix[3]' must be used for location,
+ * besides this it's up to the gizmos internal code how the
+ * rotation components are used for drawing and interaction. */
+
+ /** The space this gizmo is being modified in. */
+ float matrix_space[4][4];
+ /** Transformation of this gizmo. */
+ float matrix_basis[4][4];
+ /** Custom offset from origin. */
+ float matrix_offset[4][4];
+ /** Runtime property, set the scale while drawing on the viewport. */
+ float scale_final;
+ /** User defined scale, in addition to the original one. */
+ float scale_basis;
+ /** User defined width for line drawing. */
+ float line_width;
+ /** Gizmo colors (uses default fallbacks if not defined). */
+ float color[4], color_hi[4];
+
+ /** Data used during interaction. */
+ void *interaction_data;
+
+ /** Operator to spawn when activating the gizmo (overrides property editing),
+ * an array of items (aligned with #wmGizmo.highlight_part). */
+ Vector<wmGizmoOpElem, 4> op_data;
+
+ IDProperty *properties;
+
+ /* TODO: Once wmGizmo itself gets an actual constructor, this can most likely become a
+ * `Array`, since length is defined by the gizmo type. */
+ Vector<wmGizmoProperty, 0> target_properties;
+
+ /** Redraw tag. */
+ bool do_draw;
+
+ /** Temporary data (assume dirty). */
+ union {
+ float f;
+ } temp;
+};
+
+/** Similar to #PropertyElemRNA, but has an identifier. */
+struct wmGizmoProperty {
+ const wmGizmoPropertyType *type = nullptr;
+
+ PointerRNA ptr = PointerRNA_NULL;
+ PropertyRNA *prop = nullptr;
+ int index = -1;
+
+ /* Optional functions for converting to/from RNA. */
+ struct {
+ wmGizmoPropertyFnGet value_get_fn = nullptr;
+ wmGizmoPropertyFnSet value_set_fn = nullptr;
+ wmGizmoPropertyFnRangeGet range_get_fn = nullptr;
+ wmGizmoPropertyFnFree free_fn = nullptr;
+ wmGizmoPropertyFnForeachRNAProp foreach_rna_prop_fn = nullptr;
+ void *user_data = nullptr;
+ } custom_func = {};
+};
+
+struct wmGizmoPropertyType {
+ wmGizmoPropertyType *next, *prev;
+ /** #PropertyType, typically #PROP_FLOAT. */
+ int data_type;
+ int array_length;
+
+ /** Index within #wmGizmoType. */
+ int index_in_type;
+
+ /** Over allocate. */
+ char idname[0];
+};
+
+/**
+ * Simple utility wrapper for storing a single gizmo as wmGizmoGroup.customdata (which gets freed).
+ */
+struct wmGizmoWrapper {
+ wmGizmo *gizmo;
+};
+
+struct wmGizmoMapType_Params {
+ short spaceid;
+ short regionid;
+};
+
+struct wmGizmoType {
+
+ const char *idname; /* #MAX_NAME. */
+
+ /** Set to `sizeof(wmGizmo)` or larger for instances of this type,
+ * use so we can cast to other types without the hassle of a custom-data pointer. */
+ uint struct_size;
+
+ /** Initialize struct (calloc'd 'struct_size' region). */
+ wmGizmoFnSetup setup;
+
+ /** Draw gizmo. */
+ wmGizmoFnDraw draw;
+
+ /** Determines 3d intersection by rendering the gizmo in a selection routine. */
+ wmGizmoFnDrawSelect draw_select;
+
+ /** Determine if the mouse intersects with the gizmo.
+ * The calculation should be done in the callback itself, -1 for no selection. */
+ wmGizmoFnTestSelect test_select;
+
+ /** Handler used by the gizmo. Usually handles interaction tied to a gizmo type. */
+ wmGizmoFnModal modal;
+
+ /** Gizmo-specific handler to update gizmo attributes based on the property value. */
+ wmGizmoFnPropertyUpdate property_update;
+
+ /**
+ * Returns the final transformation which may be different from the 'matrix',
+ * depending on the gizmo.
+ * Notes:
+ * - Scale isn't applied (wmGizmo.scale/user_scale).
+ * - Offset isn't applied (wmGizmo.matrix_offset).
+ */
+ wmGizmoFnMatrixBasisGet matrix_basis_get;
+
+ /**
+ * Returns screen-space bounding box in the window space
+ * (compatible with #wmEvent.xy).
+ *
+ * Used for tool-tip placement (otherwise the cursor location is used).
+ */
+ wmGizmoFnScreenBoundsGet screen_bounds_get;
+
+ /** Activate a gizmo state when the user clicks on it. */
+ wmGizmoFnInvoke invoke;
+
+ /** Called when gizmo tweaking is done - used to free data and reset property when canceling. */
+ wmGizmoFnExit exit;
+
+ wmGizmoFnCursorGet cursor_get;
+
+ /** Called when gizmo selection state changes. */
+ wmGizmoFnSelectRefresh select_refresh;
+
+ /** Free data (not the gizmo itself), use when the gizmo allocates its own members. */
+ wmGizmoFnFree free;
+
+ /** RNA for properties. */
+ StructRNA *srna;
+
+ /** RNA integration. */
+ ExtensionRNA rna_ext;
+
+ ListBaseT<wmGizmoPropertyType> target_property_defs;
+ int target_property_defs_len;
+};
+
+/* -------------------------------------------------------------------- */
+/* #wmGizmoGroup. */
+
+/** Factory class for a gizmo-group type, gets called every time a new area is spawned. */
+struct wmGizmoGroupTypeRef {
+ wmGizmoGroupTypeRef *next, *prev;
+ wmGizmoGroupType *type;
+};
+
+/** Factory class for a gizmo-group type, gets called every time a new area is spawned. */
+struct wmGizmoGroupType {
+ const char *idname; /* #MAX_NAME. */
+ /** Gizmo-group name - displayed in UI (keymap editor). */
+ const char *name;
+ /** Optional, see: #wmOwnerID. */
+ char owner_id[128];
+
+ /** Optional, used when drawing a group background with `draw_background`. */
+ float4 background_color;
+ float4 outline_color;
+
+ /** Poll if gizmo-map should be visible. */
+ wmGizmoGroupFnPoll poll;
+ /** Initially create gizmos and set permanent data - stuff you only need to do once. */
+ wmGizmoGroupFnInit setup;
+ /** Refresh data, only called if recreate flag is set (WM_gizmomap_tag_refresh). */
+ wmGizmoGroupFnRefresh refresh;
+ /** Refresh data for drawing, called before each redraw. */
+ wmGizmoGroupFnDrawPrepare draw_prepare;
+ /** Optionally draw the background of the group itself. */
+ wmGizmoGroupFnDrawBackground draw_background;
+ /** Initialize data for before invoke. */
+ wmGizmoGroupFnInvokePrepare invoke_prepare;
+
+ /** Keymap init callback for this gizmo-group (optional),
+ * will fall back to default tweak keymap when left NULL. */
+ wmGizmoGroupFnSetupKeymap setup_keymap;
+
+ /** Optionally subscribe to wmMsgBus events,
+ * these are calculated automatically from RNA properties,
+ * only needed if gizmos depend indirectly on properties. */
+ wmGizmoGroupFnMsgBusSubscribe message_subscribe;
+
+ /** Keymap created with callback from above. */
+ wmKeyMap *keymap;
+ /** Only for convenient removal. */
+ wmKeyConfig *keyconf;
+
+ /* NOTE: currently gizmo-group instances don't store properties,
+ * they're kept in the tool properties. */
+
+ /** RNA for properties. */
+ StructRNA *srna;
+
+ /** RNA integration. */
+ ExtensionRNA rna_ext;
+
+ eWM_GizmoFlagGroupTypeFlag flag;
+
+ /** So we know which group type to update. */
+ eWM_GizmoFlagMapTypeUpdateFlag type_update_flag;
+
+ /** Same as gizmo-maps, so registering/unregistering goes to the correct region. */
+ wmGizmoMapType_Params gzmap_params;
+
+ /**
+ * Number of #wmGizmoGroup instances.
+ * Decremented when 'tag_remove' is set, or when removed.
+ */
+ int users;
+};
+
+struct wmGizmoGroup {
+ wmGizmoGroup *next, *prev;
+
+ wmGizmoGroupType *type;
+ ListBaseT<wmGizmo> gizmos;
+
+ wmGizmoMap *parent_gzmap;
+
+ /** Python stores the class instance here. */
+ void *py_instance;
+
+ /** Has the same result as hiding all gizmos individually. */
+ union {
+ /** Reasons for hiding. */
+ struct {
+ uint delay_refresh_for_tweak : 1;
+ };
+ /** All, when we only want to check if any are hidden. */
+ uint any;
+ } hide;
+
+ bool tag_remove;
+
+ void *customdata;
+ /** For freeing customdata from above. */
+ void (*customdata_free)(void *);
+ eWM_GizmoFlagGroupInitFlag init_flag;
+};
+
+/* -------------------------------------------------------------------- */
+/* #wmGizmoMap. */
+
+/**
+ * Pass a value of this enum to #WM_gizmomap_draw to tell it what to draw.
+ */
+enum eWM_GizmoFlagMapDrawStep {
+ /** Draw 2D gizmo-groups (#WM_GIZMOGROUPTYPE_3D not set). */
+ WM_GIZMOMAP_DRAWSTEP_2D = 0,
+ /** Draw 3D gizmo-groups (#WM_GIZMOGROUPTYPE_3D set). */
+ WM_GIZMOMAP_DRAWSTEP_3D,
+};
+#define WM_GIZMOMAP_DRAWSTEP_MAX 2
+
+} // namespace blender
diff --git a/compat/include/WM_keymap.hh b/compat/include/WM_keymap.hh
new file mode 100644
index 0000000..cafabdf
--- /dev/null
+++ b/compat/include/WM_keymap.hh
@@ -0,0 +1,246 @@
+/* SPDX-FileCopyrightText: 2007 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup wm
+ */
+
+#include <optional>
+#include <string>
+
+#include "DNA_windowmanager_types.h"
+#include "WM_types.hh"
+
+namespace blender {
+
+#ifdef hyper /* MSVC defines. */
+# undef hyper
+#endif
+
+struct EnumPropertyItem;
+
+/* Key Configuration. */
+
+void WM_keyconfig_init(bContext *C);
+void WM_keyconfig_reload(bContext *C);
+
+wmKeyConfig *WM_keyconfig_new(wmWindowManager *wm, const char *idname, bool user_defined);
+wmKeyConfig *WM_keyconfig_ensure(wmWindowManager *wm, const char *idname, bool user_defined);
+void WM_keyconfig_remove(wmWindowManager *wm, wmKeyConfig *keyconf);
+void WM_keyconfig_clear(wmKeyConfig *keyconf);
+void WM_keyconfig_free(wmKeyConfig *keyconf);
+
+void WM_keyconfig_set_active(wmWindowManager *wm, const char *idname);
+
+/**
+ * \param keep_properties: When true, the properties for operators which cannot be found are kept.
+ * This is needed for operator reloading that validates key-map items for operators that may have
+ * their operators loaded back in the future, see: #113309.
+ */
+void WM_keyconfig_update_ex(wmWindowManager *wm, bool keep_properties);
+void WM_keyconfig_update(wmWindowManager *wm);
+void WM_keyconfig_update_on_startup(wmWindowManager *wm);
+void WM_keyconfig_update_tag(wmKeyMap *keymap, wmKeyMapItem *kmi);
+void WM_keyconfig_update_operatortype_tag();
+
+void WM_keyconfig_update_suppress_begin();
+void WM_keyconfig_update_suppress_end();
+
+void WM_keyconfig_update_postpone_begin();
+void WM_keyconfig_update_postpone_end();
+
+/** Keymap. */
+
+/** Parameters for matching events, passed into functions that create key-map items. */
+struct KeyMapItem_Params {
+ /** #wmKeyMapItem.type. */
+ int16_t type;
+ /** #wmKeyMapItem.val. */
+ int8_t value;
+ /**
+ * This value is used to initialize #wmKeyMapItem `ctrl, shift, alt, oskey, hyper`.
+ *
+ * Valid values:
+ *
+ * - Combinations of: #KM_SHIFT, #KM_CTRL, #KM_ALT, #KM_OSKEY, #KM_HYPER.
+ * Are mapped to #KM_MOD_HELD.
+ * - Combinations of the modifier flags bit-shifted using #KMI_PARAMS_MOD_TO_ANY.
+ * Are mapped to #KM_ANY.
+ * - The value #KM_ANY is represents all modifiers being set to #KM_ANY.
+ */
+ int16_t modifier;
+
+ /** #wmKeyMapItem.keymodifier. */
+ int16_t keymodifier;
+ /** #wmKeyMapItem.direction. */
+ int8_t direction;
+};
+
+/**
+ * Use to assign modifiers to #KeyMapItem_Params::modifier
+ * which can have any state (held or released).
+ */
+#define KMI_PARAMS_MOD_TO_ANY(mod) ((mod) << 8)
+/**
+ * Use to read modifiers from #KeyMapItem_Params::modifier
+ * which can have any state (held or released).
+ */
+#define KMI_PARAMS_MOD_FROM_ANY(mod) ((mod) >> 8)
+
+void WM_keymap_clear(wmKeyMap *keymap);
+
+/**
+ * Always add item.
+ */
+wmKeyMapItem *WM_keymap_add_item(wmKeyMap *keymap,
+ const char *idname,
+ const KeyMapItem_Params *params);
+wmKeyMapItem *WM_keymap_add_item_copy(wmKeyMap *keymap, const wmKeyMapItem *kmi_src);
+
+void WM_keymap_remove_item(wmKeyMap *keymap, wmKeyMapItem *kmi);
+std::optional<std::string> WM_keymap_item_to_string(const wmKeyMapItem *kmi, bool compact);
+
+wmKeyMap *WM_keymap_list_find(ListBaseT<wmKeyMap> *lb,
+ const char *idname,
+ int spaceid,
+ int regionid);
+wmKeyMap *WM_keymap_list_find_spaceid_or_empty(ListBaseT<wmKeyMap> *lb,
+ const char *idname,
+ int spaceid,
+ int regionid);
+wmKeyMap *WM_keymap_ensure(wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid);
+wmKeyMap *WM_keymap_find_all(wmWindowManager *wm, const char *idname, int spaceid, int regionid);
+wmKeyMap *WM_keymap_find_all_spaceid_or_empty(wmWindowManager *wm,
+ const char *idname,
+ int spaceid,
+ int regionid);
+wmKeyMap *WM_keymap_active(const wmWindowManager *wm, wmKeyMap *keymap);
+void WM_keymap_remove(wmKeyConfig *keyconf, wmKeyMap *keymap);
+bool WM_keymap_poll(bContext *C, wmKeyMap *keymap);
+
+wmKeyMapItem *WM_keymap_item_find_id(wmKeyMap *keymap, int id);
+bool WM_keymap_item_compare(const wmKeyMapItem *k1, const wmKeyMapItem *k2);
+
+/**
+ * Return the user key-map item from `km_base` based on `km_match` & `kmi_match`,
+ * currently the supported use case is looking up "User" key-map items from "Add-on" key-maps.
+ * Other lookups may be supported.
+ */
+wmKeyMapItem *WM_keymap_item_find_match(wmKeyMap *km_base,
+ wmKeyMap *km_match,
+ const wmKeyMapItem *kmi_match,
+ ReportList *reports);
+
+/* `wm_keymap_utils.cc`. */
+
+/* Wrappers for #WM_keymap_add_item. */
+
+/**
+ * Menu wrapper for #WM_keymap_add_item.
+ */
+wmKeyMapItem *WM_keymap_add_menu(wmKeyMap *keymap,
+ const char *idname,
+ const KeyMapItem_Params *params);
+/**
+ * Pie-menu wrapper for #WM_keymap_add_item.
+ */
+wmKeyMapItem *WM_keymap_add_menu_pie(wmKeyMap *keymap,
+ const char *idname,
+ const KeyMapItem_Params *params);
+/**
+ * Panel (popover) wrapper for #WM_keymap_add_item.
+ */
+wmKeyMapItem *WM_keymap_add_panel(wmKeyMap *keymap,
+ const char *idname,
+ const KeyMapItem_Params *params);
+/**
+ * Tool wrapper for #WM_keymap_add_item.
+ */
+wmKeyMapItem *WM_keymap_add_tool(wmKeyMap *keymap,
+ const char *idname,
+ const KeyMapItem_Params *params);
+
+wmKeyMap *WM_keymap_guess_from_context(const bContext *C);
+
+/**
+ * Guess an appropriate key-map from the operator name.
+ *
+ * \note Needs to be kept up to date with Key-map and Operator naming.
+ */
+wmKeyMap *WM_keymap_guess_opname(const bContext *C, const char *opname);
+
+bool WM_keymap_uses_event_modifier(const wmKeyMap *keymap, int event_modifier);
+
+void WM_keymap_fix_linking();
+
+/* Modal Keymap. */
+
+std::optional<std::string> WM_modalkeymap_items_to_string(const wmKeyMap *km,
+ int propvalue,
+ bool compact);
+std::optional<std::string> WM_modalkeymap_operator_items_to_string(wmOperatorType *ot,
+ int propvalue,
+ bool compact);
+
+wmKeyMap *WM_modalkeymap_ensure(wmKeyConfig *keyconf,
+ const char *idname,
+ const EnumPropertyItem *items);
+wmKeyMap *WM_modalkeymap_find(wmKeyConfig *keyconf, const char *idname);
+wmKeyMapItem *WM_modalkeymap_add_item(wmKeyMap *km, const KeyMapItem_Params *params, int value);
+wmKeyMapItem *WM_modalkeymap_add_item_str(wmKeyMap *km,
+ const KeyMapItem_Params *params,
+ const char *value);
+const wmKeyMapItem *WM_modalkeymap_find_propvalue(const wmKeyMap *km, int propvalue);
+void WM_modalkeymap_assign(wmKeyMap *km, const char *opname);
+
+/* Keymap Editor. */
+
+void WM_keymap_restore_to_default(wmKeyMap *keymap, wmWindowManager *wm);
+/**
+ * Properties can be NULL, otherwise the arg passed is used and ownership is given to the `kmi`.
+ */
+void WM_keymap_item_properties_reset(wmKeyMapItem *kmi, IDProperty *properties);
+void WM_keymap_item_restore_to_default(wmWindowManager *wm, wmKeyMap *keymap, wmKeyMapItem *kmi);
+int WM_keymap_item_map_type_get(const wmKeyMapItem *kmi);
+
+/* Key Event. */
+
+const char *WM_key_event_string(short type, bool compact);
+std::optional<std::string> WM_keymap_item_raw_to_string(int8_t shift,
+ int8_t ctrl,
+ int8_t alt,
+ int8_t oskey,
+ int8_t hyper,
+ short keymodifier,
+ short val,
+ short type,
+ bool compact);
+/**
+ * \param include_mask, exclude_mask:
+ * Event types to include/exclude when looking up keys (#eEventType_Mask).
+ */
+wmKeyMapItem *WM_key_event_operator(const bContext *C,
+ const char *opname,
+ wm::OpCallContext opcontext,
+ IDProperty *properties,
+ short include_mask,
+ short exclude_mask,
+ wmKeyMap **r_keymap);
+std::optional<std::string> WM_key_event_operator_string(const bContext *C,
+ const char *opname,
+ wm::OpCallContext opcontext,
+ IDProperty *properties,
+ bool is_strict);
+
+wmKeyMapItem *WM_key_event_operator_from_keymap(wmKeyMap *keymap,
+ const char *opname,
+ IDProperty *properties,
+ short include_mask,
+ short exclude_mask);
+
+const char *WM_bool_as_string(bool test);
+
+} // namespace blender
diff --git a/compat/include/WM_message.hh b/compat/include/WM_message.hh
new file mode 100644
index 0000000..8d075ab
--- /dev/null
+++ b/compat/include/WM_message.hh
@@ -0,0 +1,11 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup wm
+ */
+
+#pragma once
+
+#include "message_bus/wm_message_bus.hh" // IWYU pragma: export
diff --git a/compat/include/WM_toolsystem.hh b/compat/include/WM_toolsystem.hh
new file mode 100644
index 0000000..549a3e4
--- /dev/null
+++ b/compat/include/WM_toolsystem.hh
@@ -0,0 +1,169 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+/** \file
+ * \ingroup wm
+ */
+
+#include "BKE_paint_types.hh"
+
+namespace blender {
+
+struct Brush;
+struct IDProperty;
+struct Main;
+struct Paint;
+struct PointerRNA;
+struct Scene;
+struct ScrArea;
+struct StructRNA;
+struct WorkSpace;
+struct bContext;
+struct bToolRef;
+struct bToolRef_Runtime;
+struct ViewLayer;
+struct wmMsgSubscribeKey;
+struct wmMsgSubscribeValue;
+struct wmOperatorType;
+struct wmWindow;
+struct AssetWeakReference;
+
+/* `wm_toolsystem.cc` */
+
+#define WM_TOOLSYSTEM_SPACE_MASK \
+ ((1 << SPACE_IMAGE) | (1 << SPACE_NODE) | (1 << SPACE_VIEW3D) | (1 << SPACE_SEQ))
+/**
+ * Space-types that define their own "mode" (as returned by #WM_toolsystem_mode_from_spacetype).
+ */
+#define WM_TOOLSYSTEM_SPACE_MASK_MODE_FROM_SPACE ((1 << SPACE_IMAGE) | (1 << SPACE_SEQ))
+
+/**
+ * Values that define a category of active tool.
+ */
+struct bToolKey {
+ int space_type;
+ int mode;
+};
+
+bToolRef *WM_toolsystem_ref_from_context(const bContext *C);
+bToolRef *WM_toolsystem_ref_find(WorkSpace *workspace, const bToolKey *tkey);
+bool WM_toolsystem_ref_ensure(WorkSpace *workspace, const bToolKey *tkey, bToolRef **r_tref);
+
+bToolRef *WM_toolsystem_ref_set_by_id_ex(
+ bContext *C, WorkSpace *workspace, const bToolKey *tkey, const char *name, bool cycle);
+bToolRef *WM_toolsystem_ref_set_by_id(bContext *C, const char *name);
+
+bToolRef_Runtime *WM_toolsystem_runtime_from_context(const bContext *C);
+bToolRef_Runtime *WM_toolsystem_runtime_find(WorkSpace *workspace, const bToolKey *tkey);
+
+/**
+ * Activate the brush through the tool system. This will call #BKE_paint_brush_set() with \a brush,
+ * but it will also switch to the tool appropriate for this brush type (if necessary) and update
+ * the current tool-brush references to remember the last used brush for that tool.
+ *
+ * \return True if the brush was successfully activated.
+ */
+bool WM_toolsystem_activate_brush_and_tool(bContext *C, Paint *paint, Brush *brush);
+
+/**
+ * Get an asset reference to the last activated brush asset of a specific brush type.
+ */
+std::optional<AssetWeakReference> WM_toolsystem_last_brush_asset_from_brush_type(
+ Scene *scene, const int brush_type, const PaintMode paint_mode);
+
+void WM_toolsystem_unlink(bContext *C, WorkSpace *workspace, const bToolKey *tkey);
+void WM_toolsystem_refresh(const bContext *C, WorkSpace *workspace, const bToolKey *tkey);
+void WM_toolsystem_reinit(bContext *C, WorkSpace *workspace, const bToolKey *tkey);
+
+/**
+ * Operate on all active tools.
+ */
+void WM_toolsystem_unlink_all(bContext *C, WorkSpace *workspace);
+void WM_toolsystem_refresh_all(const bContext *C, WorkSpace *workspace);
+void WM_toolsystem_reinit_all(bContext *C, wmWindow *win);
+
+void WM_toolsystem_ref_set_from_runtime(bContext *C,
+ WorkSpace *workspace,
+ bToolRef *tref,
+ const bToolRef_Runtime *tref_rt,
+ const char *idname);
+
+/**
+ * Sync the internal active state of a tool back into the tool system,
+ * this is needed for active brushes where the real active state is not stored in the tool system.
+ *
+ * \see #toolsystem_ref_link
+ */
+void WM_toolsystem_ref_sync_from_context(Main *bmain, WorkSpace *workspace, bToolRef *tref);
+
+void WM_toolsystem_init(const bContext *C);
+
+int WM_toolsystem_mode_from_spacetype(
+ const Main &bmain, const Scene *scene, ViewLayer *view_layer, ScrArea *area, int space_type);
+bool WM_toolsystem_key_from_context(
+ const Main &bmain, const Scene *scene, ViewLayer *view_layer, ScrArea *area, bToolKey *tkey);
+
+void WM_toolsystem_update_from_context_view3d(bContext *C);
+void WM_toolsystem_update_from_context(
+ bContext *C, WorkSpace *workspace, const Scene *scene, ViewLayer *view_layer, ScrArea *area);
+
+/**
+ * For paint modes to support non-brush tools.
+ */
+bool WM_toolsystem_active_tool_is_brush(const bContext *C);
+bool WM_toolsystem_active_tool_has_custom_cursor(const bContext *C);
+
+/** Follow #wmMsgNotifyFn spec. */
+void WM_toolsystem_do_msg_notify_tag_refresh(bContext *C,
+ wmMsgSubscribeKey *msg_key,
+ wmMsgSubscribeValue *msg_val);
+
+IDProperty *WM_toolsystem_ref_properties_get_idprops(bToolRef *tref);
+IDProperty *WM_toolsystem_ref_properties_ensure_idprops(bToolRef *tref);
+void WM_toolsystem_ref_properties_ensure_ex(bToolRef *tref,
+ const char *idname,
+ StructRNA *type,
+ PointerRNA *r_ptr);
+
+#define WM_toolsystem_ref_properties_ensure_from_operator(tref, ot, r_ptr) \
+ WM_toolsystem_ref_properties_ensure_ex(tref, (ot)->idname, (ot)->srna, r_ptr)
+#define WM_toolsystem_ref_properties_ensure_from_gizmo_group(tref, gzgroup, r_ptr) \
+ WM_toolsystem_ref_properties_ensure_ex(tref, (gzgroup)->idname, (gzgroup)->srna, r_ptr)
+
+bool WM_toolsystem_ref_properties_get_ex(bToolRef *tref,
+ const char *idname,
+ StructRNA *type,
+ PointerRNA *r_ptr);
+#define WM_toolsystem_ref_properties_get_from_operator(tref, ot, r_ptr) \
+ WM_toolsystem_ref_properties_get_ex(tref, (ot)->idname, (ot)->srna, r_ptr)
+#define WM_toolsystem_ref_properties_get_from_gizmo_group(tref, gzgroup, r_ptr) \
+ WM_toolsystem_ref_properties_get_ex(tref, (gzgroup)->idname, (gzgroup)->srna, r_ptr)
+
+void WM_toolsystem_ref_properties_init_for_keymap(bToolRef *tref,
+ PointerRNA *dst_ptr,
+ PointerRNA *src_ptr,
+ wmOperatorType *ot);
+
+/**
+ * Use to update the active tool (shown in the top bar) in the least disruptive way.
+ *
+ * This is a little involved since there may be multiple valid active tools
+ * depending on the mode and space type.
+ *
+ * Used when undoing since the active mode may have changed.
+ */
+void WM_toolsystem_refresh_active(bContext *C);
+/**
+ * \return true if the tool changed.
+ */
+bool WM_toolsystem_refresh_screen_area(const Main &bmain,
+ WorkSpace *workspace,
+ const Scene *scene,
+ ViewLayer *view_layer,
+ ScrArea *area);
+void WM_toolsystem_refresh_screen_window(const Main &bmain, wmWindow *win);
+void WM_toolsystem_refresh_screen_all(Main *bmain);
+
+} // namespace blender
diff --git a/compat/include/WM_types.hh b/compat/include/WM_types.hh
new file mode 100644
index 0000000..5fb896b
--- /dev/null
+++ b/compat/include/WM_types.hh
@@ -0,0 +1,1527 @@
+/* SPDX-FileCopyrightText: 2007 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup wm
+ *
+ *
+ * Overview of WM structs
+ * ======================
+ *
+ * - #wmWindowManager.windows -> #wmWindow <br>
+ * Window manager stores a list of windows.
+ *
+ * - #wmWindow.screen -> #bScreen <br>
+ * Window has an active screen.
+ *
+ * - #bScreen.areabase -> #ScrArea <br>
+ * Link to #ScrArea.
+ *
+ * - #ScrArea.spacedata <br>
+ * Stores multiple spaces via space links.
+ *
+ * - #SpaceLink <br>
+ * Base struct for space data for all different space types.
+ *
+ * - #ScrArea.regionbase -> #ARegion <br>
+ * Stores multiple regions.
+ *
+ * - #bScreen.regionbase -> #ARegion <br>
+ * Global screen level regions, e.g. popups, popovers, menus.
+ *
+ * - #wmWindow.global_areas -> #ScrAreaMap <br>
+ * Global screen via `areabase`, e.g. top-bar & status-bar.
+ *
+ *
+ * Window Layout
+ * =============
+ *
+ * <pre>
+ * wmWindow -> bScreen
+ * +----------------------------------------------------------+
+ * |+-----------------------------------------+-------------+ |
+ * ||ScrArea (links to 3D view) |ScrArea | |
+ * ||+-------++----------+-------------------+|(links to | |
+ * |||ARegion|| |ARegion (quad view)|| properties) | |
+ * |||(tools)|| | || | |
+ * ||| || | || | |
+ * ||| || | || | |
+ * ||| || | || | |
+ * ||| |+----------+-------------------+| | |
+ * ||| || | || | |
+ * ||| || | || | |
+ * ||| || | || | |
+ * ||| || | || | |
+ * ||| || | || | |
+ * ||+-------++----------+-------------------+| | |
+ * |+-----------------------------------------+-------------+ |
+ * +----------------------------------------------------------+
+ * </pre>
+ *
+ * Space Data
+ * ==========
+ *
+ * <pre>
+ * ScrArea's store a list of space data (SpaceLinks), each of unique type.
+ * The first one is the displayed in the UI, others are added as needed.
+ *
+ * +----------------------------+ <-- area->spacedata.first;
+ * | |
+ * | |---+ <-- other inactive SpaceLink's stored.
+ * | | |
+ * | | |---+
+ * | | | |
+ * | | | |
+ * | | | |
+ * | | | |
+ * +----------------------------+ | |
+ * | | |
+ * +-----------------------------+ |
+ * | |
+ * +------------------------------+
+ * </pre>
+ *
+ * A common way to get the space from the ScrArea:
+ * \code{.c}
+ * if (area->spacetype == SPACE_VIEW3D) {
+ * View3D *v3d = area->spacedata.first;
+ * ...
+ * }
+ * \endcode
+ */
+
+#pragma once
+
+#include <memory>
+#include <string>
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_enum_flags.hh"
+#include "BLI_vector.hh"
+
+#include "DNA_listBase.h"
+#include "DNA_uuid_types.h"
+#include "DNA_vec_types.h"
+#include "DNA_xr_types.h"
+
+#include "BKE_wm_runtime.hh" // IWYU pragma: export
+
+#include "RNA_types.hh"
+
+/* Exported types for WM. */
+#include "WM_gizmo_types.hh" // IWYU pragma: export
+#include "wm_cursors.hh" // IWYU pragma: export
+#include "wm_event_types.hh" // IWYU pragma: export
+
+/* Include external gizmo API's. */
+#include "WM_gizmo_api.hh" // IWYU pragma: export
+
+struct CLG_LogRef;
+
+namespace blender {
+
+struct ID;
+struct ImBuf;
+struct bContext;
+struct bContextStore;
+struct GreasePencil;
+struct GreasePencilLayerTreeNode;
+struct ReportList;
+struct wmDrag;
+struct wmDropBox;
+struct wmEvent;
+struct wmOperator;
+struct wmOperatorTypeMacro;
+struct wmWindowManager;
+
+namespace asset_system {
+class AssetRepresentation;
+}
+
+using wmGenericUserDataFreeFn = void (*)(void *data);
+
+struct wmGenericUserData {
+ void *data;
+ /** When NULL, use #MEM_delete_void. */
+ wmGenericUserDataFreeFn free_fn;
+ bool use_free;
+};
+
+using wmGenericCallbackFn = void (*)(bContext *C, void *user_data);
+
+struct wmGenericCallback {
+ wmGenericCallbackFn exec;
+ void *user_data;
+ wmGenericUserDataFreeFn free_user_data;
+};
+
+/* ************** wmOperatorType ************************ */
+
+/** #wmOperatorType.flag */
+enum {
+ /**
+ * Register operators in stack after finishing (needed for redo).
+ *
+ * \note Typically this flag should be enabled along with #OPTYPE_UNDO.
+ * There are some exceptions to this:
+ *
+ * - Operators can conditionally perform an undo push,
+ * Examples include operators that may modify "screen" data
+ * (which the undo system doesn't track), or data-blocks such as objects, meshes etc.
+ * In this case the undo push depends on the operators internal logic.
+ *
+ * We could support this as part of the operator return flag,
+ * currently it requires explicit calls to undo push.
+ *
+ * - Operators can perform an undo push indirectly.
+ * (`UI_OT_reset_default_button` for example).
+ *
+ * In this case, register needs to be enabled so as not to clear the "Redo" panel, see #133761.
+ * Unless otherwise stated, any operators that register without the undo flag
+ * can be assumed to be creating undo steps indirectly (potentially at least).
+ */
+ OPTYPE_REGISTER = (1 << 0),
+ /** Do an undo push after the operator runs. */
+ OPTYPE_UNDO = (1 << 1),
+ /** Let Blender grab all input from the WM (X11). */
+ OPTYPE_BLOCKING = (1 << 2),
+ OPTYPE_MACRO = (1 << 3),
+
+ /** Grabs the cursor and optionally enables continuous cursor wrapping. */
+ OPTYPE_GRAB_CURSOR_XY = (1 << 4),
+ /** Only warp on the X axis. */
+ OPTYPE_GRAB_CURSOR_X = (1 << 5),
+ /** Only warp on the Y axis. */
+ OPTYPE_GRAB_CURSOR_Y = (1 << 6),
+
+ /** Show preset menu. */
+ OPTYPE_PRESET = (1 << 7),
+
+ /**
+ * Some operators are mainly for internal use and don't make sense
+ * to be accessed from the search menu, even if poll() returns true.
+ * Currently only used for the search toolbox.
+ */
+ OPTYPE_INTERNAL = (1 << 8),
+
+ /** Allow operator to run when interface is locked. */
+ OPTYPE_LOCK_BYPASS = (1 << 9),
+ /** Special type of undo which doesn't store itself multiple times. */
+ OPTYPE_UNDO_GROUPED = (1 << 10),
+
+ /**
+ * Depends on the cursor location, when activated from a menu wait for mouse press.
+ *
+ * In practice these operators often end up being accessed:
+ * - Directly from key bindings.
+ * - As tools in the toolbar.
+ *
+ * Even so, accessing from the menu should behave usefully.
+ */
+ OPTYPE_DEPENDS_ON_CURSOR = (1 << 11),
+
+ /** Handle events before modal operators without this flag. */
+ OPTYPE_MODAL_PRIORITY = (1 << 12),
+
+ /** Operator is registered from a local node group or a node group asset. */
+ OPTYPE_NODE_TOOL = (1 << 13),
+};
+
+/** For #WM_cursor_grab_enable wrap axis. */
+enum eWM_CursorWrapAxis {
+ WM_CURSOR_WRAP_NONE = 0,
+ WM_CURSOR_WRAP_X,
+ WM_CURSOR_WRAP_Y,
+ WM_CURSOR_WRAP_XY,
+};
+
+/**
+ * Context to call operator in for #WM_operator_name_call.
+ * rna_ui.cc contains EnumPropertyItem's of these, keep in sync.
+ */
+namespace wm {
+enum class OpCallContext : int8_t {
+ /* If there's invoke, call it, otherwise exec. */
+ InvokeDefault,
+ InvokeRegionWin,
+ InvokeRegionChannels,
+ InvokeRegionPreview,
+ InvokeArea,
+ InvokeScreen,
+ /* Only call exec. */
+ ExecDefault,
+ ExecRegionWin,
+ ExecRegionChannels,
+ ExecRegionPreview,
+ ExecArea,
+ ExecScreen,
+};
+}
+
+#define WM_OP_CONTEXT_HAS_AREA(type) \
+ (CHECK_TYPE_INLINE(type, wm::OpCallContext), \
+ !ELEM(type, wm::OpCallContext::InvokeScreen, wm::OpCallContext::ExecScreen))
+#define WM_OP_CONTEXT_HAS_REGION(type) \
+ (WM_OP_CONTEXT_HAS_AREA(type) && \
+ !ELEM(type, wm::OpCallContext::InvokeArea, wm::OpCallContext::ExecArea))
+
+/** Property tags for #RNA_OperatorProperties. */
+enum eOperatorPropTags {
+ OP_PROP_TAG_ADVANCED = (1 << 0),
+};
+#define OP_PROP_TAG_ADVANCED ((eOperatorPropTags)OP_PROP_TAG_ADVANCED)
+
+/* -------------------------------------------------------------------- */
+/** \name #wmKeyMapItem
+ * \{ */
+
+/**
+ * Modifier keys, not actually used for #wmKeyMapItem (never stored in DNA), used for:
+ * - #wmEvent.modifier.
+ * - #WM_keymap_add_item & #WM_modalkeymap_add_item
+ */
+enum wmEventModifierFlag : uint8_t {
+ KM_SHIFT = (1 << 0),
+ KM_CTRL = (1 << 1),
+ KM_ALT = (1 << 2),
+ /** Use for Windows-Key on MS-Windows, Command-key on macOS and Super on Linux. */
+ KM_OSKEY = (1 << 3),
+ /**
+ * An additional modifier available on Unix systems (in addition to "Super").
+ * Even though standard keyboards don't have a "Hyper" key it is a valid modifier
+ * on Wayland and X11, where it is possible to map a key (typically CapsLock)
+ * to be a Hyper modifier, see !136340.
+ *
+ * Note that this is currently only supported on Wayland & X11
+ * but could be supported on other platforms if desired.
+ */
+ KM_HYPER = (1 << 4),
+};
+ENUM_OPERATORS(wmEventModifierFlag);
+
+/** The number of modifiers #wmKeyMapItem & #wmEvent can use. */
+#define KM_MOD_NUM 5
+
+/**
+ * #wmKeyMapItem.type
+ * NOTE: most types are defined in `wm_event_types.hh`.
+ */
+enum {
+ KM_TEXTINPUT = -2,
+};
+
+/** #wmKeyMapItem.val */
+enum {
+ KM_ANY = -1,
+ KM_NOTHING = 0,
+ KM_PRESS = 1,
+ KM_RELEASE = 2,
+ KM_CLICK = 3,
+ KM_DBL_CLICK = 4,
+ /**
+ * \note The cursor location at the point dragging starts is set to #wmEvent.prev_press_xy
+ * some operators such as box selection should use this location instead of #wmEvent.xy.
+ */
+ KM_PRESS_DRAG = 5,
+};
+/**
+ * Alternate define for #wmKeyMapItem::shift and other modifiers.
+ * While this matches the value of #KM_PRESS, modifiers should only be compared with:
+ * (#KM_ANY, #KM_NOTHING, #KM_MOD_HELD).
+ */
+#define KM_MOD_HELD 1
+
+/**
+ * #wmKeyMapItem.direction
+ *
+ * Direction set for #KM_PRESS_DRAG key-map items. #KM_ANY (-1) to ignore direction.
+ */
+enum {
+ KM_DIRECTION_N = 1,
+ KM_DIRECTION_NE = 2,
+ KM_DIRECTION_E = 3,
+ KM_DIRECTION_SE = 4,
+ KM_DIRECTION_S = 5,
+ KM_DIRECTION_SW = 6,
+ KM_DIRECTION_W = 7,
+ KM_DIRECTION_NW = 8,
+};
+
+/** \} */
+
+/* ************** UI Handler ***************** */
+
+#define WM_UI_HANDLER_CONTINUE 0
+#define WM_UI_HANDLER_BREAK 1
+
+/* ************** Notifiers ****************** */
+
+struct wmNotifier {
+ wmNotifier *next, *prev;
+
+ const wmWindow *window;
+
+ unsigned int category, data, subtype, action;
+
+ void *reference;
+};
+
+/* 4 levels
+ *
+ * 0xFF000000; category
+ * 0x00FF0000; data
+ * 0x0000FF00; data subtype (unused?)
+ * 0x000000FF; action
+ */
+
+/* Category. */
+#define NOTE_CATEGORY 0xFF000000
+#define NOTE_CATEGORY_TAG_CLEARED NOTE_CATEGORY
+#define NC_WM (1 << 24)
+#define NC_WINDOW (2 << 24)
+#define NC_WORKSPACE (3 << 24)
+#define NC_SCREEN (4 << 24)
+#define NC_SCENE (5 << 24)
+#define NC_OBJECT (6 << 24)
+#define NC_MATERIAL (7 << 24)
+#define NC_TEXTURE (8 << 24)
+#define NC_LAMP (9 << 24)
+#define NC_GROUP (10 << 24)
+#define NC_IMAGE (11 << 24)
+#define NC_BRUSH (12 << 24)
+#define NC_TEXT (13 << 24)
+#define NC_WORLD (14 << 24)
+#define NC_ANIMATION (15 << 24)
+/* When passing a space as reference data with this (e.g. `WM_event_add_notifier(..., space)`),
+ * the notifier will only be sent to this space. That avoids unnecessary updates for unrelated
+ * spaces. */
+#define NC_SPACE (16 << 24)
+#define NC_GEOM (17 << 24)
+#define NC_NODE (18 << 24)
+#define NC_ID (19 << 24)
+#define NC_PAINTCURVE (20 << 24)
+#define NC_MOVIECLIP (21 << 24)
+#define NC_MASK (22 << 24)
+#define NC_GPENCIL (23 << 24)
+#define NC_LINESTYLE (24 << 24)
+#define NC_CAMERA (25 << 24)
+#define NC_LIGHTPROBE (26 << 24)
+/* Changes to asset data in the current .blend. */
+#define NC_ASSET (27 << 24)
+/* Changes to the active viewer path. */
+#define NC_VIEWER_PATH (28 << 24)
+
+/* Changes that affects UI drawing. */
+#define NC_UI (29 << 24)
+
+/* Data type, 256 entries is enough, it can overlap. */
+#define NOTE_DATA 0x00FF0000
+
+/* NC_WM (window-manager). */
+#define ND_FILEREAD (1 << 16)
+#define ND_FILESAVE (2 << 16)
+#define ND_DATACHANGED (3 << 16)
+#define ND_HISTORY (4 << 16)
+#define ND_JOB (5 << 16)
+#define ND_UNDO (6 << 16)
+#define ND_XR_DATA_CHANGED (7 << 16)
+#define ND_LIB_OVERRIDE_CHANGED (8 << 16)
+
+/* NC_SCREEN. */
+#define ND_LAYOUTBROWSE (1 << 16)
+#define ND_LAYOUTDELETE (2 << 16)
+#define ND_ANIMPLAY (4 << 16)
+#define ND_GPENCIL (5 << 16)
+#define ND_LAYOUTSET (6 << 16)
+#define ND_SKETCH (7 << 16)
+#define ND_WORKSPACE_SET (8 << 16)
+#define ND_WORKSPACE_DELETE (9 << 16)
+/* Notifies if frames changes as part of animation playback. */
+#define ND_ANIMATION_PLAYBACK (10 << 16)
+
+/* NC_SCENE Scene. */
+#define ND_SCENEBROWSE (1 << 16)
+#define ND_MARKERS (2 << 16)
+#define ND_FRAME (3 << 16)
+#define ND_RENDER_OPTIONS (4 << 16)
+#define ND_NODES (5 << 16)
+#define ND_SEQUENCER (6 << 16)
+/* NOTE: If an object was added, removed, merged/joined, ..., it is not enough to notify with
+ * this. This affects the layer so also send a layer change notifier (e.g. ND_LAYER_CONTENT)! */
+#define ND_OB_ACTIVE (7 << 16)
+/* See comment on ND_OB_ACTIVE. */
+#define ND_OB_SELECT (8 << 16)
+#define ND_OB_VISIBLE (9 << 16)
+#define ND_OB_RENDER (10 << 16)
+#define ND_MODE (11 << 16)
+#define ND_RENDER_RESULT (12 << 16)
+#define ND_COMPO_RESULT (13 << 16)
+#define ND_KEYINGSET (14 << 16)
+#define ND_TOOLSETTINGS (15 << 16)
+#define ND_LAYER (16 << 16)
+#define ND_FRAME_RANGE (17 << 16)
+#define ND_WORLD (92 << 16)
+#define ND_LAYER_CONTENT (101 << 16)
+
+/* NC_OBJECT Object. */
+#define ND_TRANSFORM (18 << 16)
+#define ND_OB_SHADING (19 << 16)
+/**
+ * For non-structural pose-mode changes like transforms.
+ * \note renaming, selecting, bone collections have their own dedicated notifiers,
+ * also see #ND_BONE_SELECT.
+ */
+#define ND_POSE (20 << 16)
+#define ND_BONE_ACTIVE (21 << 16)
+/** Intended for selection and visibility changes in pose/armature edit modes.
+ * Historically this was also used for most edit-mode changes (also "structural" like adding,
+ * deleting, subdividing, filling, ..., bones). Also covers hiding/revealing (in pose-mode and
+ * edit-mode). Note this causes a full (possibly slow) rebuild of the Outliner tree. For such
+ * changes, new code should use #ND_ARMATURE_STRUCTURE. */
+#define ND_BONE_SELECT (22 << 16)
+/** Indicate a change to the structure of the armature; this has implications for both the armature
+ * object and the armature data.
+ *
+ * The value is set to #ND_BONE_SELECT as a transitional state, as currently that notifier is
+ * already used to signify such structural changes. In the future, those uses of #ND_BONE_SELECT
+ * should be replaced with #ND_ARMATURE_STRUCTURE, making the selection notifier only relevant for
+ * selection again. See #153774. */
+#define ND_ARMATURE_STRUCTURE ND_BONE_SELECT
+#define ND_DRAW (23 << 16)
+#define ND_MODIFIER (24 << 16)
+#define ND_KEYS (25 << 16)
+#define ND_CONSTRAINT (26 << 16)
+#define ND_PARTICLE (27 << 16)
+#define ND_POINTCACHE (28 << 16)
+#define ND_PARENT (29 << 16)
+#define ND_LOD (30 << 16)
+/** For camera & sequencer viewport update, also with #NC_SCENE. */
+#define ND_DRAW_RENDER_VIEWPORT (31 << 16)
+#define ND_SHADERFX (32 << 16)
+/* For updating motion paths in 3dview. */
+#define ND_DRAW_ANIMVIZ (33 << 16)
+#define ND_BONE_COLLECTION (34 << 16)
+/* For sequencer prefetch indicator redraw. */
+#define ND_SEQUENCER_PREFETCH (35 << 16)
+
+/* NC_MATERIAL Material. */
+#define ND_SHADING (30 << 16)
+#define ND_SHADING_DRAW (31 << 16)
+#define ND_SHADING_LINKS (32 << 16)
+#define ND_SHADING_PREVIEW (33 << 16)
+
+/* NC_LAMP Light. */
+#define ND_LIGHTING (40 << 16)
+#define ND_LIGHTING_DRAW (41 << 16)
+
+/* NC_WORLD World. */
+#define ND_WORLD_DRAW (45 << 16)
+
+/* NC_TEXT Text. */
+#define ND_CURSOR (50 << 16)
+#define ND_DISPLAY (51 << 16)
+
+/* NC_ANIMATION Animato. */
+#define ND_KEYFRAME (70 << 16)
+#define ND_KEYFRAME_PROP (71 << 16)
+#define ND_ANIMCHAN (72 << 16)
+#define ND_NLA (73 << 16)
+#define ND_NLA_ACTCHANGE (74 << 16)
+#define ND_FCURVES_ORDER (75 << 16)
+#define ND_NLA_ORDER (76 << 16)
+#define ND_KEYFRAME_AUTO (77 << 16)
+
+/* NC_GPENCIL. */
+#define ND_GPENCIL_EDITMODE (85 << 16)
+
+/* NC_GEOM Geometry. */
+/* Mesh, Curve, MetaBall, Armature, etc. */
+#define ND_SELECT (90 << 16)
+#define ND_DATA (91 << 16)
+#define ND_VERTEX_GROUP (92 << 16)
+
+/* NC_NODE Nodes. */
+
+/* Influences which menus node assets are included in. */
+#define ND_NODE_ASSET_DATA (1 << 16)
+#define ND_NODE_GIZMO (2 << 16)
+
+/* NC_SPACE. */
+#define ND_SPACE_CONSOLE (1 << 16) /* General redraw. */
+#define ND_SPACE_INFO_REPORT (2 << 16) /* Update for reports, could specify type. */
+#define ND_SPACE_INFO (3 << 16)
+#define ND_SPACE_IMAGE (4 << 16)
+#define ND_SPACE_FILE_PARAMS (5 << 16)
+#define ND_SPACE_FILE_LIST (6 << 16)
+#define ND_SPACE_ASSET_PARAMS (7 << 16)
+#define ND_SPACE_NODE (8 << 16)
+#define ND_SPACE_OUTLINER (9 << 16)
+#define ND_SPACE_VIEW3D (10 << 16)
+#define ND_SPACE_PROPERTIES (11 << 16)
+#define ND_SPACE_TEXT (12 << 16)
+#define ND_SPACE_TIME (13 << 16)
+#define ND_SPACE_GRAPH (14 << 16)
+#define ND_SPACE_DOPESHEET (15 << 16)
+#define ND_SPACE_NLA (16 << 16)
+#define ND_SPACE_SEQUENCER (17 << 16)
+#define ND_SPACE_NODE_VIEW (18 << 16)
+/* Sent to a new editor type after it's replaced an old one. */
+#define ND_SPACE_CHANGED (19 << 16)
+#define ND_SPACE_CLIP (20 << 16)
+#define ND_SPACE_FILE_PREVIEW (21 << 16)
+#define ND_SPACE_SPREADSHEET (22 << 16)
+/* Not a space itself, but a part of another space. */
+#define ND_REGIONS_ASSET_SHELF (23 << 16)
+
+/* NC_ASSET. */
+/* Denotes that the AssetList is done reading some previews. NOT that the preview generation of
+ * assets is done. */
+#define ND_ASSET_LIST (1 << 16)
+#define ND_ASSET_LIST_PREVIEW (2 << 16)
+#define ND_ASSET_LIST_READING (3 << 16)
+/**
+ * Catalog data changed, requiring a redraw of catalog UIs. Note that this doesn't denote a
+ * reloading of asset libraries & their catalogs should happen.
+ * That only happens on explicit user action.
+ */
+#define ND_ASSET_CATALOGS (4 << 16)
+
+/* Changes in theme preferences that affects UI text drawing. */
+#define ND_UI_FONT (1 << 16)
+
+/* Subtype, 256 entries too. */
+#define NOTE_SUBTYPE 0x0000FF00
+
+/* Subtype scene mode. */
+#define NS_MODE_OBJECT (1 << 8)
+
+#define NS_EDITMODE_MESH (2 << 8)
+#define NS_EDITMODE_CURVE (3 << 8)
+#define NS_EDITMODE_SURFACE (4 << 8)
+#define NS_EDITMODE_TEXT (5 << 8)
+#define NS_EDITMODE_MBALL (6 << 8)
+#define NS_EDITMODE_LATTICE (7 << 8)
+#define NS_EDITMODE_ARMATURE (8 << 8)
+#define NS_MODE_POSE (9 << 8)
+#define NS_MODE_PARTICLE (10 << 8)
+#define NS_EDITMODE_CURVES (11 << 8)
+#define NS_EDITMODE_GREASE_PENCIL (12 << 8)
+#define NS_EDITMODE_POINTCLOUD (13 << 8)
+
+/* Subtype 3d view editing. */
+#define NS_VIEW3D_GPU (16 << 8)
+#define NS_VIEW3D_SHADING (17 << 8)
+
+/* Subtype layer editing. */
+#define NS_LAYER_COLLECTION (24 << 8)
+
+/* Action classification. */
+#define NOTE_ACTION (0x000000FF)
+#define NA_EDITED 1
+#define NA_EVALUATED 2
+#define NA_ADDED 3
+#define NA_REMOVED 4
+#define NA_RENAME 5
+#define NA_SELECTED 6
+#define NA_ACTIVATED 7
+#define NA_PAINTING 8
+#define NA_JOB_FINISHED 9
+#define NA_DOWNLOAD_FINISHED 10
+
+/* ************** Gesture Manager data ************** */
+
+namespace wm::gesture {
+constexpr float POLYLINE_CLICK_RADIUS = 15.0f;
+}
+
+/** #wmGesture::type */
+#define WM_GESTURE_LINES 1
+#define WM_GESTURE_RECT 2
+#define WM_GESTURE_CROSS_RECT 3
+#define WM_GESTURE_LASSO 4
+#define WM_GESTURE_CIRCLE 5
+#define WM_GESTURE_STRAIGHTLINE 6
+#define WM_GESTURE_POLYLINE 7
+
+/**
+ * wmGesture is registered to #wmWindow.gesture, handled by operator callbacks.
+ */
+struct wmGesture {
+ wmGesture *next, *prev;
+ /** #wmEvent.type. */
+ int event_type;
+ /** #wmEvent.modifier. */
+ uint8_t event_modifier;
+ /** #wmEvent.keymodifier. */
+ short event_keymodifier;
+ /** Gesture type define. */
+ int type;
+ /** Bounds of region to draw gesture within. */
+ rcti winrct;
+ /** Optional, amount of points stored. */
+ int points;
+ /** Optional, maximum amount of points stored. */
+ int points_alloc;
+ int modal_state;
+ /** Optional, draw the active side of the straight-line gesture. */
+ bool draw_active_side;
+ /** Latest mouse position relative to area. Currently only used by lasso drawing code. */
+ int2 mval;
+
+ /**
+ * For modal operators which may be running idle, waiting for an event to activate the gesture.
+ * Typically this is set when the user is click-dragging the gesture
+ * (box and circle select for eg).
+ */
+ uint is_active : 1;
+ /** Previous value of is-active (use to detect first run & edge cases). */
+ uint is_active_prev : 1;
+ /** Use for gestures that support both immediate or delayed activation. */
+ uint wait_for_input : 1;
+ /** Use for gestures that can be moved, like box selection. */
+ uint move : 1;
+ /** For gestures that support snapping, stores if snapping is enabled using the modal keymap
+ * toggle. */
+ uint use_snap : 1;
+ /** For gestures that support flip, stores if flip is enabled using the modal keymap
+ * toggle. */
+ uint use_flip : 1;
+ /** For gestures that support smoothing, stores if smoothing is enabled using the modal keymap
+ * toggle. */
+ uint use_smooth : 1;
+
+ /**
+ * customdata
+ * - for border is a #rcti.
+ * - for circle is #rcti, (`xmin`, `ymin`) is center, `xmax` radius.
+ * - for lasso is short array.
+ * - for straight line is a #rcti: (`xmin`, `ymin`) is start, (`xmax`, `ymax`) is end.
+ */
+ void *customdata;
+
+ /** Free pointer to use for operator allocations (if set, its freed on exit). */
+ wmGenericUserData user_data;
+};
+
+/* ************** wmEvent ************************ */
+
+enum eWM_EventFlag {
+ /**
+ * True if the operating system inverted the delta x/y values and resulting
+ * `prev_xy` values, for natural scroll direction.
+ * For absolute scroll direction, the delta must be negated again.
+ */
+ WM_EVENT_SCROLL_INVERT = (1 << 0),
+ /**
+ * Generated by auto-repeat, note that this must only ever be set for keyboard events
+ * where `ISKEYBOARD(event->type) == true`.
+ *
+ * See #KMI_REPEAT_IGNORE for details on how key-map handling uses this.
+ */
+ WM_EVENT_IS_REPEAT = (1 << 1),
+ /**
+ * Generated for consecutive trackpad or NDOF-motion events,
+ * the repeat chain is broken by key/button events,
+ * or cursor motion exceeding #WM_EVENT_CURSOR_MOTION_THRESHOLD.
+ *
+ * Changing the type of trackpad or gesture event also breaks the chain.
+ */
+ WM_EVENT_IS_CONSECUTIVE = (1 << 2),
+ /**
+ * Mouse-move events may have this flag set to force creating a click-drag event
+ * even when the threshold has not been met.
+ */
+ WM_EVENT_FORCE_DRAG_THRESHOLD = (1 << 3),
+};
+ENUM_OPERATORS(eWM_EventFlag);
+
+struct wmTabletData {
+ /** 0=EVT_TABLET_NONE, 1=EVT_TABLET_STYLUS, 2=EVT_TABLET_ERASER. */
+ int active;
+ /** Range 0.0 (not touching) to 1.0 (full pressure). */
+ float pressure;
+ /**
+ * X axis range: -1.0 (left) to +1.0 (right).
+ * Y axis range: -1.0 (away from user) to +1.0 (toward user).
+ */
+ float2 tilt;
+ /** Interpret mouse motion as absolute as typical for tablets. */
+ char is_motion_absolute;
+};
+
+/**
+ * Each event should have full modifier state.
+ * event comes from event manager and from keymap.
+ *
+ *
+ * Previous State (`prev_*`)
+ * =========================
+ *
+ * Events hold information about the previous event.
+ *
+ * - Previous values are only set for events types that generate #KM_PRESS.
+ * See: #ISKEYBOARD_OR_BUTTON.
+ *
+ * - Previous x/y are exceptions: #wmEvent.prev
+ * these are set on mouse motion, see #MOUSEMOVE & trackpad events.
+ *
+ * - Modal key-map handling sets `prev_val` & `prev_type` to `val` & `type`,
+ * this allows modal keys-maps to check the original values (needed in some cases).
+ *
+ *
+ * Press State (`prev_press_*`)
+ * ============================
+ *
+ * Events hold information about the state when the last #KM_PRESS event was added.
+ * This is used for generating #KM_CLICK, #KM_DBL_CLICK & #KM_PRESS_DRAG events.
+ * See #wm_handlers_do for the implementation.
+ *
+ * - Previous values are only set when a #KM_PRESS event is detected.
+ * See: #ISKEYBOARD_OR_BUTTON.
+ *
+ * - The reason to differentiate between "press" and the previous event state is
+ * the previous event may be set by key-release events. In the case of a single key click
+ * this isn't a problem however releasing other keys such as modifiers prevents click/click-drag
+ * events from being detected, see: #89989.
+ *
+ * - Mouse-wheel events are excluded even though they generate #KM_PRESS
+ * as clicking and dragging don't make sense for mouse wheel events.
+ */
+struct wmEvent {
+ wmEvent *next, *prev;
+
+ /** Event code itself (short, is also in key-map). */
+ wmEventType type;
+ /** Press, release, scroll-value. */
+ short val;
+ /** Mouse pointer position, screen coord. */
+ int xy[2];
+ /** Region relative mouse position (name convention before Blender 2.5). */
+ int mval[2];
+ /**
+ * A single UTF8 encoded character.
+ *
+ * - Not null terminated although it may not be set `(utf8_buf[0] == '\0')`.
+ * - #BLI_str_utf8_size_or_error() must _always_ return a valid value,
+ * check when assigning so we don't need to check on every access after.
+ */
+ char utf8_buf[6];
+
+ /** Modifier states: #KM_SHIFT, #KM_CTRL, #KM_ALT, #KM_OSKEY & #KM_HYPER. */
+ wmEventModifierFlag modifier;
+
+ /** The direction (for #KM_PRESS_DRAG events only). */
+ int8_t direction;
+
+ /**
+ * Raw-key modifier (allow using any key as a modifier).
+ * Compatible with values in `type`.
+ */
+ wmEventType keymodifier;
+
+ /** Tablet info, available for mouse move and button events. */
+ wmTabletData tablet;
+
+ eWM_EventFlag flag;
+
+ /* Custom data. */
+
+ /** Custom data type, stylus, 6-DOF, see `wm_event_types.hh`. */
+ short custom;
+ short customdata_free;
+ /**
+ * The #wmEvent::type implies the following #wmEvent::custodata.
+ *
+ * - #EVT_ACTIONZONE_AREA / #EVT_ACTIONZONE_FULLSCREEN / #EVT_ACTIONZONE_FULLSCREEN:
+ * Uses #sActionzoneData.
+ * - #EVT_DROP: uses #ListBaseT<wmDrag> (also #wmEvent::custom == #EVT_DATA_DRAGDROP).
+ * Typically set to #wmWindowManger::drags.
+ * - #EVT_FILESELECT: uses #wmOperator.
+ * - #EVT_XR_ACTION: uses #wmXrActionData (also #wmEvent::custom == #EVT_DATA_XR).
+ * - #NDOF_MOTION: uses #wmNDOFMotionData (also #wmEvent::custom == #EVT_DATA_NDOF_MOTION).
+ * - #TIMER: uses #wmTimer (also #wmEvent::custom == #EVT_DATA_TIMER).
+ */
+ void *customdata;
+
+ /* Previous State. */
+
+ /** The previous value of `type`. */
+ wmEventType prev_type;
+ /** The previous value of `val`. */
+ short prev_val;
+ /**
+ * The previous value of #wmEvent.xy,
+ * Unlike other previous state variables, this is set on any mouse motion.
+ * Use `prev_press_*` for the value at time of pressing.
+ */
+ int prev_xy[2];
+
+ /* Previous Press State (when `val == KM_PRESS`). */
+
+ /** The `type` at the point of the press action. */
+ wmEventType prev_press_type;
+ /**
+ * The location when the key is pressed.
+ * used to enforce drag threshold & calculate the `direction`.
+ */
+ int prev_press_xy[2];
+ /** The `modifier` at the point of the press action. */
+ wmEventModifierFlag prev_press_modifier;
+ /** The `keymodifier` at the point of the press action. */
+ wmEventType prev_press_keymodifier;
+};
+
+/**
+ * Values below are ignored when detecting if the user intentionally moved the cursor.
+ * Keep this very small since it's used for selection cycling for eg,
+ * where we want intended adjustments to pass this threshold and select new items.
+ *
+ * Always check for <= this value since it may be zero.
+ */
+#define WM_EVENT_CURSOR_MOTION_THRESHOLD ((float)U.move_threshold * UI_SCALE_FAC)
+
+/**
+ * Motion progress, for modal handlers,
+ * a copy of #GHOST_TProgress (keep in sync).
+ */
+enum wmProgress {
+ P_NOT_STARTED = 0,
+ /** Only sent for NDOF motion. */
+ P_STARTING,
+ /** Only sent for NDOF motion. */
+ P_IN_PROGRESS,
+ /** Only sent for NDOF motion. */
+ P_FINISHING,
+ P_FINISHED,
+};
+
+#ifdef WITH_INPUT_NDOF
+/**
+ * NDOF (3D mouse) motion event data.
+ *
+ * Awfully similar to #GHOST_TEventNDOFMotionData.
+ */
+struct wmNDOFMotionData {
+ /**
+ * Each component normally ranges from -1 to +1, but can exceed that.
+ * These use blender standard view coordinates,
+ * with positive rotations being CCW about the axis.
+ */
+ /** Translation. */
+ float tvec[3];
+ /** Rotation.
+ * <pre>
+ * axis = (rx,ry,rz).normalized.
+ * amount = (rx,ry,rz).magnitude [in revolutions, 1.0 = 360 deg]
+ * </pre>
+ */
+ float rvec[3];
+ /**
+ * Time since previous NDOF Motion event (in seconds).
+ *
+ * This is reset when motion begins: when progress changes from #P_NOT_STARTED to #P_STARTING.
+ * In this case a dummy value is used, see #GHOST_NDOF_TIME_DELTA_STARTING.
+ */
+ float time_delta;
+ /** Is this the first event, the last, or one of many in between? */
+ wmProgress progress;
+};
+#endif /* WITH_INPUT_NDOF */
+
+#ifdef WITH_XR_OPENXR
+/** Similar to #GHOST_XrPose. */
+struct wmXrPose {
+ float position[3];
+ /** Blender convention (w, x, y, z). */
+ float orientation_quat[4];
+};
+
+struct wmXrActionState {
+ union {
+ bool state_boolean;
+ float state_float;
+ float state_vector2f[2];
+ wmXrPose state_pose;
+ };
+ int type; /* #eXrActionType. */
+};
+
+struct wmXrActionData {
+ /** Action set name. */
+ char action_set[64];
+ /** Action name. */
+ char action[64];
+ /** User path. E.g. "/user/hand/left". */
+ char user_path[64];
+ /** Other user path, for bimanual actions. E.g. "/user/hand/right". */
+ char user_path_other[64];
+ /** Type. */
+ eXrActionType type;
+ /** State. Set appropriately based on type. */
+ float state[2];
+ /** State of the other sub-action path for bimanual actions. */
+ float state_other[2];
+
+ /** Input threshold for float/vector2f actions. */
+ float float_threshold;
+
+ /** Controller aim pose corresponding to the action's sub-action path. */
+ float controller_loc[3];
+ float controller_rot[4];
+ /** Controller aim pose of the other sub-action path for bimanual actions. */
+ float controller_loc_other[3];
+ float controller_rot_other[4];
+
+ /** Operator. */
+ wmOperatorType *ot;
+ IDProperty *op_properties;
+
+ /** Whether bimanual interaction is occurring. */
+ bool bimanual;
+};
+#endif
+
+/** Timer flags. */
+enum wmTimerFlags {
+ /** Do not attempt to free custom-data pointer even if non-NULL. */
+ WM_TIMER_NO_FREE_CUSTOM_DATA = 1 << 0,
+
+ /* Internal flags, should not be used outside of WM code. */
+ /**
+ * This timer has been tagged for removal and deletion, handled by WM code to ensure timers are
+ * deleted in a safe context.
+ */
+ WM_TIMER_TAGGED_FOR_REMOVAL = 1 << 16,
+};
+ENUM_OPERATORS(wmTimerFlags)
+
+struct wmTimer {
+ wmTimer *next, *prev;
+
+ /** Window this timer is attached to (optional). */
+ wmWindow *win;
+
+ /** Set by timer user. */
+ double time_step;
+ /** Set by timer user, goes to event system. */
+ wmEventType event_type;
+ /** Various flags controlling timer options, see below. */
+ wmTimerFlags flags;
+ /** Set by timer user, to allow custom values. */
+ void *customdata;
+
+ /** Total running time in seconds. */
+ double time_duration;
+ /** Time since previous step in seconds. */
+ double time_delta;
+
+ /** Internal, last time timer was activated. */
+ double time_last;
+ /** Internal, next time we want to activate the timer. */
+ double time_next;
+ /** Internal, when the timer started. */
+ double time_start;
+ /** Internal, put timers to sleep when needed. */
+ bool sleep;
+};
+
+enum wmPopupSize {
+ WM_POPUP_SIZE_SMALL = 0,
+ WM_POPUP_SIZE_LARGE,
+};
+
+enum wmPopupPosition {
+ WM_POPUP_POSITION_MOUSE = 0,
+ WM_POPUP_POSITION_CENTER,
+};
+
+/**
+ * Communication/status data owned by the wmJob, and passed to the worker code when calling
+ * `startjob` callback.
+ *
+ * `OUTPUT` members mean that they are defined by the worker thread, and read/used by the wmJob
+ * management code from the main thread. And vice-versa for `INPUT` members.
+ *
+ * \warning There is currently no thread-safety or synchronization when accessing these values.
+ * This is fine as long as:
+ * - All members are independent of each other, value-wise.
+ * - Each member is 'simple enough' that accessing it or setting it can be considered as atomic.
+ * - There is no requirement of immediate synchronization of these values between the main
+ * controlling thread (i.e. wmJob management code) and the worker thread.
+ */
+struct wmJobWorkerStatus {
+ /**
+ * OUTPUT - Set to true by the worker to request update processing from the main thread (as part
+ * of the wmJob 'event loop', see #wm_jobs_timer).
+ */
+ bool do_update;
+
+ /**
+ * INPUT - Set by the wmJob management code to request a worker to stop/abort its processing.
+ *
+ * \note Some job types (rendering or baking ones e.g.) also use the #Global.is_break flag to
+ * cancel their processing.
+ */
+ bool stop;
+
+ /** OUTPUT - Progress as reported by the worker, from `0.0f` to `1.0f`. */
+ float progress;
+
+ /**
+ * OUTPUT - Storage of reports generated during this job's run. Contains its own locking for
+ * thread-safety.
+ */
+ ReportList *reports;
+};
+
+struct wmOperatorType {
+
+ /** Subclassed to store data for additional information for specific operator types. */
+ struct TypeData {
+ virtual ~TypeData() = default;
+ };
+
+ /** Text for UI, undo (should not exceed #OP_MAX_TYPENAME). */
+ const char *name = nullptr;
+ /** Unique identifier (must not exceed #OP_MAX_TYPENAME). */
+ const char *idname = nullptr;
+ /** Translation context (must not exceed #BKE_ST_MAXNAME). */
+ const char *translation_context = nullptr;
+ /** Use for tooltips and Python docs. */
+ const char *description = nullptr;
+ /** Identifier to group operators together. */
+ const char *undo_group = nullptr;
+
+ /**
+ * This callback executes the operator without any interactive input,
+ * parameters may be provided through operator properties. cannot use
+ * any interface code or input device state.
+ * See defines below for return values.
+ */
+ wmOperatorStatus (*exec)(bContext *C, wmOperator *op) ATTR_WARN_UNUSED_RESULT = nullptr;
+
+ /**
+ * This callback executes on a running operator whenever as property
+ * is changed. It can correct its own properties or report errors for
+ * invalid settings in exceptional cases.
+ * Boolean return value, True denotes a change has been made and to redraw.
+ */
+ bool (*check)(bContext *C, wmOperator *op) = nullptr;
+
+ /**
+ * For modal temporary operators, initially invoke is called, then
+ * any further events are handled in #modal. If the operation is
+ * canceled due to some external reason, cancel is called
+ * See defines below for return values.
+ */
+ wmOperatorStatus (*invoke)(bContext *C,
+ wmOperator *op,
+ const wmEvent *event) ATTR_WARN_UNUSED_RESULT = nullptr;
+
+ /**
+ * Called when a modal operator is canceled (not used often).
+ * Internal cleanup can be done here if needed.
+ */
+ void (*cancel)(bContext *C, wmOperator *op) = nullptr;
+
+ /**
+ * Modal is used for operators which continuously run. Fly mode, knife tool, circle select are
+ * all examples of modal operators. Modal operators can handle events which would normally invoke
+ * or execute other operators. They keep running until they don't return
+ * `OPERATOR_RUNNING_MODAL`.
+ */
+ wmOperatorStatus (*modal)(bContext *C,
+ wmOperator *op,
+ const wmEvent *event) ATTR_WARN_UNUSED_RESULT = nullptr;
+
+ /**
+ * Verify if the operator can be executed in the current context. Note
+ * that the operator may still fail to execute even if this returns true.
+ */
+ bool (*poll)(bContext *C) ATTR_WARN_UNUSED_RESULT = nullptr;
+
+ /**
+ * Used to check if properties should be displayed in auto-generated UI.
+ * Use 'check' callback to enforce refreshing.
+ */
+ bool (*poll_property)(const bContext *C,
+ wmOperator *op,
+ const PropertyRNA *prop) ATTR_WARN_UNUSED_RESULT = nullptr;
+
+ /** Optional panel for redo and repeat, auto-generated if not set. */
+ void (*ui)(bContext *C, wmOperator *op) = nullptr;
+ /**
+ * Optional check for whether the #ui callback should be called (usually to create the redo
+ * panel interface).
+ */
+ bool (*ui_poll)(wmOperatorType *ot, PointerRNA *ptr) = nullptr;
+
+ /**
+ * Return a different name to use in the user interface, based on property values.
+ * The returned string is expected to be translated if needed.
+ *
+ * WARNING: This callback does not currently work as expected in most common usage cases (e.g.
+ * any definition of an operator button through the layout API will fail to execute it). See
+ * #112253 for details.
+ */
+ std::string (*get_name)(wmOperatorType *ot, PointerRNA *ptr) = nullptr;
+
+ /**
+ * Return a different description to use in the user interface, based on property values.
+ * The returned string is expected to be translated if needed.
+ */
+ std::string (*get_description)(bContext *C, wmOperatorType *ot, PointerRNA *ptr) = nullptr;
+
+ /** A dynamic version of #OPTYPE_DEPENDS_ON_CURSOR which can depend on operator properties. */
+ bool (*depends_on_cursor)(bContext &C, wmOperatorType &ot, PointerRNA *ptr) = nullptr;
+
+ /** RNA for properties. */
+ StructRNA *srna = nullptr;
+
+ /** Previous settings - for initializing on re-use. */
+ IDProperty *last_properties = nullptr;
+
+ /**
+ * Default rna property to use for generic invoke functions.
+ * menus, enum search... etc. Example: Enum 'type' for a Delete menu.
+ *
+ * When assigned a string/number property,
+ * immediately edit the value when used in a popup. see: #BUT_ACTIVATE_ON_INIT.
+ */
+ PropertyRNA *prop = nullptr;
+
+ /** #wmOperatorTypeMacro. */
+ ListBaseT<wmOperatorTypeMacro> macro = {};
+
+ /** Pointer to modal keymap. Do not free! */
+ wmKeyMap *modalkeymap = nullptr;
+
+ /** Python needs the operator type as well. */
+ bool (*pyop_poll)(bContext *C, wmOperatorType *ot) ATTR_WARN_UNUSED_RESULT = nullptr;
+
+ /** Extra information used statically for this operator type. */
+ std::unique_ptr<TypeData> custom_data;
+
+ /** RNA integration. */
+ ExtensionRNA rna_ext = {};
+
+ /** Cursor to use when waiting for cursor input, see: #OPTYPE_DEPENDS_ON_CURSOR. */
+ int cursor_pending = 0;
+
+ /** Flag last for padding. */
+ short flag = 0;
+};
+
+/**
+ * Wrapper to reference a #wmOperatorType together with some set properties and other relevant
+ * information to invoke the operator in a customizable way.
+ */
+struct wmOperatorCallParams {
+ wmOperatorType *optype;
+ PointerRNA *opptr;
+ wm::OpCallContext opcontext;
+};
+
+#ifdef WITH_INPUT_IME
+/* *********** Input Method Editor (IME) *********** */
+/**
+ * \warning this is a duplicate of #GHOST_TEventImeData.
+ * All members must remain aligned and the struct size match!
+ */
+struct wmIMEData {
+ /** UTF8 encoding. */
+ std::string result;
+ /** UTF8 encoding. */
+ std::string composite;
+
+ /** Cursor position in the IME composition. */
+ int cursor_pos;
+ /** Beginning of the selection. */
+ int sel_start;
+ /** End of the selection. */
+ int sel_end;
+};
+#endif
+
+/* **************** Paint Cursor ******************* */
+
+using wmPaintCursorDraw = void (*)(bContext *C,
+ const int2 &xy,
+ const float2 &tilt,
+ void *customdata);
+
+/* *************** Drag and drop *************** */
+
+enum eWM_DragDataType : int8_t {
+ WM_DRAG_ID,
+ WM_DRAG_ASSET,
+ /** The user is dragging multiple assets. This is only supported in few specific cases, proper
+ * multi-item support for dragging isn't supported well yet. Therefore this is kept separate from
+ * #WM_DRAG_ASSET. */
+ WM_DRAG_ASSET_LIST,
+ WM_DRAG_RNA,
+ WM_DRAG_PATH,
+ WM_DRAG_NAME,
+ /**
+ * Arbitrary text such as dragging from a text editor,
+ * this is also used when dragging a URL from a browser.
+ *
+ * An #std::string expected to be UTF8 encoded.
+ * Callers that require valid UTF8 sequences must validate the text.
+ */
+ WM_DRAG_STRING,
+ WM_DRAG_COLOR,
+ WM_DRAG_DATASTACK,
+ WM_DRAG_ASSET_CATALOG,
+ WM_DRAG_GREASE_PENCIL_LAYER,
+ WM_DRAG_GREASE_PENCIL_GROUP,
+ WM_DRAG_NODE_TREE_INTERFACE,
+ WM_DRAG_BONE_COLLECTION,
+ WM_DRAG_SHAPE_KEY,
+};
+
+enum eWM_DragFlags {
+ WM_DRAG_NOP = 0,
+ WM_DRAG_FREE_DATA = 1,
+};
+ENUM_OPERATORS(eWM_DragFlags)
+
+/* NOTE: structs need not exported? */
+
+struct wmDragID {
+ wmDragID *next, *prev;
+ ID *id;
+ ID *from_parent;
+};
+
+struct wmDragAsset {
+ const asset_system::AssetRepresentation *asset;
+ AssetImportSettings import_settings;
+};
+
+struct wmDragAssetCatalog {
+ bUUID drag_catalog_id;
+};
+
+/**
+ * For some specific cases we support dragging multiple assets (#WM_DRAG_ASSET_LIST). There is no
+ * proper support for dragging multiple items in the `wmDrag`/`wmDrop` API yet, so this is really
+ * just to enable specific features for assets.
+ *
+ * This struct basically contains a tagged union to either store a local ID pointer, or information
+ * about an externally stored asset.
+ */
+struct wmDragAssetListItem {
+ wmDragAssetListItem *next, *prev;
+
+ union {
+ ID *local_id;
+ wmDragAsset *external_info;
+ } asset_data;
+
+ bool is_external;
+};
+
+struct wmDragPath {
+ Vector<std::string> paths;
+ /** File type of each path in #paths. */
+ Vector<int> file_types; /* #eFileSel_File_Types. */
+ /** Bit flag of file types in #paths. */
+ int file_types_bit_flag; /* #eFileSel_File_Types. */
+ std::string tooltip;
+};
+
+struct wmDragGreasePencilLayer {
+ GreasePencil *grease_pencil;
+ GreasePencilLayerTreeNode *node;
+};
+
+using WMDropboxTooltipFunc = std::string (*)(bContext *C,
+ wmDrag *drag,
+ const int xy[2],
+ wmDropBox *drop);
+
+struct wmDragActiveDropState {
+ wmDragActiveDropState();
+ ~wmDragActiveDropState();
+
+ /**
+ * Informs which dropbox is activated with the drag item.
+ * When this value changes, the #on_enter() and #on_exit() dropbox callbacks are triggered.
+ */
+ wmDropBox *active_dropbox;
+
+ /**
+ * If `active_dropbox` is set, the area it successfully polled in.
+ * To restore the context of it as needed.
+ */
+ ScrArea *area_from;
+ /**
+ * If `active_dropbox` is set, the region it successfully polled in.
+ * To restore the context of it as needed.
+ */
+ ARegion *region_from;
+
+ /**
+ * If `active_dropbox` is set, additional context provided by the active (i.e. hovered) button.
+ * Activated before context sensitive operations (polling, drawing, dropping).
+ */
+ std::unique_ptr<bContextStore> ui_context;
+
+ /**
+ * Text to show when a dropbox poll succeeds (so the dropbox itself is available) but the
+ * operator poll fails. Typically the message the operator set with
+ * #CTX_wm_operator_poll_msg_set().
+ */
+ std::optional<std::string> disabled_info;
+
+ std::string tooltip;
+};
+
+struct wmDrag {
+ wmDrag *next, *prev;
+
+ int icon;
+ eWM_DragDataType type;
+ void *poin;
+
+ /** If no small icon but imbuf should be drawn around cursor. */
+ const ImBuf *imb;
+ float imbuf_scale;
+ /** If #imb is not set, draw this as a big preview instead of the small #icon. */
+ int preview_icon_id; /* BIFIconID */
+
+ wmDragActiveDropState drop_state;
+
+ eWM_DragFlags flags;
+
+ /** List of wmDragIDs, all are guaranteed to have the same ID type. */
+ ListBaseT<wmDragID> ids;
+ /** List of `wmDragAssetListItem`s. */
+ ListBaseT<wmDragAssetListItem> asset_items;
+};
+
+/**
+ * Drop-boxes are like key-maps, part of the screen/area/region definition.
+ * Allocation and free is on startup and exit.
+ *
+ * The operator is polled and invoked with the current context
+ * (#wm::OpCallContext::InvokeDefault), there is no way to override that (by design, since
+ * drop-boxes should act on the exact mouse position). So the drop-boxes are supposed to check the
+ * required area and region context in their poll.
+ */
+struct wmDropBox {
+ wmDropBox *next, *prev;
+
+ /** Test if the dropbox is active. */
+ bool (*poll)(bContext *C, wmDrag *drag, const wmEvent *event);
+
+ /** Called when the drag action starts. Can be used to prefetch data for previews.
+ * \note The dropbox that will be called eventually is not known yet when starting the drag.
+ * So this callback is called on every dropbox that is registered in the current screen. */
+ void (*on_drag_start)(bContext *C, wmDrag *drag);
+
+ /** Called when poll returns true the first time. Typically used to setup some drawing data. */
+ void (*on_enter)(wmDropBox *drop, wmDrag *drag);
+
+ /** Called when poll returns false the first time or when the drag event ends (successful drop or
+ * canceled). Typically used to cleanup resources or end drawing. */
+ void (*on_exit)(wmDropBox *drop, wmDrag *drag);
+
+ /** Before exec, this copies drag info to #wmDrop properties. */
+ void (*copy)(bContext *C, wmDrag *drag, wmDropBox *drop);
+
+ /**
+ * If the operator is canceled (returns `OPERATOR_CANCELLED`), this can be used for cleanup of
+ * `copy()` resources.
+ */
+ void (*cancel)(Main *bmain, wmDrag *drag, wmDropBox *drop);
+
+ /**
+ * Override the default cursor overlay drawing function.
+ * Can be used to draw text or thumbnails. IE a tool-tip for drag and drop.
+ * \param xy: Cursor location in window coordinates (#wmEvent.xy compatible).
+ */
+ void (*draw_droptip)(bContext *C, wmWindow *win, wmDrag *drag, const int xy[2]);
+
+ /**
+ * Called with the draw buffer (#GPUViewport) set up for drawing into the region's view.
+ * \note Only setups the drawing buffer for drawing in view, not the GPU transform matrices.
+ * The callback has to do that itself, with for example #view2d_view_ortho.
+ * \param xy: Cursor location in window coordinates (#wmEvent.xy compatible).
+ */
+ void (*draw_in_view)(bContext *C, wmWindow *win, wmDrag *drag, const int xy[2]);
+
+ /**
+ * Used by tree views to scroll when the mouse is near the edge.
+ * Called for every event while the dropbox is active (hovered and poll succeeds).
+ * For #wmEventType::TIMER events, only the ones created from this #wmDropBox.timer are passed to
+ * it.
+ */
+ void (*on_event_while_hover)(bContext *C, wmDropBox &dropbox, const wmEvent *event);
+ /** Custom data for drawing. */
+ void *draw_data;
+
+ /** Custom tool-tip shown during dragging. */
+ WMDropboxTooltipFunc tooltip;
+
+ /**
+ * If poll succeeds, operator is called.
+ * Not saved in file, so can be pointer.
+ * This may be null when the operator has been unregistered,
+ * where `opname` can be used to re-initialize it.
+ */
+ wmOperatorType *ot;
+ /** #wmOperatorType::idname, needed for re-registration. */
+ char opname[64];
+
+ /** Operator properties, assigned to `ptr->data` and can be written to a file. */
+ IDProperty *properties;
+ /** RNA pointer to access properties. */
+ PointerRNA *ptr;
+ wmTimer *timer;
+};
+
+/**
+ * Struct to store tool-tip timer and possible creation if the time is reached.
+ * Allows UI code to call #WM_tooltip_timer_init without each user having to handle the timer.
+ */
+struct wmTooltipState {
+ /** Create tool-tip on this event. */
+ wmTimer *timer;
+ /** The area the tool-tip is created in. */
+ ScrArea *area_from;
+ /** The region the tool-tip is created in. */
+ ARegion *region_from;
+ /** The tool-tip region. */
+ ARegion *region;
+ /** Create the tool-tip region (assign to 'region'). */
+ ARegion *(*init)(
+ bContext *C, ARegion *region, int *pass, double *pass_delay, bool *r_exit_on_event);
+ /** Exit on any event, not needed for buttons since their highlight state is used. */
+ bool exit_on_event;
+ /** Cursor location at the point of tool-tip creation. */
+ int event_xy[2];
+ /** Pass, use when we want multiple tips, count down to zero. */
+ int pass;
+};
+
+/* *************** migrated stuff, clean later? ************** */
+
+struct RecentFile {
+ RecentFile *next, *prev;
+ char *filepath;
+};
+
+/* Logging. */
+/* `wm_init_exit.cc`. */
+
+extern CLG_LogRef *WM_LOG_OPERATORS;
+extern CLG_LogRef *WM_LOG_EVENTS;
+extern CLG_LogRef *WM_LOG_TOOL_GIZMO;
+extern CLG_LogRef *WM_LOG_MSGBUS_PUB;
+extern CLG_LogRef *WM_LOG_MSGBUS_SUB;
+
+} // namespace blender
+
diff --git a/compat/include/gizmo/WM_gizmo_types.hh b/compat/include/gizmo/WM_gizmo_types.hh
new file mode 100644
index 0000000..c5f9a47
--- /dev/null
+++ b/compat/include/gizmo/WM_gizmo_types.hh
@@ -0,0 +1,528 @@
+/* SPDX-FileCopyrightText: 2016 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup wm
+ *
+ * \name Gizmo Types
+ * \brief Gizmo defines for external use.
+ *
+ * Only included in WM_types.hh and lower level files.
+ */
+
+#pragma once
+
+#include "BLI_enum_flags.hh"
+#include "BLI_vector.hh"
+
+#include "DNA_listBase.h"
+
+#include "RNA_types.hh"
+
+struct IDProperty;
+struct wmGizmo;
+struct wmGizmoType;
+struct wmGizmoGroup;
+struct wmGizmoGroupType;
+struct wmGizmoMap;
+struct wmGizmoMapType;
+struct wmGizmoProperty;
+struct wmGizmoPropertyType;
+struct wmKeyConfig;
+struct wmOperatorType;
+
+/* -------------------------------------------------------------------- */
+/* Enum Typedef's. */
+
+/**
+ * #wmGizmo.state
+ */
+enum eWM_GizmoFlagState {
+ /** While hovered. */
+ WM_GIZMO_STATE_HIGHLIGHT = (1 << 0),
+ /** While dragging. */
+ WM_GIZMO_STATE_MODAL = (1 << 1),
+ WM_GIZMO_STATE_SELECT = (1 << 2),
+};
+ENUM_OPERATORS(eWM_GizmoFlagState)
+
+/**
+ * #wmGizmo.flag
+ * Flags for individual gizmos.
+ */
+enum eWM_GizmoFlag {
+ /** Draw *only* while hovering. */
+ WM_GIZMO_DRAW_HOVER = (1 << 0),
+ /** Draw while dragging. */
+ WM_GIZMO_DRAW_MODAL = (1 << 1),
+ /** Draw an indicator for the current value while dragging. */
+ WM_GIZMO_DRAW_VALUE = (1 << 2),
+ WM_GIZMO_HIDDEN = (1 << 3),
+ WM_GIZMO_HIDDEN_SELECT = (1 << 4),
+ /** Ignore the key-map for this gizmo. */
+ WM_GIZMO_HIDDEN_KEYMAP = (1 << 5),
+ /**
+ * When set 'scale_final' value also scales the offset.
+ * Use when offset is to avoid screen-space overlap instead of absolute positioning. */
+ WM_GIZMO_DRAW_OFFSET_SCALE = (1 << 6),
+ /**
+ * User should still use 'scale_final' for any handles and UI elements.
+ * This simply skips scale when calculating the final matrix.
+ * Needed when the gizmo needs to align with the interface underneath it. */
+ WM_GIZMO_DRAW_NO_SCALE = (1 << 7),
+ /**
+ * Hide the cursor and lock its position while interacting with this gizmo.
+ */
+ WM_GIZMO_MOVE_CURSOR = (1 << 8),
+ /** Don't write into the depth buffer when selecting. */
+ WM_GIZMO_SELECT_BACKGROUND = (1 << 9),
+
+ /** Use the active tools operator properties when running as an operator. */
+ WM_GIZMO_OPERATOR_TOOL_INIT = (1 << 10),
+
+ /** Don't pass through events to other handlers
+ * (allows click/drag not to have its events stolen by press events in other keymaps). */
+ WM_GIZMO_EVENT_HANDLE_ALL = (1 << 11),
+
+ /** Don't use tool-tips for this gizmo (can be distracting). */
+ WM_GIZMO_NO_TOOLTIP = (1 << 12),
+ /** Push an undo step after each use of the gizmo. */
+ WM_GIZMO_NEEDS_UNDO = (1 << 13),
+
+ /** This gizmo should be visually distinct and not shown grouped with other gizmos. */
+ WM_GIZMO_NO_GROUPING = (1 << 14),
+};
+ENUM_OPERATORS(eWM_GizmoFlag);
+
+/**
+ * #wmGizmoGroupType.flag
+ * Flags that influence the behavior of all gizmos in the group.
+ */
+enum eWM_GizmoFlagGroupTypeFlag {
+ /** Mark gizmo-group as being 3D. */
+ WM_GIZMOGROUPTYPE_3D = (1 << 0),
+ /** Scale gizmos as 3D object that respects zoom (otherwise zoom independent draw size).
+ * NOTE: currently only for 3D views, 2D support needs adding. */
+ WM_GIZMOGROUPTYPE_SCALE = (1 << 1),
+ /** Gizmos can be depth culled with scene objects (covered by other geometry - TODO). */
+ WM_GIZMOGROUPTYPE_DEPTH_3D = (1 << 2),
+ /** Gizmos can be selected. */
+ WM_GIZMOGROUPTYPE_SELECT = (1 << 3),
+ /** The gizmo group is to be kept (not removed on loading a new file for eg). */
+ WM_GIZMOGROUPTYPE_PERSISTENT = (1 << 4),
+ /**
+ * Show all other gizmos when interacting.
+ * Also show this group when another group is being interacted with.
+ */
+ WM_GIZMOGROUPTYPE_DRAW_MODAL_ALL = (1 << 5),
+
+ /** Don't draw this gizmo group when it is modal. */
+ WM_GIZMOGROUPTYPE_DRAW_MODAL_EXCLUDE = (1 << 6),
+
+ /**
+ * When used with tool, only run when activating the tool,
+ * instead of linking the gizmo while the tool is active.
+ *
+ * \warning this option has some limitations, we might even re-implement this differently.
+ * Currently it's quite minimal so we can see how it works out.
+ * The main issue is controlling how a gizmo is activated with a tool
+ * when a tool can activate multiple operators based on the key-map.
+ * We could even move the options into the key-map item.
+ * ~ campbell. */
+ WM_GIZMOGROUPTYPE_TOOL_INIT = (1 << 7),
+
+ /**
+ * This gizmo type supports using the fall back tools keymap.
+ * #wmGizmoGroup.use_tool_fallback will need to be set too.
+ *
+ * Often useful in combination with #WM_GIZMOGROUPTYPE_DELAY_REFRESH_FOR_TWEAK
+ */
+ WM_GIZMOGROUPTYPE_TOOL_FALLBACK_KEYMAP = (1 << 8),
+
+ /**
+ * Use this from a gizmos refresh callback so we can postpone the refresh operation
+ * until the tweak operation is finished.
+ * Only do this when the group doesn't have a highlighted gizmo.
+ *
+ * The result for the user is tweak events delay the gizmo from flashing under the users cursor,
+ * for selection operations. This means gizmos that use this check don't interfere
+ * with click-drag events by popping up under the cursor and catching the drag-drag event.
+ */
+ WM_GIZMOGROUPTYPE_DELAY_REFRESH_FOR_TWEAK = (1 << 9),
+
+ /**
+ * Cause continuous redraws, i.e. set the region redraw flag on every main loop iteration. This
+ * should really be avoided by using proper region redraw tagging, notifiers and the message-bus,
+ * however for VR it's sometimes needed.
+ */
+ WM_GIZMOGROUPTYPE_VR_REDRAWS = (1 << 10),
+};
+
+ENUM_OPERATORS(eWM_GizmoFlagGroupTypeFlag);
+
+/**
+ * #wmGizmoGroup.init_flag
+ */
+enum eWM_GizmoFlagGroupInitFlag {
+ /** Gizmo-group has been initialized. */
+ WM_GIZMOGROUP_INIT_SETUP = (1 << 0),
+ WM_GIZMOGROUP_INIT_REFRESH = (1 << 1),
+};
+ENUM_OPERATORS(eWM_GizmoFlagGroupInitFlag)
+
+/**
+ * #wmGizmoMapType.type_update_flag
+ * Gizmo-map type update flag
+ */
+enum eWM_GizmoFlagMapTypeUpdateFlag {
+ /** A new type has been added, needs to be initialized for all views. */
+ WM_GIZMOMAPTYPE_UPDATE_INIT = (1 << 0),
+ WM_GIZMOMAPTYPE_UPDATE_REMOVE = (1 << 1),
+
+ /** Needed because keymap may be registered before and after window initialization.
+ * So we need to keep track of keymap initialization separately. */
+ WM_GIZMOMAPTYPE_KEYMAP_INIT = (1 << 2),
+};
+ENUM_OPERATORS(eWM_GizmoFlagMapTypeUpdateFlag)
+
+/* -------------------------------------------------------------------- */
+/* #wmGizmo. */
+
+/**
+ * \brief Gizmo tweak flag.
+ * Bit-flag passed to gizmo while tweaking.
+ *
+ * \note Gizmos are responsible for handling this #wmGizmo.modal callback.
+ */
+enum eWM_GizmoFlagTweak {
+ /** Drag with extra precision (Shift). */
+ WM_GIZMO_TWEAK_PRECISE = (1 << 0),
+ /** Drag with snap enabled (Control). */
+ WM_GIZMO_TWEAK_SNAP = (1 << 1),
+};
+
+#include "wm_gizmo_fn.hh"
+
+struct wmGizmoOpElem {
+ wmOperatorType *type = nullptr;
+ /** Operator properties if gizmo spawns and controls an operator,
+ * or owner pointer if gizmo spawns and controls a property. */
+ PointerRNA ptr = {};
+
+ bool is_redo = false;
+};
+
+/** Gizmos are set per region by registering them on gizmo-maps. */
+struct wmGizmo {
+ wmGizmo *next, *prev;
+
+ /** While we don't have a real type, use this to put type-like vars. */
+ const wmGizmoType *type;
+
+ /** Overrides 'type->modal' when set.
+ * Note that this is a workaround, remove if we can. */
+ wmGizmoFnModal custom_modal;
+
+ /** Pointer back to group this gizmo is in (just for quick access). */
+ wmGizmoGroup *parent_gzgroup;
+
+ /** Optional keymap to use for this gizmo (overrides #wmGizmoGroupType.keymap). */
+ wmKeyMap *keymap;
+
+ void *py_instance;
+
+ /** Rna pointer to access properties. */
+ PointerRNA *ptr;
+
+ /** Flags that influence the behavior or how the gizmos are drawn. */
+ eWM_GizmoFlag flag;
+ /** State flags (active, highlighted, selected). */
+ eWM_GizmoFlagState state;
+
+ /** Optional ID for highlighting different parts of this gizmo.
+ * -1 when unset, otherwise a valid index. (Used as index to 'op_data'). */
+ int highlight_part;
+
+ /**
+ * For gizmos that differentiate between click & drag,
+ * use a different part for any drag events, -1 when unused.
+ */
+ int drag_part;
+
+ /** Distance to bias this gizmo above others when picking
+ * (in world-space, scaled by the gizmo scale - when used). */
+ float select_bias;
+
+ /* Transformation of the gizmo in 2d or 3d space.
+ * - Matrix axis are expected to be unit length (scale is applied after).
+ * - Behavior when axis aren't orthogonal depends on each gizmo.
+ * - Typically the +Z is the primary axis for gizmos to use.
+ * - 'matrix[3]' must be used for location,
+ * besides this it's up to the gizmos internal code how the
+ * rotation components are used for drawing and interaction. */
+
+ /** The space this gizmo is being modified in. */
+ float matrix_space[4][4];
+ /** Transformation of this gizmo. */
+ float matrix_basis[4][4];
+ /** Custom offset from origin. */
+ float matrix_offset[4][4];
+ /** Runtime property, set the scale while drawing on the viewport. */
+ float scale_final;
+ /** User defined scale, in addition to the original one. */
+ float scale_basis;
+ /** User defined width for line drawing. */
+ float line_width;
+ /** Gizmo colors (uses default fallbacks if not defined). */
+ float color[4], color_hi[4];
+
+ /** Data used during interaction. */
+ void *interaction_data;
+
+ /** Operator to spawn when activating the gizmo (overrides property editing),
+ * an array of items (aligned with #wmGizmo.highlight_part). */
+ Vector<wmGizmoOpElem, 4> op_data;
+
+ IDProperty *properties;
+
+ /* TODO: Once wmGizmo itself gets an actual constructor, this can most likely become a
+ * `Array`, since length is defined by the gizmo type. */
+ Vector<wmGizmoProperty, 0> target_properties;
+
+ /** Redraw tag. */
+ bool do_draw;
+
+ /** Temporary data (assume dirty). */
+ union {
+ float f;
+ } temp;
+};
+
+/** Similar to #PropertyElemRNA, but has an identifier. */
+struct wmGizmoProperty {
+ const wmGizmoPropertyType *type = nullptr;
+
+ PointerRNA ptr = PointerRNA_NULL;
+ PropertyRNA *prop = nullptr;
+ int index = -1;
+
+ /* Optional functions for converting to/from RNA. */
+ struct {
+ wmGizmoPropertyFnGet value_get_fn = nullptr;
+ wmGizmoPropertyFnSet value_set_fn = nullptr;
+ wmGizmoPropertyFnRangeGet range_get_fn = nullptr;
+ wmGizmoPropertyFnFree free_fn = nullptr;
+ wmGizmoPropertyFnForeachRNAProp foreach_rna_prop_fn = nullptr;
+ void *user_data = nullptr;
+ } custom_func = {};
+};
+
+struct wmGizmoPropertyType {
+ wmGizmoPropertyType *next, *prev;
+ /** #PropertyType, typically #PROP_FLOAT. */
+ int data_type;
+ int array_length;
+
+ /** Index within #wmGizmoType. */
+ int index_in_type;
+
+ /** Over allocate. */
+ char idname[0];
+};
+
+/**
+ * Simple utility wrapper for storing a single gizmo as wmGizmoGroup.customdata (which gets freed).
+ */
+struct wmGizmoWrapper {
+ wmGizmo *gizmo;
+};
+
+struct wmGizmoMapType_Params {
+ short spaceid;
+ short regionid;
+};
+
+struct wmGizmoType {
+
+ const char *idname; /* #MAX_NAME. */
+
+ /** Set to `sizeof(wmGizmo)` or larger for instances of this type,
+ * use so we can cast to other types without the hassle of a custom-data pointer. */
+ uint struct_size;
+
+ /** Initialize struct (calloc'd 'struct_size' region). */
+ wmGizmoFnSetup setup;
+
+ /** Draw gizmo. */
+ wmGizmoFnDraw draw;
+
+ /** Determines 3d intersection by rendering the gizmo in a selection routine. */
+ wmGizmoFnDrawSelect draw_select;
+
+ /** Determine if the mouse intersects with the gizmo.
+ * The calculation should be done in the callback itself, -1 for no selection. */
+ wmGizmoFnTestSelect test_select;
+
+ /** Handler used by the gizmo. Usually handles interaction tied to a gizmo type. */
+ wmGizmoFnModal modal;
+
+ /** Gizmo-specific handler to update gizmo attributes based on the property value. */
+ wmGizmoFnPropertyUpdate property_update;
+
+ /**
+ * Returns the final transformation which may be different from the 'matrix',
+ * depending on the gizmo.
+ * Notes:
+ * - Scale isn't applied (wmGizmo.scale/user_scale).
+ * - Offset isn't applied (wmGizmo.matrix_offset).
+ */
+ wmGizmoFnMatrixBasisGet matrix_basis_get;
+
+ /**
+ * Returns screen-space bounding box in the window space
+ * (compatible with #wmEvent.xy).
+ *
+ * Used for tool-tip placement (otherwise the cursor location is used).
+ */
+ wmGizmoFnScreenBoundsGet screen_bounds_get;
+
+ /** Activate a gizmo state when the user clicks on it. */
+ wmGizmoFnInvoke invoke;
+
+ /** Called when gizmo tweaking is done - used to free data and reset property when canceling. */
+ wmGizmoFnExit exit;
+
+ wmGizmoFnCursorGet cursor_get;
+
+ /** Called when gizmo selection state changes. */
+ wmGizmoFnSelectRefresh select_refresh;
+
+ /** Free data (not the gizmo itself), use when the gizmo allocates its own members. */
+ wmGizmoFnFree free;
+
+ /** RNA for properties. */
+ StructRNA *srna;
+
+ /** RNA integration. */
+ ExtensionRNA rna_ext;
+
+ ListBaseT<wmGizmoPropertyType> target_property_defs;
+ int target_property_defs_len;
+};
+
+/* -------------------------------------------------------------------- */
+/* #wmGizmoGroup. */
+
+/** Factory class for a gizmo-group type, gets called every time a new area is spawned. */
+struct wmGizmoGroupTypeRef {
+ wmGizmoGroupTypeRef *next, *prev;
+ wmGizmoGroupType *type;
+};
+
+/** Factory class for a gizmo-group type, gets called every time a new area is spawned. */
+struct wmGizmoGroupType {
+ const char *idname; /* #MAX_NAME. */
+ /** Gizmo-group name - displayed in UI (keymap editor). */
+ const char *name;
+ /** Optional, see: #wmOwnerID. */
+ char owner_id[128];
+
+ /** Optional, used when drawing a group background with `draw_background`. */
+ float4 background_color;
+ float4 outline_color;
+
+ /** Poll if gizmo-map should be visible. */
+ wmGizmoGroupFnPoll poll;
+ /** Initially create gizmos and set permanent data - stuff you only need to do once. */
+ wmGizmoGroupFnInit setup;
+ /** Refresh data, only called if recreate flag is set (WM_gizmomap_tag_refresh). */
+ wmGizmoGroupFnRefresh refresh;
+ /** Refresh data for drawing, called before each redraw. */
+ wmGizmoGroupFnDrawPrepare draw_prepare;
+ /** Optionally draw the background of the group itself. */
+ wmGizmoGroupFnDrawBackground draw_background;
+ /** Initialize data for before invoke. */
+ wmGizmoGroupFnInvokePrepare invoke_prepare;
+
+ /** Keymap init callback for this gizmo-group (optional),
+ * will fall back to default tweak keymap when left NULL. */
+ wmGizmoGroupFnSetupKeymap setup_keymap;
+
+ /** Optionally subscribe to wmMsgBus events,
+ * these are calculated automatically from RNA properties,
+ * only needed if gizmos depend indirectly on properties. */
+ wmGizmoGroupFnMsgBusSubscribe message_subscribe;
+
+ /** Keymap created with callback from above. */
+ wmKeyMap *keymap;
+ /** Only for convenient removal. */
+ wmKeyConfig *keyconf;
+
+ /* NOTE: currently gizmo-group instances don't store properties,
+ * they're kept in the tool properties. */
+
+ /** RNA for properties. */
+ StructRNA *srna;
+
+ /** RNA integration. */
+ ExtensionRNA rna_ext;
+
+ eWM_GizmoFlagGroupTypeFlag flag;
+
+ /** So we know which group type to update. */
+ eWM_GizmoFlagMapTypeUpdateFlag type_update_flag;
+
+ /** Same as gizmo-maps, so registering/unregistering goes to the correct region. */
+ wmGizmoMapType_Params gzmap_params;
+
+ /**
+ * Number of #wmGizmoGroup instances.
+ * Decremented when 'tag_remove' is set, or when removed.
+ */
+ int users;
+};
+
+struct wmGizmoGroup {
+ wmGizmoGroup *next, *prev;
+
+ wmGizmoGroupType *type;
+ ListBaseT<wmGizmo> gizmos;
+
+ wmGizmoMap *parent_gzmap;
+
+ /** Python stores the class instance here. */
+ void *py_instance;
+
+ /** Has the same result as hiding all gizmos individually. */
+ union {
+ /** Reasons for hiding. */
+ struct {
+ uint delay_refresh_for_tweak : 1;
+ };
+ /** All, when we only want to check if any are hidden. */
+ uint any;
+ } hide;
+
+ bool tag_remove;
+
+ void *customdata;
+ /** For freeing customdata from above. */
+ void (*customdata_free)(void *);
+ eWM_GizmoFlagGroupInitFlag init_flag;
+};
+
+/* -------------------------------------------------------------------- */
+/* #wmGizmoMap. */
+
+/**
+ * Pass a value of this enum to #WM_gizmomap_draw to tell it what to draw.
+ */
+enum eWM_GizmoFlagMapDrawStep {
+ /** Draw 2D gizmo-groups (#WM_GIZMOGROUPTYPE_3D not set). */
+ WM_GIZMOMAP_DRAWSTEP_2D = 0,
+ /** Draw 3D gizmo-groups (#WM_GIZMOGROUPTYPE_3D set). */
+ WM_GIZMOMAP_DRAWSTEP_3D,
+};
+#define WM_GIZMOMAP_DRAWSTEP_MAX 2
+
diff --git a/compat/include/wm_cursors.hh b/compat/include/wm_cursors.hh
new file mode 100644
index 0000000..bcf3c91
--- /dev/null
+++ b/compat/include/wm_cursors.hh
@@ -0,0 +1,78 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup wm
+ */
+
+#pragma once
+
+namespace blender {
+
+struct wmEvent;
+struct wmWindow;
+
+enum wmCursorType {
+ WM_CURSOR_DEFAULT = 1,
+ WM_CURSOR_TEXT_EDIT,
+ WM_CURSOR_WAIT,
+ WM_CURSOR_STOP,
+ WM_CURSOR_EDIT,
+ WM_CURSOR_COPY,
+ WM_CURSOR_MOVE,
+ WM_CURSOR_HAND,
+ WM_CURSOR_HAND_CLOSED,
+ WM_CURSOR_HAND_POINT,
+
+ WM_CURSOR_CROSS,
+ WM_CURSOR_PAINT,
+ WM_CURSOR_DOT,
+ WM_CURSOR_CROSSC,
+
+ WM_CURSOR_KNIFE,
+ WM_CURSOR_BLADE,
+ WM_CURSOR_VERTEX_LOOP,
+ WM_CURSOR_PAINT_BRUSH,
+ WM_CURSOR_ERASER,
+ WM_CURSOR_EYEDROPPER,
+
+ WM_CURSOR_SWAP_AREA,
+ WM_CURSOR_X_MOVE,
+ WM_CURSOR_Y_MOVE,
+ WM_CURSOR_H_SPLIT,
+ WM_CURSOR_V_SPLIT,
+
+ WM_CURSOR_NW_ARROW,
+ WM_CURSOR_NS_ARROW,
+ WM_CURSOR_EW_ARROW,
+ WM_CURSOR_N_ARROW,
+ WM_CURSOR_S_ARROW,
+ WM_CURSOR_E_ARROW,
+ WM_CURSOR_W_ARROW,
+
+ WM_CURSOR_NSEW_SCROLL,
+ WM_CURSOR_NS_SCROLL,
+ WM_CURSOR_EW_SCROLL,
+
+ WM_CURSOR_ZOOM_IN,
+ WM_CURSOR_ZOOM_OUT,
+
+ WM_CURSOR_NONE,
+ WM_CURSOR_MUTE,
+
+ WM_CURSOR_PICK_AREA,
+
+ WM_CURSOR_LEFT_HANDLE,
+ WM_CURSOR_RIGHT_HANDLE,
+ WM_CURSOR_BOTH_HANDLES,
+ WM_CURSOR_SLIP,
+
+ /* --- ALWAYS LAST ----- */
+ WM_CURSOR_NUM,
+};
+
+void wm_init_cursor_data();
+bool wm_cursor_arrow_move(wmWindow *win, const wmEvent *event);
+
+} // namespace blender
diff --git a/compat/include/wm_draw.hh b/compat/include/wm_draw.hh
new file mode 100644
index 0000000..9b185e9
--- /dev/null
+++ b/compat/include/wm_draw.hh
@@ -0,0 +1,39 @@
+/* SPDX-FileCopyrightText: 2007 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup wm
+ */
+
+#pragma once
+
+namespace blender {
+
+struct ARegion;
+struct GPUOffScreen;
+namespace gpu {
+class Texture;
+}
+struct GPUViewport;
+struct ScrArea;
+struct bContext;
+struct wmWindow;
+
+struct wmDrawBuffer {
+ GPUOffScreen *offscreen;
+ GPUViewport *viewport;
+ bool stereo;
+ int bound_view;
+};
+
+/* `wm_draw.cc` */
+
+void wm_draw_update(bContext *C);
+void wm_draw_region_clear(wmWindow *win, ARegion *region);
+void wm_draw_region_blend(ARegion *region, int view, bool blend);
+void wm_draw_region_test(bContext *C, ScrArea *area, ARegion *region);
+
+gpu::Texture *wm_draw_region_texture(ARegion *region, int view);
+
+} // namespace blender
diff --git a/compat/include/wm_event_system.hh b/compat/include/wm_event_system.hh
new file mode 100644
index 0000000..cec7f1d
--- /dev/null
+++ b/compat/include/wm_event_system.hh
@@ -0,0 +1,220 @@
+/* SPDX-FileCopyrightText: 2007 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup wm
+ */
+
+#pragma once
+
+#include "WM_api.hh"
+struct GHOST_TabletData;
+namespace blender {
+
+struct ARegion;
+struct bToolRef;
+struct ScrArea;
+struct wmEvent;
+struct wmKeyMap;
+struct wmDropBox;
+struct wmKeyMapItem;
+
+namespace wm {
+enum class OpCallContext : int8_t;
+}
+
+#ifdef WITH_XR_OPENXR
+struct wmXrActionData;
+#endif
+
+/* #wmKeyMap is in `DNA_windowmanager.h`, it's saveable. */
+
+/** Custom types for handlers, for signaling, freeing. */
+enum eWM_EventHandlerType {
+ WM_HANDLER_TYPE_GIZMO = 1,
+ WM_HANDLER_TYPE_UI,
+ WM_HANDLER_TYPE_OP,
+ WM_HANDLER_TYPE_DROPBOX,
+ WM_HANDLER_TYPE_KEYMAP,
+};
+
+using EventHandlerPoll = bool (*)(const wmWindow *win,
+ const ScrArea *area,
+ const ARegion *region,
+ const wmEvent *event);
+
+struct wmEventHandler {
+ wmEventHandler *next, *prev;
+
+ eWM_EventHandlerType type;
+ eWM_EventHandlerFlag flag;
+
+ EventHandlerPoll poll;
+};
+
+/** Run after the keymap item runs. */
+struct wmEventHandler_KeymapPost {
+ void (*post_fn)(wmKeyMap *keymap, wmKeyMapItem *kmi, void *user_data);
+ void *user_data;
+};
+
+/** Support for a getter function that looks up the keymap each access. */
+struct wmEventHandler_KeymapDynamic {
+ wmEventHandler_KeymapDynamicFn keymap_fn;
+ void *user_data;
+};
+
+/** #WM_HANDLER_TYPE_KEYMAP. */
+struct wmEventHandler_Keymap {
+ wmEventHandler head;
+
+ /** Pointer to builtin/custom keymaps (never NULL). */
+ wmKeyMap *keymap;
+
+ wmEventHandler_KeymapPost post;
+ wmEventHandler_KeymapDynamic dynamic;
+
+ bToolRef *keymap_tool;
+};
+
+/** #WM_HANDLER_TYPE_GIZMO. */
+struct wmEventHandler_Gizmo {
+ wmEventHandler head;
+
+ /** Gizmo handler (never NULL). */
+ struct wmGizmoMap *gizmo_map;
+};
+
+/** #WM_HANDLER_TYPE_UI. */
+struct wmEventHandler_UI {
+ wmEventHandler head;
+
+ /** Callback receiving events. */
+ wmUIHandlerFunc handle_fn;
+ /** Callback when handler is removed. */
+ wmUIHandlerRemoveFunc remove_fn;
+ /** User data pointer. */
+ void *user_data;
+
+ /** Store context for this handler for derived/modal handlers. */
+ struct {
+ ScrArea *area;
+ ARegion *region;
+ /**
+ * Temporary, floating regions stored in #Screen::regionbase.
+ * Used for menus, popovers & dialogs.
+ */
+ ARegion *region_popup;
+ } context;
+};
+
+/** #WM_HANDLER_TYPE_OP. */
+struct wmEventHandler_Op {
+ wmEventHandler head;
+
+ /** Operator can be NULL. */
+ wmOperator *op;
+
+ /** Workaround: special case for file-select. */
+ bool is_fileselect;
+
+ /** Store context for this handler for derived/modal handlers. */
+ struct {
+ /**
+ * To override the window, and hence the screen.
+ * Set for few cases only, usually window/screen can be taken from current context.
+ */
+ wmWindow *win;
+
+ ScrArea *area;
+ ARegion *region;
+ short region_type;
+ } context;
+};
+
+/** #WM_HANDLER_TYPE_DROPBOX. */
+struct wmEventHandler_Dropbox {
+ wmEventHandler head;
+
+ /** Never NULL. */
+ ListBaseT<wmDropBox> *dropboxes;
+};
+
+/* `wm_event_system.cc` */
+
+void wm_event_free_all(wmWindow *win);
+void wm_event_free(wmEvent *event);
+void wm_event_free_handler(wmEventHandler *handler);
+
+/**
+ * Goes over entire hierarchy: events -> window -> screen -> area -> region.
+ *
+ * \note Called in main loop.
+ */
+void wm_event_do_handlers(bContext *C);
+
+/**
+ * Windows store their own event queues #wmWindow.event_queue (no #bContext here).
+ */
+void wm_event_add_ghostevent(wmWindowManager *wm,
+ wmWindow *win,
+ int type,
+ const void *customdata,
+ const uint64_t event_time_ms);
+#ifdef WITH_XR_OPENXR
+void wm_event_add_xrevent(wmWindow *win, wmXrActionData *actiondata, short val);
+#endif
+
+void wm_event_do_depsgraph(bContext *C, bool is_after_open_file);
+/**
+ * Was part of #wm_event_do_notifiers,
+ * split out so it can be called once before entering the #WM_main loop.
+ * This ensures operators don't run before the UI and depsgraph are initialized.
+ */
+void wm_event_do_refresh_wm_and_depsgraph(bContext *C);
+/**
+ * Called in main-loop.
+ */
+void wm_event_do_notifiers(bContext *C);
+
+void wm_event_handler_ui_cancel_ex(bContext *C,
+ wmWindow *win,
+ ARegion *region,
+ bool reactivate_button);
+
+/* `wm_event_query.cc`. */
+
+/**
+ * Applies the global tablet pressure correction curve.
+ */
+float wm_pressure_curve(float raw_pressure);
+void wm_tablet_data_from_ghost(const GHOST_TabletData *tablet_data, wmTabletData *wmtab);
+
+/* `wm_dropbox.cc`. */
+
+void wm_dropbox_free();
+/**
+ * Additional work to cleanly end dragging. Additional because this doesn't actually remove the
+ * drag items. Should be called whenever dragging is stopped
+ * (successful or not, also when canceled).
+ */
+void wm_drags_exit(wmWindowManager *wm, wmWindow *win);
+void wm_drop_prepare(bContext *C, wmDrag *drag, wmDropBox *drop);
+void wm_drop_end(bContext *C, wmDrag *drag, wmDropBox *drop);
+/**
+ * Called in inner handler loop, region context.
+ */
+void wm_drags_handle_events(bContext *C, const wmEvent *event);
+/**
+ * The operator of a dropbox should always be executed in the context determined by the mouse
+ * coordinates. The dropbox poll should check the context area and region as needed.
+ * So this always returns #wm::OpCallContext::InvokeDefault.
+ */
+wm::OpCallContext wm_drop_operator_context_get(const wmDropBox *drop);
+/**
+ * Called in #wm_draw_window_onscreen.
+ */
+void wm_drags_draw(bContext *C, wmWindow *win);
+
+} // namespace blender
diff --git a/compat/include/wm_event_types.hh b/compat/include/wm_event_types.hh
new file mode 100644
index 0000000..9c79b85
--- /dev/null
+++ b/compat/include/wm_event_types.hh
@@ -0,0 +1,549 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup wm
+ */
+
+/*
+ * These define have its origin at SGI, where all device defines were written down in device.h.
+ * Blender copied the conventions quite some, and expanded it with internal new defines (ton)
+ */
+
+#pragma once
+
+#include <cstdint>
+
+namespace blender {
+
+/** #wmEvent.customdata type. */
+enum {
+ EVT_DATA_TIMER = 2,
+ EVT_DATA_DRAGDROP = 3,
+ EVT_DATA_NDOF_MOTION = 4,
+ EVT_DATA_XR = 5,
+};
+
+/**
+ * #wmTabletData.active tablet active, matches #GHOST_TTabletMode.
+ *
+ * Typically access via `event->tablet.active`.
+ */
+enum {
+ EVT_TABLET_NONE = 0,
+ EVT_TABLET_STYLUS = 1,
+ EVT_TABLET_ERASER = 2,
+};
+
+/**
+ * #wmEvent.type
+ *
+ * \note Also used for #wmKeyMapItem.type which is saved in key-map files,
+ * do not change the values of existing values which can be used in key-maps.
+ */
+enum wmEventType : int16_t {
+ /* Non-event, for example disabled timer. */
+ EVENT_NONE = 0x0000,
+
+/* ********** Start of Input devices. ********** */
+
+/* Minimum mouse value (inclusive). */
+#define _EVT_MOUSE_MIN 0x0001
+
+ /* MOUSE: 0x000x, 0x001x. */
+ LEFTMOUSE = 0x0001, /* 1 */
+ MIDDLEMOUSE = 0x0002, /* 2 */
+ RIGHTMOUSE = 0x0003, /* 3 */
+ MOUSEMOVE = 0x0004, /* 4 */
+ /* Extra mouse buttons. */
+ BUTTON4MOUSE = 0x0007, /* 7 */
+ BUTTON5MOUSE = 0x0008, /* 8 */
+ /* More mouse buttons - can't use 9 and 10 here (wheel). */
+ BUTTON6MOUSE = 0x0012, /* 18 */
+ BUTTON7MOUSE = 0x0013, /* 19 */
+ /* Extra trackpad gestures (check #WM_EVENT_IS_CONSECUTIVE to detect motion events). */
+ MOUSEPAN = 0x000e, /* 14 */
+ MOUSEZOOM = 0x000f, /* 15 */
+ MOUSEROTATE = 0x0010, /* 13 */
+ MOUSESMARTZOOM = 0x0017, /* 23 */
+
+ /* Defaults from ghost. */
+ WHEELUPMOUSE = 0x000a, /* 10 */
+ WHEELDOWNMOUSE = 0x000b, /* 11 */
+ /* Mapped based on #USER_WHEELZOOMDIR. */
+ WHEELINMOUSE = 0x000c, /* 12 */
+ WHEELOUTMOUSE = 0x000d, /* 13 */
+ /* Successive MOUSEMOVE's are converted to this, so we can easily
+ * ignore all but the most recent MOUSEMOVE (for better performance),
+ * paint and drawing tools however will want to handle these. */
+ INBETWEEN_MOUSEMOVE = 0x0011, /* 17 */
+ /* Horizontal scrolling events. */
+ WHEELLEFTMOUSE = 0x0014, /* 20 */
+ WHEELRIGHTMOUSE = 0x0015, /* 21 */
+
+/* Maximum mouse value (inclusive). */
+#define _EVT_MOUSE_MAX 0x0015 /* 21 */
+
+ /* IME event, GHOST_kEventImeCompositionStart in ghost. */
+ WM_IME_COMPOSITE_START = 0x0016, /* 22 */
+ /* 0x0017 is MOUSESMARTZOOM. */
+ /* IME event, GHOST_kEventImeComposition in ghost. */
+ WM_IME_COMPOSITE_EVENT = 0x0018, /* 24 */
+ /* IME event, GHOST_kEventImeCompositionEnd in ghost. */
+ WM_IME_COMPOSITE_END = 0x0019, /* 25 */
+
+ /* Tablet/Pen Specific Events. */
+ TABLET_STYLUS = 0x001a, /* 26 */
+ TABLET_ERASER = 0x001b, /* 27 */
+
+/* *** Start of keyboard codes. *** */
+
+/* Minimum keyboard value (inclusive). */
+#define _EVT_KEYBOARD_MIN 0x0020 /* 32 */
+
+ /* Standard keyboard.
+ * - 0x0020 to 0x00ff [#_EVT_KEYBOARD_MIN to #_EVT_KEYBOARD_MAX] inclusive - for keys.
+ * - 0x012c to 0x0143 [#EVT_F1KEY to #EVT_F24KEY] inclusive - for function keys. */
+
+ EVT_ZEROKEY = 0x0030, /* '0' (48). */
+ EVT_ONEKEY = 0x0031, /* '1' (49). */
+ EVT_TWOKEY = 0x0032, /* '2' (50). */
+ EVT_THREEKEY = 0x0033, /* '3' (51). */
+ EVT_FOURKEY = 0x0034, /* '4' (52). */
+ EVT_FIVEKEY = 0x0035, /* '5' (53). */
+ EVT_SIXKEY = 0x0036, /* '6' (54). */
+ EVT_SEVENKEY = 0x0037, /* '7' (55). */
+ EVT_EIGHTKEY = 0x0038, /* '8' (56). */
+ EVT_NINEKEY = 0x0039, /* '9' (57). */
+
+ EVT_AKEY = 0x0061, /* 'a' (97). */
+ EVT_BKEY = 0x0062, /* 'b' (98). */
+ EVT_CKEY = 0x0063, /* 'c' (99). */
+ EVT_DKEY = 0x0064, /* 'd' (100). */
+ EVT_EKEY = 0x0065, /* 'e' (101). */
+ EVT_FKEY = 0x0066, /* 'f' (102). */
+ EVT_GKEY = 0x0067, /* 'g' (103). */
+ EVT_HKEY = 0x0068, /* 'h' (104). */
+ EVT_IKEY = 0x0069, /* 'i' (105). */
+ EVT_JKEY = 0x006a, /* 'j' (106). */
+ EVT_KKEY = 0x006b, /* 'k' (107). */
+ EVT_LKEY = 0x006c, /* 'l' (108). */
+ EVT_MKEY = 0x006d, /* 'm' (109). */
+ EVT_NKEY = 0x006e, /* 'n' (110). */
+ EVT_OKEY = 0x006f, /* 'o' (111). */
+ EVT_PKEY = 0x0070, /* 'p' (112). */
+ EVT_QKEY = 0x0071, /* 'q' (113). */
+ EVT_RKEY = 0x0072, /* 'r' (114). */
+ EVT_SKEY = 0x0073, /* 's' (115). */
+ EVT_TKEY = 0x0074, /* 't' (116). */
+ EVT_UKEY = 0x0075, /* 'u' (117). */
+ EVT_VKEY = 0x0076, /* 'v' (118). */
+ EVT_WKEY = 0x0077, /* 'w' (119). */
+ EVT_XKEY = 0x0078, /* 'x' (120). */
+ EVT_YKEY = 0x0079, /* 'y' (121). */
+ EVT_ZKEY = 0x007a, /* 'z' (122). */
+
+ EVT_LEFTARROWKEY = 0x0089, /* 137 */
+ EVT_DOWNARROWKEY = 0x008a, /* 138 */
+ EVT_RIGHTARROWKEY = 0x008b, /* 139 */
+ EVT_UPARROWKEY = 0x008c, /* 140 */
+
+ EVT_PAD0 = 0x0096, /* 150 */
+ EVT_PAD1 = 0x0097, /* 151 */
+ EVT_PAD2 = 0x0098, /* 152 */
+ EVT_PAD3 = 0x0099, /* 153 */
+ EVT_PAD4 = 0x009a, /* 154 */
+ EVT_PAD5 = 0x009b, /* 155 */
+ EVT_PAD6 = 0x009c, /* 156 */
+ EVT_PAD7 = 0x009d, /* 157 */
+ EVT_PAD8 = 0x009e, /* 158 */
+ EVT_PAD9 = 0x009f, /* 159 */
+ /* Key-pad keys. */
+ EVT_PADASTERKEY = 0x00a0, /* 160 */
+ EVT_PADSLASHKEY = 0x00a1, /* 161 */
+ EVT_PADMINUS = 0x00a2, /* 162 */
+ EVT_PADENTER = 0x00a3, /* 163 */
+ EVT_PADPLUSKEY = 0x00a4, /* 164 */
+
+ EVT_PAUSEKEY = 0x00a5, /* 165 */
+ EVT_INSERTKEY = 0x00a6, /* 166 */
+ EVT_HOMEKEY = 0x00a7, /* 167 */
+ EVT_PAGEUPKEY = 0x00a8, /* 168 */
+ EVT_PAGEDOWNKEY = 0x00a9, /* 169 */
+ EVT_ENDKEY = 0x00aa, /* 170 */
+ /* Note that 'PADPERIOD' is defined out-of-order. */
+ EVT_UNKNOWNKEY = 0x00ab, /* 171 */
+ /** OS modifier, see: #KM_OSKEY for details. */
+ EVT_OSKEY = 0x00ac, /* 172 */
+ EVT_GRLESSKEY = 0x00ad, /* 173 */
+ /* Media keys. */
+ EVT_MEDIAPLAY = 0x00ae, /* 174 */
+ EVT_MEDIASTOP = 0x00af, /* 175 */
+ EVT_MEDIAFIRST = 0x00b0, /* 176 */
+ EVT_MEDIALAST = 0x00b1, /* 177 */
+ /* Menu/App key. */
+ EVT_APPKEY = 0x00b2, /* 178 */
+
+ /** Additional modifier, see: #KM_HYPER for details. */
+ EVT_HYPER = 0x00b3, /* 179 */
+
+ EVT_PADPERIOD = 0x00c7, /* 199 */
+
+ EVT_CAPSLOCKKEY = 0x00d3, /* 211 */
+
+ /* Modifier keys. */
+ EVT_LEFTCTRLKEY = 0x00d4, /* 212 */
+ EVT_LEFTALTKEY = 0x00d5, /* 213 */
+ EVT_RIGHTALTKEY = 0x00d6, /* 214 */
+ EVT_RIGHTCTRLKEY = 0x00d7, /* 215 */
+ EVT_RIGHTSHIFTKEY = 0x00d8, /* 216 */
+ EVT_LEFTSHIFTKEY = 0x00d9, /* 217 */
+ /* Special characters. */
+ EVT_ESCKEY = 0x00da, /* 218 */
+ EVT_TABKEY = 0x00db, /* 219 */
+ EVT_RETKEY = 0x00dc, /* 220 */
+ EVT_SPACEKEY = 0x00dd, /* 221 */
+ EVT_LINEFEEDKEY = 0x00de, /* 222 */
+ EVT_BACKSPACEKEY = 0x00df, /* 223 */
+ EVT_DELKEY = 0x00e0, /* 224 */
+ EVT_SEMICOLONKEY = 0x00e1, /* 225 */
+ EVT_PERIODKEY = 0x00e2, /* 226 */
+ EVT_COMMAKEY = 0x00e3, /* 227 */
+ EVT_QUOTEKEY = 0x00e4, /* 228 */
+ EVT_ACCENTGRAVEKEY = 0x00e5, /* 229 */
+ EVT_MINUSKEY = 0x00e6, /* 230 */
+ EVT_PLUSKEY = 0x00e7, /* 231 */
+ EVT_SLASHKEY = 0x00e8, /* 232 */
+ EVT_BACKSLASHKEY = 0x00e9, /* 233 */
+ EVT_EQUALKEY = 0x00ea, /* 234 */
+ EVT_LEFTBRACKETKEY = 0x00eb, /* 235 */
+ EVT_RIGHTBRACKETKEY = 0x00ec, /* 236 */
+
+/* Maximum keyboard value (inclusive). */
+#define _EVT_KEYBOARD_MAX 0x00ff /* 255 */
+
+ /* WARNING: 0x010x are used for internal events
+ * (but are still stored in the key-map). */
+
+ EVT_F1KEY = 0x012c, /* 300 */
+ EVT_F2KEY = 0x012d, /* 301 */
+ EVT_F3KEY = 0x012e, /* 302 */
+ EVT_F4KEY = 0x012f, /* 303 */
+ EVT_F5KEY = 0x0130, /* 304 */
+ EVT_F6KEY = 0x0131, /* 305 */
+ EVT_F7KEY = 0x0132, /* 306 */
+ EVT_F8KEY = 0x0133, /* 307 */
+ EVT_F9KEY = 0x0134, /* 308 */
+ EVT_F10KEY = 0x0135, /* 309 */
+ EVT_F11KEY = 0x0136, /* 310 */
+ EVT_F12KEY = 0x0137, /* 311 */
+ EVT_F13KEY = 0x0138, /* 312 */
+ EVT_F14KEY = 0x0139, /* 313 */
+ EVT_F15KEY = 0x013a, /* 314 */
+ EVT_F16KEY = 0x013b, /* 315 */
+ EVT_F17KEY = 0x013c, /* 316 */
+ EVT_F18KEY = 0x013d, /* 317 */
+ EVT_F19KEY = 0x013e, /* 318 */
+ EVT_F20KEY = 0x013f, /* 319 */
+ EVT_F21KEY = 0x0140, /* 320 */
+ EVT_F22KEY = 0x0141, /* 321 */
+ EVT_F23KEY = 0x0142, /* 322 */
+ EVT_F24KEY = 0x0143, /* 323 */
+
+ /* *** End of keyboard codes. *** */
+
+ /* NDOF (from "Space Navigator" & friends)
+ * These must be kept in sync with `GHOST_NDOFManager.hh`.
+ * Ordering matters, exact values do not. */
+
+ /**
+ * Motion from 3D input (translation & rotation).
+ * Check #WM_EVENT_IS_CONSECUTIVE to detect motion events.
+ */
+ NDOF_MOTION = 0x0190, /* 400 */
+
+#define _NDOF_MIN NDOF_MOTION
+#define _NDOF_BUTTON_MIN NDOF_BUTTON_MENU
+
+ /* These two are available from any 3Dconnexion device. */
+
+ NDOF_BUTTON_MENU = 0x0191, /* 401 */
+ NDOF_BUTTON_FIT = 0x0192, /* 402 */
+ /* Standard views. */
+ NDOF_BUTTON_TOP = 0x0193, /* 403 */
+ NDOF_BUTTON_BOTTOM = 0x0194, /* 404 */
+ NDOF_BUTTON_LEFT = 0x0195, /* 405 */
+ NDOF_BUTTON_RIGHT = 0x0196, /* 406 */
+ NDOF_BUTTON_FRONT = 0x0197, /* 407 */
+ NDOF_BUTTON_BACK = 0x0198, /* 408 */
+ /* More views. */
+ NDOF_BUTTON_ISO1 = 0x0199, /* 409 */
+ NDOF_BUTTON_ISO2 = 0x019a, /* 410 */
+ /* 90 degree rotations. */
+ NDOF_BUTTON_ROLL_CW = 0x019b, /* 411 */
+ NDOF_BUTTON_ROLL_CCW = 0x019c, /* 412 */
+ NDOF_BUTTON_SPIN_CW = 0x019d, /* 413 */
+ NDOF_BUTTON_SPIN_CCW = 0x019e, /* 414 */
+ NDOF_BUTTON_TILT_CW = 0x019f, /* 415 */
+ NDOF_BUTTON_TILT_CCW = 0x01a0, /* 416 */
+ /* Device control. */
+ NDOF_BUTTON_ROTATE = 0x01a1, /* 417 */
+ NDOF_BUTTON_PANZOOM = 0x01a2, /* 418 */
+ NDOF_BUTTON_DOMINANT = 0x01a3, /* 419 */
+ NDOF_BUTTON_PLUS = 0x01a4, /* 420 */
+ NDOF_BUTTON_MINUS = 0x01a5, /* 421 */
+ /* Restore views. */
+ NDOF_BUTTON_V1 = 0x01a6, /* 422 */
+ NDOF_BUTTON_V2 = 0x01a7, /* 423 */
+ NDOF_BUTTON_V3 = 0x01a8, /* 424 */
+ /* General-purpose buttons. */
+ NDOF_BUTTON_1 = 0x01aa, /* 426 */
+ NDOF_BUTTON_2 = 0x01ab, /* 427 */
+ NDOF_BUTTON_3 = 0x01ac, /* 428 */
+ NDOF_BUTTON_4 = 0x01ad, /* 429 */
+ NDOF_BUTTON_5 = 0x01ae, /* 430 */
+ NDOF_BUTTON_6 = 0x01af, /* 431 */
+ NDOF_BUTTON_7 = 0x01b0, /* 432 */
+ NDOF_BUTTON_8 = 0x01b1, /* 433 */
+ NDOF_BUTTON_9 = 0x01b2, /* 434 */
+ NDOF_BUTTON_10 = 0x01b3, /* 435 */
+ /* More general-purpose buttons. */
+ NDOF_BUTTON_11 = 0x01b4, /* 436 */
+ NDOF_BUTTON_12 = 0x01b5, /* 437 */
+
+/* Disabled as GHOST converts these to keyboard events
+ * which use regular keyboard event handling logic. */
+#if 0
+ /* Keyboard emulation. */
+ NDOF_BUTTON_ESC = 0x01b6, /* 438 */
+ NDOF_BUTTON_ENTER = 0x01b7, /* 439 */
+ NDOF_BUTTON_DELETE = 0x01b8, /* 440 */
+ NDOF_BUTTON_TAB = 0x01b9, /* 441 */
+ NDOF_BUTTON_SPACE = 0x01ba, /* 442 */
+ NDOF_BUTTON_ALT = 0x01bb, /* 443 */
+ NDOF_BUTTON_SHIFT = 0x01bc, /* 444 */
+ NDOF_BUTTON_CTRL = 0x01bd, /* 445 */
+#endif
+
+ /* Store views. */
+ NDOF_BUTTON_SAVE_V1 = 0x01be, /* 446 */
+ NDOF_BUTTON_SAVE_V2 = 0x01bf, /* 447 */
+ NDOF_BUTTON_SAVE_V3 = 0x01c0, /* 448 */
+
+#define _NDOF_MAX NDOF_BUTTON_SAVE_V3
+#define _NDOF_BUTTON_MAX NDOF_BUTTON_SAVE_V3
+
+ /* ********** End of Input devices. ********** */
+
+ /* ********** Start of Blender internal events. ********** */
+
+ /* XXX Those are mixed inside keyboard 'area'! */
+ /* System: 0x010x. */
+ // INPUTCHANGE = 0x0103, /* Input connected or disconnected, (259). */ /* UNUSED. */
+ WINDEACTIVATE = 0x0104, /* Window is deactivated, focus lost, (260). */
+ /* Timer: 0x011x. */
+ TIMER = 0x0110, /* Timer event, passed on to all queues (272). */
+ TIMER0 = 0x0111, /* Timer event, slot for internal use (273). */
+ TIMER1 = 0x0112, /* Timer event, slot for internal use (274). */
+ TIMER2 = 0x0113, /* Timer event, slot for internal use (275). */
+ TIMERJOBS = 0x0114, /* Timer event, jobs system (276). */
+ TIMERAUTOSAVE = 0x0115, /* Timer event, autosave (277). */
+ TIMERREPORT = 0x0116, /* Timer event, reports (278). */
+ TIMERREGION = 0x0117, /* Timer event, region slide in/out (279). */
+ TIMERNOTIFIER = 0x0118, /* Timer event, notifier sender (280). */
+/* Timer max (287). */
+#define _TIMER_MAX 0x011F
+
+ /* Action-zones, tweak, gestures: 0x500x, 0x501x
+ * Keep in sync with #IS_EVENT_ACTIONZONE(...). */
+ EVT_ACTIONZONE_AREA = 0x5000, /* 20480 */
+ EVT_ACTIONZONE_REGION = 0x5001, /* 20481 */
+ EVT_ACTIONZONE_REGION_QUAD = 0x5002, /* 20482 */
+ EVT_ACTIONZONE_FULLSCREEN = 0x5011, /* 20497 */
+
+ /* NOTE: these values are saved in key-map files, do not change them but just add new ones. */
+
+ /* 0x5011 is taken, see #EVT_ACTIONZONE_FULLSCREEN. */
+
+ /* Misc Blender internals: 0x502x. */
+ EVT_FILESELECT = 0x5020, /* 20512 */
+ EVT_BUT_OPEN = 0x5021, /* 20513 */
+ EVT_MODAL_MAP = 0x5022, /* 20514 */
+ EVT_DROP = 0x5023, /* 20515 */
+ /* When value is 0, re-activate, when 1, don't re-activate the button under the cursor. */
+ EVT_BUT_CANCEL = 0x5024, /* 20516 */
+
+ /* Could become gizmo callback. */
+ EVT_GIZMO_UPDATE = 0x5025, /* 20517 */
+
+ /* XR events: 0x503x. */
+ EVT_XR_ACTION = 0x5030, /* 20528 */
+ /* ********** End of Blender internal events. ********** */
+};
+
+/* -------------------------------------------------------------------- */
+/** \name #wmEvent.type Helpers
+ * \{ */
+
+/** Test whether the event is timer event. */
+#define ISTIMER(event_type) ((event_type) >= TIMER && (event_type) <= _TIMER_MAX)
+
+/** Test whether the event is a key on the keyboard (including modifier keys). */
+#define ISKEYBOARD(event_type) \
+ (((event_type) >= _EVT_KEYBOARD_MIN && (event_type) <= _EVT_KEYBOARD_MAX) || \
+ ((event_type) >= EVT_F1KEY && (event_type) <= EVT_F24KEY))
+
+/**
+ * Test whether the event is a key on the keyboard
+ * or any other kind of button that supports press & release
+ * (use for click & click-drag detection).
+ *
+ * \note Mouse wheel events are excluded from this macro, while they do generate press events it
+ * doesn't make sense to have click & click-drag events for a mouse-wheel as it can't be held down.
+ */
+#define ISKEYBOARD_OR_BUTTON(event_type) \
+ (ISMOUSE_BUTTON(event_type) || ISKEYBOARD(event_type) || ISNDOF_BUTTON(event_type))
+
+/** Test whether the event is a modifier key. */
+#define ISKEYMODIFIER(event_type) \
+ (((event_type) >= EVT_LEFTCTRLKEY && (event_type) <= EVT_LEFTSHIFTKEY) || \
+ ELEM((event_type), EVT_OSKEY, EVT_HYPER))
+
+/**
+ * Test whether the event is any kind:
+ * #ISMOUSE_MOTION, #ISMOUSE_BUTTON, #ISMOUSE_WHEEL & #ISMOUSE_GESTURE.
+ *
+ * \note It's best to use more specific check if possible as mixing motion/buttons/gestures
+ * is very broad and not necessarily obvious which kinds of events are important.
+ */
+#define ISMOUSE(event_type) ((event_type) >= _EVT_MOUSE_MIN && (event_type) <= _EVT_MOUSE_MAX)
+/** Test whether the event is a mouse button (excluding mouse-wheel). */
+#define ISMOUSE_MOTION(event_type) ELEM(event_type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)
+/** Test whether the event is a mouse button (excluding mouse-wheel). */
+#define ISMOUSE_BUTTON(event_type) \
+ (ELEM(event_type, \
+ LEFTMOUSE, \
+ MIDDLEMOUSE, \
+ RIGHTMOUSE, \
+ BUTTON4MOUSE, \
+ BUTTON5MOUSE, \
+ BUTTON6MOUSE, \
+ BUTTON7MOUSE))
+/** Test whether the event is a mouse wheel. */
+#define ISMOUSE_WHEEL(event_type) \
+ (((event_type) >= WHEELUPMOUSE && (event_type) <= WHEELOUTMOUSE) || \
+ ELEM((event_type), WHEELLEFTMOUSE, WHEELRIGHTMOUSE))
+/** Test whether the event is a mouse (trackpad) gesture. */
+#define ISMOUSE_GESTURE(event_type) ((event_type) >= MOUSEPAN && (event_type) <= MOUSESMARTZOOM)
+
+/** Test whether the event is a NDOF event. */
+#define ISNDOF(event_type) ((event_type) >= _NDOF_MIN && (event_type) <= _NDOF_MAX)
+#define ISNDOF_BUTTON(event_type) \
+ ((event_type) >= _NDOF_BUTTON_MIN && (event_type) <= _NDOF_BUTTON_MAX)
+
+#define IS_EVENT_ACTIONZONE(event_type) \
+ ELEM(event_type, \
+ EVT_ACTIONZONE_AREA, \
+ EVT_ACTIONZONE_REGION, \
+ EVT_ACTIONZONE_REGION_QUAD, \
+ EVT_ACTIONZONE_FULLSCREEN)
+
+/** Test whether event type is acceptable as hotkey (excluding modifiers). */
+#define ISHOTKEY(event_type) \
+ ((ISKEYBOARD(event_type) || ISMOUSE_BUTTON(event_type) || ISMOUSE_WHEEL(event_type) || \
+ ISNDOF_BUTTON(event_type)) && \
+ (ISKEYMODIFIER(event_type) == false))
+
+enum eEventType_Mask {
+ /** #ISKEYMODIFIER. */
+ EVT_TYPE_MASK_KEYBOARD_MODIFIER = (1 << 0),
+ /** #ISKEYBOARD. */
+ EVT_TYPE_MASK_KEYBOARD = (1 << 1),
+ /** #ISMOUSE_WHEEL. */
+ EVT_TYPE_MASK_MOUSE_WHEEL = (1 << 2),
+ /** #ISMOUSE_BUTTON. */
+ EVT_TYPE_MASK_MOUSE_GESTURE = (1 << 3),
+ /** #ISMOUSE_GESTURE. */
+ EVT_TYPE_MASK_MOUSE_BUTTON = (1 << 4),
+ /** #ISMOUSE. */
+ EVT_TYPE_MASK_MOUSE = (1 << 5),
+ /** #ISNDOF. */
+ EVT_TYPE_MASK_NDOF = (1 << 6),
+ /** #IS_EVENT_ACTIONZONE. */
+ EVT_TYPE_MASK_ACTIONZONE = (1 << 7),
+};
+#define EVT_TYPE_MASK_ALL \
+ (EVT_TYPE_MASK_KEYBOARD | EVT_TYPE_MASK_MOUSE | EVT_TYPE_MASK_NDOF | EVT_TYPE_MASK_ACTIONZONE)
+
+#define EVT_TYPE_MASK_HOTKEY_INCLUDE \
+ (EVT_TYPE_MASK_KEYBOARD | EVT_TYPE_MASK_MOUSE | EVT_TYPE_MASK_NDOF)
+#define EVT_TYPE_MASK_HOTKEY_EXCLUDE EVT_TYPE_MASK_KEYBOARD_MODIFIER
+
+bool WM_event_type_mask_test(int event_type, enum eEventType_Mask mask);
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name #wmEvent.val Values
+ * \{ */
+
+/* Gestures. */
+
+/**
+ * File selector.
+ * When #wmEvent::type is #EVT_FILESELECT, this value is stored in #wmEvent::val.
+ */
+enum {
+ EVT_FILESELECT_FULL_OPEN = 1,
+ EVT_FILESELECT_EXEC = 2,
+ EVT_FILESELECT_CANCEL = 3,
+ EVT_FILESELECT_EXTERNAL_CANCEL = 4,
+};
+
+/**
+ * Gesture
+ * Used in #wmEvent.val
+ *
+ * \note These values are saved in keymap files,
+ * do not change them but just add new ones.
+ */
+enum {
+ GESTURE_MODAL_CANCEL = 1,
+ GESTURE_MODAL_CONFIRM = 2,
+
+ /** Uses 'deselect' operator property. */
+ GESTURE_MODAL_SELECT = 3,
+ GESTURE_MODAL_DESELECT = 4,
+
+ /** Circle select: when no mouse button is pressed. */
+ GESTURE_MODAL_NOP = 5,
+
+ /** Circle select: larger brush. */
+ GESTURE_MODAL_CIRCLE_ADD = 6,
+ /** Circle select: smaller brush. */
+ GESTURE_MODAL_CIRCLE_SUB = 7,
+
+ /** Box select/straight line, activate, use release to detect which button. */
+ GESTURE_MODAL_BEGIN = 8,
+
+ /** Uses 'zoom_out' operator property. */
+ GESTURE_MODAL_IN = 9,
+ GESTURE_MODAL_OUT = 10,
+
+ /** Circle select: size brush (for trackpad event). */
+ GESTURE_MODAL_CIRCLE_SIZE = 11,
+
+ /** Move selection area. */
+ GESTURE_MODAL_MOVE = 12,
+
+ /** Toggle to activate snapping (angle snapping for straight line). */
+ GESTURE_MODAL_SNAP = 13,
+
+ /** Toggle to activate flip (flip the active side of a straight line). */
+ GESTURE_MODAL_FLIP = 14,
+};
+
+/** \} */
+
+} // namespace blender
diff --git a/compat/include/wm_gizmo_fn.hh b/compat/include/wm_gizmo_fn.hh
new file mode 100644
index 0000000..f222a64
--- /dev/null
+++ b/compat/include/wm_gizmo_fn.hh
@@ -0,0 +1,97 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup wm
+ *
+ * Callback function definitions, needed for both Types & API headers.
+ */
+
+#pragma once
+
+#include "DNA_windowmanager_enums.h" /* For `wmOperatorStatus`. */
+
+namespace blender {
+
+struct bContext;
+struct rcti;
+struct wmEvent;
+struct wmGizmo;
+struct wmGizmoGroup;
+struct wmGizmoGroupType;
+struct wmGizmoProperty;
+struct wmKeyConfig;
+struct wmKeyMap;
+struct wmMsgBus;
+
+/* #wmGizmoGroup. */
+using wmGizmoGroupFnPoll = bool (*)(const bContext *, wmGizmoGroupType *);
+using wmGizmoGroupFnInit = void (*)(const bContext *, wmGizmoGroup *);
+using wmGizmoGroupFnRefresh = void (*)(const bContext *, wmGizmoGroup *);
+using wmGizmoGroupFnDrawPrepare = void (*)(const bContext *, wmGizmoGroup *);
+using wmGizmoGroupFnDrawBackground = void (*)(const bContext *, wmGizmoGroup *);
+using wmGizmoGroupFnInvokePrepare = void (*)(const bContext *,
+ wmGizmoGroup *,
+ wmGizmo *,
+ const wmEvent *);
+using wmGizmoGroupFnSetupKeymap = wmKeyMap *(*)(const wmGizmoGroupType *, wmKeyConfig *);
+using wmGizmoGroupFnMsgBusSubscribe = void (*)(const bContext *, wmGizmoGroup *, wmMsgBus *);
+
+/* #wmGizmo. */
+/* See: wmGizmoType for docs on each type. */
+
+using wmGizmoFnSetup = void (*)(wmGizmo *);
+using wmGizmoFnDraw = void (*)(const bContext *, wmGizmo *);
+using wmGizmoFnDrawSelect = void (*)(const bContext *, wmGizmo *, int);
+using wmGizmoFnTestSelect = int (*)(bContext *, wmGizmo *, const int mval[2]);
+using wmGizmoFnModal = wmOperatorStatus (*)(bContext *,
+ wmGizmo *,
+ const wmEvent *,
+ eWM_GizmoFlagTweak);
+using wmGizmoFnPropertyUpdate = void (*)(wmGizmo *, wmGizmoProperty *);
+using wmGizmoFnMatrixBasisGet = void (*)(const wmGizmo *, float[4][4]);
+using wmGizmoFnInvoke = wmOperatorStatus (*)(bContext *, wmGizmo *, const wmEvent *);
+using wmGizmoFnExit = void (*)(bContext *, wmGizmo *, const bool);
+using wmGizmoFnCursorGet = int (*)(wmGizmo *);
+using wmGizmoFnScreenBoundsGet = bool (*)(const bContext *, wmGizmo *, rcti *r_bounding_box);
+using wmGizmoFnSelectRefresh = void (*)(wmGizmo *);
+using wmGizmoFnFree = void (*)(wmGizmo *);
+
+/* #wmGizmoProperty ('value' type defined by 'wmGizmoProperty.data_type'). */
+using wmGizmoPropertyFnGet = void (*)(const wmGizmo *,
+ wmGizmoProperty *,
+ /* Typically `float *`. */
+ void *value);
+using wmGizmoPropertyFnSet = void (*)(const wmGizmo *,
+ wmGizmoProperty *,
+ /* Typically `const float *`. */
+ const void *value);
+using wmGizmoPropertyFnRangeGet = void (*)(const wmGizmo *,
+ wmGizmoProperty *,
+ /* Typically `float[2]`. */
+ void *range);
+/**
+ * To inspect the RNA properties gizmos are manipulating (can be multiple).
+ * Used e.g. for auto-keying.
+ *
+ * \param gz_prop: The gizmo property to inspect.
+ * \param callback: Called for each RNA property being manipulated.
+ * - `index`: Property element index (-1 for all items).
+ */
+using wmGizmoPropertyFnForeachRNAProp =
+ void (*)(wmGizmoProperty *,
+ const FunctionRef<void(PointerRNA &ptr, PropertyRNA *prop, int index)> callback);
+
+using wmGizmoPropertyFnFree = void (*)(const wmGizmo *, wmGizmoProperty *);
+
+struct wmGizmoPropertyFnParams {
+ wmGizmoPropertyFnGet value_get_fn;
+ wmGizmoPropertyFnSet value_set_fn;
+ wmGizmoPropertyFnRangeGet range_get_fn;
+ wmGizmoPropertyFnFree free_fn;
+ wmGizmoPropertyFnForeachRNAProp foreach_rna_prop_fn;
+ void *user_data;
+};
+
+} // namespace blender
diff --git a/compat/include/wm_window.hh b/compat/include/wm_window.hh
new file mode 100644
index 0000000..9dad895
--- /dev/null
+++ b/compat/include/wm_window.hh
@@ -0,0 +1,163 @@
+/* SPDX-FileCopyrightText: 2007 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup wm
+ */
+
+#pragma once
+
+#include "BLI_compiler_attrs.h"
+
+#include "DNA_windowmanager_enums.h"
+
+namespace blender {
+
+struct bContext;
+struct Main;
+struct PointerRNA;
+struct wmOperator;
+struct wmOperatorType;
+struct wmWindow;
+struct wmWindowManager;
+
+/* *************** Internal API ************** */
+
+/**
+ * \note #bContext can be null in background mode because we don't
+ * need to event handling.
+ */
+void wm_ghost_init(bContext *C);
+void wm_ghost_init_background();
+void wm_ghost_exit();
+
+void wm_clipboard_free();
+
+/**
+ * This one should correctly check for apple top header...
+ * done for Cocoa: returns window contents (and not frame) max size.
+ * \return true on success.
+ */
+bool wm_get_screensize(int r_size[2]) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT;
+/**
+ * Size of all screens (desktop), useful since the mouse is bound by this.
+ * \return true on success.
+ */
+bool wm_get_desktopsize(int r_size[2]) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT;
+
+/**
+ * Don't change context itself.
+ */
+wmWindow *wm_window_new(const Main *bmain, wmWindowManager *wm, wmWindow *parent, bool dialog);
+/**
+ * Part of `wm_window.cc` API.
+ */
+wmWindow *wm_window_copy(
+ Main *bmain, wmWindowManager *wm, wmWindow *win_src, bool duplicate_layout, bool child);
+/**
+ * A higher level version of copy that tests the new window can be added.
+ * (called from the operator directly).
+ */
+wmWindow *wm_window_copy_test(bContext *C, wmWindow *win_src, bool duplicate_layout, bool child);
+/**
+ * Including window itself.
+ * \param C: can be NULL.
+ * \note #ED_screen_exit should have been called.
+ */
+void wm_window_free(bContext *C, wmWindowManager *wm, wmWindow *win);
+/**
+ * User request to close the window (close event for example, or exit operator).
+ *
+ * - Close may be deferred (if the file isn't saved).
+ * - Store temp window screen coordinates.
+ */
+void wm_window_close_request(bContext *C, wmWindowManager *wm, wmWindow *win);
+/**
+ * Close the window unconditionally.
+ *
+ * \note Lower level, may run if GHOST failed to initialize the window.
+ * We cannot assume GHOST or the GPU context is valid at this point.
+ */
+void wm_window_close(bContext *C, wmWindowManager *wm, wmWindow *win);
+
+/**
+ * Initialize #wmWindow without `ghostwin`, open these and clear.
+ *
+ * Window size is read from window, if 0 it uses prefsize
+ * called in #WM_check, also initialize stuff after file read.
+ *
+ * \warning After running, `win->ghostwin` can be NULL in rare cases
+ * (where OpenGL driver fails to create a context for eg).
+ * We could remove them with #wm_window_ghostwindows_remove_invalid
+ * but better not since caller may continue to use.
+ * Instead, caller needs to handle the error case and cleanup.
+ */
+void wm_window_ghostwindows_ensure(wmWindowManager *wm);
+/**
+ * Call after #wm_window_ghostwindows_ensure or #WM_check
+ * (after loading a new file) in the unlikely event a window couldn't be created.
+ */
+void wm_window_ghostwindows_remove_invalid(bContext *C, wmWindowManager *wm);
+void wm_window_events_process(const bContext *C);
+
+void wm_window_clear_drawable(wmWindowManager *wm);
+void wm_window_make_drawable(wmWindowManager *wm, wmWindow *win);
+/**
+ * Reset active the current window gpu drawing context.
+ */
+void wm_window_reset_drawable();
+
+void wm_window_raise(wmWindow *win);
+void wm_window_lower(wmWindow *win);
+void wm_window_set_size(wmWindow *win, int width, int height);
+/**
+ * \brief Push rendered buffer to the screen.
+ */
+void wm_window_swap_buffer_acquire(wmWindow *win);
+void wm_window_swap_buffer_release(wmWindow *win);
+void wm_window_set_swap_interval(wmWindow *win, int interval);
+bool wm_window_get_swap_interval(wmWindow *win, int *r_interval);
+
+bool wm_cursor_position_get(wmWindow *win, int *r_x, int *r_y) ATTR_WARN_UNUSED_RESULT;
+void wm_cursor_position_from_ghost_screen_coords(wmWindow *win, int *x, int *y);
+void wm_cursor_position_to_ghost_screen_coords(wmWindow *win, int *x, int *y);
+
+void wm_cursor_position_from_ghost_client_coords(wmWindow *win, int *x, int *y);
+void wm_cursor_position_to_ghost_client_coords(wmWindow *win, int *x, int *y);
+
+#ifdef WITH_INPUT_IME
+void wm_window_IME_begin(wmWindow *win, int x, int y, int w, int h, bool complete);
+void wm_window_IME_end(wmWindow *win);
+#endif
+
+/**
+ * Effectively remove timers from the list and delete them. Calling this should only be done by
+ * internal WM management code, from specific, safe places.
+ */
+void wm_window_timers_delete_removed(wmWindowManager *wm);
+
+/* *************** window operators ************** */
+
+wmOperatorStatus wm_window_close_exec(bContext *C, wmOperator *op);
+/**
+ * Full-screen operator callback.
+ */
+wmOperatorStatus wm_window_fullscreen_toggle_exec(bContext *C, wmOperator *op);
+/**
+ * Call the quit confirmation prompt or exit directly if needed. The use can
+ * still cancel via the confirmation popup. Also, this may not quit Blender
+ * immediately, but rather schedule the closing.
+ *
+ * \param win: The window to show the confirmation popup/window in.
+ */
+void wm_quit_with_optional_confirmation_prompt(bContext *C, wmWindow *win) ATTR_NONNULL();
+
+wmOperatorStatus wm_window_new_exec(bContext *C, wmOperator *op);
+wmOperatorStatus wm_window_new_main_exec(bContext *C, wmOperator *op);
+
+void wm_test_autorun_revert_action_set(wmOperatorType *ot, PointerRNA *ptr);
+void wm_test_autorun_warning(bContext *C);
+void wm_test_foreign_file_warning(bContext *C);
+
+} // namespace blender
diff --git a/compat/intern/bui_stubs.cc b/compat/intern/bui_stubs.cc
new file mode 100644
index 0000000..56f9a37
Binary files /dev/null and b/compat/intern/bui_stubs.cc differ
diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt
index 4177da4..58f93ec 100644
--- a/core/CMakeLists.txt
+++ b/core/CMakeLists.txt
@@ -42,6 +42,7 @@ add_library(bui::core ALIAS bui_core)
target_include_directories(bui_core PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/include
+ ${CMAKE_SOURCE_DIR}/types/dna/include
# headers #include "intern/*.c" inline implementations, relative to module root
${CMAKE_CURRENT_SOURCE_DIR}
)
@@ -60,3 +61,4 @@ endif()
find_package(Threads REQUIRED)
target_link_libraries(bui_core PUBLIC Threads::Threads)
+
diff --git a/core/include/BLI_allocator.hh b/core/include/BLI_allocator.hh
index ad91441..af8f7d7 100644
--- a/core/include/BLI_allocator.hh
+++ b/core/include/BLI_allocator.hh
@@ -1,3 +1,4 @@
+#include <cstring>
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
@@ -133,3 +134,4 @@ class RawAllocator {
};
} // namespace blender
+
diff --git a/core/include/BLI_args.h b/core/include/BLI_args.h
new file mode 100644
index 0000000..b2e5559
--- /dev/null
+++ b/core/include/BLI_args.h
@@ -0,0 +1,72 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ * \brief A general argument parsing module.
+ */
+
+#include <stdarg.h> /* For `va_list`. */
+#include <stdbool.h>
+
+#include "BLI_compiler_attrs.h"
+
+namespace blender {
+
+struct bArgs;
+
+/**
+ * Returns the number of extra arguments consumed by the function.
+ * - 0 is normal value,
+ * - -1 stops parsing arguments, other negative indicates skip
+ */
+using BA_ArgCallback = int (*)(int argc, const char **argv, void *data);
+
+struct bArgs *BLI_args_create(int argc, const char **argv);
+void BLI_args_destroy(struct bArgs *ba);
+
+using bArgPrintFn = void (*)(void *user_data, const char *format, va_list args);
+void BLI_args_printf(struct bArgs *ba, const char *format, ...);
+void BLI_args_print_fn_set(struct bArgs *ba,
+ ATTR_PRINTF_FORMAT(2, 0) bArgPrintFn print_fn,
+ void *user_data);
+
+/** The pass to use for #BLI_args_add. */
+void BLI_args_pass_set(struct bArgs *ba, int current_pass);
+
+/**
+ * Pass starts at 1, -1 means valid all the time
+ * short_arg or long_arg can be null to specify no short or long versions
+ */
+void BLI_args_add(struct bArgs *ba,
+ const char *short_arg,
+ const char *long_arg,
+ const char *doc,
+ BA_ArgCallback cb,
+ void *data);
+
+/**
+ * Short_case and long_case specify if those arguments are case specific
+ */
+void BLI_args_add_case(struct bArgs *ba,
+ const char *short_arg,
+ int short_case,
+ const char *long_arg,
+ int long_case,
+ const char *doc,
+ BA_ArgCallback cb,
+ void *data);
+
+void BLI_args_parse(struct bArgs *ba, int pass, BA_ArgCallback default_cb, void *default_data);
+
+void BLI_args_print_arg_doc(struct bArgs *ba, const char *arg);
+void BLI_args_print_other_doc(struct bArgs *ba);
+
+bool BLI_args_has_other_doc(const struct bArgs *ba);
+
+void BLI_args_print(const struct bArgs *ba);
+
+} // namespace blender
diff --git a/core/include/BLI_array.hh b/core/include/BLI_array.hh
index 4043fff..636e010 100644
--- a/core/include/BLI_array.hh
+++ b/core/include/BLI_array.hh
@@ -1,3 +1,4 @@
+#include <cstring>
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
@@ -485,3 +486,4 @@ class Array {
};
} // namespace blender
+
diff --git a/core/include/BLI_array_store.h b/core/include/BLI_array_store.h
new file mode 100644
index 0000000..68044a2
--- /dev/null
+++ b/core/include/BLI_array_store.h
@@ -0,0 +1,131 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ * \brief Efficient in-memory storage of multiple similar arrays.
+ */
+
+#include "BLI_sys_types.h"
+
+namespace blender {
+
+struct BArrayState;
+struct BArrayStore;
+
+/**
+ * Create a new array store, which can store any number of arrays
+ * as long as their stride matches.
+ *
+ * \param stride: `sizeof()` each element,
+ *
+ * \note while a stride of `1` will always work,
+ * its less efficient since duplicate chunks of memory will be searched
+ * at positions unaligned with the array data.
+ *
+ * \param chunk_count: Number of elements to split each chunk into.
+ * - A small value increases the ability to de-duplicate chunks,
+ * but adds overhead by increasing the number of chunks to look up when searching for duplicates,
+ * as well as some overhead constructing the original array again, with more calls to `memcpy`.
+ * - Larger values reduce the *book keeping* overhead,
+ * but increase the chance a small,
+ * isolated change will cause a larger amount of data to be duplicated.
+ *
+ * \return A new array store, to be freed with #BLI_array_store_destroy.
+ */
+BArrayStore *BLI_array_store_create(unsigned int stride, unsigned int chunk_count);
+/**
+ * Free the #BArrayStore, including all states and chunks.
+ */
+void BLI_array_store_destroy(BArrayStore *bs);
+/**
+ * Clear all contents, allowing reuse of \a bs.
+ */
+void BLI_array_store_clear(BArrayStore *bs);
+
+/**
+ * Find the memory used by all states (expanded & real).
+ *
+ * \return the total amount of memory that would be used by getting the arrays for all states.
+ */
+size_t BLI_array_store_calc_size_expanded_get(const BArrayStore *bs);
+/**
+ * \return the amount of memory used by all #BChunk.data
+ * (duplicate chunks are only counted once).
+ */
+size_t BLI_array_store_calc_size_compacted_get(const BArrayStore *bs);
+
+/**
+ * \param data: Data used to create
+ * \param state_reference: The state to use as a reference when adding the new state,
+ * typically this is the previous state,
+ * however it can be any previously created state from this \a bs.
+ *
+ * \return The new state,
+ * which is used by the caller as a handle to get back the contents of \a data.
+ * This may be removed using #BLI_array_store_state_remove,
+ * otherwise it will be removed with #BLI_array_store_destroy.
+ */
+BArrayState *BLI_array_store_state_add(BArrayStore *bs,
+ const void *data,
+ size_t data_len,
+ const BArrayState *state_reference);
+/**
+ * Remove a state and free any unused #BChunk data.
+ *
+ * The states can be freed in any order.
+ */
+void BLI_array_store_state_remove(BArrayStore *bs, BArrayState *state);
+
+/**
+ * \return the expanded size of the array,
+ * use this to know how much memory to allocate #BLI_array_store_state_data_get's argument.
+ */
+size_t BLI_array_store_state_size_get(const BArrayState *state);
+/**
+ * Fill in existing allocated memory with the contents of \a state.
+ */
+void BLI_array_store_state_data_get(const BArrayState *state, void *data);
+/**
+ * Allocate an array for \a state and return it.
+ */
+void *BLI_array_store_state_data_get_alloc(const BArrayState *state, size_t *r_data_len);
+
+/**
+ * \note Only for tests.
+ */
+bool BLI_array_store_is_valid(BArrayStore *bs);
+
+/* `array_store_rle.cc` */
+
+/**
+ * Return a run-length encoded copy of `data_dec`.
+ *
+ * \param data_dec: The data to encode.
+ * \param data_dec_len: The size of the data to encode.
+ * \param data_enc_extra_size: Allocate extra memory at the beginning of the array.
+ * - This doesn't impact the value of `r_data_enc_len`.
+ * - This must be skipped when decoding.
+ * \param r_data_enc_len: The size of the resulting RLE encoded data.
+ */
+uint8_t *BLI_array_store_rle_encode(const uint8_t *data_dec,
+ size_t data_dec_len,
+ size_t data_enc_extra_size,
+ size_t *r_data_enc_len);
+/**
+ * Decode a run-length encoded array, writing the result into `data_dec_v`.
+ *
+ * \param data_enc: The data to encode (returned by #BLI_array_store_rle_encode).
+ * \param data_enc_len: The size of `data_enc`.
+ * \param data_dec: The destination for the decoded data to be written to.
+ * \param data_dec_len: The size of the destination (as passed to #BLI_array_store_rle_encode).
+ */
+void BLI_array_store_rle_decode(const uint8_t *data_enc,
+ const size_t data_enc_len,
+ void *data_dec_v,
+ const size_t data_dec_len);
+
+} // namespace blender
diff --git a/core/include/BLI_array_store_utils.h b/core/include/BLI_array_store_utils.h
new file mode 100644
index 0000000..e51a5d1
--- /dev/null
+++ b/core/include/BLI_array_store_utils.h
@@ -0,0 +1,34 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include <stddef.h>
+
+namespace blender {
+
+struct BArrayStore;
+
+struct BArrayStore_AtSize {
+ struct BArrayStore **stride_table;
+ int stride_table_len;
+};
+
+struct BArrayStore *BLI_array_store_at_size_ensure(struct BArrayStore_AtSize *bs_stride,
+ int stride,
+ int chunk_size);
+
+struct BArrayStore *BLI_array_store_at_size_get(struct BArrayStore_AtSize *bs_stride, int stride);
+
+void BLI_array_store_at_size_clear(struct BArrayStore_AtSize *bs_stride);
+
+void BLI_array_store_at_size_calc_memory_usage(const struct BArrayStore_AtSize *bs_stride,
+ size_t *r_size_expanded,
+ size_t *r_size_compacted);
+
+} // namespace blender
diff --git a/core/include/BLI_astar.h b/core/include/BLI_astar.h
new file mode 100644
index 0000000..5a9eed5
--- /dev/null
+++ b/core/include/BLI_astar.h
@@ -0,0 +1,150 @@
+/* SPDX-FileCopyrightText: 2014 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ * \brief An implementation of the A* (AStar) algorithm to solve shortest path problem.
+ */
+
+#include "DNA_listBase.h"
+
+#include "BLI_bitmap.h"
+
+namespace blender {
+
+/* -------------------------------------------------------------------- */
+
+struct BLI_AStarGNLink {
+ int nodes[2];
+ float cost;
+
+ void *custom_data;
+};
+
+struct BLI_AStarGNode {
+ ListBaseT<LinkData> neighbor_links;
+
+ void *custom_data;
+};
+
+struct BLI_AStarSolution {
+ /* Final 'most useful' data. */
+ /** Number of steps (i.e. walked links) in path
+ * (nodes num, including start and end, is steps + 1). */
+ int steps;
+ /** Store the path, in reversed order (from destination to source node), as indices. */
+ int *prev_nodes;
+ /** Indices are nodes' ones, as prev_nodes, but they map to relevant link. */
+ BLI_AStarGNLink **prev_links;
+
+ void *custom_data;
+
+ /* Mostly runtime data. */
+ BLI_bitmap *done_nodes;
+ float *g_costs;
+ int *g_steps;
+
+ struct MemArena *mem; /* Memory arena. */
+};
+
+struct BLI_AStarGraph {
+ int node_num;
+ BLI_AStarGNode *nodes;
+
+ void *custom_data;
+
+ struct MemArena *mem; /* Memory arena. */
+};
+
+/**
+ * Initialize a node in A* graph.
+ *
+ * \param custom_data: an opaque pointer attached to this link,
+ * available e.g. to cost callback function.
+ */
+void BLI_astar_node_init(BLI_AStarGraph *as_graph, int node_index, void *custom_data);
+/**
+ * Add a link between two nodes of our A* graph.
+ *
+ * \param cost: The 'length' of the link
+ * (actual distance between two vertices or face centers e.g.).
+ * \param custom_data: An opaque pointer attached to this link,
+ * available e.g. to cost callback function.
+ */
+void BLI_astar_node_link_add(
+ BLI_AStarGraph *as_graph, int node1_index, int node2_index, float cost, void *custom_data);
+/**
+ * \return The index of the other node of given link.
+ */
+int BLI_astar_node_link_other_node(BLI_AStarGNLink *lnk, int idx);
+
+/**
+ * Initialize a solution data for given A* graph. Does not compute anything!
+ *
+ * \param custom_data: an opaque pointer attached to this link, available e.g.
+ * to cost callback function.
+ *
+ * \note BLI_AStarSolution stores nearly all data needed during solution compute.
+ */
+void BLI_astar_solution_init(BLI_AStarGraph *as_graph,
+ BLI_AStarSolution *as_solution,
+ void *custom_data);
+/**
+ * Clear given solution's data, but does not release its memory.
+ * Avoids having to recreate/allocate a memory-arena in loops, e.g.
+ *
+ * \note This *has to be called* between each path solving.
+ */
+void BLI_astar_solution_clear(BLI_AStarSolution *as_solution);
+/**
+ * Release the memory allocated for this solution.
+ */
+void BLI_astar_solution_free(BLI_AStarSolution *as_solution);
+
+/**
+ * Callback computing the current cost (distance) to next node,
+ * and the estimated overall cost to destination node
+ * (A* expects this estimation to always be less or equal than actual shortest path
+ * from next node to destination one).
+ *
+ * \param link: the graph link between current node and next one.
+ * \param node_idx_curr: current node index.
+ * \param node_idx_next: next node index.
+ * \param node_idx_dst: destination node index.
+ */
+using astar_f_cost = float (*)(BLI_AStarGraph *as_graph,
+ BLI_AStarSolution *as_solution,
+ BLI_AStarGNLink *link,
+ int node_idx_curr,
+ int node_idx_next,
+ int node_idx_dst);
+
+/**
+ * Initialize an A* graph. Total number of nodes must be known.
+ *
+ * Nodes might be e.g. vertices, faces, ... etc.
+ *
+ * \param custom_data: an opaque pointer attached to this link,
+ * available e.g. to cost callback function.
+ */
+void BLI_astar_graph_init(BLI_AStarGraph *as_graph, int node_num, void *custom_data);
+void BLI_astar_graph_free(BLI_AStarGraph *as_graph);
+/**
+ * Solve a path in given graph, using given 'cost' callback function.
+ *
+ * \param max_steps: maximum number of nodes the found path may have.
+ * Useful in performance-critical usages.
+ * If no path is found within given steps, returns false too.
+ * \return true if a path was found, false otherwise.
+ */
+bool BLI_astar_graph_solve(BLI_AStarGraph *as_graph,
+ int node_index_src,
+ int node_index_dst,
+ astar_f_cost f_cost_cb,
+ BLI_AStarSolution *r_solution,
+ int max_steps);
+
+} // namespace blender
diff --git a/core/include/BLI_bitmap.h b/core/include/BLI_bitmap.h
new file mode 100644
index 0000000..988e936
--- /dev/null
+++ b/core/include/BLI_bitmap.h
@@ -0,0 +1,150 @@
+/* SPDX-FileCopyrightText: 2012 by Nicholas Bishop. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include "BLI_utildefines.h"
+
+namespace blender {
+
+typedef unsigned int BLI_bitmap;
+
+/* WARNING: the bitmap does not keep track of its own size or check
+ * for out-of-bounds access */
+
+/* internal use */
+/* 2^5 = 32 (bits) */
+#define _BITMAP_POWER 5
+/* 0b11111 */
+#define _BITMAP_MASK 31
+
+/**
+ * Number of blocks needed to hold '_num' bits.
+ */
+#define _BITMAP_NUM_BLOCKS(_num) (((_num) + _BITMAP_MASK) >> _BITMAP_POWER)
+
+/**
+ * Size (in bytes) used to hold '_num' bits.
+ */
+#define BLI_BITMAP_SIZE(_num) ((size_t)(_BITMAP_NUM_BLOCKS(_num)) * sizeof(BLI_bitmap))
+
+/**
+ * Allocate memory for a bitmap with '_num' bits; free with MEM_delete().
+ */
+#define BLI_BITMAP_NEW(_num, _alloc_string) \
+ ((BLI_bitmap *)MEM_new_zeroed(BLI_BITMAP_SIZE(_num), _alloc_string))
+
+/**
+ * Allocate a bitmap on the stack.
+ */
+#define BLI_BITMAP_NEW_ALLOCA(_num) \
+ ((BLI_bitmap *)memset(alloca(BLI_BITMAP_SIZE(_num)), 0, BLI_BITMAP_SIZE(_num)))
+
+/**
+ * Allocate using given MemArena.
+ */
+#define BLI_BITMAP_NEW_MEMARENA(_mem, _num) \
+ (CHECK_TYPE_INLINE(_mem, MemArena *), \
+ ((BLI_bitmap *)BLI_memarena_calloc(_mem, BLI_BITMAP_SIZE(_num))))
+
+/**
+ * Declares a bitmap as a variable.
+ */
+#define BLI_BITMAP_DECLARE(_name, _num) BLI_bitmap _name[_BITMAP_NUM_BLOCKS(_num)] = {}
+
+/**
+ * Get the value of a single bit at '_index'.
+ */
+#define BLI_BITMAP_TEST(_bitmap, _index) \
+ (CHECK_TYPE_ANY(_bitmap, BLI_bitmap *, const BLI_bitmap *), \
+ ((_bitmap)[(_index) >> _BITMAP_POWER] & (1u << ((_index) & _BITMAP_MASK))))
+
+#define BLI_BITMAP_TEST_AND_SET_ATOMIC(_bitmap, _index) \
+ (CHECK_TYPE_ANY(_bitmap, BLI_bitmap *, const BLI_bitmap *), \
+ (atomic_fetch_and_or_uint32((uint32_t *)&(_bitmap)[(_index) >> _BITMAP_POWER], \
+ (1u << ((_index) & _BITMAP_MASK))) & \
+ (1u << ((_index) & _BITMAP_MASK))))
+
+#define BLI_BITMAP_TEST_BOOL(_bitmap, _index) \
+ (CHECK_TYPE_ANY(_bitmap, BLI_bitmap *, const BLI_bitmap *), \
+ (BLI_BITMAP_TEST(_bitmap, _index) != 0))
+
+/**
+ * Set the value of a single bit at '_index'.
+ */
+#define BLI_BITMAP_ENABLE(_bitmap, _index) \
+ (CHECK_TYPE_ANY(_bitmap, BLI_bitmap *, const BLI_bitmap *), \
+ ((_bitmap)[(_index) >> _BITMAP_POWER] |= (1u << ((_index) & _BITMAP_MASK))))
+
+/**
+ * Clear the value of a single bit at '_index'.
+ */
+#define BLI_BITMAP_DISABLE(_bitmap, _index) \
+ (CHECK_TYPE_ANY(_bitmap, BLI_bitmap *, const BLI_bitmap *), \
+ ((_bitmap)[(_index) >> _BITMAP_POWER] &= ~(1u << ((_index) & _BITMAP_MASK))))
+
+/**
+ * Flip the value of a single bit at '_index'.
+ */
+#define BLI_BITMAP_FLIP(_bitmap, _index) \
+ (CHECK_TYPE_ANY(_bitmap, BLI_bitmap *, const BLI_bitmap *), \
+ ((_bitmap)[(_index) >> _BITMAP_POWER] ^= (1u << ((_index) & _BITMAP_MASK))))
+
+/**
+ * Set or clear the value of a single bit at '_index'.
+ */
+#define BLI_BITMAP_SET(_bitmap, _index, _set) \
+ { \
+ CHECK_TYPE(_bitmap, BLI_bitmap *); \
+ if (_set) { \
+ BLI_BITMAP_ENABLE(_bitmap, _index); \
+ } \
+ else { \
+ BLI_BITMAP_DISABLE(_bitmap, _index); \
+ } \
+ } \
+ (void)0
+
+/**
+ * Resize bitmap to have space for '_num' bits.
+ */
+#define BLI_BITMAP_RESIZE(_bitmap, _num) \
+ { \
+ CHECK_TYPE(_bitmap, BLI_bitmap *); \
+ (_bitmap) = (unsigned int *)MEM_realloc_zeroed(_bitmap, BLI_BITMAP_SIZE(_num)); \
+ } \
+ (void)0
+
+/**
+ * Set or clear all bits in the bitmap.
+ */
+void BLI_bitmap_set_all(BLI_bitmap *bitmap, bool set, size_t bits);
+/**
+ * Invert all bits in the bitmap.
+ */
+void BLI_bitmap_flip_all(BLI_bitmap *bitmap, size_t bits);
+/**
+ * Copy all bits from one bitmap to another.
+ */
+void BLI_bitmap_copy_all(BLI_bitmap *dst, const BLI_bitmap *src, size_t bits);
+/**
+ * Combine two bitmaps with boolean AND.
+ */
+void BLI_bitmap_and_all(BLI_bitmap *dst, const BLI_bitmap *src, size_t bits);
+/**
+ * Combine two bitmaps with boolean OR.
+ */
+void BLI_bitmap_or_all(BLI_bitmap *dst, const BLI_bitmap *src, size_t bits);
+
+/**
+ * Find index of the lowest unset bit.
+ * Returns -1 if all the bits are set.
+ */
+int BLI_bitmap_find_first_unset(const BLI_bitmap *bitmap, size_t bits);
+
+} // namespace blender
diff --git a/core/include/BLI_bitmap_draw_2d.h b/core/include/BLI_bitmap_draw_2d.h
new file mode 100644
index 0000000..add1fda
--- /dev/null
+++ b/core/include/BLI_bitmap_draw_2d.h
@@ -0,0 +1,55 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include "BLI_math_vector_types.hh"
+#include "BLI_span.hh"
+
+namespace blender {
+
+/**
+ * Plot a line from \a p1 to \a p2 (inclusive).
+ *
+ * \note For clipped line drawing, see: http://stackoverflow.com/a/40902741/432509
+ */
+void BLI_bitmap_draw_2d_line_v2v2i(const int p1[2],
+ const int p2[2],
+ bool (*callback)(int, int, void *),
+ void *user_data);
+
+/**
+ * \note Unclipped (clipped version can be added if needed).
+ */
+void BLI_bitmap_draw_2d_tri_v2i(const int p1[2],
+ const int p2[2],
+ const int p3[2],
+ void (*callback)(int x, int x_end, int y, void *),
+ void *user_data);
+
+/**
+ * Draws a filled polygon with support for self intersections.
+ *
+ * \param callback: Takes the x, y coords and x-span (\a x_end is not inclusive),
+ * note that \a x_end will always be greater than \a x, so we can use:
+ *
+ * \code{.c}
+ * do {
+ * func(x, y);
+ * } while (++x != x_end);
+ * \endcode
+ */
+void BLI_bitmap_draw_2d_poly_v2i_n(int xmin,
+ int ymin,
+ int xmax,
+ int ymax,
+ Span<int2> verts,
+ void (*callback)(int x, int x_end, int y, void *),
+ void *user_data);
+
+} // namespace blender
diff --git a/core/include/BLI_boxpack_2d.h b/core/include/BLI_boxpack_2d.h
new file mode 100644
index 0000000..aca2c8a
--- /dev/null
+++ b/core/include/BLI_boxpack_2d.h
@@ -0,0 +1,74 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include "DNA_listBase.h"
+
+namespace blender {
+
+/* Box Packer */
+
+struct BoxPack {
+ float x;
+ float y;
+ float w;
+ float h;
+
+ /* Verts this box uses
+ * (BL,TR,TL,BR) / 0,1,2,3 */
+ struct BoxVert *v[4];
+
+ int index;
+};
+
+/**
+ * Main box-packing function accessed from other functions
+ * This sets boxes x,y to positive values, sorting from 0,0 outwards.
+ * There is no limit to the space boxes may take, only that they will be packed
+ * tightly into the lower left hand corner (0,0)
+ *
+ * \param box_array: a pre-allocated array of boxes.
+ * only the 'box->x' and 'box->y' are set, 'box->w' and 'box->h' are used,
+ * 'box->index' is not used at all, the only reason its there
+ * is that the box array is sorted by area and programs need to be able
+ * to have some way of writing the boxes back to the original data.
+ * \param len: the number of boxes in the array.
+ * \param sort_boxes: Sort `box_array` before packing.
+ * \param r_tot_x, r_tot_y: set so you can normalize the data.
+ */
+void BLI_box_pack_2d(
+ BoxPack *boxarray, unsigned int len, bool sort_boxes, float *r_tot_x, float *r_tot_y);
+
+struct FixedSizeBoxPack {
+ struct FixedSizeBoxPack *next, *prev;
+ int x, y;
+ int w, h;
+};
+
+/**
+ * Packs boxes into a fixed area.
+ *
+ * Boxes and packed are linked lists containing structs that can be cast to
+ * #FixedSizeBoxPack (i.e. contains a #FixedSizeBoxPack as its first element).
+ * Boxes that were packed successfully are placed into *packed and removed from *boxes.
+ *
+ * The algorithm is a simplified version of https://github.com/TeamHypersomnia/rectpack2D.
+ * Better ones could be used, but for the current use case (packing Image tiles into GPU
+ * textures) this is fine.
+ *
+ * Note that packing efficiency depends on the order of the input boxes. Generally speaking,
+ * larger boxes should come first, though how exactly size is best defined (e.g. area, perimeter)
+ * depends on the particular application.
+ */
+void BLI_box_pack_2d_fixedarea(ListBaseT<FixedSizeBoxPack> *boxes,
+ int width,
+ int height,
+ ListBaseT<FixedSizeBoxPack> *packed);
+
+} // namespace blender
diff --git a/core/include/BLI_console.h b/core/include/BLI_console.h
new file mode 100644
index 0000000..02431e9
--- /dev/null
+++ b/core/include/BLI_console.h
@@ -0,0 +1,18 @@
+/* SPDX-FileCopyrightText: 2018 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ * \brief Set of utility functions and constants to work with consoles.
+ */
+
+/* Format string where one could BLI_snprintf() R, G and B values
+ * and get proper marker to start colored output in the console.
+ */
+#define TRUECOLOR_ANSI_COLOR_FORMAT "\x1b[38;2;%d;%d;%dm"
+
+/* Marker which indicates that colored output is finished. */
+#define TRUECOLOR_ANSI_COLOR_FINISH "\x1b[0m"
diff --git a/core/include/BLI_dial_2d.h b/core/include/BLI_dial_2d.h
new file mode 100644
index 0000000..7e208fb
--- /dev/null
+++ b/core/include/BLI_dial_2d.h
@@ -0,0 +1,45 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ *
+ * \note dials act similar to old rotation based phones and output an angle.
+ *
+ * They just are initialized with the center of the dial and a threshold value as input.
+ *
+ * When the distance of the current position of the dial from the center
+ * exceeds the threshold, this position is used to calculate the initial direction.
+ * After that, the angle from the initial direction is calculated based on
+ * current and previous directions of the digit, and returned to the user.
+ *
+ * Usage examples:
+ *
+ * \code{.c}
+ * float start_position[2] = {0.0f, 0.0f};
+ * float current_position[2];
+ * float threshold = 0.5f;
+ * float angle;
+ * Dial *dial;
+ *
+ * dial = BLI_dial_init(start_position, threshold);
+ *
+ * angle = BLI_dial_angle(dial, current_position);
+ *
+ * BLI_dial_free(dial);
+ * \endcode
+ */
+
+namespace blender {
+
+struct Dial;
+
+Dial *BLI_dial_init(const float start_position[2], float threshold);
+void BLI_dial_free(Dial *dial);
+
+float BLI_dial_angle(Dial *dial, const float current_position[2]);
+
+} // namespace blender
diff --git a/core/include/BLI_easing.h b/core/include/BLI_easing.h
new file mode 100644
index 0000000..9071d35
--- /dev/null
+++ b/core/include/BLI_easing.h
@@ -0,0 +1,51 @@
+/* SPDX-FileCopyrightText: 2001 Robert Penner. All rights reserved.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+namespace blender {
+
+float BLI_easing_back_ease_in(
+ float time, float begin, float change, float duration, float overshoot);
+float BLI_easing_back_ease_out(
+ float time, float begin, float change, float duration, float overshoot);
+float BLI_easing_back_ease_in_out(
+ float time, float begin, float change, float duration, float overshoot);
+float BLI_easing_bounce_ease_out(float time, float begin, float change, float duration);
+float BLI_easing_bounce_ease_in(float time, float begin, float change, float duration);
+float BLI_easing_bounce_ease_in_out(float time, float begin, float change, float duration);
+float BLI_easing_circ_ease_in(float time, float begin, float change, float duration);
+float BLI_easing_circ_ease_out(float time, float begin, float change, float duration);
+float BLI_easing_circ_ease_in_out(float time, float begin, float change, float duration);
+float BLI_easing_cubic_ease_in(float time, float begin, float change, float duration);
+float BLI_easing_cubic_ease_out(float time, float begin, float change, float duration);
+float BLI_easing_cubic_ease_in_out(float time, float begin, float change, float duration);
+float BLI_easing_elastic_ease_in(
+ float time, float begin, float change, float duration, float amplitude, float period);
+float BLI_easing_elastic_ease_out(
+ float time, float begin, float change, float duration, float amplitude, float period);
+float BLI_easing_elastic_ease_in_out(
+ float time, float begin, float change, float duration, float amplitude, float period);
+float BLI_easing_expo_ease_in(float time, float begin, float change, float duration);
+float BLI_easing_expo_ease_out(float time, float begin, float change, float duration);
+float BLI_easing_expo_ease_in_out(float time, float begin, float change, float duration);
+float BLI_easing_linear_ease(float time, float begin, float change, float duration);
+float BLI_easing_quad_ease_in(float time, float begin, float change, float duration);
+float BLI_easing_quad_ease_out(float time, float begin, float change, float duration);
+float BLI_easing_quad_ease_in_out(float time, float begin, float change, float duration);
+float BLI_easing_quart_ease_in(float time, float begin, float change, float duration);
+float BLI_easing_quart_ease_out(float time, float begin, float change, float duration);
+float BLI_easing_quart_ease_in_out(float time, float begin, float change, float duration);
+float BLI_easing_quint_ease_in(float time, float begin, float change, float duration);
+float BLI_easing_quint_ease_out(float time, float begin, float change, float duration);
+float BLI_easing_quint_ease_in_out(float time, float begin, float change, float duration);
+float BLI_easing_sine_ease_in(float time, float begin, float change, float duration);
+float BLI_easing_sine_ease_out(float time, float begin, float change, float duration);
+float BLI_easing_sine_ease_in_out(float time, float begin, float change, float duration);
+
+} // namespace blender
diff --git a/core/include/BLI_expr_pylike_eval.h b/core/include/BLI_expr_pylike_eval.h
new file mode 100644
index 0000000..13b6970
--- /dev/null
+++ b/core/include/BLI_expr_pylike_eval.h
@@ -0,0 +1,61 @@
+/* SPDX-FileCopyrightText: 2018 Blender Authors, Alexander Gavrilov. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+namespace blender {
+
+/** Opaque structure containing pre-parsed data for evaluation. */
+struct ExprPyLike_Parsed;
+
+/** Expression evaluation return code. */
+enum eExprPyLike_EvalStatus {
+ EXPR_PYLIKE_SUCCESS = 0,
+ /* Computation errors; result is still set, but may be NaN */
+ EXPR_PYLIKE_DIV_BY_ZERO,
+ EXPR_PYLIKE_MATH_ERROR,
+ /* Expression dependent errors or bugs; result is 0 */
+ EXPR_PYLIKE_INVALID,
+ EXPR_PYLIKE_FATAL_ERROR,
+};
+
+/**
+ * Free the parsed data; NULL argument is ok.
+ */
+void BLI_expr_pylike_free(struct ExprPyLike_Parsed *expr);
+/**
+ * Check if the parsing result is valid for evaluation.
+ */
+bool BLI_expr_pylike_is_valid(const struct ExprPyLike_Parsed *expr);
+/**
+ * Check if the parsed expression always evaluates to the same value.
+ */
+bool BLI_expr_pylike_is_constant(const struct ExprPyLike_Parsed *expr);
+/**
+ * Check if the parsed expression uses the parameter with the given index.
+ */
+bool BLI_expr_pylike_is_using_param(const struct ExprPyLike_Parsed *expr, int index);
+/**
+ * Compile the expression and return the result.
+ *
+ * Parse the expression for evaluation later.
+ * Returns non-NULL even on failure; use is_valid to check.
+ */
+ExprPyLike_Parsed *BLI_expr_pylike_parse(const char *expression,
+ const char **param_names,
+ int param_names_len);
+/**
+ * Evaluate the expression with the given parameters.
+ * The order and number of parameters must match the names given to parse.
+ */
+eExprPyLike_EvalStatus BLI_expr_pylike_eval(struct ExprPyLike_Parsed *expr,
+ const double *param_values,
+ int param_values_len,
+ double *r_result);
+
+} // namespace blender
diff --git a/core/include/BLI_fileops.h b/core/include/BLI_fileops.h
new file mode 100644
index 0000000..ad81764
--- /dev/null
+++ b/core/include/BLI_fileops.h
@@ -0,0 +1,473 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup bli
+ * \brief File and directory operations.
+ */
+
+#pragma once
+
+#include <stdint.h>
+#include <stdio.h>
+#include <sys/stat.h>
+
+/* for size_t (needed on windows) */
+#include <stddef.h>
+
+#include <limits.h> /* for PATH_MAX */
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_enum_flags.hh"
+#include "BLI_fileops_types.h"
+
+namespace blender {
+
+#ifndef PATH_MAX
+# define PATH_MAX 4096
+#endif
+
+/* -------------------------------------------------------------------- */
+/** \name Common
+ * \{ */
+
+/**
+ * Returns true if the path (file or directory) exists.
+ */
+bool BLI_exists(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+
+/**
+ * Returns the st_mode from stat-ing the specified path name, or 0 if stat fails
+ * (most likely doesn't exist or no access).
+ */
+int BLI_file_stat_mode(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+
+/**
+ * \return 0 on success.
+ */
+int BLI_copy(const char *path_src, const char *path_dst) ATTR_NONNULL();
+/**
+ * When `path_src` points to a directory, moves all its contents into `path_dst`,
+ * else rename `path_src` itself to `path_dst`.
+ * \return 0 on success.
+ */
+int BLI_path_move(const char *path_src, const char *path_dst) ATTR_NONNULL();
+
+/**
+ * Rename a file or directory, unless `to` already exists.
+ *
+ * \note This matches Windows `rename` logic, _not_ Unix one. It does not allow to replace an
+ * existing target. Use #BLI_rename_overwrite instead if existing file should be replaced.
+ *
+ * \param from: The path to rename from (return failure if it does not exist).
+ * \param to: The destination path.
+ * \return zero on success (matching 'rename' behavior).
+ */
+int BLI_rename(const char *from, const char *to) ATTR_NONNULL();
+
+/**
+ * Rename a file or directory, replacing target `to` path if it exists.
+ *
+ * \note This matches Unix `rename` logic. It does allow to replace an existing target. Use
+ * #BLI_rename instead if existing file should never be replaced. However, if `to` is an existing,
+ * non-empty directory, the operation will fail.
+ *
+ * \note There is still no feature-parity between behaviors on Windows and Unix, in case the target
+ * `to` exists and is opened by some process in the system:
+ * - On Unix, it will typically succeed
+ * (see https://man7.org/linux/man-pages/man2/rename.2.html for details).
+ * - On Windows, it will always fail
+ * (see https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw for
+ * details).
+ *
+ * \warning Due to internal limitation/implementation, on Windows, in case paths point to
+ * directories, it's up to the caller to ensure that `from` and `to` are not the same directory.
+ * Since `to` is being deleted to make room for `from`, this will result in `from` being deleted as
+ * well.
+ *
+ * See #BLI_path_move to move directories.
+ *
+ * \param from: The path to rename from (return failure if it does not exist).
+ * \param to: The destination path.
+ * This will be deleted if it already exists, unless it's a directory which will fail.
+ * \return zero on success (matching 'rename' behavior).
+ */
+int BLI_rename_overwrite(const char *from, const char *to) ATTR_NONNULL();
+/**
+ * Deletes the specified file or directory.
+ *
+ * \param dir: Delete an empty directory instead of a file.
+ * The value is ignored when `recursive` is true but should true to make the intention clear.
+ * If the directory is not empty, delete fails.
+ * \param recursive: Recursively delete files including `path` which may be a directory of a file.
+ *
+ * \note Symbolic-Links for (UNIX) behave as follows:
+ * - Never followed, treated as regular files.
+ * - Links are removed, not the files/directories they references.
+ * - When `path` itself links to another directory,
+ * deleting `path` behaves as if a regular file is being deleted.
+ * - If `dir` is true and `path` is a link, delete fails.
+ *
+ * \return zero on success (matching 'remove' behavior).
+ */
+int BLI_delete(const char *path, bool dir, bool recursive) ATTR_NONNULL();
+/**
+ * Soft deletes the specified file or directory (depending on dir) by moving the files to the
+ * recycling bin, optionally doing recursive delete of directory contents.
+ *
+ * \return zero on success (matching 'remove' behavior).
+ */
+int BLI_delete_soft(const char *filepath, const char **r_error_message) ATTR_NONNULL();
+#if 0 /* Unused */
+int BLI_create_symlink(const char *path, const char *path_dst) ATTR_NONNULL();
+#endif
+
+/* Keep in sync with the definition of struct `direntry` in `BLI_fileops_types.h`. */
+#ifdef WIN32
+# if defined(_MSC_VER)
+typedef struct _stat64 BLI_stat_t;
+# else
+typedef struct _stat BLI_stat_t;
+# endif
+#else
+typedef struct stat BLI_stat_t;
+#endif
+
+int BLI_fstat(int fd, BLI_stat_t *buffer) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+int BLI_stat(const char *path, BLI_stat_t *buffer) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+int64_t BLI_ftell(FILE *stream) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+int BLI_fseek(FILE *stream, int64_t offset, int whence);
+int64_t BLI_lseek(int fd, int64_t offset, int whence);
+
+#ifdef WIN32
+int BLI_wstat(const wchar_t *path, BLI_stat_t *buffer);
+#endif
+
+enum eFileAttributes {
+ FILE_ATTR_READONLY = 1 << 0, /* Read-only or Immutable. */
+ FILE_ATTR_HIDDEN = 1 << 1, /* Hidden or invisible. */
+ FILE_ATTR_SYSTEM = 1 << 2, /* Used by the Operating System. */
+ FILE_ATTR_ARCHIVE = 1 << 3, /* Marked as archived. */
+ FILE_ATTR_COMPRESSED = 1 << 4, /* Compressed. */
+ FILE_ATTR_ENCRYPTED = 1 << 5, /* Encrypted. */
+ FILE_ATTR_RESTRICTED = 1 << 6, /* Protected by OS. */
+ FILE_ATTR_TEMPORARY = 1 << 7, /* Used for temporary storage. */
+ FILE_ATTR_SPARSE_FILE = 1 << 8, /* Sparse File. */
+ FILE_ATTR_OFFLINE = 1 << 9, /* Contents available after a short delay. */
+ FILE_ATTR_ALIAS = 1 << 10, /* Mac Alias or Windows LNK. File-based redirection. */
+ FILE_ATTR_REPARSE_POINT = 1 << 11, /* File has associated re-parse point. */
+ FILE_ATTR_SYMLINK = 1 << 12, /* Reference to another file. */
+ FILE_ATTR_JUNCTION_POINT = 1 << 13, /* Folder Symbolic-link. */
+ FILE_ATTR_MOUNT_POINT = 1 << 14, /* Volume mounted as a folder. */
+ FILE_ATTR_HARDLINK = 1 << 15, /* Duplicated directory entry. */
+};
+ENUM_OPERATORS(eFileAttributes);
+
+#define FILE_ATTR_ANY_LINK \
+ (FILE_ATTR_ALIAS | FILE_ATTR_REPARSE_POINT | FILE_ATTR_SYMLINK | FILE_ATTR_JUNCTION_POINT | \
+ FILE_ATTR_MOUNT_POINT | FILE_ATTR_HARDLINK)
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name External File Operations
+ * \{ */
+
+enum FileExternalOperation {
+ FILE_EXTERNAL_OPERATION_OPEN = 1,
+ FILE_EXTERNAL_OPERATION_FOLDER_OPEN,
+ /* Following are Windows-only: */
+ FILE_EXTERNAL_OPERATION_EDIT,
+ FILE_EXTERNAL_OPERATION_NEW,
+ FILE_EXTERNAL_OPERATION_FIND,
+ FILE_EXTERNAL_OPERATION_SHOW,
+ FILE_EXTERNAL_OPERATION_PLAY,
+ FILE_EXTERNAL_OPERATION_BROWSE,
+ FILE_EXTERNAL_OPERATION_PREVIEW,
+ FILE_EXTERNAL_OPERATION_PRINT,
+ FILE_EXTERNAL_OPERATION_INSTALL,
+ FILE_EXTERNAL_OPERATION_RUNAS,
+ FILE_EXTERNAL_OPERATION_PROPERTIES,
+ FILE_EXTERNAL_OPERATION_FOLDER_FIND,
+ FILE_EXTERNAL_OPERATION_FOLDER_CMD,
+};
+
+bool BLI_file_external_operation_supported(const char *filepath, FileExternalOperation operation);
+bool BLI_file_external_operation_execute(const char *filepath, FileExternalOperation operation);
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Directories
+ * \{ */
+
+struct direntry;
+
+/**
+ * Does the specified path point to a directory?
+ * \note Would be better in `fileops.cc` except that it needs `stat.h` so add here.
+ */
+bool BLI_is_dir(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+/**
+ * Does the specified path point to a non-directory?
+ */
+bool BLI_is_file(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+/**
+ * \return true on success (i.e. given path now exists on FS), false otherwise.
+ */
+bool BLI_dir_create_recursive(const char *dirname) ATTR_NONNULL();
+/**
+ * Returns the number of free bytes on the volume containing the specified path.
+ *
+ * \note Not actually used anywhere.
+ */
+double BLI_dir_free_space(const char *dir) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+/**
+ * Copies the current working directory into *dir (max size maxncpy), and
+ * returns a pointer to same.
+ *
+ * \note can return NULL when the size is not big enough
+ */
+char *BLI_current_working_dir(char *dir, size_t maxncpy) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+
+/**
+ * Get the user's home directory, i.e.
+ * - Unix: `$HOME` or #passwd::pw_dir.
+ * - Windows: `%userprofile%`
+ *
+ * \return The home directory or null when it cannot be accessed.
+ *
+ * \note By convention, failure to access home means any derived directories fail as well
+ * instead of attempting to create a fallback such as `/`, `/tmp`, `C:\` ... etc.
+ * Although there may be rare cases where a fallback is appropriate.
+ */
+const char *BLI_dir_home();
+
+eFileAttributes BLI_file_attributes(const char *path);
+/**
+ * Changes the current working directory to the provided path.
+ *
+ * Usage of this function is strongly discouraged as it is not thread safe. It will likely cause
+ * issues if there is an operation on another thread that does not expect the current working
+ * directory to change. This has been added to support USDZ export, which has a problematic
+ * "feature" described in this issue #99807. It will be removed if it is possible to resolve
+ * that issue upstream in the USD library.
+ *
+ * \return true on success, false otherwise.
+ */
+bool BLI_change_working_dir(const char *dir);
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name File-List
+ * \{ */
+
+/**
+ * Scans the contents of the directory named `dirname`, and allocates and fills in an
+ * array of entries describing them in `r_filelist`.
+ *
+ * \return The length of `r_filelist` array.
+ */
+unsigned int BLI_filelist_dir_contents(const char *dirname, struct direntry **r_filelist);
+/**
+ * Deep-duplicate of a single direntry.
+ */
+void BLI_filelist_entry_duplicate(struct direntry *dst, const struct direntry *src);
+/**
+ * Deep-duplicate of a #direntry array including the array itself.
+ */
+void BLI_filelist_duplicate(struct direntry **dest_filelist,
+ struct direntry *const src_filelist,
+ unsigned int nrentries);
+/**
+ * Frees storage for a single direntry, not the direntry itself.
+ */
+void BLI_filelist_entry_free(struct direntry *entry);
+/**
+ * Frees storage for an array of #direntry, including the array itself.
+ */
+void BLI_filelist_free(struct direntry *filelist, unsigned int nrentries);
+
+/**
+ * Convert given entry's size into human-readable strings.
+ */
+void BLI_filelist_entry_size_to_string(const struct stat *st,
+ uint64_t st_size_fallback,
+ bool compact,
+ char r_size[FILELIST_DIRENTRY_SIZE_LEN]);
+/**
+ * Convert given entry's modes into human-readable strings.
+ */
+void BLI_filelist_entry_mode_to_string(const struct stat *st,
+ bool compact,
+ char r_mode1[FILELIST_DIRENTRY_MODE_LEN],
+ char r_mode2[FILELIST_DIRENTRY_MODE_LEN],
+ char r_mode3[FILELIST_DIRENTRY_MODE_LEN]);
+/**
+ * Convert given entry's owner into human-readable strings.
+ */
+void BLI_filelist_entry_owner_to_string(const struct stat *st,
+ bool compact,
+ char r_owner[FILELIST_DIRENTRY_OWNER_LEN]);
+/**
+ * Convert given entry's time into human-readable strings.
+ *
+ * \param r_is_today: optional, returns true if the date matches today's.
+ * \param r_is_yesterday: optional, returns true if the date matches yesterday's.
+ */
+void BLI_filelist_entry_datetime_to_string(const struct stat *st,
+ int64_t ts,
+ bool compact,
+ char r_time[FILELIST_DIRENTRY_TIME_LEN],
+ char r_date[FILELIST_DIRENTRY_DATE_LEN],
+ bool *r_is_today,
+ bool *r_is_yesterday);
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Files
+ * \{ */
+
+FILE *BLI_fopen(const char *filepath, const char *mode) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+void *BLI_gzopen(const char *filepath, const char *mode) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+int BLI_open(const char *filepath, int oflag, int pmode) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+int BLI_access(const char *filepath, int mode) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+
+/**
+ * A version of `read` with the following differences:
+ * - continues reading until failure or the requested size is met.
+ * - Reads `size_t` bytes instead of `int` on WIN32.
+ * \return the number of bytes read.
+ */
+int64_t BLI_read(int fd, void *buf, size_t nbytes);
+
+/**
+ * Returns true if the file with the specified name can be written.
+ * This implementation uses access(2), which makes the check according
+ * to the real UID and GID of the process, not its effective UID and GID.
+ * This shouldn't matter for Blender, which is not going to run privileged anyway.
+ */
+bool BLI_file_is_writable(const char *filepath) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+/**
+ * Creates the file with nothing in it, or updates its last-modified date if it already exists.
+ * Returns true if successful (like the unix touch command).
+ */
+bool BLI_file_touch(const char *filepath) ATTR_NONNULL(1);
+/**
+ * Ensures that the parent directory of `filepath` exists.
+ *
+ * \return true on success (i.e. given path now exists on file-system), false otherwise.
+ */
+bool BLI_file_ensure_parent_dir_exists(const char *filepath) ATTR_NONNULL(1);
+
+/**
+ * Return alias/shortcut file target.
+ * \param filepath: The source of the alias.
+ * \param r_targetpath: Buffer for the target path an alias points to.
+ *
+ * \return true when an alias was found and set.
+ *
+ * \note This is only used on APPLE/WIN32.
+ */
+bool BLI_file_alias_target(const char *filepath,
+ char r_targetpath[/*FILE_MAXDIR*/ 768]) ATTR_WARN_UNUSED_RESULT;
+
+bool BLI_file_magic_is_gzip(const char header[4]);
+
+size_t BLI_file_zstd_from_mem_at_pos(void *buf,
+ size_t len,
+ FILE *file,
+ size_t file_offset,
+ int compression_level) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+size_t BLI_file_unzstd_to_mem_at_pos(void *buf, size_t len, FILE *file, size_t file_offset)
+ ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+bool BLI_file_magic_is_zstd(const char header[4]);
+
+/**
+ * Returns the file size of an opened file descriptor or `size_t(-1)` on failure.
+ */
+size_t BLI_file_descriptor_size(int file) ATTR_WARN_UNUSED_RESULT;
+/**
+ * Returns the size of a file or `size_t(-1)` on failure..
+ */
+size_t BLI_file_size(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+
+/**
+ * Compare if one was last modified before the other.
+ *
+ * \return true when is `file1` older than `file2`.
+ */
+bool BLI_file_older(const char *file1, const char *file2) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+
+/**
+ * Reads the contents of a text file.
+ *
+ * \return the lines in a linked list (an empty list when file reading fails).
+ */
+struct LinkNode *BLI_file_read_as_lines(const char *filepath) ATTR_WARN_UNUSED_RESULT
+ ATTR_NONNULL();
+
+/**
+ * Read the contents of `fp`, returning the result as a buffer or null when it can't be read.
+ *
+ * \param r_size: The size of the file contents read into the buffer (excluding `pad_bytes`).
+ */
+void *BLI_file_read_data_as_mem_from_handle(FILE *fp,
+ bool read_size_exact,
+ size_t pad_bytes,
+ size_t *r_size);
+
+char *BLI_file_read_text_as_mem(const char *filepath, size_t pad_bytes, size_t *r_size);
+/**
+ * Return the text file data with:
+ *
+ * - Newlines replaced with '\0'.
+ * - Optionally trim white-space, replacing trailing <space> & <tab> with '\0'.
+ *
+ * This is an alternative to using #BLI_file_read_as_lines,
+ * allowing us to loop over lines without converting it into a linked list
+ * with individual allocations.
+ *
+ * \param trim_trailing_space: Replace trailing spaces & tabs with nil.
+ * This arguments prevents the caller from counting blank lines (if that's important).
+ * \param pad_bytes: When this is non-zero, the first byte is set to nil,
+ * to simplify parsing the file.
+ * It's recommended to pass in 1, so all text is nil terminated.
+ * \param r_size: The size of the file contents read into the buffer (excluding `pad_bytes`).
+ *
+ * Example looping over lines:
+ *
+ * \code{.c}
+ * size_t data_len;
+ * char *data = BLI_file_read_text_as_mem_with_newline_as_nil(filepath, true, 1, &data_len);
+ * char *data_end = data + data_len;
+ * for (char *line = data; line != data_end; line = strlen(line) + 1) {
+ * printf("line='%s'\n", line);
+ * }
+ * \endcode
+ */
+char *BLI_file_read_text_as_mem_with_newline_as_nil(const char *filepath,
+ bool trim_trailing_space,
+ size_t pad_bytes,
+ size_t *r_size);
+void *BLI_file_read_binary_as_mem(const char *filepath, size_t pad_bytes, size_t *r_size);
+/**
+ * Frees memory from a previous call to #BLI_file_read_as_lines.
+ */
+void BLI_file_free_lines(struct LinkNode *lines);
+
+/* This weirdo pops up in two places. */
+#if !defined(WIN32)
+# ifndef O_BINARY
+# define O_BINARY 0
+# endif
+#else
+void BLI_get_short_name(char short_name[256], const char *filepath);
+#endif
+
+/** \} */
+
+} // namespace blender
diff --git a/core/include/BLI_fileops_types.h b/core/include/BLI_fileops_types.h
new file mode 100644
index 0000000..f2b79da
--- /dev/null
+++ b/core/include/BLI_fileops_types.h
@@ -0,0 +1,46 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ * \brief Some types for dealing with directories.
+ */
+
+#include <sys/stat.h>
+
+namespace blender {
+
+#if defined(WIN32)
+typedef unsigned int mode_t;
+#endif
+
+#define FILELIST_DIRENTRY_SIZE_LEN 16
+#define FILELIST_DIRENTRY_MODE_LEN 4
+#define FILELIST_DIRENTRY_OWNER_LEN 16
+#define FILELIST_DIRENTRY_TIME_LEN 8
+#define FILELIST_DIRENTRY_DATE_LEN 16
+
+struct direntry {
+ mode_t type;
+ const char *relname;
+ const char *path;
+#ifdef WIN32 /* keep in sync with the definition of BLI_stat_t in BLI_fileops.h */
+# if defined(_MSC_VER)
+ struct _stat64 s;
+# else
+ struct _stat s;
+# endif
+#else
+ struct stat s;
+#endif
+};
+
+struct dirlink {
+ struct dirlink *next, *prev;
+ char *name;
+};
+
+} // namespace blender
diff --git a/core/include/BLI_filereader.h b/core/include/BLI_filereader.h
new file mode 100644
index 0000000..8138c3b
--- /dev/null
+++ b/core/include/BLI_filereader.h
@@ -0,0 +1,63 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup bli
+ * \brief Wrapper for reading from various sources (e.g. raw files, compressed files, memory...).
+ */
+
+#pragma once
+
+#ifdef WIN32
+# include "BLI_winstuff.h"
+#else
+# include <sys/types.h>
+#endif
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_utildefines.h"
+
+namespace blender {
+
+#if defined(_MSC_VER) || defined(__APPLE__) || defined(__HAIKU__) || defined(__NetBSD__) || \
+ defined(__OpenBSD__)
+typedef int64_t off64_t;
+#endif
+
+struct FileReader;
+
+typedef int64_t (*FileReaderReadFn)(struct FileReader *reader, void *buffer, size_t size);
+typedef off64_t (*FileReaderSeekFn)(struct FileReader *reader, off64_t offset, int whence);
+typedef void (*FileReaderCloseFn)(struct FileReader *reader);
+
+/** General structure for all #FileReaders, implementations add custom fields at the end. */
+struct FileReader {
+ FileReaderReadFn read;
+ FileReaderSeekFn seek;
+ FileReaderCloseFn close;
+
+ off64_t offset;
+};
+
+/* Functions for opening the various types of FileReader.
+ * They either succeed and return a valid FileReader, or fail and return NULL.
+ *
+ * If a FileReader is created, it has to be cleaned up and freed by calling its close()
+ * function unless another FileReader has taken ownership - for example, `Zstd` & `Gzip`
+ * take over the base FileReader and will clean it up when their clean() is called.
+ */
+
+/** Create #FileReader from raw file descriptor. */
+FileReader *BLI_filereader_new_file(int filedes) ATTR_WARN_UNUSED_RESULT;
+/** Create #FileReader from raw file descriptor using memory-mapped IO. */
+FileReader *BLI_filereader_new_mmap(int filedes) ATTR_WARN_UNUSED_RESULT;
+/** Create #FileReader from a region of memory. */
+FileReader *BLI_filereader_new_memory(const void *data, size_t len) ATTR_WARN_UNUSED_RESULT
+ ATTR_NONNULL();
+/** Create #FileReader from applying `Zstd` decompression on an underlying file. */
+FileReader *BLI_filereader_new_zstd(FileReader *base) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+/** Create #FileReader from applying `Gzip` decompression on an underlying file. */
+FileReader *BLI_filereader_new_gzip(FileReader *base) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+
+} // namespace blender
diff --git a/core/include/BLI_hash.h b/core/include/BLI_hash.h
new file mode 100644
index 0000000..48a12a0
--- /dev/null
+++ b/core/include/BLI_hash.h
@@ -0,0 +1,110 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include "BLI_utildefines.h"
+
+namespace blender {
+
+/**
+ * Jenkins Lookup3 Hash Functions.
+ * Source: http://burtleburtle.net/bob/c/lookup3.c
+ */
+
+#define rot(x, k) (((x) << (k)) | ((x) >> (32 - (k))))
+#define final(a, b, c) \
+ { \
+ c ^= b; \
+ c -= rot(b, 14); \
+ a ^= c; \
+ a -= rot(c, 11); \
+ b ^= a; \
+ b -= rot(a, 25); \
+ c ^= b; \
+ c -= rot(b, 16); \
+ a ^= c; \
+ a -= rot(c, 4); \
+ b ^= a; \
+ b -= rot(a, 14); \
+ c ^= b; \
+ c -= rot(b, 24); \
+ } \
+ ((void)0)
+
+BLI_INLINE unsigned int BLI_hash_int_3d(unsigned int kx, unsigned int ky, unsigned int kz)
+{
+ unsigned int a, b, c;
+ a = b = c = 0xdeadbeef + (3 << 2) + 13;
+
+ c += kz;
+ b += ky;
+ a += kx;
+ final(a, b, c);
+
+ return c;
+}
+
+BLI_INLINE unsigned int BLI_hash_int_2d(unsigned int kx, unsigned int ky)
+{
+ unsigned int a, b, c;
+
+ a = b = c = 0xdeadbeef + (2 << 2) + 13;
+ a += kx;
+ b += ky;
+
+ final(a, b, c);
+
+ return c;
+}
+
+#undef final
+#undef rot
+
+BLI_INLINE unsigned int BLI_hash_string(const char *str)
+{
+ unsigned int i = 0, c;
+
+ while ((c = *str++)) {
+ i = i * 37 + c;
+ }
+ return i;
+}
+
+BLI_INLINE float BLI_hash_int_2d_to_float(uint32_t kx, uint32_t ky)
+{
+ return float(BLI_hash_int_2d(kx, ky)) / float(0xFFFFFFFFu);
+}
+
+BLI_INLINE float BLI_hash_int_3d_to_float(uint32_t kx, uint32_t ky, uint32_t kz)
+{
+ return float(BLI_hash_int_3d(kx, ky, kz)) / float(0xFFFFFFFFu);
+}
+
+BLI_INLINE unsigned int BLI_hash_int(unsigned int k)
+{
+ return BLI_hash_int_2d(k, 0);
+}
+
+BLI_INLINE float BLI_hash_int_01(unsigned int k)
+{
+ return float(BLI_hash_int(k)) * (1.0f / float(0xFFFFFFFF));
+}
+
+BLI_INLINE void BLI_hash_pointer_to_color(const void *ptr, int *r, int *g, int *b)
+{
+ size_t val = reinterpret_cast<size_t>(ptr);
+ const size_t hash_a = BLI_hash_int(val & 0x0000ffff);
+ const size_t hash_b = BLI_hash_int(uint((val & 0xffff0000) >> 16));
+ const size_t hash = hash_a ^ (hash_b + 0x9e3779b9 + (hash_a << 6) + (hash_a >> 2));
+ *r = (hash & 0xff0000) >> 16;
+ *g = (hash & 0x00ff00) >> 8;
+ *b = hash & 0x0000ff;
+}
+
+} // namespace blender
diff --git a/core/include/BLI_heap.h b/core/include/BLI_heap.h
new file mode 100644
index 0000000..a8483b3
--- /dev/null
+++ b/core/include/BLI_heap.h
@@ -0,0 +1,79 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ * \brief A min-heap / priority queue ADT
+ */
+
+#include <stdbool.h>
+#include <stddef.h>
+
+#include "BLI_compiler_attrs.h"
+
+namespace blender {
+
+struct Heap;
+struct HeapNode;
+
+typedef void (*HeapFreeFP)(void *ptr);
+
+/**
+ * Creates a new heap. Removed nodes are recycled, so memory usage will not shrink.
+ *
+ * \note Use when the size of the heap is known in advance.
+ */
+Heap *BLI_heap_new_ex(unsigned int reserve_num) ATTR_WARN_UNUSED_RESULT;
+Heap *BLI_heap_new() ATTR_WARN_UNUSED_RESULT;
+void BLI_heap_clear(Heap *heap, HeapFreeFP ptrfreefp) ATTR_NONNULL(1);
+void BLI_heap_free(Heap *heap, HeapFreeFP ptrfreefp) ATTR_NONNULL(1);
+/**
+ * Insert heap node with a value (often a 'cost') and pointer into the heap,
+ * duplicate values are allowed.
+ */
+HeapNode *BLI_heap_insert(Heap *heap, float value, void *ptr) ATTR_NONNULL(1);
+/**
+ * Convenience function since this is a common pattern.
+ */
+void BLI_heap_insert_or_update(Heap *heap, HeapNode **node_p, float value, void *ptr)
+ ATTR_NONNULL(1, 2);
+void BLI_heap_remove(Heap *heap, HeapNode *node) ATTR_NONNULL(1, 2);
+bool BLI_heap_is_empty(const Heap *heap) ATTR_NONNULL(1);
+unsigned int BLI_heap_len(const Heap *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+/**
+ * Return the top node of the heap.
+ * This is the node with the lowest value.
+ */
+HeapNode *BLI_heap_top(const Heap *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+/**
+ * Return the value of top node of the heap.
+ * This is the node with the lowest value.
+ */
+float BLI_heap_top_value(const Heap *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+/**
+ * Pop the top node off the heap and return its pointer.
+ */
+void *BLI_heap_pop_min(Heap *heap) ATTR_NONNULL(1);
+/**
+ * Can be used to avoid #BLI_heap_remove, #BLI_heap_insert calls,
+ * balancing the tree still has a performance cost,
+ * but is often much less than remove/insert, difference is most noticeable with large heaps.
+ */
+void BLI_heap_node_value_update(Heap *heap, HeapNode *node, float value) ATTR_NONNULL(1, 2);
+void BLI_heap_node_value_update_ptr(Heap *heap, HeapNode *node, float value, void *ptr)
+ ATTR_NONNULL(1, 2);
+
+/**
+ * Return the value or pointer of a heap node.
+ */
+float BLI_heap_node_value(const HeapNode *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+void *BLI_heap_node_ptr(const HeapNode *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+/**
+ * Only for checking internal errors (gtest).
+ */
+bool BLI_heap_is_valid(const Heap *heap);
+
+} // namespace blender
diff --git a/core/include/BLI_heap_simple.h b/core/include/BLI_heap_simple.h
new file mode 100644
index 0000000..2490db1
--- /dev/null
+++ b/core/include/BLI_heap_simple.h
@@ -0,0 +1,46 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ * \brief A min-heap / priority queue ADT
+ */
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_sys_types.h"
+
+namespace blender {
+
+struct HeapSimple;
+
+typedef void (*HeapSimpleFreeFP)(void *ptr);
+
+/**
+ * Creates a new simple heap, which only supports insertion and removal from top.
+ *
+ * \note Use when the size of the heap is known in advance.
+ */
+HeapSimple *BLI_heapsimple_new_ex(unsigned int reserve_num) ATTR_WARN_UNUSED_RESULT;
+HeapSimple *BLI_heapsimple_new() ATTR_WARN_UNUSED_RESULT;
+void BLI_heapsimple_clear(HeapSimple *heap, HeapSimpleFreeFP ptrfreefp) ATTR_NONNULL(1);
+void BLI_heapsimple_free(HeapSimple *heap, HeapSimpleFreeFP ptrfreefp) ATTR_NONNULL(1);
+/**
+ * Insert heap node with a value (often a 'cost') and pointer into the heap,
+ * duplicate values are allowed.
+ */
+void BLI_heapsimple_insert(HeapSimple *heap, float value, void *ptr) ATTR_NONNULL(1);
+bool BLI_heapsimple_is_empty(const HeapSimple *heap) ATTR_NONNULL(1);
+uint BLI_heapsimple_len(const HeapSimple *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+/**
+ * Return the lowest value of the heap.
+ */
+float BLI_heapsimple_top_value(const HeapSimple *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+/**
+ * Pop the top node off the heap and return its pointer.
+ */
+void *BLI_heapsimple_pop_min(HeapSimple *heap) ATTR_NONNULL(1);
+
+} // namespace blender
diff --git a/core/include/BLI_implicit_sharing.h b/core/include/BLI_implicit_sharing.h
new file mode 100644
index 0000000..5412186
--- /dev/null
+++ b/core/include/BLI_implicit_sharing.h
@@ -0,0 +1,26 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ *
+ * This file only exists to forward declare `ImplicitSharingInfo` in C code.
+ */
+
+namespace blender {
+
+#ifdef __cplusplus
+
+class ImplicitSharingInfo;
+using ImplicitSharingInfoHandle = ImplicitSharingInfo;
+
+#else
+
+struct ImplicitSharingInfoHandle;
+
+#endif
+
+} // namespace blender
diff --git a/core/include/BLI_iterator.h b/core/include/BLI_iterator.h
new file mode 100644
index 0000000..445f305
--- /dev/null
+++ b/core/include/BLI_iterator.h
@@ -0,0 +1,51 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include <stdbool.h>
+
+namespace blender {
+
+struct BLI_Iterator {
+ void *current; /* current pointer we iterate over */
+ void *data; /* stored data required for this iterator */
+ bool skip;
+ bool valid;
+};
+
+typedef void (*IteratorCb)(BLI_Iterator *iter);
+typedef void (*IteratorBeginCb)(BLI_Iterator *iter, void *data_in);
+
+#define BLI_ITERATOR_INIT(iter) \
+ { \
+ (iter)->skip = false; \
+ (iter)->valid = true; \
+ } \
+ ((void)0)
+
+#define ITER_BEGIN(callback_begin, callback_next, callback_end, _data_in, _type, _instance) \
+ { \
+ _type _instance; \
+ blender::IteratorCb callback_end_func = callback_end; \
+ blender::BLI_Iterator iter_macro; \
+ BLI_ITERATOR_INIT(&iter_macro); \
+ for (callback_begin(&iter_macro, (_data_in)); iter_macro.valid; callback_next(&iter_macro)) { \
+ if (iter_macro.skip) { \
+ iter_macro.skip = false; \
+ continue; \
+ } \
+ _instance = (_type)iter_macro.current;
+
+#define ITER_END \
+ } \
+ callback_end_func(&iter_macro); \
+ } \
+ ((void)0)
+
+} // namespace blender
diff --git a/core/include/BLI_jitter_2d.h b/core/include/BLI_jitter_2d.h
new file mode 100644
index 0000000..687e833
--- /dev/null
+++ b/core/include/BLI_jitter_2d.h
@@ -0,0 +1,17 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+namespace blender {
+
+void BLI_jitter_init(float (*jitarr)[2], int num);
+void BLI_jitterate1(float (*jit1)[2], float (*jit2)[2], int num, float radius1);
+void BLI_jitterate2(float (*jit1)[2], float (*jit2)[2], int num, float radius2);
+
+} // namespace blender
diff --git a/core/include/BLI_linklist_lockfree.h b/core/include/BLI_linklist_lockfree.h
new file mode 100644
index 0000000..0e8b1a8
--- /dev/null
+++ b/core/include/BLI_linklist_lockfree.h
@@ -0,0 +1,56 @@
+/* SPDX-FileCopyrightText: 2018 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+namespace blender {
+
+struct LockfreeLinkNode {
+ struct LockfreeLinkNode *next;
+ /* NOTE: "Subclass" this structure to add custom-defined data. */
+};
+
+struct LockfreeLinkList {
+ /* We keep a dummy node at the beginning of the list all the time.
+ * This allows us to make sure head and tail pointers are always
+ * valid, and saves from annoying exception cases in insert().
+ */
+ LockfreeLinkNode dummy_node;
+ /* NOTE: This fields might point to a dummy node. */
+ LockfreeLinkNode *head, *tail;
+};
+
+typedef void (*LockfreeeLinkNodeFreeFP)(void *link);
+
+/* ************************************************************************** */
+/* NOTE: These functions are NOT safe for use from threads. */
+/* NOTE: !!! I REPEAT: DO NOT USE THEM WITHOUT EXTERNAL LOCK !!! */
+
+/** Make list ready for lock-free access. */
+void BLI_linklist_lockfree_init(LockfreeLinkList *list);
+
+/** Completely free the whole list, it is NOT re-usable after this. */
+void BLI_linklist_lockfree_free(LockfreeLinkList *list, LockfreeeLinkNodeFreeFP free_func);
+
+/**
+ * Remove all the elements from the list, keep it usable for further inserts.
+ */
+void BLI_linklist_lockfree_clear(LockfreeLinkList *list, LockfreeeLinkNodeFreeFP free_func);
+
+/**
+ * Begin iteration of lock-free linked list, starting with a
+ * first user=defined node. Will ignore the dummy node.
+ */
+LockfreeLinkNode *BLI_linklist_lockfree_begin(LockfreeLinkList *list);
+
+/* ************************************************************************** */
+/* NOTE: These functions are safe for use from threads. */
+
+void BLI_linklist_lockfree_insert(LockfreeLinkList *list, LockfreeLinkNode *node);
+
+} // namespace blender
diff --git a/core/include/BLI_linklist_stack.h b/core/include/BLI_linklist_stack.h
new file mode 100644
index 0000000..7fc7c67
--- /dev/null
+++ b/core/include/BLI_linklist_stack.h
@@ -0,0 +1,171 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ * \brief BLI_LINKSTACK_*** wrapper macros for using a \a LinkNode
+ * to store a stack of pointers, using a single linked list
+ * allocated from a mempool.
+ *
+ * \note These macros follow STACK_* macros defined in `BLI_utildefines.h`
+ * and should be kept (mostly) interchangeable.
+ *
+ * \note `_##var##_type` is a dummy variable only used for type-checks.
+ */
+
+/* -------------------------------------------------------------------- */
+/** \name Linked Stack (mempool)
+ *
+ * Uses #BLI_mempool for storage.
+ * \{ */
+
+#define BLI_LINKSTACK_DECLARE(var, type) \
+ LinkNode *var; \
+ BLI_mempool *var##_pool_; \
+ type var##_type_
+
+#define BLI_LINKSTACK_INIT(var) \
+ { \
+ var = NULL; \
+ var##_pool_ = BLI_mempool_create(sizeof(LinkNode), 0, 64, BLI_MEMPOOL_NOP); \
+ } \
+ (void)0
+
+#define BLI_LINKSTACK_SIZE(var) BLI_mempool_len(var##_pool_)
+
+/* Check for `decltype()` or `typeof()` support. */
+#define BLI_LINKSTACK_PUSH(var, ptr) \
+ (CHECK_TYPE_INLINE_NONCONST(ptr, decltype(var##_type_)), \
+ BLI_linklist_prepend_pool(&(var), ptr, var##_pool_))
+#define BLI_LINKSTACK_POP(var) \
+ (decltype(var##_type_))(var ? BLI_linklist_pop_pool(&(var), var##_pool_) : NULL)
+#define BLI_LINKSTACK_POP_DEFAULT(var, r) \
+ (decltype(var##_type_))(var ? BLI_linklist_pop_pool(&(var), var##_pool_) : r)
+
+#define BLI_LINKSTACK_SWAP(var_a, var_b) \
+ { \
+ CHECK_TYPE_PAIR(var_a##_type_, var_b##_type_); \
+ SWAP(LinkNode *, var_a, var_b); \
+ SWAP(BLI_mempool *, var_a##_pool_, var_b##_pool_); \
+ } \
+ (void)0
+
+#define BLI_LINKSTACK_FREE(var) \
+ { \
+ BLI_mempool_destroy(var##_pool_); \
+ var##_pool_ = NULL; \
+ (void)var##_pool_; \
+ var = NULL; \
+ (void)var; \
+ (void)&(var##_type_); \
+ } \
+ (void)0
+
+#include "BLI_linklist.h"
+#include "BLI_mempool.h"
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Linked Stack (alloca)
+ *
+ * Linked Stack, using stack memory (alloca).
+ *
+ * alloca never frees, pop'd items are stored in a free-list for reuse.
+ * only use for lists small enough to fit on the stack.
+ * \{ */
+
+#ifdef __GNUC__
+# define _BLI_SMALLSTACK_CAST(var) (typeof(_##var##_type))
+#else
+# define _BLI_SMALLSTACK_CAST(var)
+#endif
+
+#define _BLI_SMALLSTACK_FAKEUSER(var) (void)(&(_##var##_type))
+
+#define BLI_SMALLSTACK_DECLARE(var, type) \
+ LinkNode *_##var##_stack = NULL, *_##var##_free = NULL, *_##var##_temp = NULL; \
+ type _##var##_type
+
+#define BLI_SMALLSTACK_PUSH(var, data) \
+ { \
+ CHECK_TYPE_PAIR(data, _##var##_type); \
+ if (_##var##_free) { \
+ _##var##_temp = _##var##_free; \
+ _##var##_free = _##var##_free->next; \
+ } \
+ else { \
+ _##var##_temp = (LinkNode *)alloca(sizeof(LinkNode)); \
+ } \
+ _##var##_temp->next = _##var##_stack; \
+ _##var##_temp->link = data; \
+ _##var##_stack = _##var##_temp; \
+ _BLI_SMALLSTACK_FAKEUSER(var); \
+ } \
+ (void)0
+
+/* internal use, no null check */
+#define _BLI_SMALLSTACK_DEL_EX(var_src, var_dst) \
+ (void)(_BLI_SMALLSTACK_FAKEUSER(var_src), \
+ _BLI_SMALLSTACK_FAKEUSER(var_dst), \
+ (_##var_src##_temp = _##var_src##_stack->next), \
+ (_##var_src##_stack->next = _##var_dst##_free), \
+ (_##var_dst##_free = _##var_src##_stack), \
+ (_##var_src##_stack = _##var_src##_temp))
+
+#define _BLI_SMALLSTACK_DEL(var) _BLI_SMALLSTACK_DEL_EX(var, var)
+
+/* check for typeof() */
+#define BLI_SMALLSTACK_POP(var) \
+ (_BLI_SMALLSTACK_CAST(var)( \
+ (_##var##_stack) ? (_BLI_SMALLSTACK_DEL(var), (_##var##_free->link)) : NULL))
+
+/* support to put the free-node into another stack */
+#define BLI_SMALLSTACK_POP_EX(var_src, var_dst) \
+ (_BLI_SMALLSTACK_CAST(var_src)( \
+ (_##var_src##_stack) ? \
+ (_BLI_SMALLSTACK_DEL_EX(var_src, var_dst), (_##var_dst##_free->link)) : \
+ NULL))
+
+#define BLI_SMALLSTACK_PEEK(var) \
+ (_BLI_SMALLSTACK_CAST(var)((_##var##_stack) ? _##var##_stack->link : NULL))
+
+#define BLI_SMALLSTACK_IS_EMPTY(var) ((_BLI_SMALLSTACK_CAST(var) _##var##_stack) == NULL)
+
+/* fill in a lookup table */
+#define BLI_SMALLSTACK_AS_TABLE(var, data) \
+ { \
+ LinkNode *_##var##_iter; \
+ unsigned int i; \
+ for (_##var##_iter = _##var##_stack, i = 0; _##var##_iter; \
+ _##var##_iter = _##var##_iter->next, i++) \
+ { \
+ *(void **)&(data)[i] = _##var##_iter->link; \
+ } \
+ } \
+ ((void)0)
+
+/* loop over stack members last-added-first */
+#define BLI_SMALLSTACK_ITER_BEGIN(var, item) \
+ { \
+ LinkNode *_##var##_iter; \
+ for (_##var##_iter = _##var##_stack; _##var##_iter; _##var##_iter = _##var##_iter->next) { \
+ item = _BLI_SMALLSTACK_CAST(var)(_##var##_iter->link);
+
+#define BLI_SMALLSTACK_ITER_END \
+ } \
+ } \
+ (void)0
+
+#define BLI_SMALLSTACK_SWAP(var_a, var_b) \
+ { \
+ CHECK_TYPE_PAIR(_##var_a##_type, _##var_b##_type); \
+ SWAP(LinkNode *, _##var_a##_stack, _##var_b##_stack); \
+ SWAP(LinkNode *, _##var_a##_free, _##var_b##_free); \
+ } \
+ (void)0
+
+/** \} */
diff --git a/core/include/BLI_listbase.h b/core/include/BLI_listbase.h
index 4ade1ba..11fa8b8 100644
--- a/core/include/BLI_listbase.h
+++ b/core/include/BLI_listbase.h
@@ -14,6 +14,10 @@
#include "BLI_compiler_compat.h"
#include "DNA_listBase.h"
+#ifdef __cplusplus
+# include "BLI_listbase_iterator.hh"
+#endif
+
@@ -363,3 +367,4 @@ LinkData *BLI_genericNodeN(void *data);
+
diff --git a/core/include/BLI_listbase_iterator.hh b/core/include/BLI_listbase_iterator.hh
index f829294..677d6dc 100644
--- a/core/include/BLI_listbase_iterator.hh
+++ b/core/include/BLI_listbase_iterator.hh
@@ -10,8 +10,6 @@
namespace blender {
-struct Link;
-
/** An iterator for use with #ListBase. */
template<typename T> struct ListBaseTIterator {
public:
@@ -29,7 +27,7 @@ template<typename T> struct ListBaseTIterator {
ListBaseTIterator &operator++()
{
- data_ = reinterpret_cast<T *>((reinterpret_cast<const Link *>(data_))->next);
+ data_ = reinterpret_cast<T *>((reinterpret_cast<const ::Link *>(data_))->next);
return *this;
}
@@ -42,7 +40,7 @@ template<typename T> struct ListBaseTIterator {
ListBaseTIterator &operator--()
{
- data_ = reinterpret_cast<T *>((reinterpret_cast<const Link *>(data_))->prev);
+ data_ = reinterpret_cast<T *>((reinterpret_cast<const ::Link *>(data_))->prev);
return *this;
}
@@ -87,7 +85,7 @@ template<typename T> struct ListBaseEnumerateIterator {
ListBaseEnumerateIterator &operator++()
{
- data_ = reinterpret_cast<T *>(reinterpret_cast<const Link *>(data_)->next);
+ data_ = reinterpret_cast<T *>(reinterpret_cast<const ::Link *>(data_)->next);
index_++;
return *this;
}
@@ -146,7 +144,7 @@ template<typename T> struct ListBaseMutableIterator {
ListBaseMutableIterator(T *data) : current_(data)
{
if (current_) {
- next_ = reinterpret_cast<T *>((reinterpret_cast<const Link *>(current_))->next);
+ next_ = reinterpret_cast<T *>((reinterpret_cast<const ::Link *>(current_))->next);
}
}
@@ -154,7 +152,7 @@ template<typename T> struct ListBaseMutableIterator {
{
current_ = next_;
if (current_) {
- next_ = reinterpret_cast<T *>((reinterpret_cast<const Link *>(current_))->next);
+ next_ = reinterpret_cast<T *>((reinterpret_cast<const ::Link *>(current_))->next);
}
return *this;
}
@@ -213,7 +211,7 @@ template<typename T> struct ListBaseBackwardIterator {
ListBaseBackwardIterator &operator++()
{
- data_ = reinterpret_cast<T *>((reinterpret_cast<const Link *>(data_))->prev);
+ data_ = reinterpret_cast<T *>((reinterpret_cast<const ::Link *>(data_))->prev);
return *this;
}
@@ -271,7 +269,7 @@ template<typename T> struct ListBaseMutableBackwardIterator {
ListBaseMutableBackwardIterator(T *data) : current_(data)
{
if (current_) {
- prev_ = reinterpret_cast<T *>((reinterpret_cast<const Link *>(current_))->prev);
+ prev_ = reinterpret_cast<T *>((reinterpret_cast<const ::Link *>(current_))->prev);
}
}
@@ -279,7 +277,7 @@ template<typename T> struct ListBaseMutableBackwardIterator {
{
current_ = prev_;
if (current_) {
- prev_ = reinterpret_cast<T *>((reinterpret_cast<const Link *>(current_))->prev);
+ prev_ = reinterpret_cast<T *>((reinterpret_cast<const ::Link *>(current_))->prev);
}
return *this;
}
diff --git a/core/include/BLI_math_color_blend.h b/core/include/BLI_math_color_blend.h
new file mode 100644
index 0000000..a240bbc
--- /dev/null
+++ b/core/include/BLI_math_color_blend.h
@@ -0,0 +1,131 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include "BLI_math_inline.h"
+#include "BLI_sys_types.h"
+
+namespace blender {
+
+/******************** Blending Modes **********************
+ * - byte function assume straight alpha
+ * - float functions assume premultiplied alpha
+ */
+
+MINLINE void blend_color_mix_byte(unsigned char dst[4],
+ const unsigned char src1[4],
+ const unsigned char src2[4]);
+MINLINE void blend_color_add_byte(unsigned char dst[4],
+ const unsigned char src1[4],
+ const unsigned char src2[4]);
+MINLINE void blend_color_sub_byte(unsigned char dst[4],
+ const unsigned char src1[4],
+ const unsigned char src2[4]);
+MINLINE void blend_color_mul_byte(unsigned char dst[4],
+ const unsigned char src1[4],
+ const unsigned char src2[4]);
+MINLINE void blend_color_lighten_byte(unsigned char dst[4],
+ const unsigned char src1[4],
+ const unsigned char src2[4]);
+MINLINE void blend_color_darken_byte(unsigned char dst[4],
+ const unsigned char src1[4],
+ const unsigned char src2[4]);
+MINLINE void blend_color_erase_alpha_byte(unsigned char dst[4],
+ const unsigned char src1[4],
+ const unsigned char src2[4]);
+MINLINE void blend_color_add_alpha_byte(unsigned char dst[4],
+ const unsigned char src1[4],
+ const unsigned char src2[4]);
+
+MINLINE void blend_color_overlay_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_hardlight_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_burn_byte(unsigned char dst[4], const uchar src1[4], const uchar src2[4]);
+MINLINE void blend_color_linearburn_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_dodge_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_screen_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_softlight_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_pinlight_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_linearlight_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_vividlight_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_difference_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_exclusion_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_color_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_hue_byte(unsigned char dst[4], const uchar src1[4], const uchar src2[4]);
+MINLINE void blend_color_saturation_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+MINLINE void blend_color_luminosity_byte(unsigned char dst[4],
+ const uchar src1[4],
+ const uchar src2[4]);
+
+MINLINE void blend_color_interpolate_byte(unsigned char dst[4],
+ const unsigned char src1[4],
+ const unsigned char src2[4],
+ float ft);
+
+MINLINE void blend_color_mix_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_add_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_sub_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_mul_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_lighten_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_darken_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_erase_alpha_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_add_alpha_float(float dst[4], const float src1[4], const float src2[4]);
+
+MINLINE void blend_color_overlay_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_hardlight_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_burn_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_linearburn_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_dodge_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_screen_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_softlight_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_pinlight_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_linearlight_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_vividlight_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_difference_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_exclusion_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_color_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_hue_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_saturation_float(float dst[4], const float src1[4], const float src2[4]);
+MINLINE void blend_color_luminosity_float(float dst[4], const float src1[4], const float src2[4]);
+
+MINLINE void blend_color_interpolate_float(float dst[4],
+ const float src1[4],
+ const float src2[4],
+ float t);
+
+} // namespace blender
+
+#if BLI_MATH_DO_INLINE
+# include "intern/math_color_blend_inline.cc" // IWYU pragma: export
+#endif
diff --git a/core/include/BLI_math_matrix.hh b/core/include/BLI_math_matrix.hh
index f87b7f9..b18b314 100644
--- a/core/include/BLI_math_matrix.hh
+++ b/core/include/BLI_math_matrix.hh
@@ -9,6 +9,7 @@
*/
#include "BLI_math_base.hh"
+#include "BLI_math_matrix.h"
#include "BLI_math_matrix_types.hh"
#include "BLI_math_rotation_types.hh"
#include "BLI_math_vector.hh"
diff --git a/core/include/BLI_math_statistics.h b/core/include/BLI_math_statistics.h
new file mode 100644
index 0000000..449641d
--- /dev/null
+++ b/core/include/BLI_math_statistics.h
@@ -0,0 +1,63 @@
+/* SPDX-FileCopyrightText: 2015 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include "BLI_math_inline.h"
+#include "BLI_sys_types.h"
+
+namespace blender {
+
+#ifdef BLI_MATH_GCC_WARN_PRAGMA
+# pragma GCC diagnostic push
+# pragma GCC diagnostic ignored "-Wredundant-decls"
+#endif
+
+/* -------------------------------------------------------------------- */
+/** \name Covariance Matrices
+ * \{ */
+
+/**
+ * \brief Compute the covariance matrix of given set of nD coordinates.
+ *
+ * \param n: the dimension of the vectors (and hence, of the covariance matrix to compute).
+ * \param cos_vn: the nD points to compute covariance from.
+ * \param cos_vn_num: the number of nD coordinates in cos_vn.
+ * \param center: the center (or mean point) of cos_vn. If NULL,
+ * it is assumed cos_vn is already centered.
+ * \param use_sample_correction: whether to apply sample correction
+ * (i.e. get 'sample variance' instead of 'population variance').
+ * \return r_covmat the computed covariance matrix.
+ */
+void BLI_covariance_m_vn_ex(int n,
+ const float *cos_vn,
+ int cos_vn_num,
+ const float *center,
+ bool use_sample_correction,
+ float *r_covmat);
+/**
+ * \brief Compute the covariance matrix of given set of 3D coordinates.
+ *
+ * \param cos_v3: the 3D points to compute covariance from.
+ * \param cos_v3_num: the number of 3D coordinates in cos_v3.
+ * \return r_covmat the computed covariance matrix.
+ * \return r_center the computed center (mean) of 3D points (may be NULL).
+ */
+void BLI_covariance_m3_v3n(const float (*cos_v3)[3],
+ int cos_v3_num,
+ bool use_sample_correction,
+ float r_covmat[3][3],
+ float r_center[3]);
+
+#ifdef BLI_MATH_GCC_WARN_PRAGMA
+# pragma GCC diagnostic pop
+#endif
+
+/** \} */
+
+} // namespace blender
diff --git a/core/include/BLI_math_time.h b/core/include/BLI_math_time.h
new file mode 100644
index 0000000..0ec3ef5
--- /dev/null
+++ b/core/include/BLI_math_time.h
@@ -0,0 +1,57 @@
+/* SPDX-FileCopyrightText: 2021 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+namespace blender {
+
+/* -------------------------------------------------------------------- */
+/** \name Time Constants Definitions
+ * \{ */
+
+#define SECONDS_IN_MILLISECONDS 0.001
+#define SECONDS_IN_MINUTE 60.0
+#define MINUTES_IN_HOUR 60.0
+#define HOURS_IN_DAY 24.0
+
+#define MINUTES_IN_DAY (MINUTES_IN_HOUR * HOURS_IN_DAY)
+#define SECONDS_IN_DAY (MINUTES_IN_DAY * SECONDS_IN_MINUTE)
+#define SECONDS_IN_HOUR (MINUTES_IN_HOUR * SECONDS_IN_MINUTE)
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Time API
+ * \{ */
+
+/**
+ * Explode given time value expressed in seconds, into a set of days, hours, minutes, seconds
+ * and/or milliseconds (depending on which return parameters are not NULL).
+ *
+ * \note The smallest given return parameter will get the potential fractional remaining time
+ * value. E.g. if you give `seconds=90.0` and do not pass `r_seconds` and `r_milliseconds`,
+ * `r_minutes` will be set to `1.5`.
+ */
+void BLI_math_time_seconds_decompose(double seconds,
+ double *r_days,
+ double *r_hours,
+ double *r_minutes,
+ double *r_seconds,
+ double *r_milliseconds);
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Inline Definitions
+ * \{ */
+
+/* None. */
+
+/** \} */
+
+} // namespace blender
diff --git a/core/include/BLI_memblock.h b/core/include/BLI_memblock.h
new file mode 100644
index 0000000..5e7e050
--- /dev/null
+++ b/core/include/BLI_memblock.h
@@ -0,0 +1,55 @@
+/* SPDX-FileCopyrightText: 2008 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_sys_types.h"
+
+namespace blender {
+
+#define BLI_MEM_BLOCK_CHUNK_SIZE (1 << 15) /* 32KiB */
+
+struct BLI_memblock;
+
+struct BLI_memblock;
+typedef void (*MemblockValFreeFP)(void *val);
+
+BLI_memblock *BLI_memblock_create_ex(uint elem_size, uint chunk_size) ATTR_WARN_UNUSED_RESULT;
+void *BLI_memblock_alloc(BLI_memblock *mblk) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+/**
+ * Reset elem count to 0 but keep as much memory allocated needed
+ * for at least the previous elem count.
+ */
+void BLI_memblock_clear(BLI_memblock *mblk, MemblockValFreeFP free_callback) ATTR_NONNULL(1);
+void BLI_memblock_destroy(BLI_memblock *mblk, MemblockValFreeFP free_callback) ATTR_NONNULL(1);
+
+#define BLI_memblock_create(elem_size) BLI_memblock_create_ex(elem_size, BLI_MEM_BLOCK_CHUNK_SIZE)
+
+struct BLI_memblock_iter {
+ void **chunk_list;
+ int cur_index;
+ int end_index;
+ int chunk_max_ofs;
+ int chunk_idx;
+ int elem_size;
+ int elem_ofs;
+};
+
+void BLI_memblock_iternew(BLI_memblock *mblk, BLI_memblock_iter *iter) ATTR_NONNULL();
+void *BLI_memblock_iterstep(BLI_memblock_iter *iter) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+
+/**
+ * Direct access. elem is element index inside the chosen chunk.
+ * Double usage: You can set chunk to 0 and set the absolute elem index.
+ * The correct chunk will be retrieve.
+ */
+void *BLI_memblock_elem_get(BLI_memblock *mblk, int chunk, int elem) ATTR_WARN_UNUSED_RESULT
+ ATTR_NONNULL();
+
+} // namespace blender
diff --git a/core/include/BLI_memiter.h b/core/include/BLI_memiter.h
new file mode 100644
index 0000000..2fe3ff8
--- /dev/null
+++ b/core/include/BLI_memiter.h
@@ -0,0 +1,67 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_compiler_compat.h"
+#include "BLI_sys_types.h"
+
+namespace blender {
+
+/* 512kb, good default for small elems. */
+#define BLI_MEMITER_DEFAULT_SIZE (1 << 19)
+
+struct BLI_memiter;
+
+struct BLI_memiter;
+
+/**
+ * \param chunk_size_min: Should be a power of two and
+ * significantly larger than the average element size used.
+ *
+ * While allocations of any size are supported, they won't be efficient
+ * (effectively becoming a single-linked list).
+ *
+ * Its intended that many elements can be stored per chunk.
+ */
+BLI_memiter *BLI_memiter_create(unsigned int chunk_size_min)
+ ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL;
+void *BLI_memiter_alloc(BLI_memiter *mi, unsigned int elem_size)
+ /* WARNING: `ATTR_MALLOC` attribute on #BLI_memiter_alloc causes crash, see: D2756. */
+ ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL ATTR_NONNULL(1);
+void BLI_memiter_alloc_from(BLI_memiter *mi, uint elem_size, const void *data_from)
+ ATTR_NONNULL(1, 3);
+void *BLI_memiter_calloc(BLI_memiter *mi,
+ unsigned int elem_size) ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL
+ ATTR_NONNULL(1);
+void BLI_memiter_destroy(BLI_memiter *mi) ATTR_NONNULL(1);
+void BLI_memiter_clear(BLI_memiter *mi) ATTR_NONNULL(1);
+unsigned int BLI_memiter_count(const BLI_memiter *mi) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+
+/* Utilities. */
+
+/**
+ * Support direct lookup for the first item.
+ */
+void *BLI_memiter_elem_first(BLI_memiter *mi);
+void *BLI_memiter_elem_first_size(BLI_memiter *mi, unsigned int *r_size);
+
+/** Private structure. */
+struct BLI_memiter_handle {
+ struct BLI_memiter_elem *elem;
+ uint elem_left;
+};
+
+void BLI_memiter_iter_init(BLI_memiter *mi, BLI_memiter_handle *iter) ATTR_NONNULL(1, 2);
+bool BLI_memiter_iter_done(const BLI_memiter_handle *iter) ATTR_NONNULL(1);
+void *BLI_memiter_iter_step(BLI_memiter_handle *iter) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+void *BLI_memiter_iter_step_size(BLI_memiter_handle *iter, uint *r_size) ATTR_WARN_UNUSED_RESULT
+ ATTR_NONNULL(1, 2);
+
+} // namespace blender
diff --git a/core/include/BLI_mmap.h b/core/include/BLI_mmap.h
new file mode 100644
index 0000000..3528a5c
--- /dev/null
+++ b/core/include/BLI_mmap.h
@@ -0,0 +1,39 @@
+/* SPDX-FileCopyrightText: 2020 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_utildefines.h"
+
+namespace blender {
+
+/* Memory-mapped file IO that implements all the OS-specific details and error handling. */
+
+struct BLI_mmap_file;
+
+struct BLI_mmap_file;
+
+/* Prepares an opened file for memory-mapped IO.
+ * May return NULL if the operation fails.
+ * Note that this seeks to the end of the file to determine its length. */
+BLI_mmap_file *BLI_mmap_open(int fd) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+
+/* Reads length bytes from file at the given offset into dest.
+ * Returns whether the operation was successful (may fail when reading beyond the file
+ * end or when IO errors occur). */
+bool BLI_mmap_read(BLI_mmap_file *file, void *dest, size_t offset, size_t length)
+ ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+
+void *BLI_mmap_get_pointer(BLI_mmap_file *file) ATTR_WARN_UNUSED_RESULT;
+size_t BLI_mmap_get_length(const BLI_mmap_file *file) ATTR_WARN_UNUSED_RESULT;
+bool BLI_mmap_any_io_error(const BLI_mmap_file *file) ATTR_WARN_UNUSED_RESULT;
+
+void BLI_mmap_free(BLI_mmap_file *file) ATTR_NONNULL(1);
+
+} // namespace blender
diff --git a/core/include/BLI_noise.h b/core/include/BLI_noise.h
new file mode 100644
index 0000000..5ce19c8
--- /dev/null
+++ b/core/include/BLI_noise.h
@@ -0,0 +1,138 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include "BLI_sys_types.h"
+
+namespace blender {
+
+extern const uchar BLI_noise_hash_uchar_512[512]; /* Quiet warning. */
+
+float BLI_noise_hnoise(float noisesize, float x, float y, float z);
+float BLI_noise_hnoisep(float noisesize, float x, float y, float z);
+/**
+ * Original turbulence functions.
+ */
+float BLI_noise_turbulence(float noisesize, float x, float y, float z, int nr);
+/**
+ * newnoise: generic noise & turbulence functions
+ * to replace the above BLI_noise_hnoise/p & BLI_noise_turbulence/1.
+ * This is done so different noise basis functions can be used.
+ */
+/**
+ * newnoise: generic noise function for use with different `noisebasis`.
+ */
+float BLI_noise_generic_noise(
+ float noisesize, float x, float y, float z, bool hard, int noisebasis);
+/**
+ * newnoise: generic turbulence function for use with different `noisebasis`.
+ */
+float BLI_noise_generic_turbulence(
+ float noisesize, float x, float y, float z, int oct, bool hard, int noisebasis);
+
+/* newnoise: musgrave functions */
+
+/**
+ * Procedural `fBm` evaluated at "point"; returns value stored in "value".
+ *
+ * \param H: is the fractal increment parameter.
+ * \param lacunarity: is the gap between successive frequencies.
+ * \param octaves: is the number of frequencies in the `fBm`.
+ */
+float BLI_noise_mg_fbm(
+ float x, float y, float z, float H, float lacunarity, float octaves, int noisebasis);
+/**
+ * Procedural multi-fractal evaluated at "point";
+ * returns value stored in "value".
+ *
+ * \param H: determines the highest fractal dimension.
+ * \param lacunarity: is gap between successive frequencies.
+ * \param octaves: is the number of frequencies in the `fBm`.
+ *
+ * \note There used to be a parameter called `offset`, old docs read:
+ * is the zero offset, which determines multi-fractality.
+ */
+float BLI_noise_mg_multi_fractal(
+ float x, float y, float z, float H, float lacunarity, float octaves, int noisebasis);
+/**
+ * "Variable Lacunarity Noise"
+ * A distorted variety of Perlin noise.
+ */
+float BLI_noise_mg_variable_lacunarity(
+ float x, float y, float z, float distortion, int nbas1, int nbas2);
+/**
+ * Heterogeneous procedural terrain function: stats by altitude method.
+ * Evaluated at "point"; returns value stored in "value".
+ *
+ * \param H: Determines the fractal dimension of the roughest areas.
+ * \param lacunarity: Is the gap between successive frequencies.
+ * \param octaves: Is the number of frequencies in the `fBm`.
+ * \param offset: Raises the terrain from `sea level`.
+ */
+float BLI_noise_mg_hetero_terrain(float x,
+ float y,
+ float z,
+ float H,
+ float lacunarity,
+ float octaves,
+ float offset,
+ int noisebasis);
+/**
+ * Hybrid additive/multiplicative multi-fractal terrain model.
+ *
+ * Some good parameter values to start with:
+ *
+ * \param H: 0.25
+ * \param offset: 0.7
+ */
+float BLI_noise_mg_hybrid_multi_fractal(float x,
+ float y,
+ float z,
+ float H,
+ float lacunarity,
+ float octaves,
+ float offset,
+ float gain,
+ int noisebasis);
+/**
+ * Ridged multi-fractal terrain model.
+ *
+ * Some good parameter values to start with:
+ *
+ * \param H: 1.0
+ * \param offset: 1.0
+ * \param gain: 2.0
+ */
+float BLI_noise_mg_ridged_multi_fractal(float x,
+ float y,
+ float z,
+ float H,
+ float lacunarity,
+ float octaves,
+ float offset,
+ float gain,
+ int noisebasis);
+/* newnoise: voronoi */
+
+/**
+ * Not 'pure' Worley, but the results are virtually the same.
+ * Returns distances in da and point coords in `pa`.
+ */
+void BLI_noise_voronoi(float x, float y, float z, float *da, float *pa, float me, int dtype);
+/**
+ * newnoise: BLI_noise_cell & BLI_noise_cell_v3 (for vector/point/color).
+ * idem, signed.
+ */
+float BLI_noise_cell(float x, float y, float z);
+/**
+ * Returns a vector/point/color in `r_ca`, using point hash-array directly.
+ */
+void BLI_noise_cell_v3(float x, float y, float z, float r_ca[3]);
+
+} // namespace blender
diff --git a/core/include/BLI_polyfill_2d.h b/core/include/BLI_polyfill_2d.h
new file mode 100644
index 0000000..c7bd2f3
--- /dev/null
+++ b/core/include/BLI_polyfill_2d.h
@@ -0,0 +1,46 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+namespace blender {
+
+struct MemArena;
+
+/**
+ * A version of #BLI_polyfill_calc that uses a memory arena to avoid re-allocations.
+ */
+void BLI_polyfill_calc_arena(const float (*coords)[2],
+ unsigned int coords_num,
+ int coords_sign,
+ unsigned int (*r_tris)[3],
+
+ struct MemArena *arena);
+
+/**
+ * Triangulates the given (convex or concave) simple polygon to a list of triangle vertices.
+ *
+ * \param coords: 2D coordinates describing vertices of the polygon,
+ * in either clockwise or counterclockwise order.
+ * \param coords_num: Total points in the array.
+ * \param coords_sign: Pass this when we know the sign in advance to avoid extra calculations.
+ *
+ * \param r_tris: This array is filled in with triangle indices in clockwise order.
+ * The length of the array must be `coords_num - 2`.
+ * Indices are guaranteed to be assigned to unique triangles, with valid indices,
+ * even in the case of degenerate input (self intersecting polygons, zero area ears... etc).
+ */
+void BLI_polyfill_calc(const float (*coords)[2],
+ unsigned int coords_num,
+ int coords_sign,
+ unsigned int (*r_tris)[3]);
+
+/* default size of polyfill arena */
+#define BLI_POLYFILL_ARENA_SIZE MEM_SIZE_OPTIMAL(1 << 14)
+
+} // namespace blender
diff --git a/core/include/BLI_polyfill_2d_beautify.h b/core/include/BLI_polyfill_2d_beautify.h
new file mode 100644
index 0000000..0b541d6
--- /dev/null
+++ b/core/include/BLI_polyfill_2d_beautify.h
@@ -0,0 +1,65 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include <stdbool.h>
+
+namespace blender {
+
+struct Heap;
+struct MemArena;
+
+/**
+ * The intention is that this calculates the output of #BLI_polyfill_calc
+ * \note assumes the \a coords form a boundary,
+ * so any edges running along contiguous (wrapped) indices,
+ * are ignored since the edges won't share 2 faces.
+ */
+void BLI_polyfill_beautify(const float (*coords)[2],
+ unsigned int coords_num,
+ unsigned int (*tris)[3],
+
+ /* structs for reuse */
+ struct MemArena *arena,
+ struct Heap *eheap);
+
+/**
+ * Assuming we have 2 triangles sharing an edge (2 - 4),
+ * check if the edge running from (1 - 3) gives better results.
+ *
+ * \param lock_degenerate: Use to avoid rotating out of a degenerate state:
+ * - When true, an existing zero area face on either side of the (2 - 4
+ * split will return a positive value.
+ * - When false, the check must be non-biased towards either split direction.
+ * \param r_area: Return the area of the quad,
+ * This can be useful when comparing the return value with near zero epsilons.
+ * In this case the epsilon can be scaled by the area to avoid the return value
+ * of very large faces not having a reliable way to detect near-zero output.
+ *
+ * \return (negative number means the edge can be rotated, lager == better).
+ */
+float BLI_polyfill_beautify_quad_rotate_calc_ex(const float v1[2],
+ const float v2[2],
+ const float v3[2],
+ const float v4[2],
+ bool lock_degenerate,
+ float *r_area);
+#define BLI_polyfill_beautify_quad_rotate_calc(v1, v2, v3, v4) \
+ BLI_polyfill_beautify_quad_rotate_calc_ex(v1, v2, v3, v4, false, NULL)
+
+float BLI_polyfill_edge_calc_rotate_beauty__area(const float v1[3],
+ const float v2[3],
+ const float v3[3],
+ const float v4[3],
+ bool lock_degenerate);
+
+/* avoid realloc's when creating new structures for polyfill ngons */
+#define BLI_POLYFILL_ALLOC_NGON_RESERVE 64
+
+} // namespace blender
diff --git a/core/include/BLI_quadric.h b/core/include/BLI_quadric.h
new file mode 100644
index 0000000..1df0ee4
--- /dev/null
+++ b/core/include/BLI_quadric.h
@@ -0,0 +1,37 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include <stdbool.h>
+
+namespace blender {
+
+struct Quadric {
+ double a2, ab, ac, ad, b2, bc, bd, c2, cd, d2;
+};
+
+/* Conversion. */
+
+void BLI_quadric_from_plane(Quadric *q, const double v[4]);
+void BLI_quadric_to_vector_v3(const Quadric *q, double v[3]);
+
+void BLI_quadric_clear(Quadric *q);
+
+/* Math operations. */
+
+void BLI_quadric_add_qu_qu(Quadric *a, const Quadric *b);
+void BLI_quadric_add_qu_ququ(Quadric *r, const Quadric *a, const Quadric *b);
+void BLI_quadric_mul(Quadric *a, double scalar);
+
+/* Solve. */
+
+double BLI_quadric_evaluate(const Quadric *q, const double v[3]);
+bool BLI_quadric_optimize(const Quadric *q, double v[3], double epsilon);
+
+} // namespace blender
diff --git a/core/include/BLI_rand.h b/core/include/BLI_rand.h
new file mode 100644
index 0000000..928e26c
--- /dev/null
+++ b/core/include/BLI_rand.h
@@ -0,0 +1,101 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_sys_types.h"
+
+namespace blender {
+
+/** \file
+ * \ingroup bli
+ * \brief Random number functions.
+ */
+
+/**
+ * RNG is an abstract random number generator type that avoids using globals.
+ * Always use this instead of the global RNG unless you have a good reason,
+ * the global RNG is not thread safe and will not give repeatable results.
+ */
+struct RNG;
+struct RNG_THREAD_ARRAY;
+
+struct RNG *BLI_rng_new(unsigned int seed);
+/**
+ * A version of #BLI_rng_new that hashes the seed.
+ */
+struct RNG *BLI_rng_new_srandom(unsigned int seed);
+void BLI_rng_free(struct RNG *rng) ATTR_NONNULL(1);
+
+void BLI_rng_seed(struct RNG *rng, unsigned int seed) ATTR_NONNULL(1);
+/**
+ * Use a hash table to create better seed.
+ */
+void BLI_rng_srandom(struct RNG *rng, unsigned int seed) ATTR_NONNULL(1);
+void BLI_rng_get_char_n(RNG *rng, char *bytes, size_t bytes_len) ATTR_NONNULL(1, 2);
+int BLI_rng_get_int(struct RNG *rng) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+unsigned int BLI_rng_get_uint(struct RNG *rng) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+/**
+ * \return Random value (0..1), but never 1.0.
+ */
+double BLI_rng_get_double(struct RNG *rng) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+/**
+ * \return Random value (0..1), but never 1.0.
+ */
+float BLI_rng_get_float(struct RNG *rng) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+/**
+ * Generate a random point inside given tri.
+ */
+void BLI_rng_get_tri_sample_float_v2(struct RNG *rng,
+ const float v1[2],
+ const float v2[2],
+ const float v3[2],
+ float r_pt[2]) ATTR_NONNULL();
+
+void BLI_rng_shuffle_array(struct RNG *rng,
+ void *data,
+ unsigned int elem_size_i,
+ unsigned int elem_num) ATTR_NONNULL(1, 2);
+
+void BLI_rng_shuffle_bitmap(struct RNG *rng, unsigned int *bitmap, unsigned int bits_num)
+ ATTR_NONNULL(1, 2);
+
+/** Note that skipping is as slow as generating n numbers! */
+/**
+ * Simulate getting \a n random values.
+ *
+ * \note Useful when threaded code needs consistent values, independent of task division.
+ */
+void BLI_rng_skip(struct RNG *rng, int n) ATTR_NONNULL(1);
+
+/** Return a pseudo-random (hash) float from an integer value */
+float BLI_hash_frand(unsigned int seed) ATTR_WARN_UNUSED_RESULT;
+
+/**
+ * Shuffle an array randomly using the given seed contents.
+ * This routine does not use nor modify the state of the BLI random number generator.
+ */
+void BLI_array_randomize(void *data,
+ unsigned int elem_size,
+ unsigned int elem_num,
+ unsigned int seed);
+
+void BLI_bitmap_randomize(unsigned int *bitmap, unsigned int bits_num, unsigned int seed)
+ ATTR_NONNULL(1);
+
+/** array versions for thread safe random generation */
+RNG_THREAD_ARRAY *BLI_rng_threaded_new();
+void BLI_rng_threaded_free(struct RNG_THREAD_ARRAY *rngarr) ATTR_NONNULL(1);
+int BLI_rng_thread_rand(RNG_THREAD_ARRAY *rngarr, int thread) ATTR_WARN_UNUSED_RESULT;
+
+/* Low-discrepancy sequences. */
+
+/** Return the _n_th number of the given low-discrepancy sequence. */
+void BLI_halton_1d(unsigned int prime, double offset, int n, double *r);
+void BLI_halton_2d(const unsigned int prime[2], double offset[2], int n, double *r);
+void BLI_halton_3d(const unsigned int prime[3], double offset[3], int n, double *r);
+void BLI_hammersley_1d(unsigned int n, double *r);
+
+} // namespace blender
diff --git a/core/include/BLI_rect.h b/core/include/BLI_rect.h
index 53946b6..7d5cbc8 100644
--- a/core/include/BLI_rect.h
+++ b/core/include/BLI_rect.h
@@ -13,18 +13,19 @@
#include "DNA_vec_types.h"
-typedef struct rctf rctf;
-typedef struct rcti rcti;
+
+
+
/**
* Determine if a `rect` is empty.
* An empty `rect` is one with a zero (or negative) width or height.
*
* \return True if \a rect is empty.
*/
-bool BLI_rcti_is_empty(const struct rcti *rect);
-bool BLI_rctf_is_empty(const struct rctf *rect);
-void BLI_rctf_init(struct rctf *rect, float xmin, float xmax, float ymin, float ymax);
-void BLI_rcti_init(struct rcti *rect, int xmin, int xmax, int ymin, int ymax);
+bool BLI_rcti_is_empty(const rcti *rect);
+bool BLI_rctf_is_empty(const rctf *rect);
+void BLI_rctf_init(rctf *rect, float xmin, float xmax, float ymin, float ymax);
+void BLI_rcti_init(rcti *rect, int xmin, int xmax, int ymin, int ymax);
/**
* Check if X-min and Y-min are less than or equal to X-max and Y-max, respectively.
* If this returns false, #BLI_rctf_sanitize() can be called to address this.
@@ -32,20 +33,20 @@ void BLI_rcti_init(struct rcti *rect, int xmin, int xmax, int ymin, int ymax);
* This is not a hard constraint or invariant for rectangles, in some cases it may be useful to
* have max < min. Usually this is what you'd want though.
*/
-bool BLI_rctf_is_valid(const struct rctf *rect);
-bool BLI_rcti_is_valid(const struct rcti *rect);
+bool BLI_rctf_is_valid(const rctf *rect);
+bool BLI_rcti_is_valid(const rcti *rect);
/**
* Ensure X-min and Y-min are less than or equal to X-max and Y-max, respectively.
*/
-void BLI_rctf_sanitize(struct rctf *rect);
-void BLI_rcti_sanitize(struct rcti *rect);
-void BLI_rctf_init_pt_radius(struct rctf *rect, const float xy[2], float size);
-void BLI_rcti_init_pt_radius(struct rcti *rect, const int xy[2], int size);
-void BLI_rcti_init_minmax(struct rcti *rect);
-void BLI_rctf_init_minmax(struct rctf *rect);
-void BLI_rcti_do_minmax_v(struct rcti *rect, const int xy[2]);
-void BLI_rctf_do_minmax_v(struct rctf *rect, const float xy[2]);
-void BLI_rcti_do_minmax_rcti(struct rcti *rect, const struct rcti *other);
+void BLI_rctf_sanitize(rctf *rect);
+void BLI_rcti_sanitize(rcti *rect);
+void BLI_rctf_init_pt_radius(rctf *rect, const float xy[2], float size);
+void BLI_rcti_init_pt_radius(rcti *rect, const int xy[2], int size);
+void BLI_rcti_init_minmax(rcti *rect);
+void BLI_rctf_init_minmax(rctf *rect);
+void BLI_rcti_do_minmax_v(rcti *rect, const int xy[2]);
+void BLI_rctf_do_minmax_v(rctf *rect, const float xy[2]);
+void BLI_rcti_do_minmax_rcti(rcti *rect, const rcti *other);
/**
* Given 2 rectangles, transform a point from one to another.
@@ -65,36 +66,36 @@ void BLI_rctf_transform_calc_m4_pivot_min_ex(
void BLI_rctf_transform_calc_m4_pivot_min(const rctf *dst, const rctf *src, float matrix[4][4]);
void BLI_rctf_transform_calc_m3_pivot_min(const rctf *dst, const rctf *src, float matrix[3][3]);
-void BLI_rctf_translate(struct rctf *rect, float x, float y);
-void BLI_rcti_translate(struct rcti *rect, int x, int y);
-void BLI_rctf_mul(struct rctf *rect, float factor);
-void BLI_rcti_mul(struct rcti *rect, int factor);
-void BLI_rcti_recenter(struct rcti *rect, int x, int y);
-void BLI_rctf_recenter(struct rctf *rect, float x, float y);
-void BLI_rcti_resize(struct rcti *rect, int x, int y);
+void BLI_rctf_translate(rctf *rect, float x, float y);
+void BLI_rcti_translate(rcti *rect, int x, int y);
+void BLI_rctf_mul(rctf *rect, float factor);
+void BLI_rcti_mul(rcti *rect, int factor);
+void BLI_rcti_recenter(rcti *rect, int x, int y);
+void BLI_rctf_recenter(rctf *rect, float x, float y);
+void BLI_rcti_resize(rcti *rect, int x, int y);
/**
* Change width & height around the central X location.
*/
-void BLI_rcti_resize_x(struct rcti *rect, int x);
+void BLI_rcti_resize_x(rcti *rect, int x);
/**
* Change width & height around the central Y location.
*/
-void BLI_rcti_resize_y(struct rcti *rect, int y);
-void BLI_rcti_pad(struct rcti *rect, int pad_x, int pad_y);
-void BLI_rctf_pad(struct rctf *rect, float pad_x, float pad_y);
-void BLI_rctf_resize(struct rctf *rect, float x, float y);
-void BLI_rctf_resize_x(struct rctf *rect, float x);
-void BLI_rctf_resize_y(struct rctf *rect, float y);
+void BLI_rcti_resize_y(rcti *rect, int y);
+void BLI_rcti_pad(rcti *rect, int pad_x, int pad_y);
+void BLI_rctf_pad(rctf *rect, float pad_x, float pad_y);
+void BLI_rctf_resize(rctf *rect, float x, float y);
+void BLI_rctf_resize_x(rctf *rect, float x);
+void BLI_rctf_resize_y(rctf *rect, float y);
void BLI_rcti_scale(rcti *rect, float scale);
void BLI_rctf_scale(rctf *rect, float scale);
-void BLI_rctf_pad_y(struct rctf *rect, float boundary_size, float pad_min, float pad_max);
-void BLI_rctf_interp(struct rctf *rect,
- const struct rctf *rect_a,
- const struct rctf *rect_b,
+void BLI_rctf_pad_y(rctf *rect, float boundary_size, float pad_min, float pad_max);
+void BLI_rctf_interp(rctf *rect,
+ const rctf *rect_a,
+ const rctf *rect_b,
float fac);
-// void BLI_rcti_interp(struct rctf *rect, struct rctf *rect_a, struct rctf *rect_b, float fac);
-bool BLI_rctf_clamp_pt_v(const struct rctf *rect, float xy[2]);
-bool BLI_rcti_clamp_pt_v(const struct rcti *rect, int xy[2]);
+// void BLI_rcti_interp(rctf *rect, rctf *rect_a, rctf *rect_b, float fac);
+bool BLI_rctf_clamp_pt_v(const rctf *rect, float xy[2]);
+bool BLI_rcti_clamp_pt_v(const rcti *rect, int xy[2]);
/**
* Clamp \a rect within \a rect_bounds, setting \a r_xy to the offset.
*
@@ -103,24 +104,24 @@ bool BLI_rcti_clamp_pt_v(const struct rcti *rect, int xy[2]);
*
* \return true if a change is made.
*/
-bool BLI_rctf_clamp(struct rctf *rect, const struct rctf *rect_bounds, float r_xy[2]);
-bool BLI_rcti_clamp(struct rcti *rect, const struct rcti *rect_bounds, int r_xy[2]);
-bool BLI_rctf_compare(const struct rctf *rect_a, const struct rctf *rect_b, float limit);
-bool BLI_rcti_compare(const struct rcti *rect_a, const struct rcti *rect_b);
-bool BLI_rctf_isect(const struct rctf *src1, const struct rctf *src2, struct rctf *dest);
-bool BLI_rcti_isect(const struct rcti *src1, const struct rcti *src2, struct rcti *dest);
-bool BLI_rctf_isect_rect_x(const struct rctf *src1, const struct rctf *src2, float range_x[2]);
-bool BLI_rctf_isect_rect_y(const struct rctf *src1, const struct rctf *src2, float range_y[2]);
-bool BLI_rcti_isect_rect_x(const struct rcti *src1, const struct rcti *src2, int range_x[2]);
-bool BLI_rcti_isect_rect_y(const struct rcti *src1, const struct rcti *src2, int range_y[2]);
+bool BLI_rctf_clamp(rctf *rect, const rctf *rect_bounds, float r_xy[2]);
+bool BLI_rcti_clamp(rcti *rect, const rcti *rect_bounds, int r_xy[2]);
+bool BLI_rctf_compare(const rctf *rect_a, const rctf *rect_b, float limit);
+bool BLI_rcti_compare(const rcti *rect_a, const rcti *rect_b);
+bool BLI_rctf_isect(const rctf *src1, const rctf *src2, rctf *dest);
+bool BLI_rcti_isect(const rcti *src1, const rcti *src2, rcti *dest);
+bool BLI_rctf_isect_rect_x(const rctf *src1, const rctf *src2, float range_x[2]);
+bool BLI_rctf_isect_rect_y(const rctf *src1, const rctf *src2, float range_y[2]);
+bool BLI_rcti_isect_rect_x(const rcti *src1, const rcti *src2, int range_x[2]);
+bool BLI_rcti_isect_rect_y(const rcti *src1, const rcti *src2, int range_y[2]);
bool BLI_rcti_isect_x(const rcti *rect, int x);
bool BLI_rcti_isect_y(const rcti *rect, int y);
-bool BLI_rcti_isect_pt(const struct rcti *rect, int x, int y);
-bool BLI_rcti_isect_pt_v(const struct rcti *rect, const int xy[2]);
+bool BLI_rcti_isect_pt(const rcti *rect, int x, int y);
+bool BLI_rcti_isect_pt_v(const rcti *rect, const int xy[2]);
bool BLI_rctf_isect_x(const rctf *rect, float x);
bool BLI_rctf_isect_y(const rctf *rect, float y);
-bool BLI_rctf_isect_pt(const struct rctf *rect, float x, float y);
-bool BLI_rctf_isect_pt_v(const struct rctf *rect, const float xy[2]);
+bool BLI_rctf_isect_pt(const rctf *rect, float x, float y);
+bool BLI_rctf_isect_pt_v(const rctf *rect, const float xy[2]);
/**
* \returns shortest distance from \a rect to x (0 if inside)
*/
@@ -131,23 +132,23 @@ int BLI_rcti_length_x(const rcti *rect, int x);
int BLI_rcti_length_y(const rcti *rect, int y);
float BLI_rctf_length_x(const rctf *rect, float x);
float BLI_rctf_length_y(const rctf *rect, float y);
-bool BLI_rcti_isect_segment(const struct rcti *rect, const int s1[2], const int s2[2]);
-bool BLI_rctf_isect_segment(const struct rctf *rect, const float s1[2], const float s2[2]);
-bool BLI_rcti_isect_circle(const struct rcti *rect, const float xy[2], float radius);
-bool BLI_rctf_isect_circle(const struct rctf *rect, const float xy[2], float radius);
+bool BLI_rcti_isect_segment(const rcti *rect, const int s1[2], const int s2[2]);
+bool BLI_rctf_isect_segment(const rctf *rect, const float s1[2], const float s2[2]);
+bool BLI_rcti_isect_circle(const rcti *rect, const float xy[2], float radius);
+bool BLI_rctf_isect_circle(const rctf *rect, const float xy[2], float radius);
bool BLI_rcti_inside_rcti(const rcti *rct_a, const rcti *rct_b);
/**
* is \a rct_b inside \a rct_a
*/
bool BLI_rctf_inside_rctf(const rctf *rct_a, const rctf *rct_b);
-void BLI_rcti_union(struct rcti *rct_a, const struct rcti *rct_b);
-void BLI_rctf_union(struct rctf *rct_a, const struct rctf *rct_b);
-void BLI_rctf_union_x(struct rctf *rct, float x);
-void BLI_rctf_union_y(struct rctf *rct, float y);
-void BLI_rcti_rctf_copy(struct rcti *dst, const struct rctf *src);
-void BLI_rctf_rcti_copy(struct rctf *dst, const struct rcti *src);
-void BLI_rcti_rctf_copy_floor(struct rcti *dst, const struct rctf *src);
-void BLI_rcti_rctf_copy_round(struct rcti *dst, const struct rctf *src);
+void BLI_rcti_union(rcti *rct_a, const rcti *rct_b);
+void BLI_rctf_union(rctf *rct_a, const rctf *rct_b);
+void BLI_rctf_union_x(rctf *rct, float x);
+void BLI_rctf_union_y(rctf *rct, float y);
+void BLI_rcti_rctf_copy(rcti *dst, const rctf *src);
+void BLI_rctf_rcti_copy(rctf *dst, const rcti *src);
+void BLI_rcti_rctf_copy_floor(rcti *dst, const rctf *src);
+void BLI_rcti_rctf_copy_round(rcti *dst, const rctf *src);
/**
* Clamps the given segment to be within the rectangle.
@@ -155,57 +156,57 @@ void BLI_rcti_rctf_copy_round(struct rcti *dst, const struct rctf *src);
* \return False when no part of the segment is within the rectangle, in which case the s1 and s2
* values should be ignored.
*/
-bool BLI_rctf_clamp_segment(const struct rctf *rect, float s1[2], float s2[2]);
+bool BLI_rctf_clamp_segment(const rctf *rect, float s1[2], float s2[2]);
/**
* Expand the rectangle to fit a rotated \a src.
*/
void BLI_rctf_rotate_expand(rctf *dst, const rctf *src, float angle);
-void print_rctf(const char *str, const struct rctf *rect);
-void print_rcti(const char *str, const struct rcti *rect);
+void print_rctf(const char *str, const rctf *rect);
+void print_rcti(const char *str, const rcti *rect);
#define print_rctf_id(rect) print_rctf(STRINGIFY(rect), rect)
#define print_rcti_id(rect) print_rcti(STRINGIFY(rect), rect)
-BLI_INLINE float BLI_rcti_cent_x_fl(const struct rcti *rct)
+BLI_INLINE float BLI_rcti_cent_x_fl(const rcti *rct)
{
return (float)(rct->xmin + rct->xmax) / 2.0f;
}
-BLI_INLINE float BLI_rcti_cent_y_fl(const struct rcti *rct)
+BLI_INLINE float BLI_rcti_cent_y_fl(const rcti *rct)
{
return (float)(rct->ymin + rct->ymax) / 2.0f;
}
-BLI_INLINE int BLI_rcti_cent_x(const struct rcti *rct)
+BLI_INLINE int BLI_rcti_cent_x(const rcti *rct)
{
return (rct->xmin + rct->xmax) / 2;
}
-BLI_INLINE int BLI_rcti_cent_y(const struct rcti *rct)
+BLI_INLINE int BLI_rcti_cent_y(const rcti *rct)
{
return (rct->ymin + rct->ymax) / 2;
}
-BLI_INLINE float BLI_rctf_cent_x(const struct rctf *rct)
+BLI_INLINE float BLI_rctf_cent_x(const rctf *rct)
{
return (rct->xmin + rct->xmax) / 2.0f;
}
-BLI_INLINE float BLI_rctf_cent_y(const struct rctf *rct)
+BLI_INLINE float BLI_rctf_cent_y(const rctf *rct)
{
return (rct->ymin + rct->ymax) / 2.0f;
}
-BLI_INLINE int BLI_rcti_size_x(const struct rcti *rct)
+BLI_INLINE int BLI_rcti_size_x(const rcti *rct)
{
return (rct->xmax - rct->xmin);
}
-BLI_INLINE int BLI_rcti_size_y(const struct rcti *rct)
+BLI_INLINE int BLI_rcti_size_y(const rcti *rct)
{
return (rct->ymax - rct->ymin);
}
-BLI_INLINE float BLI_rctf_size_x(const struct rctf *rct)
+BLI_INLINE float BLI_rctf_size_x(const rctf *rct)
{
return (rct->xmax - rct->xmin);
}
-BLI_INLINE float BLI_rctf_size_y(const struct rctf *rct)
+BLI_INLINE float BLI_rctf_size_y(const rctf *rct)
{
return (rct->ymax - rct->ymin);
}
@@ -213,4 +214,3 @@ BLI_INLINE float BLI_rctf_size_y(const struct rctf *rct)
-
diff --git a/core/include/BLI_scanfill.h b/core/include/BLI_scanfill.h
new file mode 100644
index 0000000..5d6294b
--- /dev/null
+++ b/core/include/BLI_scanfill.h
@@ -0,0 +1,124 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include "DNA_listBase.h"
+
+#include <stdbool.h>
+
+namespace blender {
+
+struct ScanFillVert;
+struct ScanFillEdge;
+struct ScanFillFace;
+
+struct ScanFillContext {
+ ListBaseT<ScanFillVert> fillvertbase;
+ ListBaseT<ScanFillEdge> filledgebase;
+ ListBaseT<ScanFillFace> fillfacebase;
+
+ /* increment this value before adding each curve to skip having to calculate
+ * 'poly_nr' for edges and verts (which can take approx half scan-fill time) */
+ unsigned short poly_nr;
+
+ /* private */
+ struct MemArena *arena;
+};
+
+#define BLI_SCANFILL_ARENA_SIZE MEM_SIZE_OPTIMAL(1 << 14)
+
+/**
+ * \note this is USHRT_MAX so incrementing will set to zero
+ * which happens if callers choose to increment #ScanFillContext.poly_nr before adding each curve.
+ * Nowhere else in scan-fill do we make use of intentional overflow like this.
+ */
+#define SF_POLY_UNSET ((unsigned short)-1)
+
+struct ScanFillVert {
+ struct ScanFillVert *next, *prev;
+ union {
+ struct ScanFillVert *v;
+ void *p;
+ int i;
+ unsigned int u;
+ } tmp;
+ /** vertex location */
+ float co[3];
+ /** 2D projection of vertex location */
+ float xy[2];
+ /** index, caller can use how it likes to match the scan-fill result with own data */
+ unsigned int keyindex;
+ unsigned short poly_nr;
+ /** number of edges using this vertex */
+ unsigned char edge_count;
+ /** vert status */
+ unsigned int f : 4;
+ /** flag callers can use as they like */
+ unsigned int user_flag : 4;
+};
+
+struct ScanFillEdge {
+ struct ScanFillEdge *next, *prev;
+ struct ScanFillVert *v1, *v2;
+ unsigned short poly_nr;
+ unsigned int f : 4; /* edge status */
+ unsigned int user_flag : 4; /* flag callers can use as they like */
+ union {
+ unsigned char c;
+ } tmp;
+};
+
+struct ScanFillFace {
+ struct ScanFillFace *next, *prev;
+ struct ScanFillVert *v1, *v2, *v3;
+};
+
+/* scanfill.cc */
+
+struct ScanFillVert *BLI_scanfill_vert_add(ScanFillContext *sf_ctx, const float vec[3]);
+struct ScanFillEdge *BLI_scanfill_edge_add(ScanFillContext *sf_ctx,
+ struct ScanFillVert *v1,
+ struct ScanFillVert *v2);
+
+enum {
+ /* NOTE(@ideasman42): using #BLI_SCANFILL_CALC_REMOVE_DOUBLES
+ * Assumes ordered edges, otherwise we risk an eternal loop
+ * removing double verts. */
+ BLI_SCANFILL_CALC_REMOVE_DOUBLES = (1 << 1),
+
+ /* calculate isolated polygons */
+ BLI_SCANFILL_CALC_POLYS = (1 << 2),
+
+ /* NOTE: This flag removes checks for overlapping polygons.
+ * when this flag is set, we'll never get back more faces than (totvert - 2) */
+ BLI_SCANFILL_CALC_HOLES = (1 << 3),
+
+ /* checks valid edge users - can skip for simple loops */
+ BLI_SCANFILL_CALC_LOOSE = (1 << 4),
+};
+void BLI_scanfill_begin(ScanFillContext *sf_ctx);
+unsigned int BLI_scanfill_calc(ScanFillContext *sf_ctx, int flag);
+unsigned int BLI_scanfill_calc_ex(ScanFillContext *sf_ctx, int flag, const float nor_proj[3]);
+void BLI_scanfill_end(ScanFillContext *sf_ctx);
+
+void BLI_scanfill_begin_arena(ScanFillContext *sf_ctx, struct MemArena *arena);
+void BLI_scanfill_end_arena(ScanFillContext *sf_ctx, struct MemArena *arena);
+
+/* scanfill_utils.cc */
+
+/**
+ * Call before scan-fill to remove self intersections.
+ *
+ * \return false if no changes were made.
+ */
+bool BLI_scanfill_calc_self_isect(ScanFillContext *sf_ctx,
+ ListBaseT<ScanFillVert> *remvertbase,
+ ListBaseT<ScanFillEdge> *remedgebase);
+
+} // namespace blender
diff --git a/core/include/BLI_session_uid.h b/core/include/BLI_session_uid.h
new file mode 100644
index 0000000..e0cf279
--- /dev/null
+++ b/core/include/BLI_session_uid.h
@@ -0,0 +1,54 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ *
+ * Functions for generating and handling "Session UIDs".
+ *
+ * Note that these are not true universally-unique identifiers, but only unique during the current
+ * Blender session.
+ *
+ * For true UUIDs, see `BLI_uuid.h`.
+ */
+
+#include "DNA_session_uid_types.h"
+
+#include "BLI_hash.hh"
+
+namespace blender {
+
+/** Generate new UID which is unique throughout the Blender session. */
+SessionUID BLI_session_uid_generate();
+
+/** Check whether the UID is properly generated. */
+bool BLI_session_uid_is_generated(const SessionUID *uid);
+
+/** Check whether two UIDs are identical. */
+bool BLI_session_uid_is_equal(const SessionUID *lhs, const SessionUID *rhs);
+
+uint64_t BLI_session_uid_hash_uint64(const SessionUID *uid);
+
+/* Utility functions to make it possible to create set/map with UID as a key. */
+
+uint BLI_session_uid_ghash_hash(const void *uid_v);
+bool BLI_session_uid_ghash_compare(const void *lhs_v, const void *rhs_v);
+
+inline bool operator==(const SessionUID &lhs, const SessionUID &rhs)
+{
+ return BLI_session_uid_is_equal(&lhs, &rhs);
+}
+
+template<typename T> struct DefaultHash;
+
+template<> struct DefaultHash<SessionUID> {
+ uint64_t operator()(const SessionUID &value) const
+ {
+ return BLI_session_uid_hash_uint64(&value);
+ }
+};
+
+} // namespace blender
diff --git a/core/include/BLI_smaa_textures.h b/core/include/BLI_smaa_textures.h
new file mode 100644
index 0000000..2d824b1
--- /dev/null
+++ b/core/include/BLI_smaa_textures.h
@@ -0,0 +1,41 @@
+/* SPDX-FileCopyrightText: 2013 Jorge Jimenez <[email protected]>
+ * SPDX-FileCopyrightText: 2013 Jose I. Echevarria <[email protected]>
+ * SPDX-FileCopyrightText: 2013 Belen Masia <[email protected]>
+ * SPDX-FileCopyrightText: 2013 Fernando Navarro <[email protected]>
+ * SPDX-FileCopyrightText: 2013 Diego Gutierrez <[email protected]>
+ *
+ * SPDX-License-Identifier: MIT */
+
+/** \file
+ * \ingroup bli
+ */
+
+#pragma once
+
+namespace blender {
+
+#define AREATEX_WIDTH 160
+#define AREATEX_HEIGHT 560
+#define AREATEX_PITCH (AREATEX_WIDTH * 2)
+#define AREATEX_SIZE (AREATEX_HEIGHT * AREATEX_PITCH)
+
+/**
+ * Stored in R8G8 format. Load it in the following format:
+ * - DX10: DXGI_FORMAT_R8G8_UNORM
+ * - GPU: gpu::TextureFormat::UNORM_8_8 texture format and GPU_DATA_UBYTE data format.
+ */
+extern const unsigned char areaTexBytes[];
+
+#define SEARCHTEX_WIDTH 64
+#define SEARCHTEX_HEIGHT 16
+#define SEARCHTEX_PITCH SEARCHTEX_WIDTH
+#define SEARCHTEX_SIZE (SEARCHTEX_HEIGHT * SEARCHTEX_PITCH)
+
+/**
+ * Stored in R8 format. Load it in the following format:
+ * - DX10: DXGI_FORMAT_R8_UNORM
+ * - GPU: gpu::TextureFormat::UNORM_8 texture format and GPU_DATA_UBYTE data format.
+ */
+extern const unsigned char searchTexBytes[];
+
+} // namespace blender
diff --git a/core/include/BLI_string.h b/core/include/BLI_string.h
index 21328e6..c9913b2 100644
--- a/core/include/BLI_string.h
+++ b/core/include/BLI_string.h
@@ -1,4 +1,4 @@
-/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
*
* SPDX-License-Identifier: GPL-2.0-or-later */
@@ -692,7 +692,10 @@ void BLI_string_debug_size_after_nil(char *str, size_t str_maxncpy);
* Returns the dst.
*/
-
-
-
-
+/* Upstream-compatible safe copy for fixed-size char arrays. */
+#ifdef __cplusplus
+template<size_t N> inline char *STRNCPY(char (&dst)[N], const char *src)
+{
+ return BLI_strncpy(dst, src, N);
+}
+#endif
diff --git a/core/include/BLI_string_cursor_utf8.h b/core/include/BLI_string_cursor_utf8.h
index e4499e9..52c5781 100644
--- a/core/include/BLI_string_cursor_utf8.h
+++ b/core/include/BLI_string_cursor_utf8.h
@@ -1,4 +1,4 @@
-/* SPDX-FileCopyrightText: 2011 Blender Authors
+/* SPDX-FileCopyrightText: 2011 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
@@ -11,18 +11,18 @@
#include "BLI_sys_types.h"
-typedef enum eStrCursorJumpType eStrCursorJumpType;
enum eStrCursorJumpType {
STRCUR_JUMP_NONE,
STRCUR_JUMP_DELIM,
STRCUR_JUMP_ALL,
};
+typedef enum eStrCursorJumpType eStrCursorJumpType;
-typedef enum eStrCursorJumpDirection eStrCursorJumpDirection;
enum eStrCursorJumpDirection {
STRCUR_DIR_PREV,
STRCUR_DIR_NEXT,
};
+typedef enum eStrCursorJumpDirection eStrCursorJumpDirection;
bool BLI_str_cursor_step_next_utf8(const char *str, int str_maxlen, int *pos);
bool BLI_str_cursor_step_prev_utf8(const char *str, int str_maxlen, int *pos);
diff --git a/core/include/BLI_string_utf8_symbols.h b/core/include/BLI_string_utf8_symbols.h
new file mode 100644
index 0000000..14619e8
--- /dev/null
+++ b/core/include/BLI_string_utf8_symbols.h
@@ -0,0 +1,87 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ *
+ * Unicode characters as UTF8 strings.
+ */
+
+/* Notes:
+ * - Last portion should include the official assigned name.
+ * - Please do not add defines here that are not actually in use.
+ * - Use literal UTF8 encoding as this `u8` prefixes cause both
+ * `-Wc++20-compat` & `-Wc99-compat` warnings under CLANG.
+ */
+
+/** u00B0: `°`. */
+#define BLI_STR_UTF8_DEGREE_SIGN "\xc2\xb0"
+/** u00B2: `²` */
+#define BLI_STR_UTF8_SUPERSCRIPT_2 "\xc2\xb2"
+/** u00B3: `³` */
+#define BLI_STR_UTF8_SUPERSCRIPT_3 "\xc2\xb3"
+/** u00D7: `×`. */
+#define BLI_STR_UTF8_MULTIPLICATION_SIGN "\xc3\x97"
+/** u2007: ` ` FIGURE SPACE (numeric width space) */
+#define BLI_STR_UTF8_FIGURE_SPACE "\xe2\x80\x87"
+/** u2014: `—` */
+#define BLI_STR_UTF8_EM_DASH "\xe2\x80\x94"
+/** u2022: `•` */
+#define BLI_STR_UTF8_BULLET "\xe2\x80\xa2"
+/** u2026: `…` */
+#define BLI_STR_UTF8_HORIZONTAL_ELLIPSIS "\xe2\x80\xa6"
+/** u2190: `←` */
+#define BLI_STR_UTF8_LEFTWARDS_ARROW "\xe2\x86\x90"
+/** u2191: `↑` */
+#define BLI_STR_UTF8_UPWARDS_ARROW "\xe2\x86\x91"
+/** u2192: `→` */
+#define BLI_STR_UTF8_RIGHTWARDS_ARROW "\xe2\x86\x92"
+/** u2193: `↓` */
+#define BLI_STR_UTF8_DOWNWARDS_ARROW "\xe2\x86\x93"
+/** u21E7: `⇧` */
+#define BLI_STR_UTF8_UPWARDS_WHITE_ARROW "\xe2\x87\xa7"
+/** u21FF: `⇪` For caps lock */
+#define BLI_STR_UTF8_UPWARDS_UP_ARROW_FROM_BAR "\xe2\x87\xaa"
+/** u2277: `≷` Greater than / Less than */
+#define BLI_STR_UTF8_GREATER_THAN_OR_LESS_THAN "\xe2\x89\xb7"
+/** u2303: `⌃` */
+#define BLI_STR_UTF8_UP_ARROWHEAD "\xe2\x8c\x83"
+/** u2318: `⌘` */
+#define BLI_STR_UTF8_PLACE_OF_INTEREST_SIGN "\xe2\x8c\x98"
+/** u2325: `⌥` */
+#define BLI_STR_UTF8_OPTION_KEY "\xe2\x8c\xa5"
+/** u232B: `⌫` */
+#define BLI_STR_UTF8_ERASE_TO_THE_LEFT "\xe2\x8c\xab"
+/** u238B: `⎋` */
+#define BLI_STR_UTF8_BROKEN_CIRCLE_WITH_NORTHWEST_ARROW "\xe2\x8e\x8b"
+/** u23CE: `⏎` */
+#define BLI_STR_UTF8_RETURN_SYMBOL "\xe2\x8f\x8e"
+/** u23ED: `⏭` */
+#define BLI_STR_UTF8_BLACK_RIGHT_POINTING_DOUBLE_TRIANGLE_WITH_VERTICAL_BAR "\xe2\x8f\xad"
+/** u23EE: `⏮` */
+#define BLI_STR_UTF8_BLACK_LEFT_POINTING_DOUBLE_TRIANGLE_WITH_VERTICAL_BAR "\xe2\x8f\xae"
+/** u23EF: `⏯` */
+#define BLI_STR_UTF8_BLACK_RIGHT_POINTING_TRIANGLE_WITH_DOUBLE_VERTICAL_BAR "\xe2\x8f\xaf"
+/** u23F9: `⏹` */
+#define BLI_STR_UTF8_BLACK_SQUARE_FOR_STOP "\xe2\x8f\xb9"
+/** u2423: `␣` */
+#define BLI_STR_UTF8_OPEN_BOX "\xe2\x90\xa3"
+/** u25A6: `▦` */
+#define BLI_STR_UTF8_SQUARE_WITH_ORTHOGONAL_CROSSHATCH "\xe2\x96\xa6"
+/** u25B8: `▸` */
+#define BLI_STR_UTF8_BLACK_RIGHT_POINTING_SMALL_TRIANGLE "\xe2\x96\xb8"
+/** u2B7E: `⭾` */
+#define BLI_STR_UTF8_HORIZONTAL_TAB_KEY "\xe2\xad\xbe"
+/** u270E: `✎` Tablet Pen */
+#define BLI_STR_UTF8_LOWER_RIGHT_PENCIL "\xe2\x9c\x8e"
+/** u2710: `✐` Tablet Eraser */
+#define BLI_STR_UTF8_UPPER_RIGHT_PENCIL "\xe2\x9c\x90"
+/** u2756: `❖` */
+#define BLI_STR_UTF8_BLACK_DIAMOND_MINUS_WHITE_X "\xe2\x9d\x96"
+/** u29BE: `⦾` Use for 3D Mice */
+#define BLI_STR_UTF8_CIRCLED_WHITE_BULLET "\xe2\xa6\xbe"
+/** u2B2E: `⬮` Generic Mouse */
+#define BLI_STR_UTF8_BLACK_VERTICAL_ELLIPSE "\xe2\xac\xae"
diff --git a/core/include/BLI_string_utils.hh b/core/include/BLI_string_utils.hh
index b57a399..040060a 100644
--- a/core/include/BLI_string_utils.hh
+++ b/core/include/BLI_string_utils.hh
@@ -13,13 +13,12 @@
#include "BLI_compiler_attrs.h"
#include "BLI_function_ref.hh"
+#include "DNA_listBase.h"
#include "BLI_string_ref.hh"
#include "BLI_utildefines.h"
namespace blender {
-struct ListBase;
-
/* ------------------------------------------------------------------------- */
/** \name String Replace
* \{ */
diff --git a/core/include/BLI_tempfile.h b/core/include/BLI_tempfile.h
new file mode 100644
index 0000000..4fda4c2
--- /dev/null
+++ b/core/include/BLI_tempfile.h
@@ -0,0 +1,35 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup bli
+ */
+
+#pragma once
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_sys_types.h"
+
+namespace blender {
+
+/**
+ * Sets `tempdir` from `dirpath` when it's a valid directory.
+ * Simple sanitize operations are performed and a trailing slash is ensured.
+ */
+bool BLI_temp_directory_path_copy_if_valid(char *tempdir,
+ const size_t tempdir_maxncpy,
+ const char *dirpath) ATTR_NONNULL(1, 3);
+
+/**
+ * Get the path to a directory suitable for temporary files.
+ *
+ * The return path is guaranteed to exist and to be a directory, as well as to contain a trailing
+ * directory separator.
+ *
+ * At maximum the `tempdir_maxncpy` number of characters is written to the `tempdir`.
+ * The directory path is always null-terminated.
+ */
+void BLI_temp_directory_path_get(char *tempdir, const size_t tempdir_maxncpy) ATTR_NONNULL(1);
+
+} // namespace blender
diff --git a/core/include/BLI_time_utildefines.h b/core/include/BLI_time_utildefines.h
new file mode 100644
index 0000000..cfefca5
--- /dev/null
+++ b/core/include/BLI_time_utildefines.h
@@ -0,0 +1,115 @@
+/* SPDX-FileCopyrightText: 2013 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup bli
+ * \brief Utility defines for timing/benchmarks.
+ */
+
+#pragma once
+
+#include "BLI_time.h" /* for BLI_time_now_seconds */
+#include "BLI_utildefines.h" /* for AT */
+
+#define TIMEIT_START(var) \
+ { \
+ double _timeit_##var = BLI_time_now_seconds(); \
+ printf("time start (" #var "): " AT "\n"); \
+ fflush(stdout); \
+ { \
+ (void)0
+
+/**
+ * \return the time since TIMEIT_START was called.
+ */
+#define TIMEIT_VALUE(var) (float)(BLI_time_now_seconds() - _timeit_##var)
+
+#define TIMEIT_VALUE_PRINT(var) \
+ { \
+ printf("time update (" #var \
+ "): %.6f" \
+ " " AT "\n", \
+ TIMEIT_VALUE(var)); \
+ fflush(stdout); \
+ } \
+ (void)0
+
+#define TIMEIT_END(var) \
+ } \
+ printf("time end (" #var \
+ "): %.6f" \
+ " " AT "\n", \
+ TIMEIT_VALUE(var)); \
+ fflush(stdout); \
+ } \
+ (void)0
+
+/**
+ * _AVERAGED variants do same thing as their basic counterpart,
+ * but additionally add elapsed time to an averaged static value,
+ * useful to get sensible timing of code running fast and often.
+ */
+#define TIMEIT_START_AVERAGED(var) \
+ { \
+ static float _sum_##var = 0.0f; \
+ static float _num_##var = 0.0f; \
+ double _timeit_##var = BLI_time_now_seconds(); \
+ printf("time start (" #var "): " AT "\n"); \
+ fflush(stdout); \
+ { \
+ (void)0
+
+#define TIMEIT_AVERAGED_VALUE(var) (_num##var ? (_sum_##var / _num_##var) : 0.0f)
+
+#define TIMEIT_END_AVERAGED(var) \
+ } \
+ const float _delta_##var = TIMEIT_VALUE(var); \
+ _sum_##var += _delta_##var; \
+ _num_##var++; \
+ printf("time end (" #var \
+ "): %.6f" \
+ " " AT "\n", \
+ _delta_##var); \
+ printf("time averaged (" #var "): %.6f (total: %.6f, in %d runs)\n", \
+ (_sum_##var / _num_##var), \
+ _sum_##var, \
+ (int)_num_##var); \
+ fflush(stdout); \
+ } \
+ (void)0
+
+/**
+ * Given some function/expression:
+ * TIMEIT_BENCH(some_function(), some_unique_description);
+ */
+#define TIMEIT_BENCH(expr, id) \
+ { \
+ TIMEIT_START(id); \
+ (expr); \
+ TIMEIT_END(id); \
+ } \
+ (void)0
+
+#define TIMEIT_BLOCK_INIT(id) double _timeit_var_##id = 0
+
+#define TIMEIT_BLOCK_START(id) \
+ { \
+ double _timeit_block_start_##id = BLI_time_now_seconds(); \
+ { \
+ (void)0
+
+#define TIMEIT_BLOCK_END(id) \
+ } \
+ _timeit_var_##id += (BLI_time_now_seconds() - _timeit_block_start_##id); \
+ } \
+ (void)0
+
+#define TIMEIT_BLOCK_VALUE(id) (float)(_timeit_var_##id)
+
+#define TIMEIT_BLOCK_STATS(id) \
+ { \
+ printf("%s time (in seconds): %f\n", #id, _timeit_var_##id); \
+ fflush(stdout); \
+ } \
+ (void)0
diff --git a/core/include/BLI_timecode.h b/core/include/BLI_timecode.h
new file mode 100644
index 0000000..4f41948
--- /dev/null
+++ b/core/include/BLI_timecode.h
@@ -0,0 +1,64 @@
+/* SPDX-FileCopyrightText: 2008 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+#include <stddef.h>
+
+#include "BLI_compiler_attrs.h"
+
+namespace blender {
+
+/**
+ * Generate time-code/frame number string and store in \a str
+ *
+ * \param str: destination string
+ * \param maxncpy: maximum number of characters to copy `sizeof(str)`
+ * \param brevity_level: special setting for #View2D grid drawing,
+ * used to specify how detailed we need to be
+ * \param time_seconds: time total time in seconds
+ * \param fps: frames per second
+ * \param timecode_style: enum from #eTimecodeStyles
+ * \return length of \a str
+ */
+size_t BLI_timecode_string_from_time(char *str,
+ size_t maxncpy,
+ int brevity_level,
+ float time_seconds,
+ double fps,
+ short timecode_style) ATTR_NONNULL();
+
+/**
+ * Generate time string and store in \a str
+ *
+ * \param str: destination string
+ * \param maxncpy: maximum number of characters to copy `sizeof(str)`
+ * \param time_seconds: time total time in seconds
+ * \return length of \a str
+ */
+size_t BLI_timecode_string_from_time_simple(char *str, size_t maxncpy, double time_seconds)
+ ATTR_NONNULL();
+
+/**
+ * Generate time string and store in \a str
+ *
+ * \param str: destination string
+ * \param maxncpy: maximum number of characters to copy `sizeof(str)`
+ * \param brevity_level: special setting for #View2D grid drawing,
+ * used to specify how detailed we need to be
+ * \param time_seconds: time total time in seconds
+ * \return length of \a str
+ *
+ * \note in some cases this is used to print non-seconds values.
+ */
+size_t BLI_timecode_string_from_time_seconds(char *str,
+ size_t maxncpy,
+ int brevity_level,
+ float time_seconds) ATTR_NONNULL();
+
+} // namespace blender
diff --git a/core/include/BLI_timer.h b/core/include/BLI_timer.h
new file mode 100644
index 0000000..b7ed181
--- /dev/null
+++ b/core/include/BLI_timer.h
@@ -0,0 +1,46 @@
+/* SPDX-FileCopyrightText: 2018 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+#include "BLI_sys_types.h"
+
+namespace blender {
+
+/** \file
+ * \ingroup bli
+ */
+
+/**
+ * \return A value of:
+ * - < 0: the timer will be removed.
+ * - >= 0: the timer will be called again in this number of seconds.
+ */
+typedef double (*BLI_timer_func)(uintptr_t uuid, void *user_data);
+typedef void (*BLI_timer_data_free)(uintptr_t uuid, void *user_data);
+
+/* `func(...) < 0`: The timer will be removed.
+ * `func(...) >= 0`: The function will be called again in that many seconds. */
+void BLI_timer_register(uintptr_t uuid,
+ BLI_timer_func func,
+ void *user_data,
+ BLI_timer_data_free user_data_free,
+ double first_interval,
+ bool persistent);
+
+bool BLI_timer_is_registered(uintptr_t uuid);
+
+/** Returns False when the timer does not exist (anymore). */
+bool BLI_timer_unregister(uintptr_t uuid);
+
+/** Execute all registered functions that are due. */
+void BLI_timer_execute();
+
+void BLI_timer_free();
+
+/* This function is to be called next to BKE_CB_EVT_LOAD_PRE, to make sure the module
+ * is properly configured for the new file. */
+void BLI_timer_on_file_load();
+
+} // namespace blender
diff --git a/core/include/BLI_ustring.hh b/core/include/BLI_ustring.hh
index 53d4ecc..271c064 100644
--- a/core/include/BLI_ustring.hh
+++ b/core/include/BLI_ustring.hh
@@ -1,165 +1,6 @@
-/* SPDX-FileCopyrightText: 2026 Blender Authors
- *
- * SPDX-License-Identifier: GPL-2.0-or-later */
-
+/* BUI seam: OpenImageIO ustring not bundled. Minimal stand-in. */
#pragma once
-#include <atomic>
-
-#include <OpenImageIO/ustring.h>
-
-#include "BLI_fixed_string.hh"
-#include "BLI_hash.hh"
-#include "BLI_string_ref.hh"
-
-namespace blender {
-
-/**
- * This is a thin wrapper around OpenImageIO's ustring class. Additionally it also provides
- * conversions to our StringRef types.
- *
- * See the OpenImageIO documentation for more details:
- * https://openimageio.readthedocs.io/en/stable/imageioapi.html#efficient-unique-strings-ustring
- */
-class UString {
- private:
- /**
- * Using a member instead of inheritance because it simplifies avoiding various ambiguities with
- * operator overloads (especially equality comparison between UString, StringRef, std::string,
- * std::string_view, OpenImageIO::string_view, etc.).
- */
- OpenImageIO::ustring ustr_;
-
- public:
- UString() = default;
- explicit UString(const StringRef str) : ustr_(std::string_view(str)) {}
-
- /** A constructor that is meant to generate as little code as possible at the call site. */
- static UString from_ptr_noinline(const char *str);
-
- /**
- * Access the underlying string as a #StringRefNull.
- *
- * Note: This is not an implicit conversion to work around ambiguous function calls.
- */
- StringRefNull ref() const
- {
- return StringRefNull(ustr_.c_str(), ustr_.length());
- }
-
- const std::string &string() const
- {
- return ustr_.string();
- }
-
- const char *c_str() const
- {
- return ustr_.c_str();
- }
-
- friend bool operator==(const UString &a, const UString &b)
- {
- return a.ustr_ == b.ustr_;
- }
-
- friend bool operator==(const UString &a, const StringRef b)
- {
- return a.ref() == b;
- }
-
- uint64_t hash() const
- {
- return ustr_.hash();
- }
-
- int64_t size() const
- {
- return int64_t(ustr_.size());
- }
-
- bool is_empty() const
- {
- return ustr_.empty();
- }
-
- char operator[](const int64_t i) const
- {
- /* Accessing null char at end is allowed too. */
- BLI_assert(i >= 0 && i <= this->size());
- return ustr_[i];
- }
-};
-
-/**
- * Define DefaultHash for UString keys so that it uses the cached hash on ustrings but also
- * supports hashing arbitrary (non-unique) strings in the same way.
- *
- * Note: The string hashes produced here are different from e.g. DefaultHash<StringRef>. That is
- * fine though. The only requirement is that all hashes defined in this template specialization are
- * compatible with each other.
- */
-template<> struct DefaultHash<UString> {
- uint64_t operator()(const UString &value) const
- {
- return value.hash();
- }
-
- constexpr uint64_t operator()(const StringRef value) const
- {
- /* This is the hash function used by OpenImageIO::ustring::make_unique internally. */
- return OpenImageIO::Strutil::strhash64(value.size(), value.data());
- }
-};
-
-/**
- * Create a UString from a string literal. This is a template function so that each string is only
- * made unique once and not every time the literal is used.
- *
- * Note: OpenImageIO defines a similar `_us` string literal operator. However, it newly constructs
- * the ustring in each invocation instead of caching it in a static variable. Caching it like here
- * likely only works in C++20.
- */
-template<FixedString FStr> inline UString operator""_ustr()
-{
- /* This is a more optimized variant of just doing this:
- * ```
- * static UString ustr(FStr.data);
- * return ustr
- * ```
- *
- * The goal of the actual implementation is to improve upon performance and binary size compared
- * to the above. This is possible here we have two pieces of information the compiler can't have:
- * - Once initialized, the pointer in the #UString is never null. Thus null can be used to
- * indicate that it has not been initialized yet. No separate guard variable is needed.
- * - It is valid to initialize the static variable more than once and the result will still be
- * the same because the string does not change. So a double checked lock is not needed.
- */
- /* This is initialized to null by default. */
- static std::atomic<UString> static_ustr;
- UString ustr = static_ustr.load(std::memory_order_relaxed);
- if (ustr.c_str() == nullptr) [[unlikely]] {
- ustr = UString::from_ptr_noinline(FStr.data);
- static_ustr.store(ustr, std::memory_order_relaxed);
- }
- return ustr;
-}
-
-/**
- * Support using the `fmt` library with #UString.
- */
-inline std::string_view format_as(UString str)
-{
- return str.string();
-}
-
-} // namespace blender
-
-/**
- * Disable conflicting range formatter in fmtlib. Otherwise we will get compile errors
- * where fmtlib doesn't know if it should use the formatter from format.h or ranges.h.
- */
-namespace fmt {
-
-template<> struct is_range<blender::UString, char> : std::false_type {};
+#include <string>
-} // namespace fmt
+using UString = std::string;
diff --git a/core/include/BLI_utildefines.h b/core/include/BLI_utildefines.h
index e077c25..933c9c6 100644
--- a/core/include/BLI_utildefines.h
+++ b/core/include/BLI_utildefines.h
@@ -620,7 +620,7 @@ template<class T, size_t N> constexpr size_t ARRAY_SIZE(const T (&arg)[N]) noexc
* `BOUNDED_ARRAY_TYPE_SIZE<decltype(MyType::array)>` returns 12.
*/
template<class T>
-constexpr std::enable_if_t<blenlib_internal::IsBoundedArray<T>::value, size_t>
+constexpr std::enable_if_t<IsBoundedArray<T>::value, size_t>
BOUNDED_ARRAY_TYPE_SIZE() noexcept
{
return sizeof(std::declval<T>()) / sizeof(std::declval<T>()[0]);
diff --git a/core/include/BLI_utildefines_iter.h b/core/include/BLI_utildefines_iter.h
new file mode 100644
index 0000000..cae8a30
--- /dev/null
+++ b/core/include/BLI_utildefines_iter.h
@@ -0,0 +1,36 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ *
+ * General looping helpers, use `BLI_FOREACH` prefix.
+ */
+
+/**
+ * Even value distribution.
+ *
+ * \a src must be larger than \a dst,
+ * \a dst defines the number of iterations, their values are evenly spaced.
+ *
+ * The following pairs represent (src, dst) arguments and the values they loop over.
+ * <pre>
+ * (19, 4) -> [2, 7, 11. 16]
+ * (100, 5) -> [9, 29, 49, 69, 89]
+ * (100, 3) -> [16, 49, 83]
+ * (100, 100) -> [0..99]
+ * </pre>
+ * \note this is mainly useful for numbers that might not divide evenly into each other.
+ */
+#define BLI_FOREACH_SPARSE_RANGE(src, dst, i) \
+ for (int _src = (src), \
+ _src2 = _src * 2, \
+ _dst2 = (dst) * 2, \
+ _error = _dst2 - _src, \
+ i = 0, \
+ _delta; \
+ ((void)(_delta = divide_floor_i(_error, _dst2)), (void)(i -= _delta), (i < _src)); \
+ _error -= (_delta * _dst2) + _src2)
diff --git a/core/include/BLI_utildefines_stack.h b/core/include/BLI_utildefines_stack.h
new file mode 100644
index 0000000..4a20b89
--- /dev/null
+++ b/core/include/BLI_utildefines_stack.h
@@ -0,0 +1,90 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ *
+ * Macro's for a simple array based stack
+ * \note Caller handles alloc & free.
+ */
+
+/* only validate array-bounds in debug mode */
+#ifndef NDEBUG
+# define STACK_DECLARE(stack) unsigned int _##stack##_index, _##stack##_num_alloc
+# define STACK_INIT(stack, stack_num) \
+ ((void)stack, \
+ (void)((_##stack##_index) = 0), \
+ (void)((_##stack##_num_alloc) = (unsigned int)(stack_num)))
+# define _STACK_SIZETEST(stack, off) \
+ (BLI_assert((_##stack##_index) + (off) <= _##stack##_num_alloc))
+# define _STACK_SWAP_TOTALLOC(stack_a, stack_b) \
+ SWAP(unsigned int, _##stack_a##_num_alloc, _##stack_b##_num_alloc)
+#else
+# define STACK_DECLARE(stack) unsigned int _##stack##_index
+# define STACK_INIT(stack, stack_num) \
+ ((void)stack, (void)((_##stack##_index) = 0), (void)(0 ? (stack_num) : 0))
+# define _STACK_SIZETEST(stack, off) (void)(stack), (void)(off)
+# define _STACK_SWAP_TOTALLOC(stack_a, stack_b) (void)(stack_a), (void)(stack_b)
+#endif
+#define _STACK_BOUNDSTEST(stack, index) \
+ ((void)stack, BLI_assert((unsigned int)(index) < _##stack##_index))
+
+#define STACK_SIZE(stack) ((void)stack, (_##stack##_index))
+#define STACK_CLEAR(stack) \
+ { \
+ (void)stack; \
+ _##stack##_index = 0; \
+ } \
+ ((void)0)
+/** add item to stack */
+#define STACK_PUSH(stack, val) \
+ ((void)stack, _STACK_SIZETEST(stack, 1), ((stack)[(_##stack##_index)++] = (val)))
+#define STACK_PUSH_RET(stack) \
+ ((void)stack, _STACK_SIZETEST(stack, 1), ((stack)[(_##stack##_index)++]))
+#define STACK_PUSH_RET_PTR(stack) \
+ ((void)stack, _STACK_SIZETEST(stack, 1), &((stack)[(_##stack##_index)++]))
+/** take last item from stack */
+#define STACK_POP(stack) ((_##stack##_index) ? ((stack)[--(_##stack##_index)]) : NULL)
+#define STACK_POP_PTR(stack) ((_##stack##_index) ? &((stack)[--(_##stack##_index)]) : NULL)
+#define STACK_POP_DEFAULT(stack, r) ((_##stack##_index) ? ((stack)[--(_##stack##_index)]) : (r))
+/** look at last item (assumes non-empty stack) */
+#define STACK_PEEK(stack) (BLI_assert(_##stack##_index), ((stack)[_##stack##_index - 1]))
+#define STACK_PEEK_PTR(stack) (BLI_assert(_##stack##_index), &((stack)[_##stack##_index - 1]))
+/** remove any item from the stack, take care, re-orders */
+#define STACK_REMOVE(stack, i) \
+ { \
+ const unsigned int _i = i; \
+ _STACK_BOUNDSTEST(stack, _i); \
+ if (--_##stack##_index != _i) { \
+ stack[_i] = stack[_##stack##_index]; \
+ } \
+ } \
+ ((void)0)
+#define STACK_DISCARD(stack, n) \
+ { \
+ const unsigned int _n = n; \
+ BLI_assert(_##stack##_index >= _n); \
+ (void)stack; \
+ _##stack##_index -= _n; \
+ } \
+ ((void)0)
+#ifdef __GNUC__
+# define STACK_SWAP(stack_a, stack_b) \
+ { \
+ SWAP(typeof(stack_a), stack_a, stack_b); \
+ SWAP(unsigned int, _##stack_a##_index, _##stack_b##_index); \
+ _STACK_SWAP_TOTALLOC(stack_a, stack_b); \
+ } \
+ ((void)0)
+#else
+# define STACK_SWAP(stack_a, stack_b) \
+ { \
+ SWAP(void *, *(void **)&stack_a, *(void **)&stack_b); \
+ SWAP(unsigned int, _##stack_a##_index, _##stack_b##_index); \
+ _STACK_SWAP_TOTALLOC(stack_a, stack_b); \
+ } \
+ ((void)0)
+#endif
diff --git a/core/include/BLI_uuid.h b/core/include/BLI_uuid.h
new file mode 100644
index 0000000..7fabcb3
--- /dev/null
+++ b/core/include/BLI_uuid.h
@@ -0,0 +1,92 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ *
+ * Functions for generating and handling UUID structs according to RFC4122.
+ *
+ * Note that these are true UUIDs, not to be confused with the "session uuid" defined in
+ * `BLI_session_uid.h`.
+ */
+#include "DNA_uuid_types.h"
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_string_ref.hh"
+
+#include <initializer_list>
+#include <iosfwd>
+#include <string>
+
+namespace blender {
+
+/**
+ * UUID generator for random (version 4) UUIDs. See RFC4122 section 4.4.
+ * This function is not thread-safe. */
+bUUID BLI_uuid_generate_random();
+
+/**
+ * Return the UUID nil value, consisting of all-zero fields.
+ */
+bUUID BLI_uuid_nil();
+
+/** Return true only if this is the nil UUID. */
+bool BLI_uuid_is_nil(bUUID uuid);
+
+/** Compare two UUIDs, return true only if they are equal. */
+bool BLI_uuid_equal(bUUID uuid1, bUUID uuid2);
+
+/**
+ * Format UUID as string.
+ * The buffer must be at least 37 bytes (36 bytes for the UUID + terminating 0).
+ * Use `UUID_STRING_SIZE` from DNA_uuid_types.h if you want to use a constant for this.
+ */
+void BLI_uuid_format(char *buffer, bUUID uuid) ATTR_NONNULL();
+
+/**
+ * Parse a string as UUID.
+ * The string MUST be in the format `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`,
+ * as produced by #BLI_uuid_format().
+ *
+ * Return true if the string could be parsed, and false otherwise. In the latter case, the UUID may
+ * have been partially updated.
+ */
+bool BLI_uuid_parse_string(bUUID *uuid, const char *buffer) ATTR_NONNULL();
+
+/** Output the UUID as formatted ASCII string, see #BLI_uuid_format(). */
+std::ostream &operator<<(std::ostream &stream, bUUID uuid);
+
+class UUID : public bUUID {
+ public:
+ /**
+ * Default constructor, used with `bUUID value{};`, will initialize to the nil UUID.
+ */
+ UUID() = default;
+
+ /** Initialize from the bUUID DNA struct. */
+ UUID(const bUUID &struct_uuid);
+
+ /** Initialize from 11 integers, 5 for the regular fields and 6 for the `node` array. */
+ UUID(std::initializer_list<uint32_t> field_values);
+
+ /** Initialize by parsing the string; undefined behavior when the string is invalid. */
+ explicit UUID(StringRefNull string_formatted_uuid);
+
+ /** Return the UUID as formatted ASCII string, see #BLI_uuid_format(). */
+ std::string str() const;
+
+ uint64_t hash() const;
+}; // namespace blender
+
+bool operator==(UUID uuid1, UUID uuid2);
+bool operator!=(UUID uuid1, UUID uuid2);
+
+/**
+ * Lexicographic comparison of the UUIDs.
+ * Equivalent to string comparison on the formatted UUIDs. */
+bool operator<(UUID uuid1, UUID uuid2);
+
+} // namespace blender
diff --git a/core/include/BLI_voxel.h b/core/include/BLI_voxel.h
new file mode 100644
index 0000000..9361bc7
--- /dev/null
+++ b/core/include/BLI_voxel.h
@@ -0,0 +1,22 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ */
+
+namespace blender {
+
+/** Calculate the index number of a voxel, given x/y/z integer coords and resolution vector. */
+#define BLI_VOXEL_INDEX(x, y, z, res) \
+ ((int64_t)(x) + (int64_t)(y) * (int64_t)(res)[0] + \
+ (int64_t)(z) * (int64_t)(res)[0] * (int64_t)(res)[1])
+
+/* All input coordinates must be in bounding box 0.0 - 1.0. */
+
+float BLI_voxel_sample_trilinear(const float *data, const int res[3], const float co[3]);
+
+} // namespace blender
diff --git a/core/include/BLI_winstuff.h b/core/include/BLI_winstuff.h
new file mode 100644
index 0000000..27f054e
--- /dev/null
+++ b/core/include/BLI_winstuff.h
@@ -0,0 +1,145 @@
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+/** \file
+ * \ingroup bli
+ * \brief Compatibility-like things for windows.
+ */
+
+#ifndef _WIN32
+# error "This include is for Windows only!"
+#endif
+
+#include "BLI_sys_types.h"
+
+#include <windows.h>
+
+#undef rad
+#undef rad1
+#undef rad2
+#undef rad3
+#undef vec
+#undef rect
+#undef rct1
+#undef rct2
+
+#undef small
+
+/* These definitions are also in BLI_math for simplicity. */
+
+#if !defined(_USE_MATH_DEFINES)
+# define _USE_MATH_DEFINES
+#endif
+
+#ifndef S_ISREG
+# define S_ISREG(x) (((x) & _S_IFREG) == _S_IFREG)
+#endif
+#ifndef S_ISDIR
+# define S_ISDIR(x) (((x) & _S_IFDIR) == _S_IFDIR)
+#endif
+
+#if defined(_MSC_VER)
+# define R_OK 4
+# define W_OK 2
+/* Not accepted by `access()` on windows. */
+// # define X_OK 1
+# define F_OK 0
+#endif
+
+typedef unsigned int mode_t;
+
+/** Directory reading compatibility with UNIX. */
+struct dirent {
+ int d_ino;
+ int d_off;
+ unsigned short d_reclen;
+ char *d_name;
+};
+
+/** Intentionally opaque to users. */
+typedef struct __dirstream DIR;
+
+DIR *opendir(const char *path);
+struct dirent *readdir(DIR *dp);
+int closedir(DIR *dp);
+const char *dirname(char *path);
+
+namespace blender {
+
+/* Windows utility functions. */
+
+bool BLI_windows_is_store_install(void);
+bool BLI_windows_register_blend_extension(bool all_users);
+bool BLI_windows_unregister_blend_extension(bool all_users);
+bool BLI_windows_update_pinned_launcher(const char *launcher_path);
+
+/* Gets the version of the currently loaded DirectX driver for the first device that matches
+ * deviceString. This is required for Qualcomm devices which use Mesa's Gallium D2D12 layer for
+ * OpenGL functionality */
+bool BLI_windows_get_directx_driver_version(const wchar_t *deviceSubString,
+ long long *r_driverVersion);
+
+/* Checks the version of the Windows build in the format "major.minor.build".
+ * Example: 10.0.22000 corresponds to Windows 11 21H2. */
+bool BLI_windows_is_build_version_greater_or_equal(DWORD majorVersion,
+ DWORD minorVersion,
+ DWORD buildNumber);
+
+/**
+ * Set the `root_dir` to the default root directory on MS-Windows,
+ * The string is guaranteed to be set with a length of 3 & null terminated,
+ * using a fall-back in case the root directory can't be found.
+ */
+void BLI_windows_get_default_root_dir(char root_dir[4]);
+int BLI_windows_get_executable_dir(char r_dirpath[/*FILE_MAXDIR*/]);
+
+/* ShellExecute Helpers. */
+
+bool BLI_windows_external_operation_supported(const char *filepath, const char *operation);
+bool BLI_windows_external_operation_execute(const char *filepath, const char *operation);
+
+/**
+ * Launch our own executable.
+ *
+ * \param parameters: application parameters separated by spaces.
+ * \param wait: whether to wait for the instance to exit.
+ * \param elevated: run as administrator. Will do UAC prompt.
+ * \param silent: Not show the launched program.
+ */
+bool BLI_windows_execute_self(const char *parameters,
+ const bool wait,
+ const bool elevated,
+ const bool silent);
+
+/** Quality of Service (QoS) modes as defined in the Windows documentation at:
+ * https://learn.microsoft.com/en-us/windows/win32/procthread/quality-of-service */
+enum class QoSMode {
+ /** Default mode uses heuristics described in Windows docs. */
+ DEFAULT = 0,
+ /** HighQoS mode for performance critical scenarios. */
+ HIGH = 1,
+ /** EcoQoS mode for preserving energy. */
+ ECO = 2
+};
+
+/** QoS precedence (to make sure command line args overwrite what is set by jobs).
+ * Higher values have more precedence. */
+enum class QoSPrecedence {
+ /** QoS mode requested set via the job system. */
+ JOB = 0,
+ /** QoS mode requested set via a command line argument. */
+ CMDLINE_ARG = 1,
+};
+
+/**
+ * Sets the Quality of Service (QoS) mode of the process.
+ *
+ * \param qos_mode: The QoS mode to use for the process.
+ * \param qos_precedence: The precedence of the caller (higher wins).
+ */
+void BLI_windows_process_set_qos(QoSMode qos_mode, QoSPrecedence qos_precedence);
+
+} // namespace blender
diff --git a/core/include/DNA_listBase.h b/core/include/DNA_listBase.h
index 6d78c7b..4cbc8cc 100644
--- a/core/include/DNA_listBase.h
+++ b/core/include/DNA_listBase.h
@@ -1,4 +1,4 @@
-/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
*
* SPDX-License-Identifier: GPL-2.0-or-later */
@@ -12,6 +12,12 @@
#pragma once
+/* Shared with types/dna/include/DNA_listBase.h: whichever is included first
+ * defines the global structs once so both translation units and the
+ * blender-qualified aliases below/in there refer to the same types. */
+#ifndef BUI_DNA_LISTBASE_SHARED
+#define BUI_DNA_LISTBASE_SHARED
+
/* typedef-first so the headers work in both C11 and C++ translation units. */
typedef struct Link Link;
typedef struct LinkData LinkData;
@@ -38,6 +44,8 @@ struct ListBase {
void *first, *last;
};
+#endif /* BUI_DNA_LISTBASE_SHARED */
+
#ifdef __cplusplus
template<typename T> struct ListBaseTIterator;
@@ -61,7 +69,7 @@ template<typename T> struct ListBaseT : public ListBase {
ListBaseTIterator<T> end() const
{
/* Don't use `this->last` because this iterator has to point to one-past-the-end. */
- return ListBaseTIterator<T>{NULL};
+ return ListBaseTIterator<T>{nullptr};
}
/** Iterator that returns also gives an index for every item. This helps prevent mistakes
diff --git a/core/include/DNA_vec_types.h b/core/include/DNA_vec_types.h
deleted file mode 100644
index 78298d9..0000000
--- a/core/include/DNA_vec_types.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
- *
- * SPDX-License-Identifier: GPL-2.0-or-later */
-
-/** \file
- * \ingroup DNA
- */
-
-#pragma once
-
-
-/* types */
-
-/** vector of two shorts. */
-typedef struct vec2s vec2s;
-struct vec2s {
- short x, y;
-};
-
-/** vector of two floats. */
-typedef struct vec2f vec2f;
-struct vec2f {
- float x, y;
-};
-
-typedef struct vec2i vec2i;
-struct vec2i {
- int x, y;
-};
-
-/* not used at the moment */
-/*
-typedef struct vec2d vec2d;
-struct vec2d {
- double x, y;
-};
-*/
-typedef struct vec3i vec3i;
-struct vec3i {
- int x, y, z;
-};
-
-typedef struct vec3f vec3f;
-struct vec3f {
- float x, y, z;
-};
-/*
-typedef struct vec3d vec3d;
-struct vec3d {
- double x, y, z;
-};
-
-typedef struct vec4i vec4i;
-struct vec4i {
- int x, y, z, w;
-};
-*/
-typedef struct vec4f vec4f;
-struct vec4f {
- float x, y, z, w;
-};
-
-/**
- * This type generally shouldn't be used. It only exists for cases where a DNA type that
- * corresponds to `blender:float4x4` is required. Note that `float4x4` is 16 byte aligned, but we
- * can't enforce that this struct yet.
- */
-typedef struct mat4x4f mat4x4f;
-struct mat4x4f {
- float value[4][4];
-};
-/*
-typedef struct vec4d vec4d;
-struct vec4d {
- double x, y, z, w;
-};
-*/
-
-/** integer rectangle. */
-typedef struct rcti rcti;
-struct rcti {
- int xmin, xmax;
- int ymin, ymax;
-
-#ifdef __cplusplus
- bool operator==(const rcti &other) const
- {
- return xmin == other.xmin && xmax == other.xmax && ymin == other.ymin && ymax == other.ymax;
- }
- bool operator!=(const rcti &other) const
- {
- return !(*this == other);
- }
-#endif
-};
-
-/** float rectangle. */
-typedef struct rctf rctf;
-struct rctf {
- float xmin, xmax;
- float ymin, ymax;
-};
-
-/** dual quaternion. */
-typedef struct DualQuat DualQuat;
-struct DualQuat {
- float quat[4];
- float trans[4];
-
- float scale[4][4];
- float scale_weight;
-};
-
-
-
-
-
diff --git a/core/include/MEM_guardedalloc.h b/core/include/MEM_guardedalloc.h
index 895737f..68ef94c 100644
--- a/core/include/MEM_guardedalloc.h
+++ b/core/include/MEM_guardedalloc.h
@@ -1,4 +1,4 @@
-/* Minimal stand-in for Blender's guarded memory allocator.
+/* Minimal stand-in for Blender's guarded memory allocator.
* Same API surface, plain malloc/realloc backing. Leak debugging is out of
* scope for the BUI core; swap in a real allocator behind this header later.
* SPDX-License-Identifier: GPL-2.0-or-later */
@@ -11,25 +11,92 @@
#define MEM_SIZE_OPTIMAL(size) ((size))
/* Upstream reserves bytes for per-block bookkeeping; this shim keeps none. */
#define MEM_SIZE_OVERHEAD ((size_t)0)
+
+/* Modern MEM API used by the C++ BLI headers. */
+void *MEM_new_uninitialized(size_t size, const char *name);
+void *MEM_new_zeroed(size_t size, const char *name);
+void *MEM_new_uninitialized_aligned(size_t size, size_t alignment, const char *name);
+void MEM_delete_void(void *ptr);
+void *MEM_dupalloc_void(const void *vmemh);
+
+/* Alignment guaranteed by MEM_new_zeroed / malloc on all supported targets. */
+#define MEM_MIN_CPP_ALIGNMENT ((size_t)16)
+
#ifdef __cplusplus
extern "C" {
#endif
-void *MEM_mallocN(size_t len, const char *str) /* ATTR_MALLOC */ /* ATTR_WARN_UNUSED_RESULT */;
-void *MEM_malloc_arrayN(size_t len, size_t size, const char *str) /* ATTR_WARN_UNUSED_RESULT */;
-void *MEM_mallocN_aligned(size_t len, size_t alignment, const char *str)
- /* ATTR_MALLOC */ /* ATTR_WARN_UNUSED_RESULT */;
-void *MEM_callocN(size_t len, const char *str) /* ATTR_WARN_UNUSED_RESULT */;
-void *MEM_calloc_arrayN(size_t len, size_t size, const char *str) /* ATTR_WARN_UNUSED_RESULT */;
-void *MEM_reallocN_id(void *vmemh, size_t len, const char *str) /* ATTR_WARN_UNUSED_RESULT */;
-void *MEM_recallocN_id(void *vmemh, size_t len, const char *str) /* ATTR_WARN_UNUSED_RESULT */;
-void *MEM_dupallocN(const void *vmemh) /* ATTR_WARN_UNUSED_RESULT */;
+void *MEM_mallocN(size_t len, const char *str);
+void *MEM_malloc_arrayN(size_t len, size_t size, const char *str);
+void *MEM_mallocN_aligned(size_t len, size_t alignment, const char *str);
+void *MEM_callocN(size_t len, const char *str);
+void *MEM_calloc_arrayN(size_t len, size_t size, const char *str);
+void *MEM_reallocN_id(void *vmemh, size_t len, const char *str);
+void *MEM_recallocN_id(void *vmemh, size_t len, const char *str);
+void *MEM_dupallocN(const void *vmemh);
void MEM_freeN(void *vmemh);
-size_t MEM_allocN_len(const void *vmemh) /* ATTR_WARN_UNUSED_RESULT */;
+size_t MEM_allocN_len(const void *vmemh);
#ifdef __cplusplus
}
#endif
-#endif /* __MEM_GUARDEDALLOC_H__ */
+/* C++ helpers mirroring upstream MEM_guardedalloc.hh. */
+#ifdef __cplusplus
+#include <new>
+#include <type_traits>
+/* Upstream forms: allocate a single object. */
+template<typename T> inline T *MEM_new(const char *name)
+{
+ void *mem = MEM_new_uninitialized(sizeof(T), name);
+ return new (mem) T();
+}
+template<typename T> inline T *MEM_new_uninitialized(const char *name)
+{
+ return static_cast<T *>(MEM_new_uninitialized(sizeof(T), name));
+}
+template<typename T> inline T *MEM_new_zeroed(const char *name)
+{
+ void *mem = MEM_new_zeroed(sizeof(T), name);
+ return new (mem) T();
+}
+/* Array forms. */
+template<typename T> inline T *MEM_new_uninitialized(size_t count, const char *name)
+{
+ return static_cast<T *>(MEM_new_uninitialized(count * sizeof(T), name));
+}
+template<typename T> inline T *MEM_new_zeroed(size_t count, const char *name)
+{
+ return static_cast<T *>(MEM_new_zeroed(count * sizeof(T), name));
+}
+template<typename T> inline T *MEM_new_array_uninitialized(size_t count, const char *name)
+{
+ return static_cast<T *>(MEM_new_uninitialized(count * sizeof(T), name));
+}
+
+template<typename T> void MEM_delete(T *ptr)
+{
+ if (ptr) {
+ if constexpr (!std::is_trivially_destructible_v<T>) {
+ ptr->~T();
+ }
+ MEM_freeN(ptr);
+ }
+}
+
+template<typename T> T *MEM_dupalloc(const T *vmemh)
+{
+ return static_cast<T *>(MEM_dupalloc_void(vmemh));
+}
+
+#define MEM_SAFE_DELETE(ptr) \
+ do { \
+ if (ptr) { \
+ MEM_delete(ptr); \
+ ptr = nullptr; \
+ } \
+ } while (0)
+#endif
+
+#endif /* __MEM_GUARDEDALLOC_H__ */
diff --git a/core/include/UI_interface_types.hh b/core/include/UI_interface_types.hh
new file mode 100644
index 0000000..048682d
--- /dev/null
+++ b/core/include/UI_interface_types.hh
@@ -0,0 +1,52 @@
+/* SPDX-FileCopyrightText: 2025 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+#include <string>
+
+#include "BLI_string_ref.hh"
+
+struct bContext;
+struct Block;
+struct Button;
+struct Layout;
+struct TooltipData;
+
+/* names */
+#define UI_MAX_DRAW_STR 550
+#define UI_MAX_NAME_STR 256
+#define UI_MAX_SHORTCUT_STR 64
+
+#define RNA_NO_INDEX -1
+
+/* Menu Callbacks */
+
+using MenuCreateFunc = void (*)(bContext *C, Layout *layout, void *arg1);
+using MenuHandleFunc = void (*)(bContext *C, void *arg, int event);
+
+/**
+ * Used for cycling menu values without opening the menu (Ctrl-Wheel).
+ * \param direction: forward or backwards [1 / -1].
+ * \param arg1: `Button.poin` (as with #MenuCreateFunc).
+ * \return true when the button was changed.
+ */
+using MenuStepFunc = bool (*)(bContext *C, int direction, void *arg1);
+
+using CopyArgFunc = void *(*)(const void *arg);
+using FreeArgFunc = void (*)(void *arg);
+
+/** Must return an allocated string. */
+using ButtonToolTipFunc = std::string (*)(bContext *C, void *argN, StringRef tip);
+
+/**
+ * \param data: The tooltip data to be filled.
+ * \param but: The exact button the tooltip is shown for. This is needed when the tooltip function
+ * is shared across multiple buttons but there still needs to be some customization per button.
+ * Mostly useful when using #uiLayoutSetTooltipCustomFunc.
+ */
+using ButtonToolTipCustomFunc = void (*)(bContext &C, TooltipData &data, Button *but, void *argN);
+class Display;
+using ColorManagedDisplay = ocio::Display;
+
diff --git a/core/include/fmt/format.h b/core/include/fmt/format.h
index 3c13781..1954de0 100644
--- a/core/include/fmt/format.h
+++ b/core/include/fmt/format.h
@@ -4,8 +4,9 @@
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
-#include <string>
#include <sstream>
+#include <string>
+#include <type_traits>
namespace fmt {
@@ -23,4 +24,6 @@ template<typename T> inline std::string to_string(const T &value)
return ss.str();
}
+template<typename T, typename... Args> struct is_range : std::false_type {};
+
} // namespace fmt
diff --git a/core/include/fmt/ranges.h b/core/include/fmt/ranges.h
index 3c13781..39c5fc6 100644
--- a/core/include/fmt/ranges.h
+++ b/core/include/fmt/ranges.h
@@ -1,26 +1,2 @@
-/* Minimal stand-in for the {fmt} library, used only so the vendored BLI
- * headers compile inside BUI. Formatting behavior is NOT implemented;
- * replace with a real fmt build when needed.
- * SPDX-License-Identifier: GPL-2.0-or-later */
-#pragma once
-
-#include <string>
-#include <sstream>
-
-namespace fmt {
-
-template<typename... Args> inline std::string format(const char *fmt_str, Args &&...args)
-{
- (void)fmt_str;
- (void)((int)sizeof...(args));
- return std::string(fmt_str);
-}
-
-template<typename T> inline std::string to_string(const T &value)
-{
- std::ostringstream ss;
- ss << value;
- return ss.str();
-}
-
-} // namespace fmt
+#pragma once
+#include "format.h"
diff --git a/core/intern/guardedalloc.c b/core/intern/guardedalloc.c
index f986ab6..e3137f8 100644
--- a/core/intern/guardedalloc.c
+++ b/core/intern/guardedalloc.c
@@ -106,3 +106,28 @@ size_t MEM_allocN_len(const void *vmemh)
return bui_malloc_usable_size((void *)vmemh);
}
+void *MEM_new_uninitialized(size_t size, const char *str)
+{
+ return MEM_mallocN(size, str);
+}
+
+void *MEM_new_zeroed(size_t size, const char *str)
+{
+ return MEM_callocN(size, str);
+}
+
+void *MEM_new_uninitialized_aligned(size_t size, size_t alignment, const char *str)
+{
+ return MEM_mallocN_aligned(size, alignment, str);
+}
+
+void MEM_delete_void(void *ptr)
+{
+ MEM_freeN(ptr);
+}
+
+
+void *MEM_dupalloc_void(const void *vmemh)
+{
+ return MEM_dupallocN(vmemh);
+}
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
index ce56295..c3d6e0b 100644
--- a/examples/CMakeLists.txt
+++ b/examples/CMakeLists.txt
@@ -1,3 +1,7 @@
-# Examples land here as the ui module comes online.
+# BUI examples.
# SPDX-License-Identifier: GPL-2.0-or-later
-message(STATUS "BUI: no examples yet")
+
+# Renders a showcase scene through the GPU sink into an SVG file. Works with
+# 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)
diff --git a/examples/__pycache__/components_demo.cpython-314.pyc b/examples/__pycache__/components_demo.cpython-314.pyc
new file mode 100644
index 0000000..3f18446
Binary files /dev/null and b/examples/__pycache__/components_demo.cpython-314.pyc differ
diff --git a/examples/__pycache__/tk_unchanged_app.cpython-314.pyc b/examples/__pycache__/tk_unchanged_app.cpython-314.pyc
new file mode 100644
index 0000000..a8d2924
Binary files /dev/null and b/examples/__pycache__/tk_unchanged_app.cpython-314.pyc differ
diff --git a/examples/components_demo.py b/examples/components_demo.py
new file mode 100644
index 0000000..4027e0c
--- /dev/null
+++ b/examples/components_demo.py
@@ -0,0 +1,293 @@
+"""Blender component library demo (bui.components).
+
+ python examples/components_demo.py
+
+Every component, laid out like Blender's properties editor. Try it like
+Blender:
+
+* drag number fields / sliders (cursor hides and never hits the edge;
+ Shift = precise, Ctrl = snap, Alt = all of X/Y/Z), click to type (``2*pi``)
+* Ctrl+Wheel over any value, Ctrl+C / Ctrl+V, Backspace resets, Minus negates,
+ right-click any value for its context menu
+* drag across checkboxes or panel headers; drag a panel's grip to reorder;
+ Ctrl+click a header to solo it
+* File/Edit menus: hover to switch, type to search, submenus; Q opens a pie
+* color swatches open the HSV wheel (or square) with an eyedropper
+* the side tabs on the left switch pages; hover them for names
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import os
+import sys
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "bindings", "python"))
+
+from bui.components import (App, Box, Button, Checkbox, ColorRamp, ColorSwatch, Column, # noqa: E402
+ CurveMapping, Decorator, Dropdown, EnumRow, Grid, GridView,
+ Histogram, HotkeyField, IconButton, IDSelector, Label, ListView,
+ MenuBar, MenuItem, NormalBall, NumberField, NumberSlider, Panel,
+ PathField, PieMenu, Popover, ProgressBar, Row, ScrollView,
+ SearchField, Separator, SideTabs, Split, Tabs, TextField, Toggle,
+ TreeItem, TreeView, VectorField)
+
+
+def page(*children):
+ """A properties-editor page: padded column of panels."""
+ return Column(*children, padding=8, spacing=6)
+
+
+def prop(label, component, decorate=True):
+ """Blender property row: right-aligned label | value | keyframe dot."""
+ right = Row(component, Decorator(weight=0)) if decorate else component
+ return Split(Label(label, align="right"), right, factor=0.4)
+
+
+# ---------------------------------------------------------------------------
+# Pages
+
+
+def object_page(status, progress):
+ transform = Panel(
+ "Transform",
+ VectorField("Location", (0.0, 1.25, 0.0), suffix=" m",
+ description="Location of the object\nAlt+drag edits X, Y and Z together"),
+ VectorField("Rotation", (0.0, 0.0, 90.0), suffix="°", step=5,
+ description="Rotation in degrees"),
+ prop("Scale", NumberSlider("", 1.0, min=0.0, max=4.0, step=0.1,
+ description="Uniform scale",
+ on_change=lambda v: progress.set_value(v / 4))),
+ prop("Mode", Dropdown(items=["Object Mode", "Edit Mode", "Sculpt Mode",
+ "Vertex Paint", "Weight Paint", "Texture Paint"],
+ icons=["OBJECT_DATAMODE", "EDITMODE_HLT", "SCULPTMODE_HLT",
+ "BRUSH_DATA", "BRUSH_DATA", "TEXTURE"],
+ description="Interaction mode")),
+ icon="OBJECT_DATA",
+ )
+ visibility = Panel(
+ "Visibility",
+ Row(Toggle("", True, icon="RESTRICT_SELECT_OFF", description="Selectable"),
+ Toggle("", True, icon="HIDE_OFF", description="Show in viewports"),
+ Toggle("", True, icon="RESTRICT_RENDER_OFF", description="Show in renders"),
+ align=True),
+ Grid(Checkbox("Camera", True), Checkbox("Diffuse", True), Checkbox("Glossy", True),
+ Checkbox("Transmission", True), Checkbox("Volume Scatter", False),
+ Checkbox("Shadow", True), columns=2),
+ Panel("Mask", Checkbox("Shadow Catcher"), Checkbox("Holdout")),
+ Panel("Motion Blur", prop("Steps", NumberField("", 1, min=1, max=7)),
+ header=[Checkbox("", True)]),
+ )
+ viewport = Panel(
+ "Viewport Display",
+ prop("Display As", EnumRow(items=["Bounds", "Wire", "Solid", "Textured"],
+ icons=["MESH_CUBE", "SHADING_RENDERED", "MATERIAL",
+ "TEXTURE"], icon_only=True, value="Textured")),
+ prop("Color", ColorSwatch(value=(0.28, 0.45, 0.70, 1.0),
+ description="Viewport display color")),
+ prop("Shading", EnumRow(items=["Flat", "Smooth", "Auto"], value="Smooth")),
+ Row(Toggle("X"), Toggle("Y", True), Toggle("Z"), align=True),
+ collapsed=True,
+ )
+ return page(
+ IDSelector(["Cube", "Camera", "Light", "Suzanne"], "Cube", icon="OBJECT_DATA"),
+ transform, visibility, viewport,
+ )
+
+
+def modifiers_page():
+ ramp = ColorRamp(((0.0, (0.05, 0.05, 0.2, 1.0)), (0.45, (0.9, 0.3, 0.1, 1.0)),
+ (1.0, (1.0, 0.95, 0.6, 1.0))), interpolation="Ease")
+ curves = CurveMapping(((0.0, 0.0), (0.3, 0.18), (0.7, 0.85), (1.0, 1.0)),
+ channels=("C", "R", "G", "B"))
+ subdiv = Panel(
+ "Subdivision",
+ EnumRow(items=["Catmull-Clark", "Simple"]),
+ prop("Levels Viewport", NumberField("", 1, min=0, max=6)),
+ prop("Render", NumberField("", 2, min=0, max=6)),
+ Checkbox("Optimal Display", True),
+ icon="MODIFIER",
+ )
+ return page(
+ Row(Button("Add Modifier", icon="ADD"),
+ IconButton("PREFERENCES", description="Modifier options", weight=0)),
+ subdiv,
+ Panel("Color Ramp", ramp, icon="TEXTURE"),
+ Panel("RGB Curves", curves, icon="CURVE_DATA"),
+ )
+
+
+def material_page():
+ bins = []
+ for i in range(48):
+ t = i / 47
+ bins.append((0.25 + 0.7 * t * (1 - t) * 4 * abs(__import__("math").sin(t * 7)) * 0.5,
+ 0.2 + 0.6 * (1 - abs(t - 0.45) * 2) ** 2,
+ 0.15 + 0.5 * t ** 2))
+ tiles = GridView([("Metal", (0.7, 0.72, 0.75, 1)), ("Gold", (0.95, 0.75, 0.3, 1)),
+ ("Glass", (0.6, 0.85, 0.95, 1)), ("Rubber", (0.15, 0.15, 0.15, 1)),
+ ("Emission", (1.0, 0.5, 0.2, 1)), ("Wood", (0.5, 0.3, 0.15, 1)),
+ ("World", "WORLD"), ("Node", "NODE")], tile=3.6, rows=2)
+ surface = Panel(
+ "Surface",
+ prop("Base Color", ColorSwatch(value=(0.8, 0.2, 0.15, 1.0))),
+ prop("Emission", ColorSwatch(value=(1.0, 0.6, 0.2, 0.5), picker="square",
+ description="Square picker (SV + Hue)")),
+ prop("Metallic", NumberSlider("", 0.0, min=0, max=1, step=0.05)),
+ prop("Roughness", NumberSlider("", 0.5, min=0, max=1, step=0.05)),
+ prop("IOR", NumberField("", 1.45, min=1.0, max=4.0, step=0.01)),
+ icon="MATERIAL",
+ )
+ return page(
+ IDSelector(["Material", "Metal", "Glass"], "Material", icon="MATERIAL"),
+ Panel("Preview", tiles),
+ surface,
+ Panel("Normal", Row(NormalBall("", (0.3, 0.5, 0.8)),
+ Column(Label("Drag the ball to aim"), Label("the light direction."),
+ weight=2))),
+ Panel("Histogram", Histogram(bins)),
+ )
+
+
+def outliner_page(status):
+ scene = TreeItem("Scene Collection", icon="SCENE_DATA")
+ props = TreeItem("Props", icon="OUTLINER_COLLECTION",
+ toggles={"hide": False, "render": False})
+ for name, icon in (("Cube", "MESH_CUBE"), ("Suzanne", "MESH_CUBE"),
+ ("Plane", "MESH_CUBE")):
+ props.add(TreeItem(name, TreeItem(name + " Mesh", icon="MESH_DATA"),
+ TreeItem("Material", icon="MATERIAL"), icon="OBJECT_DATA",
+ expanded=False))
+ scene.add(TreeItem("Camera", icon="CAMERA_DATA"), TreeItem("Light", icon="LIGHT"), props)
+ tree = TreeView([scene], rows=9, columns=("hide", "select", "render"),
+ on_change=lambda it: status.show("Selected " + it.label if it else ""))
+
+ names = ["Cube", "Camera", "Light", "Suzanne", "Plane", "Cylinder", "Empty", "Torus"]
+ lst = ListView(names, rows=5, icons=["OBJECT_DATA"] * len(names))
+
+ def filt(text):
+ tree.roots = [scene] if not text else [
+ it for it in _walk(scene) if text.lower() in it.label.lower()]
+
+ return page(
+ SearchField(on_change=filt, description="Filter the tree"),
+ tree,
+ Panel("UI List", lst, Row(
+ IconButton("ADD", lambda: setattr(lst, "items", lst.items + [
+ "Object.%03d" % len(lst.items)]), emboss=True, weight=0),
+ IconButton("REMOVE", lambda: setattr(lst, "items", lst.items[:-1]),
+ emboss=True, weight=0))),
+ )
+
+
+def _walk(item):
+ for c in item.children:
+ yield c
+ yield from _walk(c)
+
+
+def prefs_page(status):
+ many = ScrollView(Column(*[Checkbox("Add-on %02d" % i, i % 3 == 0) for i in range(24)]),
+ rows=5)
+ return page(
+ Panel("Input",
+ prop("Search", HotkeyField("", "F3"), decorate=False),
+ prop("Render", HotkeyField("", "F12"), decorate=False),
+ prop("Emulate", EnumRow(items=["Off", "3 Button", "Numpad"], vertical=True),
+ decorate=False),
+ icon="PREFERENCES"),
+ Panel("File Paths",
+ prop("Fonts", PathField("", "//fonts/", directory=True), decorate=False),
+ prop("Textures", PathField("", "//textures/", directory=True), decorate=False),
+ prop("Temp", TextField(placeholder="Temporary directory"), decorate=False)),
+ Panel("Add-ons", SearchField(), many),
+ Panel("Interface",
+ Popover("Viewport Options",
+ Checkbox("Show Gizmos", True), Checkbox("Show Overlays", True),
+ NumberSlider("Opacity", 0.8), icon="PREFERENCES"),
+ Tabs([("Resolution", Box(prop("Scale", NumberSlider("", 1.0, min=0.5, max=2),
+ decorate=False))),
+ ("Text", Box(prop("Hinting", Dropdown(items=["Auto", "None", "Slight",
+ "Full"]), decorate=False)))]),
+ Row(Button("Save Preferences", icon="FILE",
+ on_click=lambda: status.show("Preferences saved")),
+ Button("Disabled", enabled=False))),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Window
+
+
+class Status(Label):
+ def show(self, text):
+ self.text = text
+
+
+def build() -> App:
+ status = Status("Q: pie menu · right-click values · drag panel grips", align="left",
+ icon="INFO")
+ progress = ProgressBar(0.25, "Rendering 25%")
+
+ def say(text):
+ return lambda: status.show(text)
+
+ recent = [MenuItem("/projects/%s.blend" % n, say("Open " + n)) for n in
+ ("robot", "forest", "studio")]
+ menubar = MenuBar(
+ ("File", [MenuItem("New", say("New file"), icon="FILE", shortcut="Ctrl N"),
+ MenuItem("Open...", say("Open"), icon="FILE_FOLDER", shortcut="Ctrl O"),
+ MenuItem("Open Recent", submenu=recent, shortcut="Shift Ctrl O"),
+ "-",
+ MenuItem("Save", say("Saved"), icon="FILE", shortcut="Ctrl S"),
+ MenuItem("Save As...", say("Save as"), shortcut="Shift Ctrl S"),
+ MenuItem("Auto Save", checked=True),
+ "-",
+ MenuItem("Import", submenu=[MenuItem("glTF 2.0"), MenuItem("FBX"),
+ MenuItem("Wavefront (.obj)")], icon="IMPORT"),
+ MenuItem("Export", submenu=[MenuItem("glTF 2.0"), MenuItem("USD")],
+ icon="EXPORT"),
+ "-",
+ MenuItem("Quit", say("Quit"), shortcut="Ctrl Q")]),
+ ("Edit", [MenuItem("Undo", say("Undo"), icon="LOOP_BACK", shortcut="Ctrl Z"),
+ MenuItem("Redo", say("Redo"), icon="LOOP_FORWARDS", shortcut="Shift Ctrl Z"),
+ "-",
+ MenuItem("Lock Object Modes", checked=False),
+ MenuItem("Preferences...", say("Preferences"), icon="PREFERENCES")]),
+ ("Render", [MenuItem("Render Image", say("Render"), icon="RENDER_STILL",
+ shortcut="F12"),
+ MenuItem("Render Animation", say("Animation"), shortcut="Ctrl F12"),
+ MenuItem("View Render", enabled=False, shortcut="F11")]),
+ ("Help", [MenuItem("Manual", icon="INFO"), MenuItem("Report a Bug", icon="ERROR")]),
+ right=[IconButton("PLAY", say("Play"), description="Play animation"),
+ IconButton("SEARCH", say("Search"), description="Search (F3)")],
+ )
+
+ pages = SideTabs([
+ ("OBJECT_DATA", "Object", object_page(status, progress)),
+ ("MODIFIER", "Modifiers", modifiers_page()),
+ ("MATERIAL", "Material", material_page()),
+ ("OUTLINER", "Outliner", outliner_page(status)),
+ ("PREFERENCES", "Preferences", prefs_page(status)),
+ ])
+
+ app = App("BUI — Blender components", (520, 900), pages,
+ Column(progress, status, padding=8, spacing=4),
+ header=menubar, padding=0, spacing=0)
+
+ def pie():
+ PieMenu.show(app.ctx, [
+ MenuItem("Object Mode", say("Object Mode"), icon="OBJECT_DATAMODE"),
+ MenuItem("Edit Mode", say("Edit Mode"), icon="EDITMODE_HLT"),
+ MenuItem("Sculpt Mode", say("Sculpt Mode"), icon="SCULPTMODE_HLT"),
+ MenuItem("Vertex Paint", say("Vertex Paint"), icon="BRUSH_DATA"),
+ MenuItem("Weight Paint", say("Weight Paint"), icon="BRUSH_DATA"),
+ MenuItem("Texture Paint", say("Texture Paint"), icon="TEXTURE"),
+ ], "Mode")
+
+ app.bind("q", pie)
+ app.bind("ctrl+s", say("Saved"))
+ return app
+
+
+if __name__ == "__main__":
+ build().run()
diff --git a/examples/python_demo.py b/examples/python_demo.py
new file mode 100644
index 0000000..ac00a21
--- /dev/null
+++ b/examples/python_demo.py
@@ -0,0 +1,50 @@
+"""BUI Python example: render the demo scene to an SVG file.
+
+Works headless (CI-friendly). For a live window, see bui/qt.py or run:
+
+ python -c "import sys; from PySide6.QtWidgets import QApplication; \
+ import buipy; from bui.qt import BuiCanvas; \
+ app=QApplication(sys.argv); c=BuiCanvas(); c.resize(800,600); \
+ c.show(); sys.exit(app.exec())"
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import glob
+import os
+import sys
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+# The buipy extension lives in the build tree; the 'bui' package in the source
+# tree. BUIPY_BUILD_DIR overrides the auto-detection of build*/bindings/python.
+_candidates = [os.environ.get("BUIPY_BUILD_DIR", "")]
+_candidates += sorted(
+ glob.glob(os.path.join(_HERE, "..", "build*", "bindings", "python")), reverse=True
+)
+_seen = set()
+for _p in _candidates:
+ if _p and os.path.isdir(_p) and _p not in _seen:
+ _seen.add(_p)
+ sys.path.insert(0, _p)
+sys.path.insert(0, os.path.join(_HERE, "..", "bindings", "python"))
+
+import buipy # noqa: E402
+from bui.svg import SvgSink # noqa: E402
+
+
+def main() -> int:
+ sink = SvgSink(640, 480)
+ buipy.set_backend(sink)
+ try:
+ buipy.demo_scene(640, 480)
+ finally:
+ buipy.set_backend(None)
+
+ out = sys.argv[1] if len(sys.argv) > 1 else "bui_python_demo.svg"
+ sink.save(out)
+ print("SVG written to", out)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/examples/qt_syntax_demo.py b/examples/qt_syntax_demo.py
new file mode 100644
index 0000000..156b631
--- /dev/null
+++ b/examples/qt_syntax_demo.py
@@ -0,0 +1,89 @@
+"""Qt-syntax demo: a real Qt-style application drawn entirely by BUI.
+
+The window host is picked automatically: PySide6/PyQt6 if installed,
+otherwise a stdlib tkinter window — same code, same BUI rendering.
+
+ python examples/qt_syntax_demo.py
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import os
+import sys
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "bindings", "python"))
+
+from bui.qtsyntax import (QApplication, QComboBox, QGridLayout, QHBoxLayout,
+ QLabel, QLineEdit, QProgressBar, QPushButton,
+ QSlider, QSpinBox, QVBoxLayout, QWidget)
+
+
+def main() -> int:
+ app = QApplication(sys.argv)
+ window = QWidget()
+ window.setWindowTitle("BUI — Qt syntax")
+ window.resize(520, 420)
+
+ root = QVBoxLayout()
+ title = QLabel("Qt syntax, BUI renderer")
+ title.setStyleSheet("font-size: 18px; color: #7aa2f7;")
+ title.setAlignment("center")
+ root.addWidget(title)
+
+ grid = QGridLayout()
+ grid.addWidget(QLabel("Name:"), 0, 0)
+ name = QLineEdit()
+ name.setPlaceholderText("type here…")
+ grid.addWidget(name, 0, 1)
+
+ grid.addWidget(QLabel("Choice:"), 1, 0)
+ combo = QComboBox()
+ combo.addItems(["widget", "engine", "renderer"])
+ grid.addWidget(combo, 1, 1)
+
+ grid.addWidget(QLabel("Level:"), 2, 0)
+ slider = QSlider()
+ slider.setRange(0, 100)
+ slider.setValue(30)
+ grid.addWidget(slider, 2, 1)
+
+ grid.addWidget(QLabel("Count:"), 3, 0)
+ spin = QSpinBox()
+ spin.setRange(0, 20)
+ grid.addWidget(spin, 3, 1)
+
+ grid.addWidget(QLabel("Progress:"), 4, 0)
+ bar = QProgressBar()
+ bar.setRange(0, 100)
+ bar.setValue(30)
+ grid.addWidget(bar, 4, 1)
+ slider.valueChanged.connect(bar.setValue)
+
+ root.addLayout(grid)
+
+ status = QLabel("Press the button.")
+ status.setAlignment("center")
+ root.addWidget(status)
+
+ def on_click():
+ count = getattr(on_click, "n", 0) + 1
+ on_click.n = count
+ status.setText("{} — clicked {} time(s)!".format(
+ name.text() or "BUI", count))
+
+ buttons = QHBoxLayout()
+ go = QPushButton("Click me")
+ go.clicked.connect(on_click)
+ bye = QPushButton("Quit")
+ bye.clicked.connect(app.quit)
+ buttons.addWidget(go)
+ buttons.addWidget(bye)
+ root.addLayout(buttons)
+
+ window.setLayout(root)
+ window.show()
+ return app.exec()
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/examples/svg_demo.c b/examples/svg_demo.c
new file mode 100644
index 0000000..c18963b
--- /dev/null
+++ b/examples/svg_demo.c
@@ -0,0 +1,143 @@
+/* BUI example: draw a showcase scene through the GPU sink into an SVG file.
+ *
+ * Demonstrates the sink dispatch: the same primitives could be rendered by
+ * the Qt backend (backends/qt) or a Python backend (bindings/python).
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "bui_c_api.h"
+#include "GPU_immediate.hh"
+
+typedef struct SvgRecorder {
+ FILE *file;
+ int width;
+ int height;
+} SvgRecorder;
+
+static void hex_color(const float rgba[4], char out[8])
+{
+ for (int i = 0; i < 3; i++) {
+ float c = rgba[i];
+ c = c < 0.0f ? 0.0f : (c > 1.0f ? 1.0f : c);
+ snprintf(out + i * 2, 3, "%02x", (unsigned int)(c * 255.0f + 0.5f));
+ }
+ out[6] = '\0';
+}
+
+static void rec_triangles(void *user, const float (*coords)[2], const float (*colors)[4], int count)
+{
+ SvgRecorder *rec = user;
+ for (int i = 0; i + 2 < count; i += 3) {
+ char hex[8];
+ hex_color(colors[i], hex);
+ fprintf(rec->file,
+ "<polygon points=\"%.1f,%.1f %.1f,%.1f %.1f,%.1f\" fill=\"#%s\"/>\n",
+ coords[i][0], coords[i][1], coords[i + 1][0], coords[i + 1][1], coords[i + 2][0],
+ coords[i + 2][1], hex);
+ }
+}
+
+static void rec_lines(void *user, const float (*coords)[2], const float (*colors)[4], int count)
+{
+ SvgRecorder *rec = user;
+ for (int i = 0; i + 1 < count; i += 2) {
+ char hex[8];
+ hex_color(colors[i], hex);
+ fprintf(rec->file,
+ "<line x1=\"%.1f\" y1=\"%.1f\" x2=\"%.1f\" y2=\"%.1f\" stroke=\"#%s\" "
+ "stroke-width=\"1\"/>\n",
+ coords[i][0], coords[i][1], coords[i + 1][0], coords[i + 1][1], hex);
+ }
+}
+
+static void rec_points(void *user, const float (*coords)[2], const float (*colors)[4], int count, float size)
+{
+ SvgRecorder *rec = user;
+ for (int i = 0; i < count; i++) {
+ char hex[8];
+ hex_color(colors[i], hex);
+ fprintf(rec->file, "<circle cx=\"%.1f\" cy=\"%.1f\" r=\"%.1f\" fill=\"#%s\"/>\n",
+ coords[i][0], coords[i][1], size > 0 ? size / 2.0f : 0.5f, hex);
+ }
+}
+
+static void rec_text(void *user, float x, float y, const char *text, float size, const float rgba[4])
+{
+ SvgRecorder *rec = user;
+ char hex[8];
+ hex_color(rgba, hex);
+ fprintf(rec->file, "<text x=\"%.1f\" y=\"%.1f\" font-size=\"%.0f\" fill=\"#%s\">%s</text>\n",
+ x, y, size, hex, text);
+}
+
+static void rec_begin(void *user, int w, int h)
+{
+ SvgRecorder *rec = user;
+ rec->width = w;
+ rec->height = h;
+ fprintf(rec->file,
+ "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"%d\" height=\"%d\">\n",
+ w, h);
+}
+
+static void rec_end(void *user)
+{
+ SvgRecorder *rec = user;
+ (void)rec;
+ fprintf(rec->file, "</svg>\n");
+}
+
+int main(int argc, char **argv)
+{
+ const char *out_path = argc > 1 ? argv[1] : "bui_svg_demo.svg";
+
+ SvgRecorder rec;
+ rec.file = fopen(out_path, "w");
+ rec.width = 640;
+ rec.height = 480;
+ if (!rec.file) {
+ perror("fopen");
+ return 1;
+ }
+
+ BuiGpuSink sink = {0};
+ sink.user = &rec;
+ sink.begin_frame = rec_begin;
+ sink.triangles = rec_triangles;
+ sink.lines = rec_lines;
+ sink.points = rec_points;
+ sink.text = rec_text;
+ sink.end_frame = rec_end;
+ bui_set_render_sink(&sink);
+
+ /* Draw through the BUI immediate-mode seam; the sink receives everything. */
+ GPUVertFormat *fmt = immVertexFormat();
+ unsigned int pos_id = GPU_vertformat_attr_add(fmt, "pos", SFLOAT_32_32);
+ unsigned int col_id = GPU_vertformat_attr_add(fmt, "color", SFLOAT_32_32_32_32);
+
+ immBindBuiltinProgram(GPU_SHADER_2D_SMOOTH_COLOR);
+ immBegin(GPU_PRIM_TRIS, 3);
+ immAttr4f(col_id, 0.25f, 0.47f, 0.85f, 1.0f);
+ immVertex2f(pos_id, 320.0f, 60.0f);
+ immAttr4f(col_id, 0.85f, 0.35f, 0.35f, 1.0f);
+ immVertex2f(pos_id, 120.0f, 420.0f);
+ immAttr4f(col_id, 0.35f, 0.8f, 0.45f, 1.0f);
+ immVertex2f(pos_id, 520.0f, 420.0f);
+ immEnd();
+
+ immBegin(GPU_PRIM_LINE_STRIP, 4);
+ for (int i = 0; i < 4; i++) {
+ immAttr4f(col_id, 0.95f, 0.85f, 0.4f, 1.0f);
+ immVertex2f(pos_id, 100.0f + i * 60.0f, 450.0f - i * 8.0f);
+ }
+ immEnd();
+ immUnbindProgram();
+
+ bui_set_render_sink(NULL);
+ fclose(rec.file);
+ printf("SVG written to %s\n", out_path);
+ return 0;
+}
diff --git a/examples/tk_syntax_demo.py b/examples/tk_syntax_demo.py
new file mode 100644
index 0000000..2fdaf5b
--- /dev/null
+++ b/examples/tk_syntax_demo.py
@@ -0,0 +1,92 @@
+"""tkinter-syntax demo: a tkinter-style application drawn entirely by BUI.
+
+Laid out like a Blender properties editor: panels (LabelFrame) holding
+"label | field" rows. Runs on the stdlib alone — no Qt, no pip packages.
+
+ python examples/tk_syntax_demo.py
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import os
+import sys
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "bindings", "python"))
+
+from bui.tksyntax import (Button, Canvas, Checkbutton, Entry, Frame, IntVar,
+ Label, LabelFrame, Listbox, Progressbar, Radiobutton,
+ Scale, Spinbox, StringVar, Tk)
+
+
+def main() -> int:
+ root = Tk()
+ root.title("BUI — tkinter syntax")
+ root.geometry("440x700")
+
+ Label(root, text="tkinter syntax, BUI renderer", font=("", 15)).pack(pady=(10, 4))
+
+ def row(panel, text):
+ """A Blender-style split row: right-aligned label, field fills the rest."""
+ f = Frame(panel)
+ f.pack(fill="x", pady=2)
+ Label(f, text=text, width=9, anchor="e").pack(side="left")
+ return f
+
+ # -- Object panel ---------------------------------------------------------
+ obj = LabelFrame(root, text="Object")
+ obj.pack(fill="x", padx=8, pady=4)
+
+ name = StringVar()
+ Entry(row(obj, "Name"), textvariable=name).pack(side="left", fill="x", expand=True)
+
+ progress = None
+ level = Scale(row(obj, "Level"), from_=0, to=100, orient="horizontal",
+ command=lambda v: progress.configure(value=float(v)))
+ level.pack(side="left", fill="x", expand=True)
+
+ count = Spinbox(row(obj, "Count"), from_=0, to=10)
+ count.pack(side="left", fill="x", expand=True)
+
+ progress = Progressbar(row(obj, "Progress"), maximum=100)
+ progress.pack(side="left", fill="x", expand=True)
+
+ echo = Label(obj, text="Type a name, then click.")
+ echo.pack(pady=(6, 2))
+
+ def on_click():
+ n = getattr(on_click, "n", 0) + 1
+ on_click.n = n
+ echo.configure(text="{} — clicked {} time(s)!".format(name.get() or "BUI", n))
+
+ Button(obj, text="Click me", command=on_click).pack(fill="x", pady=(2, 4))
+
+ # -- Options panel --------------------------------------------------------
+ opts = LabelFrame(root, text="Options")
+ opts.pack(fill="x", padx=8, pady=4)
+ Checkbutton(opts, text="Enable notifications").pack(anchor="w", padx=6)
+ lvl = IntVar()
+ for text, val in (("Beginner", 1), ("Expert", 2)):
+ Radiobutton(opts, text=text, value=val, variable=lvl).pack(anchor="w", padx=6)
+
+ # -- Items panel ----------------------------------------------------------
+ items = LabelFrame(root, text="Items")
+ items.pack(fill="x", padx=8, pady=4)
+ lb = Listbox(items)
+ for item in ("Cube", "Camera", "Light", "Suzanne"):
+ lb.insert("end", item)
+ lb.pack(fill="x", padx=4, pady=2)
+
+ cv = Canvas(items, width=180, height=60, bg="#282828")
+ cv.create_rectangle(10, 10, 80, 50, fill="#4772b3", outline="")
+ cv.create_oval(100, 10, 170, 50, fill="#e6a23c", outline="")
+ cv.create_text(45, 30, text="canvas", fill="#ffffff")
+ cv.pack(pady=4)
+
+ Button(root, text="Quit", command=root.destroy).pack(fill="x", padx=8, pady=8)
+
+ root.mainloop()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/examples/tk_unchanged_app.py b/examples/tk_unchanged_app.py
new file mode 100644
index 0000000..54d0ef0
--- /dev/null
+++ b/examples/tk_unchanged_app.py
@@ -0,0 +1,104 @@
+"""A plain tkinter program - no BUI imports.
+
+Run it on BUI (Blender look, native window) without changing a line:
+
+ python -m bui.tksyntax examples/tk_unchanged_app.py
+
+or on the stdlib Tk for comparison:
+
+ python examples/tk_unchanged_app.py
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import tkinter as tk
+from tkinter import messagebox, ttk
+
+
+def build(root):
+ root.title("Inventory")
+ menubar = tk.Menu(root)
+ filemenu = tk.Menu(menubar, tearoff=0)
+ filemenu.add_command(label="New", accelerator="Ctrl+N")
+ filemenu.add_command(label="Open...", accelerator="Ctrl+O")
+ filemenu.add_separator()
+ filemenu.add_command(label="Quit", command=root.destroy)
+ menubar.add_cascade(label="File", menu=filemenu)
+ editmenu = tk.Menu(menubar, tearoff=0)
+ editmenu.add_command(label="Undo", accelerator="Ctrl+Z")
+ menubar.add_cascade(label="Edit", menu=editmenu)
+ root.config(menu=menubar)
+
+ nb = ttk.Notebook(root)
+ nb.pack(fill="both", expand=True, padx=6, pady=6)
+
+ # -- Items tab: a form and a table -------------------------------------------
+ items = ttk.Frame(nb, padding=6)
+ nb.add(items, text="Items")
+ form = ttk.LabelFrame(items, text="New item")
+ form.pack(fill="x")
+ name = tk.StringVar(value="Cube")
+ ttk.Label(form, text="Name").grid(row=0, column=0, sticky="e", padx=4, pady=2)
+ ttk.Entry(form, textvariable=name).grid(row=0, column=1, sticky="we", pady=2)
+ ttk.Label(form, text="Kind").grid(row=1, column=0, sticky="e", padx=4, pady=2)
+ kind = ttk.Combobox(form, values=("Mesh", "Light", "Camera"), state="readonly")
+ kind.current(0)
+ kind.grid(row=1, column=1, sticky="we", pady=2)
+ ttk.Label(form, text="Count").grid(row=2, column=0, sticky="e", padx=4, pady=2)
+ count = tk.Spinbox(form, from_=1, to=99)
+ count.grid(row=2, column=1, sticky="we", pady=2)
+ ttk.Label(form, text="Scale").grid(row=3, column=0, sticky="e", padx=4, pady=2)
+ scale = tk.Scale(form, from_=0, to=100, orient="horizontal")
+ scale.set(40)
+ scale.grid(row=3, column=1, sticky="we", pady=2)
+ visible = tk.BooleanVar(value=True)
+ ttk.Checkbutton(form, text="Visible", variable=visible).grid(row=4, column=1, sticky="w")
+ form.columnconfigure(1, weight=1)
+
+ table = ttk.Frame(items)
+ table.pack(fill="both", expand=True, pady=(6, 0))
+ tree = ttk.Treeview(table, columns=("name", "kind", "count"), show="headings", height=6)
+ tree.heading("name", text="Name")
+ tree.heading("kind", text="Kind")
+ tree.heading("count", text="Count")
+ for row in (("Cube", "Mesh", 2), ("Sun", "Light", 1), ("Cam", "Camera", 1)):
+ tree.insert("", "end", values=row)
+ sb = ttk.Scrollbar(table, orient="vertical", command=tree.yview)
+ tree.configure(yscrollcommand=sb.set)
+ tree.pack(side="left", fill="both", expand=True)
+ sb.pack(side="right", fill="y")
+
+ def add():
+ tree.insert("", "end", values=(name.get(), kind.get(), count.get()))
+ buttons = ttk.Frame(items)
+ buttons.pack(fill="x", pady=(6, 0))
+ ttk.Button(buttons, text="Add", command=add).pack(side="left", expand=True, fill="x")
+ ttk.Button(buttons, text="About", command=lambda: messagebox.showinfo(
+ "About", "A plain tkinter program.")).pack(side="left", expand=True, fill="x", padx=4)
+
+ # -- Notes tab: text with tags and a scrollbar ---------------------------------------
+ notes = ttk.Frame(nb, padding=6)
+ nb.add(notes, text="Notes")
+ text = tk.Text(notes, height=10, width=40)
+ tsb = ttk.Scrollbar(notes, command=text.yview)
+ text.configure(yscrollcommand=tsb.set)
+ text.pack(side="left", fill="both", expand=True)
+ tsb.pack(side="right", fill="y")
+ text.insert("end", "TODO: ", "todo")
+ text.insert("end", "light the scene\n")
+ text.tag_configure("todo", foreground="#e6a23c")
+
+ # -- Canvas tab -----------------------------------------------------------------------
+ draw = ttk.Frame(nb, padding=6)
+ nb.add(draw, text="Canvas")
+ canvas = tk.Canvas(draw, width=300, height=180)
+ canvas.pack(fill="both", expand=True)
+ canvas.create_rectangle(20, 20, 120, 80, fill="#4772b3", outline="")
+ canvas.create_oval(150, 30, 230, 110, fill="#e6a23c", outline="")
+ canvas.create_line(20, 150, 280, 120, width=2, arrow="last")
+ canvas.create_text(70, 50, text="canvas", fill="white")
+ return root
+
+
+if __name__ == "__main__":
+ build(tk.Tk()).mainloop()
diff --git a/gpu/CMakeLists.txt b/gpu/CMakeLists.txt
index a884b85..01305ed 100644
--- a/gpu/CMakeLists.txt
+++ b/gpu/CMakeLists.txt
@@ -7,6 +7,7 @@
set(SRC
intern/gpu_null.c
+ intern/gpu_raster.c
)
add_library(bui_gpu STATIC ${SRC})
@@ -17,3 +18,10 @@ target_include_directories(bui_gpu PUBLIC
${CMAKE_SOURCE_DIR}/core/include
)
target_link_libraries(bui_gpu PUBLIC bui::core)
+if(NOT MSVC)
+ target_link_libraries(bui_gpu PRIVATE m)
+endif()
+if(WIN32)
+ # gpu_raster.c: GDI glyph-run text engine + native window present.
+ target_link_libraries(bui_gpu PUBLIC gdi32 user32)
+endif()
diff --git a/gpu/include/GPU_backend_sink.h b/gpu/include/GPU_backend_sink.h
new file mode 100644
index 0000000..a897cc8
--- /dev/null
+++ b/gpu/include/GPU_backend_sink.h
@@ -0,0 +1,56 @@
+/* BUI GPU seam: render-backend dispatch.
+ *
+ * The null backend (gpu/intern/gpu_null.c) turns the toolkit's immediate-mode
+ * calls and vertex batches into flat screen-space primitive lists and hands
+ * them to a "sink" installed by the host. This is the single integration point
+ * that makes BUI renderable with any technology: a C++ QPainter backend
+ * (backends/qt), a Python/PySide6 backend (bindings/python/bui/qt.py), an SVG
+ * recorder, a terminal grid, etc.
+ *
+ * Coordinates: 2D positions in the current model space (identity matrices give
+ * pixel coordinates). Colors: RGBA floats 0..1, premultiplication not applied.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct BuiGpuSink {
+ /** Opaque handle passed back to every callback. */
+ void *user;
+
+ /** Optional: called once before a batch of primitives. */
+ void (*begin_frame)(void *user, int viewport_w, int viewport_h);
+ /** Optional: clip rect; width/height <= 0 removes the clip. */
+ void (*scissor)(void *user, int x, int y, int w, int h);
+ /** Non-indexed triangles: `count` vertices. */
+ void (*triangles)(void *user,
+ const float (*coords)[2],
+ const float (*colors)[4],
+ int count);
+ /** Line list: `count` = number of line endpoints. */
+ void (*lines)(void *user, const float (*coords)[2], const float (*colors)[4], int count);
+ /** Points: `count` vertices at `size` pixels. */
+ void (*points)(
+ void *user, const float (*coords)[2], const float (*colors)[4], int count, float size);
+ /** Optional: text at baseline position. The stub text engine emits nothing
+ * unless a host registers glyph runs via BUI_sink_text(). */
+ void (*text)(void *user, float x, float y, const char *text, float size, const float rgba[4]);
+ /** Optional: called once after a batch of primitives. */
+ void (*end_frame)(void *user);
+} BuiGpuSink;
+
+/* Install a sink (replacing any previous one). Pass NULL to restore the pure
+ * null backend, which discards all geometry. */
+void GPU_backend_sink_set(const BuiGpuSink *sink);
+const BuiGpuSink *GPU_backend_sink_get(void);
+
+/* Record the active viewport (used by hosts; the sink receives it in
+ * begin_frame). Width/height of 0 means "unknown". */
+void GPU_viewport_size_set(int width, int height);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/gpu/include/GPU_batch.hh b/gpu/include/GPU_batch.hh
index d3951ea..fcbf350 100644
--- a/gpu/include/GPU_batch.hh
+++ b/gpu/include/GPU_batch.hh
@@ -1,16 +1,15 @@
-/* BUI GPU seam: batches, vertex/index buffers, uniform buffers.
- * Minimal opaque handles + creation API for the UI toolkit.
+/* BUI GPU seam: batches, vertex/index buffers, uniform buffers.
+ * Minimal API-compatible surface for the extracted UI toolkit.
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include "GPU_state.hh"
-#ifdef __cplusplus
-extern "C" {
-#endif
+#include <stdlib.h>
+
+/* Opaque C types + shared enums first so both C and C++ consumers see them
+ * before the C++ alias block below. */
-typedef struct GPUVertFormat GPUVertFormat;
-typedef struct GPUVertBuf GPUVertBuf;
typedef struct GPUIndexBuf GPUIndexBuf;
typedef struct GPUBatch GPUBatch;
typedef struct GPUUniformBuf GPUUniformBuf;
@@ -23,6 +22,15 @@ typedef enum eGPUAttrType {
GPU_COMP_U16,
GPU_COMP_I32,
GPU_COMP_U32,
+ /* blender::gpu::VertAttrType aliases used by toolkit call-sites. */
+ SFLOAT_32 = GPU_COMP_F32,
+ SFLOAT_32_32,
+ SFLOAT_32_32_32,
+ SFLOAT_32_32_32_32,
+ UBYTE_8_UINT,
+ UINT_32 = GPU_COMP_U32,
+ UNORM_8,
+ UNORM_8_8_8_8,
} eGPUAttrType;
typedef enum eGPUAttrFetchMode {
@@ -31,29 +39,175 @@ typedef enum eGPUAttrFetchMode {
GPU_FETCH_UBYTE_TO_FLOAT,
} eGPUAttrFetchMode;
+/* Batch ownership flags (upstream: eGPUBatchFlag). */
+typedef enum eGPUBatchFlag {
+ GPU_BATCH_INVALID = (1 << 0),
+ GPU_BATCH_OWNS_VBO = (1 << 1),
+ GPU_BATCH_OWNS_IBO = (1 << 2),
+ GPU_BATCH_DIRTY = (1 << 3),
+} eGPUBatchFlag;
+/* Upstream spell-check: the index-buffer ownership flag is called OWNS_INDEX. */
+#define GPU_BATCH_OWNS_INDEX GPU_BATCH_OWNS_IBO
+
+/* Concrete format struct: call-sites stack-allocate these. */
+#define BUI_VERTFORMAT_MAX_ATTRS 8
+typedef struct GPUVertFormat GPUVertFormat;
+struct GPUVertFormat {
+ unsigned int attr_len;
+ unsigned int stride;
+ struct {
+ char name[32];
+ unsigned int attr_type;
+ unsigned int components;
+ unsigned int fetch_mode;
+ unsigned int offset;
+ } attrs[BUI_VERTFORMAT_MAX_ATTRS];
+};
+
+/* Raw attribute cursor used to fill a vertex buffer attribute in place
+ * (upstream shape). */
+typedef struct GPUVertBufRaw {
+ unsigned int size;
+ void *data;
+ void *data_init;
+ unsigned int stride;
+} GPUVertBufRaw;
+
+/* Index buffer builder (upstream shape). The null backend only records the
+ * element count; a real renderer uploads `data`. */
+typedef struct GPUIndexBufBuilder {
+ unsigned int max_allowed_index;
+ unsigned int max_index;
+ unsigned int index_len;
+ unsigned int used;
+ unsigned int index_min;
+ unsigned int index_max;
+ int prim_type;
+ unsigned int *data;
+} GPUIndexBufBuilder;
+
+#ifdef __cplusplus
+
+namespace blender::gpu {
+
+/* The toolkit only ever fills vertex buffers through the C API or through
+ * #data<T>(). The first four members form a layout contract with the C
+ * backends in gpu/intern (see GPUVertBufInternal there). */
+struct VertBuf {
+ unsigned int vertex_len = 0;
+ unsigned int stride = 0;
+ void *cpu_data = nullptr;
+ GPUVertFormat *format = nullptr; /* heap copy owned by the buffer */
+
+ template<typename T> struct DataView {
+ T *ptr;
+ T *data()
+ {
+ return ptr;
+ }
+ };
+ /* Lazily backs the buffer with CPU memory so callers can write vertices
+ * even with the null backend (which discards them at draw time). */
+ template<typename T> DataView<T> data()
+ {
+ if (cpu_data == nullptr) {
+ size_t bytes = size_t(vertex_len) * (stride ? stride : sizeof(T));
+ if (bytes == 0) {
+ bytes = sizeof(T);
+ }
+ cpu_data = calloc(1, bytes);
+ }
+ return DataView<T>(static_cast<T *>(cpu_data));
+ }
+};
+
+enum class TextureFormat : unsigned char {
+ RGBA8,
+ RGBA8UI,
+ RGBA16F,
+ RGBA32F,
+ R8,
+ RG16,
+ RGBA16,
+ UNORM_8_8_8_8,
+ UNORM_8,
+};
+
+using Batch = ::GPUBatch;
+using VertAttrType = ::eGPUAttrType;
+using VertFetchMode = ::eGPUAttrFetchMode;
+using UniformBuf = ::GPUUniformBuf;
+
+} // namespace blender::gpu
+
+typedef blender::gpu::VertBuf GPUVertBuf;
+typedef blender::gpu::TextureFormat GPUTextureFormat;
+
+/* C++ convenience overloads (upstream takes references). Allocated buffers use
+ * calloc on purpose so the C and C++ sides share one free()-consistent
+ * ownership story; zeroed bytes equal the default member initializers. */
+inline GPUVertBuf *GPU_vertbuf_create_with_format(const GPUVertFormat &format)
+{
+ GPUVertBuf *verts = static_cast<GPUVertBuf *>(calloc(1, sizeof(blender::gpu::VertBuf)));
+ verts->stride = format.stride;
+ verts->format = static_cast<GPUVertFormat *>(calloc(1, sizeof(GPUVertFormat)));
+ *verts->format = format;
+ return verts;
+}
+inline void GPU_vertbuf_data_alloc(GPUVertBuf &verts, unsigned int vertex_len)
+{
+ verts.vertex_len = vertex_len;
+}
+inline void GPU_batch_uniformbuf_bind(GPUBatch * /*batch*/,
+ const char * /*name*/,
+ GPUUniformBuf *uniformbuf)
+{
+ (void)uniformbuf;
+}
+
+#else /* __cplusplus */
+
+typedef struct GPUVertBuf GPUVertBuf;
+
+#endif /* __cplusplus */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
unsigned int GPU_vertformat_attr_add(GPUVertFormat *format,
const char *name,
- eGPUAttrType type,
- int components,
- eGPUAttrFetchMode fetch);
+ eGPUAttrType type);
+#ifndef __cplusplus
GPUVertBuf *GPU_vertbuf_create_with_format(GPUVertFormat *format);
void GPU_vertbuf_data_alloc(GPUVertBuf *verts, unsigned int vertex_len);
+#endif
void GPU_vertbuf_attr_fill(GPUVertBuf *verts, unsigned int attrib_id, const void *data);
-void GPU_vertbuf_attr_get_raw_data(GPUVertBuf *verts, unsigned int attrib_id, void **r_data);
-void *GPU_vertbuf_raw_step(void **iter);
+void GPU_vertbuf_attr_get_raw_data(GPUVertBuf *verts, unsigned int attrib_id, GPUVertBufRaw *r_raw);
+void *GPU_vertbuf_raw_step(GPUVertBufRaw *raw);
void GPU_vertbuf_tag_dirty(GPUVertBuf *verts);
void GPU_vertbuf_use(GPUVertBuf *verts);
-void GPU_indexbuf_init(void **ib, int primitive_type, unsigned int index_len, unsigned int vertex_len);
-void GPU_indexbuf_add_tri_verts(void *ib, unsigned int v1, unsigned int v2, unsigned int v3);
-GPUIndexBuf *GPU_indexbuf_build(void **ib);
+void GPU_indexbuf_init(GPUIndexBufBuilder *builder,
+ int primitive_type,
+ unsigned int index_len,
+ unsigned int max_allowed_index);
+void GPU_indexbuf_add_tri_verts(GPUIndexBufBuilder *builder,
+ unsigned int v1,
+ unsigned int v2,
+ unsigned int v3);
+void GPU_indexbuf_add_line_verts(GPUIndexBufBuilder *builder,
+ unsigned int v1,
+ unsigned int v2);
+GPUIndexBuf *GPU_indexbuf_build(GPUIndexBufBuilder *builder);
+GPUIndexBuf *GPU_indexbuf_build_in_memory(GPUIndexBufBuilder *builder, void *memory);
+void GPU_indexbuf_discard(GPUIndexBuf *index_buf);
GPUBatch *GPU_batch_create_ex(int primitive_type,
GPUVertBuf *verts,
GPUIndexBuf *index_buffer,
- unsigned int owns_buffers);
+ unsigned int owns_flags);
void GPU_batch_discard(GPUBatch *batch);
void GPU_batch_draw(GPUBatch *batch);
void GPU_batch_draw_instance_range(GPUBatch *batch, int i_first, int i_count);
@@ -61,14 +215,16 @@ void GPU_batch_program_set_builtin(GPUBatch *batch, int shader_id);
void GPU_batch_uniform_1f(GPUBatch *batch, const char *name, float value);
void GPU_batch_uniform_3fv(GPUBatch *batch, const char *name, const float data[3]);
void GPU_batch_uniform_4f(GPUBatch *batch, const char *name, float x, float y, float z, float w);
-void GPU_batch_uniform_4fv_array(GPUBatch *batch, const char *name, int len, const float *data);
+void GPU_batch_uniform_4fv_array(GPUBatch *batch,
+ const char *name,
+ int len,
+ const float (*data)[4]);
void GPU_batch_uniformbuf_bind(GPUBatch *batch, GPUUniformBuf *uniformbuf);
-/* Batch presets (spheres etc; null backend returns empty batch). */
-void gpu_batch_presets_register(void);
+/* Preset batches (spheres etc). The null backend returns empty batches. */
+void gpu_batch_presets_register(GPUBatch *preset_batch);
GPUBatch *GPU_batch_preset_sphere(int level);
#ifdef __cplusplus
}
#endif
-
diff --git a/gpu/include/GPU_immediate.hh b/gpu/include/GPU_immediate.hh
index 4caab34..f5e7692 100644
--- a/gpu/include/GPU_immediate.hh
+++ b/gpu/include/GPU_immediate.hh
@@ -1,9 +1,12 @@
-/* BUI GPU seam: immediate mode drawing.
+/* BUI GPU seam: immediate mode drawing.
* Minimal API-compatible surface for the extracted UI toolkit.
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include "BLI_sys_types.h"
+#include "GPU_batch.hh"
+#include "GPU_matrix.hh"
+#include "GPU_immediate_util.hh"
#ifdef __cplusplus
extern "C" {
@@ -14,15 +17,15 @@ typedef enum eGPUPrimType {
GPU_PRIM_POINTS,
GPU_PRIM_LINES,
GPU_PRIM_LINE_STRIP,
+ GPU_PRIM_LINE_LOOP,
GPU_PRIM_TRIS,
GPU_PRIM_TRI_STRIP,
GPU_PRIM_TRI_FAN,
} eGPUPrimType;
+typedef enum eGPUPrimType GPUPrimType;
-/* Opaque vertex format handle (see GPU_vertex_format.hh). */
-typedef struct GPUVertFormatRaw GPUVertFormatRaw;
-
-unsigned int immVertexFormat(void);
+/* Returns a scratch vertex format (upstream semantics). */
+GPUVertFormat *immVertexFormat(void);
void immBindBuiltinProgram(int shader_id);
bool immIsShaderBound(void);
void immUnbindProgram(void);
@@ -61,3 +64,4 @@ void immUniformColor4ubv(const unsigned char rgba[4]);
#ifdef __cplusplus
}
#endif
+
diff --git a/gpu/include/GPU_immediate_util.hh b/gpu/include/GPU_immediate_util.hh
index 72c7eb4..c555495 100644
--- a/gpu/include/GPU_immediate_util.hh
+++ b/gpu/include/GPU_immediate_util.hh
@@ -17,6 +17,22 @@ typedef enum eGPUBuiltinShader {
GPU_SHADER_2D_IMAGE,
GPU_SHADER_2D_CHECKER,
GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR,
+ GPU_SHADER_2D_POINT_UNIFORM_SIZE_UNIFORM_COLOR_AA,
+ GPU_SHADER_2D_POINT_UNIFORM_SIZE_UNIFORM_COLOR_OUTLINE_AA,
+ GPU_SHADER_3D_UNIFORM_COLOR,
+ GPU_SHADER_3D_FLAT_COLOR,
+ GPU_SHADER_3D_POINT_FLAT_COLOR,
+ GPU_SHADER_3D_SMOOTH_COLOR,
+ GPU_SHADER_3D_DEPTH_ONLY,
+ GPU_SHADER_3D_IMAGE_COLOR,
+ GPU_SHADER_3D_LINE_DASHED_UNIFORM_COLOR,
+ GPU_SHADER_3D_POINT_UNIFORM_SIZE_UNIFORM_COLOR_AA,
+ GPU_SHADER_3D_POINT_VARYING_SIZE_VARYING_COLOR,
+ /* Widget shaders. */
+ GPU_SHADER_2D_WIDGET_BASE,
+ GPU_SHADER_2D_WIDGET_BASE_INST,
+ GPU_SHADER_2D_WIDGET_SHADOW,
+ GPU_SHADER_SIMPLE_LIGHTING,
/* Keep last. */
GPU_SHADER_BUILTIN_LEN,
} eGPUBuiltinShader;
@@ -30,7 +46,7 @@ void imm_draw_circle_wire_2d(unsigned int pos_id, float x, float y, float radius
void imm_draw_disk_partial_fill_2d(unsigned int pos_id,
float x,
float y,
- float radius_inner,
+ float radius_inner,
float radius_outer,
float start_angle,
float sweep_angle,
@@ -38,20 +54,11 @@ void imm_draw_disk_partial_fill_2d(unsigned int pos_id,
/* Theme-color uniforms are provided by the ui module via this hook to avoid a
* gpu -> ui dependency. The toolkit installs it at startup. */
-struct bThemeUIColor; /* opaque */
extern void (*bui_imm_theme_color_hook)(int region_color_id, float r_color[4]);
extern void (*bui_imm_theme_color_alpha_hook)(int region_color_id, float alpha, float r_color[4]);
void immUniformThemeColor(int color_id);
void immUniformThemeColorAlpha(int color_id, float alpha);
-/* Pixel-texture drawing (icons etc). Null backend discards. */
-void immDrawPixelsTexSetup(int shader_id); /* placeholder signature */
-void immDrawPixelsTexScaledFullSize(
- float x, float y, float img_w, float img_h, float tex_w, float tex_h,
- float scale_x, float scale_y, int clip_min_x, int clip_min_y, int clip_max_x, int clip_max_y,
- bool linear_filter, const void *rect, int pixels_w, int pixels_h, int components,
- const float pixel_outline[4]);
-
#ifdef __cplusplus
}
#endif
diff --git a/gpu/include/GPU_matrix.hh b/gpu/include/GPU_matrix.hh
index d3ceb0d..a3db901 100644
--- a/gpu/include/GPU_matrix.hh
+++ b/gpu/include/GPU_matrix.hh
@@ -20,6 +20,8 @@ void GPU_matrix_scale_1f(float scale);
void GPU_matrix_scale_2f(float x, float y);
/* Set an orthographic projection over the given extents (z near/far too). */
+/* Depth range used by orthographic widget projections (upstream constant). */
+#define GPU_MATRIX_ORTHO_CLIP_NEAR_DEFAULT (-100)
void GPU_matrix_ortho_set_z(float near, float far);
void GPU_matrix_projection_get(float result[4][4]);
diff --git a/gpu/include/GPU_raster.h b/gpu/include/GPU_raster.h
new file mode 100644
index 0000000..f390d5d
--- /dev/null
+++ b/gpu/include/GPU_raster.h
@@ -0,0 +1,185 @@
+/* BUI software raster backend.
+ *
+ * A complete frame renderer for hosts without a GPU context (Tk, plain Qt
+ * widgets, headless). It plays the role Blender's GPU module + BLF play: the
+ * whole UI is drawn into one RGB32 frame buffer in native code, then the host
+ * presents it with a single blit — instead of turning every primitive into a
+ * host-toolkit object.
+ *
+ * - Anti-aliased analytic primitives (rect, rounded box, circle, line) using
+ * signed-distance coverage, like Blender's widget-base shaders.
+ * - Generic triangles with per-vertex color (for the BuiGpuSink seam).
+ * - Native text (GDI glyph-run cache on Windows); hosts fall back to their
+ * own text drawing where BUI_text_native() is 0.
+ * - Damage tracking: after each frame, the tiles that actually changed are
+ * reported so hosts upload only those.
+ *
+ * Pixel layout: uint32 0x00RRGGBB, top-down rows, stride == width. This is
+ * byte-compatible with a Win32 32bpp BI_RGB DIB and QImage::Format_RGB32.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#include <stdint.h>
+
+#include "GPU_backend_sink.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct BuiRaster BuiRaster;
+
+enum {
+ BUI_FONT_BOLD = 1 << 0,
+ BUI_FONT_ITALIC = 1 << 1,
+ BUI_FONT_UNDERLINE = 1 << 2,
+};
+
+BuiRaster *BUI_raster_create(int width, int height);
+void BUI_raster_free(BuiRaster *r);
+
+/* Frame bracket. begin_frame resizes (and fully damages) when the size
+ * changes; end_frame computes the damage list against the previous frame. */
+void BUI_raster_begin_frame(BuiRaster *r, int width, int height);
+void BUI_raster_end_frame(BuiRaster *r);
+
+int BUI_raster_width(const BuiRaster *r);
+int BUI_raster_height(const BuiRaster *r);
+const uint32_t *BUI_raster_pixels(const BuiRaster *r);
+
+/* Damage from the last end_frame as {x, y, w, h} rects; returns the count. */
+int BUI_raster_damage(const BuiRaster *r, const int (**r_rects)[4]);
+/* Force the next end_frame to report the full frame as damaged. */
+void BUI_raster_invalidate(BuiRaster *r);
+
+/* Clip subsequent drawing; w/h <= 0 removes the clip. */
+void BUI_raster_set_clip(BuiRaster *r, int x, int y, int w, int h);
+
+void BUI_raster_fill_rect(BuiRaster *r, float x, float y, float w, float h, const float rgba[4]);
+void BUI_raster_frame_rect(
+ BuiRaster *r, float x, float y, float w, float h, float thickness, const float rgba[4]);
+void BUI_raster_round_rect(
+ BuiRaster *r, float x, float y, float w, float h, float radius, const float rgba[4]);
+/* line_width <= 0 draws a filled disc. */
+void BUI_raster_circle(
+ BuiRaster *r, float cx, float cy, float radius, float line_width, const float rgba[4]);
+void BUI_raster_line(
+ BuiRaster *r, float x1, float y1, float x2, float y2, float width, const float rgba[4]);
+/* Axis-aligned ellipse; line_width <= 0 fills. */
+void BUI_raster_ellipse(BuiRaster *r,
+ float cx,
+ float cy,
+ float rx,
+ float ry,
+ float line_width,
+ const float rgba[4]);
+/* Filled polygon (even-odd), anti-aliased; `points` holds `n` x/y pairs. */
+void BUI_raster_polygon(BuiRaster *r, const float (*points)[2], int n, const float rgba[4]);
+
+/* Rounded-box corner mask (Blender's UI_CNR_*). */
+enum {
+ BUI_CORNER_TOP_LEFT = 1 << 0,
+ BUI_CORNER_TOP_RIGHT = 1 << 1,
+ BUI_CORNER_BOTTOM_RIGHT = 1 << 2,
+ BUI_CORNER_BOTTOM_LEFT = 1 << 3,
+ BUI_CORNER_ALL = 15,
+};
+
+/* One Blender widget base (the GPU_SHADER_2D_WIDGET_BASE look) in a single
+ * pass: inner fill shaded from `inner_top` to `inner_bottom`, an
+ * `outline_width` outline inside the edge, and an emboss line just below
+ * the box. Corners not in `corners` are square. Any color may be NULL. */
+void BUI_raster_widget(BuiRaster *r,
+ float x,
+ float y,
+ float w,
+ float h,
+ float radius,
+ int corners,
+ const float inner_top[4],
+ const float inner_bottom[4],
+ const float outline[4],
+ float outline_width,
+ const float emboss[4]);
+
+/* Parameters of Blender's widget-base shader (WidgetBaseParameters), in
+ * screen space (y down). */
+typedef struct BuiWidgetBase {
+ float rect[4]; /* x, y, w, h of the outer shape */
+ float rad, radi; /* outer / inner corner radius */
+ int corners; /* BUI_CORNER_* mask */
+ float inner1[4]; /* shade start: top (or left when shade_horizontal) */
+ float inner2[4]; /* shade end: bottom (or right) */
+ float outline[4];
+ float emboss[4];
+ int shade_horizontal; /* Blender's shade_dir == 0 */
+ int alpha_checker; /* checkerboard under the inner color */
+ float pixelsize; /* U.pixelsize */
+} BuiWidgetBase;
+
+void BUI_raster_widget_base(BuiRaster *r, const BuiWidgetBase *params);
+
+/* Image (0xAARRGGBB, iw x ih) scaled into x, y, w, h (nearest), alpha blended. */
+void BUI_raster_image(BuiRaster *r, float x, float y, float w, float h, const uint32_t *argb,
+ int iw, int ih, float alpha);
+
+/* end_frame that only diffs the given region (everything else is known to
+ * be unchanged): partial redraws cost O(region), not O(window). */
+void BUI_raster_end_frame_region(BuiRaster *r, int x, int y, int w, int h);
+
+/* Soft drop shadow around a rounded box (menus/popups), fading out over
+ * `size` pixels from `alpha`. */
+void BUI_raster_shadow(
+ BuiRaster *r, float x, float y, float w, float h, float radius, float size, float alpha);
+void BUI_raster_triangles(BuiRaster *r,
+ const float (*coords)[2],
+ const float (*colors)[4],
+ int count);
+/* HSV color wheel (Blender's layout: red at the bottom, saturation grows
+ * outward) at brightness `value`, anti-aliased edge. */
+void BUI_raster_hsv_circle(BuiRaster *r, float cx, float cy, float radius, float value);
+/* Rectangle with bilinear corner colors (top-left, top-right, bottom-right,
+ * bottom-left). */
+void BUI_raster_gradient(BuiRaster *r,
+ float x,
+ float y,
+ float w,
+ float h,
+ const float tl[4],
+ const float tr[4],
+ const float br[4],
+ const float bl[4]);
+/* Lit sphere (normal ball): `light` is the direction (x right, y up, z out). */
+void BUI_raster_sphere(
+ BuiRaster *r, float cx, float cy, float radius, const float light[3], const float rgba[4]);
+void BUI_raster_points(BuiRaster *r,
+ const float (*coords)[2],
+ const float (*colors)[4],
+ int count,
+ float size);
+
+/* Text. `family` NULL/"" means the platform UI font; `size` is the em size in
+ * pixels; y is the baseline. Returns 0 when no native text engine exists. */
+int BUI_text_native(void);
+void BUI_raster_set_font(BuiRaster *r, const char *family, int flags);
+int BUI_raster_text(BuiRaster *r,
+ float x,
+ float y,
+ const char *utf8,
+ int len,
+ float size,
+ const float rgba[4]);
+int BUI_text_measure(
+ const char *family, int flags, float size, const char *utf8, int len, float *r_width);
+
+/* A BuiGpuSink that renders into `r` (user pointer is the raster). */
+const BuiGpuSink *BUI_raster_sink(BuiRaster *r);
+
+/* Blit damaged regions (or everything when `full`) straight to a native
+ * window: an HWND on Windows. Returns 0 when unsupported on this platform. */
+int BUI_raster_present_native(BuiRaster *r, void *window_handle, int full);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/gpu/include/GPU_shader_shared.hh b/gpu/include/GPU_shader_shared.hh
index 72446e6..e313392 100644
--- a/gpu/include/GPU_shader_shared.hh
+++ b/gpu/include/GPU_shader_shared.hh
@@ -1,6 +1,19 @@
-/* BUI GPU seam header (GPU_shader_shared.hh).
+/* BUI GPU seam: shader interface structs shared between CPU and shaders.
+ * Mirrors upstream GPU_shader_shared.hh for the subset the toolkit uses.
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
-#include "GPU_batch.hh"
+#ifdef __cplusplus
+#include "BLI_math_vector_types.hh"
+namespace blender::gpu {
+
+/* UBO for the simple-lighting sphere preview (unit-vector button). */
+struct SimpleLightingData {
+ float4 l_color;
+ float3 light;
+ float _pad = 0.0f;
+};
+
+} // namespace blender::gpu
+#endif
diff --git a/gpu/include/GPU_state.hh b/gpu/include/GPU_state.hh
index 6edacf2..fa2c144 100644
--- a/gpu/include/GPU_state.hh
+++ b/gpu/include/GPU_state.hh
@@ -1,4 +1,4 @@
-/* BUI GPU seam: state management.
+/* BUI GPU seam: state management.
* Minimal replacement for upstream GPU_state.hh. Backed by a null backend;
* plug a real renderer behind these calls.
* SPDX-License-Identifier: GPL-2.0-or-later */
@@ -17,6 +17,9 @@ typedef enum eGPUBlend {
GPU_BLEND_ADDITIVE,
} eGPUBlend;
+/* Upstream spells the plain type GPUBlend in some call-sites. */
+typedef eGPUBlend GPUBlend;
+
typedef enum eGPUFaceCullTest {
GPU_CULL_NONE = 0,
GPU_CULL_FRONT,
@@ -45,3 +48,5 @@ void GPU_viewport_size_get_f(float viewport[4]);
#ifdef __cplusplus
}
#endif
+
+
diff --git a/gpu/include/GPU_uniform_buffer.hh b/gpu/include/GPU_uniform_buffer.hh
index 8db98af..1bcca38 100644
--- a/gpu/include/GPU_uniform_buffer.hh
+++ b/gpu/include/GPU_uniform_buffer.hh
@@ -1,6 +1,18 @@
-/* BUI GPU seam header (GPU_uniform_buffer.hh).
+/* BUI GPU seam header (GPU_uniform_buffer.hh).
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include "GPU_batch.hh"
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Uniform buffer lifecycle. The null backend keeps only a size record. */
+GPUUniformBuf *GPU_uniformbuf_create_ex(size_t size, const void *data, const char *name);
+void GPU_uniformbuf_update(GPUUniformBuf *uniformbuf, const void *data);
+void GPU_uniformbuf_free(GPUUniformBuf *uniformbuf);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/gpu/intern/gpu_null.c b/gpu/intern/gpu_null.c
index 35ccd87..9a48ce8 100644
--- a/gpu/intern/gpu_null.c
+++ b/gpu/intern/gpu_null.c
@@ -2,6 +2,7 @@
* Records state, discards geometry. Swap in a real renderer (GL/Metal/Vulkan/
* software rasterizer) by implementing the same seam headers.
* SPDX-License-Identifier: GPL-2.0-or-later */
+#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -12,6 +13,7 @@
#include "GPU_immediate_util.hh"
#include "GPU_matrix.hh"
#include "GPU_state.hh"
+#include "GPU_backend_sink.h"
/* -------------------------------------------------------------------- */
/** \name State
@@ -21,6 +23,25 @@ static eGPUBlend bui_blend = GPU_BLEND_NONE;
static int bui_scissor[4] = {0, 0, 0, 0};
static bool bui_scissor_enabled = false;
static float bui_viewport[4] = {0.0f, 0.0f, 0.0f, 0.0f};
+static int bui_viewport_wh[2] = {0, 0};
+static const BuiGpuSink *bui_sink = NULL;
+static float bui_point_size = 1.0f;
+
+/* --- Immediate-mode vertex recording ------------------------------------- */
+#define BUI_IMM_MAX_ATTRS BUI_VERTFORMAT_MAX_ATTRS
+static GPUVertFormat *bui_imm_fmt = NULL;
+static int bui_imm_prim = GPU_PRIM_NONE;
+static unsigned int bui_imm_vertex_cap = 0; /* rows the buffer can hold */
+static unsigned int bui_imm_vertex_len = 0; /* requested vertex count */
+static unsigned int bui_imm_cursor = 0; /* committed rows */
+static unsigned char *bui_imm_buf = NULL;
+static float bui_imm_color[4] = {1.0f, 1.0f, 1.0f, 1.0f};
+static bool bui_imm_active = false;
+typedef struct BuiImmPending {
+ bool filled;
+ float values[4];
+} BuiImmPending;
+static BuiImmPending bui_imm_pending[BUI_IMM_MAX_ATTRS];
void GPU_blend(eGPUBlend blend)
{
@@ -33,7 +54,10 @@ eGPUBlend GPU_blend_get(void)
void GPU_line_width(float UNUSED(width)) {}
void GPU_line_smooth(bool UNUSED(enable)) {}
void GPU_polygon_smooth(bool UNUSED(enable)) {}
-void GPU_point_size(float UNUSED(size)) {}
+void GPU_point_size(float size)
+{
+ bui_point_size = size;
+}
void GPU_program_point_size(bool UNUSED(enable)) {}
void GPU_scissor(int x, int y, int width, int height)
{
@@ -41,10 +65,17 @@ void GPU_scissor(int x, int y, int width, int height)
bui_scissor[1] = y;
bui_scissor[2] = width;
bui_scissor[3] = height;
+ bui_scissor_enabled = true;
+ if (bui_sink && bui_sink->scissor) {
+ bui_sink->scissor(bui_sink->user, x, y, width, height);
+ }
}
void GPU_scissor_test(bool enable)
{
bui_scissor_enabled = enable;
+ if (!enable && bui_sink && bui_sink->scissor) {
+ bui_sink->scissor(bui_sink->user, 0, 0, 0, 0);
+ }
}
void GPU_scissor_get(int coords[4])
{
@@ -64,6 +95,21 @@ void GPU_viewport_size_get_f(float viewport[4])
memcpy(viewport, bui_viewport, sizeof(bui_viewport));
}
+void GPU_viewport_size_set(int width, int height)
+{
+ bui_viewport_wh[0] = width;
+ bui_viewport_wh[1] = height;
+}
+
+void GPU_backend_sink_set(const BuiGpuSink *sink)
+{
+ bui_sink = sink;
+}
+const BuiGpuSink *GPU_backend_sink_get(void)
+{
+ return bui_sink;
+}
+
/** \} */
/* -------------------------------------------------------------------- */
@@ -82,8 +128,22 @@ static void bui_mat_identity(float m[16])
m[0] = m[5] = m[10] = m[15] = 1.0f;
}
+/* The matrix stack starts at identity so draw calls before any matrix setup
+ * pass pixel coordinates through unchanged. */
+static bool bui_matrix_initialized = false;
+static void bui_matrix_ensure_init(void)
+{
+ if (!bui_matrix_initialized) {
+ bui_matrix_initialized = true;
+ for (int i = 0; i < BUI_MATRIX_MAX_DEPTH; i++) {
+ bui_mat_identity(bui_model[i]);
+ }
+ }
+}
+
void GPU_matrix_identity_set(void)
{
+ bui_matrix_ensure_init();
bui_mat_identity(bui_model[bui_model_depth]);
}
void GPU_matrix_push(void)
@@ -148,9 +208,12 @@ void GPU_matrix_projection_get(float result[4][4])
static int bui_bound_shader = -1;
-unsigned int immVertexFormat(void)
+GPUVertFormat *immVertexFormat(void)
{
- return 0;
+ static GPUVertFormat fmt;
+ memset(&fmt, 0, sizeof(fmt));
+ bui_imm_fmt = &fmt;
+ return &fmt;
}
bool immIsShaderBound(void)
{
@@ -164,23 +227,196 @@ void immUnbindProgram(void)
{
bui_bound_shader = -1;
}
-void immBegin(eGPUPrimType UNUSED(primitive), unsigned int UNUSED(vertex_len)) {}
-void immBeginAtMost(eGPUPrimType UNUSED(primitive), unsigned int UNUSED(vertex_len)) {}
-void immEnd() {}
-void immVertex2f(unsigned int UNUSED(attrib), float UNUSED(x), float UNUSED(y)) {}
-void immVertex2fv(unsigned int UNUSED(attrib), const float UNUSED(data[2])) {}
-void immAttr3fv(unsigned int UNUSED(attrib), const float UNUSED(data[3])) {}
-void immAttr4f(unsigned int UNUSED(attrib), float UNUSED(x), float UNUSED(y), float UNUSED(z),
- float UNUSED(w))
+
+/* Transform a 2D position through the current model matrix. */
+static void bui_imm_transform(float x, float y, float r_out[2])
+{
+ bui_matrix_ensure_init();
+ const float *m = bui_model[bui_model_depth];
+ r_out[0] = m[0] * x + m[4] * y + m[12];
+ r_out[1] = m[1] * x + m[5] * y + m[13];
+}
+
+/* Returns the attribute index with `name`, or -1. */
+static int bui_imm_attr_by_name(const char *name)
+{
+ if (!bui_imm_fmt) {
+ return -1;
+ }
+ for (unsigned int i = 0; i < bui_imm_fmt->attr_len; i++) {
+ if (strcmp(bui_imm_fmt->attrs[i].name, name) == 0) {
+ return (int)i;
+ }
+ }
+ return -1;
+}
+
+static void bui_sink_flush_prim(int prim,
+ const float (*coords)[2],
+ const float (*colors)[4],
+ int count)
+{
+ if (!bui_sink) {
+ return;
+ }
+ switch (prim) {
+ case GPU_PRIM_TRIS:
+ case GPU_PRIM_TRI_STRIP:
+ case GPU_PRIM_TRI_FAN:
+ if (bui_sink->triangles) {
+ bui_sink->triangles(bui_sink->user, coords, colors, count);
+ }
+ break;
+ case GPU_PRIM_LINES:
+ case GPU_PRIM_LINE_STRIP:
+ case GPU_PRIM_LINE_LOOP:
+ if (bui_sink->lines) {
+ bui_sink->lines(bui_sink->user, coords, colors, count);
+ }
+ break;
+ case GPU_PRIM_POINTS:
+ if (bui_sink->points) {
+ bui_sink->points(bui_sink->user, coords, colors, count, bui_point_size);
+ }
+ break;
+ default:
+ break;
+ }
+}
+
+/* Expand the recorded primitive into lists and emit through the sink. */
+static void bui_imm_flush(void)
+{
+ const unsigned int n = bui_imm_cursor;
+ if (!bui_sink || n == 0) {
+ return;
+ }
+ const int pos_idx = bui_imm_attr_by_name("pos");
+ const int col_idx = bui_imm_attr_by_name("color");
+ const unsigned int pos_off = (pos_idx >= 0) ? bui_imm_fmt->attrs[pos_idx].offset : 0;
+ const bool has_col = col_idx >= 0;
+ const unsigned int col_off = has_col ? bui_imm_fmt->attrs[col_idx].offset : 0;
+ const unsigned int stride = bui_imm_fmt ? bui_imm_fmt->stride : 0;
+
+ float(*coords)[2] = (float(*)[2])malloc(sizeof(float) * 2 * n);
+ float(*colors)[4] = (float(*)[4])malloc(sizeof(float) * 4 * n);
+ for (unsigned int i = 0; i < n; i++) {
+ const unsigned char *row = bui_imm_buf + (size_t)i * stride;
+ float px, py;
+ memcpy(&px, row + pos_off, sizeof(float));
+ memcpy(&py, row + pos_off + 4, sizeof(float));
+ bui_imm_transform(px, py, coords[i]);
+ if (has_col) {
+ memcpy(colors[i], row + col_off, sizeof(float) * 4);
+ }
+ else {
+ memcpy(colors[i], bui_imm_color, sizeof(float) * 4);
+ }
+ }
+ bui_sink_flush_prim(bui_imm_prim, coords, colors, (int)n);
+ free(coords);
+ free(colors);
+}
+
+void immBegin(eGPUPrimType primitive, unsigned int vertex_len)
+{
+ bui_imm_prim = primitive;
+ bui_imm_vertex_len = vertex_len;
+ bui_imm_cursor = 0;
+ bui_imm_active = true;
+ if (bui_imm_fmt && vertex_len > bui_imm_vertex_cap) {
+ bui_imm_vertex_cap = vertex_len;
+ bui_imm_buf = (unsigned char *)realloc(bui_imm_buf, (size_t)bui_imm_fmt->stride * vertex_len);
+ }
+}
+void immBeginAtMost(eGPUPrimType primitive, unsigned int vertex_len)
+{
+ immBegin(primitive, vertex_len);
+}
+void immEnd(void)
+{
+ if (bui_imm_active) {
+ bui_imm_flush();
+ }
+ bui_imm_active = false;
+ bui_imm_prim = GPU_PRIM_NONE;
+ memset(bui_imm_pending, 0, sizeof(bui_imm_pending));
+}
+static void bui_imm_store(unsigned int attrib, const float *values)
+{
+ if (attrib < BUI_IMM_MAX_ATTRS) {
+ bui_imm_pending[attrib].filled = true;
+ memcpy(bui_imm_pending[attrib].values, values, sizeof(float) * 4);
+ }
+}
+static void bui_imm_commit_vertex(unsigned int UNUSED(pos_attrib), float x, float y)
+{
+ if (!bui_imm_fmt || !bui_imm_buf || bui_imm_cursor >= bui_imm_vertex_cap) {
+ return;
+ }
+ unsigned char *row = bui_imm_buf + (size_t)bui_imm_cursor * bui_imm_fmt->stride;
+ for (unsigned int i = 0; i < bui_imm_fmt->attr_len; i++) {
+ if (!bui_imm_pending[i].filled || strcmp(bui_imm_fmt->attrs[i].name, "pos") == 0) {
+ continue;
+ }
+ const unsigned int comps = bui_imm_fmt->attrs[i].components;
+ if (bui_imm_fmt->attrs[i].attr_type == (unsigned int)UBYTE_8_UINT) {
+ for (unsigned int c = 0; c < comps; c++) {
+ row[bui_imm_fmt->attrs[i].offset + c] = (unsigned char)(
+ bui_imm_pending[i].values[c] * 255.0f + 0.5f);
+ }
+ }
+ else {
+ memcpy(row + bui_imm_fmt->attrs[i].offset, bui_imm_pending[i].values,
+ sizeof(float) * comps);
+ }
+ bui_imm_pending[i].filled = false;
+ }
+ const int pos_idx = bui_imm_attr_by_name("pos");
+ const unsigned int pos_off = (pos_idx >= 0) ? bui_imm_fmt->attrs[pos_idx].offset : 0;
+ const float xy[2] = {x, y};
+ memcpy(row + pos_off, xy, sizeof(float) * 2);
+ bui_imm_cursor++;
+}
+void immVertex2f(unsigned int attrib, float x, float y)
+{
+ bui_imm_commit_vertex(attrib, x, y);
+}
+void immVertex2fv(unsigned int attrib, const float data[2])
+{
+ bui_imm_commit_vertex(attrib, data[0], data[1]);
+}
+void immAttr3fv(unsigned int attrib, const float data[3])
+{
+ float v[4] = {data[0], data[1], data[2], 1.0f};
+ bui_imm_store(attrib, v);
+}
+void immAttr4f(unsigned int attrib, float x, float y, float z, float w)
{
+ float v[4] = {x, y, z, w};
+ bui_imm_store(attrib, v);
}
-void immAttr4fv(unsigned int UNUSED(attrib), const float UNUSED(data[4])) {}
-void immAttr4ub(unsigned int UNUSED(attrib), unsigned char UNUSED(r), unsigned char UNUSED(g),
- unsigned char UNUSED(b), unsigned char UNUSED(a))
+void immAttr4fv(unsigned int attrib, const float data[4])
{
+ bui_imm_store(attrib, data);
+}
+void immAttr4ub(unsigned int attrib, unsigned char r, unsigned char g, unsigned char b,
+ unsigned char a)
+{
+ float v[4] = {r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f};
+ bui_imm_store(attrib, v);
+}
+void immAttr4ubv(unsigned int attrib, const unsigned char data[4])
+{
+ float v[4] = {data[0] / 255.0f, data[1] / 255.0f, data[2] / 255.0f, data[3] / 255.0f};
+ bui_imm_store(attrib, v);
+}
+void immAttrSkip(unsigned int attrib)
+{
+ if (attrib < BUI_IMM_MAX_ATTRS) {
+ bui_imm_pending[attrib].filled = false;
+ }
}
-void immAttr4ubv(unsigned int UNUSED(attrib), const unsigned char UNUSED(data[4])) {}
-void immAttrSkip(unsigned int UNUSED(attrib)) {}
void immUniform1f(const char *UNUSED(name), float UNUSED(x)) {}
void immUniform1i(const char *UNUSED(name), int UNUSED(x)) {}
@@ -192,47 +428,48 @@ void immUniform4f(const char *UNUSED(name), float UNUSED(x), float UNUSED(y), fl
}
void immUniform4fv(const char *UNUSED(name), const float UNUSED(data[4])) {}
-void immUniformColor4f(float UNUSED(r), float UNUSED(g), float UNUSED(b), float UNUSED(a)) {}
-void immUniformColor4fv(const float UNUSED(rgba[4])) {}
-void immUniformColor3f(float UNUSED(r), float UNUSED(g), float UNUSED(b)) {}
-void immUniformColor3fv(const float UNUSED(rgb[3])) {}
-void immUniformColor3fvAlpha(const float UNUSED(rgb[3]), float UNUSED(a)) {}
-void immUniformColor3ub(unsigned char UNUSED(r), unsigned char UNUSED(g), unsigned char UNUSED(b))
+void immUniformColor4f(float r, float g, float b, float a)
{
+ bui_imm_color[0] = r;
+ bui_imm_color[1] = g;
+ bui_imm_color[2] = b;
+ bui_imm_color[3] = a;
}
-void immUniformColor3ubv(const unsigned char UNUSED(rgb[3])) {}
-void immUniformColor3ubvAlpha(const unsigned char UNUSED(rgb[3]), float UNUSED(alpha)) {}
-void immUniformColor4ub(unsigned char UNUSED(r), unsigned char UNUSED(g), unsigned char UNUSED(b),
- unsigned char UNUSED(a))
+void immUniformColor4fv(const float rgba[4])
{
+ immUniformColor4f(rgba[0], rgba[1], rgba[2], rgba[3]);
}
-void immUniformColor4ubv(const unsigned char UNUSED(rgba[4])) {}
-
-/** \} */
-
-/* -------------------------------------------------------------------- */
-/** \name Immediate utilities
- * \{ */
-
-void immRectf(int pos_id, float x1, float y1, float x2, float y2)
+void immUniformColor3f(float r, float g, float b)
{
- immBegin(GPU_PRIM_TRI_FAN, 4);
- immVertex2f(pos_id, x1, y1);
- immVertex2f(pos_id, x2, y1);
- immVertex2f(pos_id, x2, y2);
- immVertex2f(pos_id, x1, y2);
- immEnd();
+ immUniformColor4f(r, g, b, 1.0f);
}
-
-void imm_draw_box_wire_2d(unsigned int pos_id, float x1, float y1, float x2, float y2)
+void immUniformColor3fv(const float rgb[3])
+{
+ immUniformColor4f(rgb[0], rgb[1], rgb[2], 1.0f);
+}
+void immUniformColor3fvAlpha(const float rgb[3], float a)
+{
+ immUniformColor4f(rgb[0], rgb[1], rgb[2], a);
+}
+void immUniformColor3ub(unsigned char r, unsigned char g, unsigned char b)
+{
+ immUniformColor4f(r / 255.0f, g / 255.0f, b / 255.0f, 1.0f);
+}
+void immUniformColor3ubv(const unsigned char rgb[3])
+{
+ immUniformColor3ub(rgb[0], rgb[1], rgb[2]);
+}
+void immUniformColor3ubvAlpha(const unsigned char rgb[3], float alpha)
+{
+ immUniformColor4f(rgb[0] / 255.0f, rgb[1] / 255.0f, rgb[2] / 255.0f, alpha);
+}
+void immUniformColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
{
- immBegin(GPU_PRIM_LINE_STRIP, 5);
- immVertex2f(pos_id, x1, y1);
- immVertex2f(pos_id, x2, y1);
- immVertex2f(pos_id, x2, y2);
- immVertex2f(pos_id, x1, y2);
- immVertex2f(pos_id, x1, y1);
- immEnd();
+ immUniformColor4f(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
+}
+void immUniformColor4ubv(const unsigned char rgba[4])
+{
+ immUniformColor4ub(rgba[0], rgba[1], rgba[2], rgba[3]);
}
void imm_draw_box_checker_2d_ex(float UNUSED(x1), float UNUSED(y1), float UNUSED(x2),
@@ -275,101 +512,251 @@ void immUniformThemeColorAlpha(int color_id, float alpha)
}
}
-void immDrawPixelsTexSetup(int UNUSED(shader_id)) {}
-void immDrawPixelsTexScaledFullSize(float UNUSED(x), float UNUSED(y), float UNUSED(img_w),
- float UNUSED(img_h), float UNUSED(tex_w), float UNUSED(tex_h),
- float UNUSED(scale_x), float UNUSED(scale_y),
- int UNUSED(clip_min_x), int UNUSED(clip_min_y),
- int UNUSED(clip_max_x), int UNUSED(clip_max_y),
- bool UNUSED(linear_filter), const void *UNUSED(rect),
- int UNUSED(pixels_w), int UNUSED(pixels_h),
- int UNUSED(components), const float UNUSED(pixel_outline[4]))
-{
-}
-
/** \} */
/* -------------------------------------------------------------------- */
/** \name Buffers & batches
* \{ */
-struct GPUVertFormatRaw {
- int placeholder;
-};
-struct GPUVertFormat {
- int attr_len;
-};
-struct GPUVertBuf {
- int vertex_len;
-};
+/* Layout contract with blender::gpu::VertBuf (GPU_batch.hh): the members
+ * must appear in this exact order so both languages share one allocation. */
+typedef struct GPUVertBufInternal {
+ unsigned int vertex_len;
+ unsigned int stride;
+ void *cpu_data;
+ GPUVertFormat *format;
+} GPUVertBufInternal;
+
struct GPUIndexBuf {
- int index_len;
+ unsigned int index_len;
+ unsigned int *data;
};
struct GPUBatch {
int prim_type;
+ GPUVertBuf *verts;
+ GPUIndexBuf *index_buffer;
+ unsigned int owns_flags;
+ float uniform_color[4];
};
struct GPUUniformBuf {
- int size;
+ size_t size;
};
-unsigned int GPU_vertformat_attr_add(GPUVertFormat *UNUSED(format), const char *UNUSED(name),
- eGPUAttrType UNUSED(type), int UNUSED(components),
- eGPUAttrFetchMode UNUSED(fetch))
+static void bui_vertbuf_ensure_data(GPUVertBufInternal *verts)
{
- return 0;
+ if (verts->cpu_data == NULL) {
+ size_t bytes = (size_t)verts->stride * (verts->vertex_len ? verts->vertex_len : 1);
+ verts->cpu_data = calloc(1, bytes ? bytes : 4);
+ }
}
-GPUVertBuf *GPU_vertbuf_create_with_format(GPUVertFormat *UNUSED(format))
+
+unsigned int GPU_vertformat_attr_add(GPUVertFormat *format, const char *name,
+ eGPUAttrType type)
{
- return (GPUVertBuf *)calloc(1, sizeof(GPUVertBuf));
+ if (!format || format->attr_len >= BUI_VERTFORMAT_MAX_ATTRS) {
+ return 0;
+ }
+ unsigned int id = format->attr_len++;
+ snprintf(format->attrs[id].name, sizeof(format->attrs[id].name), "%s", name);
+ format->attrs[id].attr_type = (unsigned int)type;
+ format->attrs[id].components = ((type == SFLOAT_32_32 || type == UBYTE_8_UINT) ? 2 :
+ (type == SFLOAT_32_32_32) ? 3 : 4);
+ format->attrs[id].offset = format->stride;
+ format->stride += format->attrs[id].components * 4;
+ return id;
+}
+
+#ifndef __cplusplus
+GPUVertBuf *GPU_vertbuf_create_with_format(GPUVertFormat *format)
+{
+ GPUVertBufInternal *verts = (GPUVertBufInternal *)calloc(1, sizeof(GPUVertBufInternal));
+ if (format) {
+ verts->stride = format->stride;
+ verts->format = (GPUVertFormat *)calloc(1, sizeof(GPUVertFormat));
+ *verts->format = *format;
+ }
+ return (GPUVertBuf *)verts;
}
-void GPU_vertbuf_data_alloc(GPUVertBuf *verts, unsigned int vertex_len)
+void GPU_vertbuf_data_alloc(GPUVertBuf *verts_ptr, unsigned int vertex_len)
{
- verts->vertex_len = (int)vertex_len;
+ GPUVertBufInternal *verts = (GPUVertBufInternal *)verts_ptr;
+ verts->vertex_len = vertex_len;
}
-void GPU_vertbuf_attr_fill(GPUVertBuf *UNUSED(verts), unsigned int UNUSED(attrib),
- const void *UNUSED(data))
+#endif
+
+void GPU_vertbuf_attr_fill(GPUVertBuf *verts_ptr, unsigned int attrib, const void *data)
{
+ GPUVertBufInternal *verts = (GPUVertBufInternal *)verts_ptr;
+ if (!verts || !data) {
+ return;
+ }
+ bui_vertbuf_ensure_data(verts);
+ if (verts->format && attrib < verts->format->attr_len) {
+ const unsigned int offset = verts->format->attrs[attrib].offset;
+ const unsigned int comp_bytes = verts->format->attrs[attrib].components * 4;
+ for (unsigned int i = 0; i < verts->vertex_len; i++) {
+ memcpy((char *)verts->cpu_data + (size_t)i * verts->stride + offset,
+ (const char *)data + (size_t)i * comp_bytes,
+ comp_bytes);
+ }
+ }
}
-void GPU_vertbuf_attr_get_raw_data(GPUVertBuf *UNUSED(verts), unsigned int UNUSED(attrib),
- void **r_data)
+
+void GPU_vertbuf_attr_get_raw_data(GPUVertBuf *verts_ptr, unsigned int attrib,
+ GPUVertBufRaw *r_raw)
{
- static char raw[4096];
- *r_data = raw;
+ GPUVertBufInternal *verts = (GPUVertBufInternal *)verts_ptr;
+ bui_vertbuf_ensure_data(verts);
+ const unsigned int offset = (verts->format && attrib < verts->format->attr_len) ?
+ verts->format->attrs[attrib].offset : 0;
+ r_raw->size = verts->vertex_len;
+ r_raw->stride = verts->stride;
+ r_raw->data_init = (char *)verts->cpu_data + offset;
+ r_raw->data = r_raw->data_init;
}
-void *GPU_vertbuf_raw_step(void **iter)
+
+void *GPU_vertbuf_raw_step(GPUVertBufRaw *raw)
{
- return *iter;
+ void *ptr = raw->data;
+ raw->data = (char *)raw->data + raw->stride;
+ raw->size--;
+ return ptr;
}
+
void GPU_vertbuf_tag_dirty(GPUVertBuf *UNUSED(verts)) {}
void GPU_vertbuf_use(GPUVertBuf *UNUSED(verts)) {}
-void GPU_indexbuf_init(void **ib, int UNUSED(primitive_type), unsigned int UNUSED(index_len),
- unsigned int UNUSED(vertex_len))
+void GPU_indexbuf_init(GPUIndexBufBuilder *builder, int primitive_type,
+ unsigned int index_len, unsigned int max_allowed_index)
+{
+ memset(builder, 0, sizeof(*builder));
+ builder->prim_type = primitive_type;
+ builder->index_len = index_len;
+ builder->max_allowed_index = max_allowed_index;
+ builder->data = (unsigned int *)calloc(index_len ? index_len : 1, sizeof(unsigned int));
+}
+void GPU_indexbuf_add_tri_verts(GPUIndexBufBuilder *builder, unsigned int v1, unsigned int v2,
+ unsigned int v3)
+{
+ if (builder->used + 3 <= builder->index_len) {
+ builder->data[builder->used++] = v1;
+ builder->data[builder->used++] = v2;
+ builder->data[builder->used++] = v3;
+ }
+ if (v1 > builder->max_index) builder->max_index = v1;
+ if (v2 > builder->max_index) builder->max_index = v2;
+ if (v3 > builder->max_index) builder->max_index = v3;
+}
+void GPU_indexbuf_add_line_verts(GPUIndexBufBuilder *builder, unsigned int v1, unsigned int v2)
{
- *ib = calloc(1, sizeof(GPUIndexBuf));
+ if (builder->used + 2 <= builder->index_len) {
+ builder->data[builder->used++] = v1;
+ builder->data[builder->used++] = v2;
+ }
+ if (v1 > builder->max_index) builder->max_index = v1;
+ if (v2 > builder->max_index) builder->max_index = v2;
+}
+GPUIndexBuf *GPU_indexbuf_build(GPUIndexBufBuilder *builder)
+{
+ GPUIndexBuf *buf = (GPUIndexBuf *)calloc(1, sizeof(GPUIndexBuf));
+ buf->index_len = builder->used;
+ buf->data = builder->data;
+ builder->data = NULL;
+ return buf;
}
-void GPU_indexbuf_add_tri_verts(void *UNUSED(ib), unsigned int UNUSED(v1), unsigned int UNUSED(v2),
- unsigned int UNUSED(v3))
+GPUIndexBuf *GPU_indexbuf_build_in_memory(GPUIndexBufBuilder *UNUSED(builder),
+ void *UNUSED(memory))
{
+ return (GPUIndexBuf *)calloc(1, sizeof(GPUIndexBuf));
}
-GPUIndexBuf *GPU_indexbuf_build(void **ib)
+void GPU_indexbuf_discard(GPUIndexBuf *index_buf)
{
- GPUIndexBuf *built = (GPUIndexBuf *)*ib;
- return built;
+ if (index_buf) {
+ free(index_buf->data);
+ free(index_buf);
+ }
}
-GPUBatch *GPU_batch_create_ex(int primitive_type, GPUVertBuf *UNUSED(verts),
- GPUIndexBuf *UNUSED(index_buffer), unsigned int UNUSED(owns))
+GPUBatch *GPU_batch_create_ex(int primitive_type, GPUVertBuf *verts,
+ GPUIndexBuf *index_buffer, unsigned int owns_flags)
{
GPUBatch *batch = (GPUBatch *)calloc(1, sizeof(GPUBatch));
batch->prim_type = primitive_type;
+ batch->verts = verts;
+ batch->index_buffer = index_buffer;
+ batch->owns_flags = owns_flags;
return batch;
}
void GPU_batch_discard(GPUBatch *batch)
{
- free(batch);
+ if (batch) {
+ if (batch->owns_flags & GPU_BATCH_OWNS_IBO) {
+ GPU_indexbuf_discard(batch->index_buffer);
+ }
+ if (batch->owns_flags & GPU_BATCH_OWNS_VBO) {
+ GPUVertBufInternal *verts = (GPUVertBufInternal *)batch->verts;
+ if (verts) {
+ free(verts->cpu_data);
+ free(verts->format);
+ }
+ free(verts);
+ }
+ free(batch);
+ }
}
-void GPU_batch_draw(GPUBatch *UNUSED(batch)) {}
+static void bui_batch_flush(GPUBatch *batch)
+{
+ if (!bui_sink || !batch || !batch->verts) {
+ return;
+ }
+ GPUVertBufInternal *verts = (GPUVertBufInternal *)batch->verts;
+ if (!verts->cpu_data || verts->vertex_len == 0 || !verts->format) {
+ return;
+ }
+ int pos_idx = -1;
+ int col_idx = -1;
+ for (unsigned int i = 0; i < verts->format->attr_len; i++) {
+ if (strcmp(verts->format->attrs[i].name, "pos") == 0) {
+ pos_idx = (int)i;
+ }
+ else if (strcmp(verts->format->attrs[i].name, "color") == 0) {
+ col_idx = (int)i;
+ }
+ }
+ if (pos_idx < 0) {
+ return;
+ }
+ const unsigned int pos_off = verts->format->attrs[pos_idx].offset;
+ const bool has_col = col_idx >= 0;
+ const unsigned int col_off = has_col ? verts->format->attrs[col_idx].offset : 0;
+ const unsigned int stride = verts->stride;
+
+ const unsigned int n = verts->vertex_len;
+ float(*coords)[2] = (float(*)[2])malloc(sizeof(float) * 2 * n);
+ float(*colors)[4] = (float(*)[4])malloc(sizeof(float) * 4 * n);
+ for (unsigned int i = 0; i < n; i++) {
+ const unsigned char *row = (unsigned char *)verts->cpu_data + (size_t)i * stride;
+ memcpy(coords[i], row + pos_off, sizeof(float) * 2);
+ if (has_col) {
+ if (verts->format->attrs[col_idx].attr_type == (unsigned int)UBYTE_8_UINT) {
+ for (int c = 0; c < 4; c++) {
+ colors[i][c] = row[col_off + c] / 255.0f;
+ }
+ }
+ else {
+ memcpy(colors[i], row + col_off, sizeof(float) * 4);
+ }
+ }
+ else {
+ memcpy(colors[i], batch->uniform_color, sizeof(float) * 4);
+ }
+ }
+ bui_sink_flush_prim(batch->prim_type, coords, colors, (int)n);
+ free(coords);
+ free(colors);
+}
+
+void GPU_batch_draw(GPUBatch *batch) { bui_batch_flush(batch); }
void GPU_batch_draw_instance_range(GPUBatch *UNUSED(batch), int UNUSED(i_first),
int UNUSED(i_count))
{
@@ -380,20 +767,44 @@ void GPU_batch_uniform_3fv(GPUBatch *UNUSED(batch), const char *UNUSED(name),
const float UNUSED(data[3]))
{
}
-void GPU_batch_uniform_4f(GPUBatch *UNUSED(batch), const char *UNUSED(name), float UNUSED(x),
- float UNUSED(y), float UNUSED(z), float UNUSED(w))
+void GPU_batch_uniform_4f(GPUBatch *batch, const char *name, float x,
+ float y, float z, float w)
{
+ if (batch && name && strcmp(name, "color") == 0) {
+ batch->uniform_color[0] = x;
+ batch->uniform_color[1] = y;
+ batch->uniform_color[2] = z;
+ batch->uniform_color[3] = w;
+ }
}
void GPU_batch_uniform_4fv_array(GPUBatch *UNUSED(batch), const char *UNUSED(name),
- int UNUSED(len), const float *UNUSED(data))
+ int UNUSED(len), const float (*data)[4])
{
+ (void)data;
}
void GPU_batch_uniformbuf_bind(GPUBatch *UNUSED(batch), GPUUniformBuf *UNUSED(uniformbuf)) {}
-void gpu_batch_presets_register() {}
+GPUUniformBuf *GPU_uniformbuf_create_ex(size_t size, const void *UNUSED(data),
+ const char *UNUSED(name))
+{
+ GPUUniformBuf *ubo = (GPUUniformBuf *)calloc(1, sizeof(GPUUniformBuf));
+ ubo->size = size;
+ return ubo;
+}
+void GPU_uniformbuf_update(GPUUniformBuf *UNUSED(uniformbuf), const void *UNUSED(data)) {}
+void GPU_uniformbuf_free(GPUUniformBuf *uniformbuf)
+{
+ free(uniformbuf);
+}
+
+void gpu_batch_presets_register(GPUBatch *UNUSED(preset_batch)) {}
GPUBatch *GPU_batch_preset_sphere(int UNUSED(level))
{
return GPU_batch_create_ex(GPU_PRIM_TRIS, NULL, NULL, 0);
}
/** \} */
+
+
+
+
diff --git a/gpu/intern/gpu_raster.c b/gpu/intern/gpu_raster.c
new file mode 100644
index 0000000..0b63e39
--- /dev/null
+++ b/gpu/intern/gpu_raster.c
@@ -0,0 +1,1730 @@
+/* BUI software raster backend — see GPU_raster.h.
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#include "GPU_raster.h"
+
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define TILE_W 64
+#define TILE_H 32
+
+struct BuiRaster {
+ int w, h;
+ uint32_t *pix; /* current frame */
+ uint32_t *prev; /* last presented frame, for damage */
+ int full_damage;
+
+ /* clip, exclusive max, always inside the buffer */
+ int cx0, cy0, cx1, cy1;
+
+ int (*damage)[4];
+ int damage_len, damage_cap;
+
+ char font_family[64];
+ int font_flags;
+
+ BuiGpuSink sink;
+};
+
+/* -------------------------------------------------------------------- */
+/** \name Pixel helpers
+ * \{ */
+
+typedef struct Paint {
+ uint32_t rgb; /* 0x00RRGGBB */
+ int a; /* 0..256 */
+} Paint;
+
+static inline int clampi(int v, int lo, int hi)
+{
+ return v < lo ? lo : (v > hi ? hi : v);
+}
+
+static inline float clampf(float v, float lo, float hi)
+{
+ return v < lo ? lo : (v > hi ? hi : v);
+}
+
+static inline Paint paint_from(const float c[4])
+{
+ Paint p;
+ int r = (int)(clampf(c[0], 0.0f, 1.0f) * 255.0f + 0.5f);
+ int g = (int)(clampf(c[1], 0.0f, 1.0f) * 255.0f + 0.5f);
+ int b = (int)(clampf(c[2], 0.0f, 1.0f) * 255.0f + 0.5f);
+ p.rgb = ((uint32_t)r << 16) | ((uint32_t)g << 8) | (uint32_t)b;
+ p.a = (int)(clampf(c[3], 0.0f, 1.0f) * 256.0f + 0.5f);
+ return p;
+}
+
+/* Blend s over d with factor f in 0..256. */
+static inline uint32_t blend(uint32_t d, uint32_t s, uint32_t f)
+{
+ const uint32_t nf = 256 - f;
+ const uint32_t rb = (((s & 0xFF00FFu) * f + (d & 0xFF00FFu) * nf) >> 8) & 0xFF00FFu;
+ const uint32_t g = (((s & 0x00FF00u) * f + (d & 0x00FF00u) * nf) >> 8) & 0x00FF00u;
+ return rb | g;
+}
+
+/* Write with coverage cov (0..1) scaled by paint alpha. */
+static inline void put_cov(uint32_t *px, Paint p, float cov)
+{
+ if (cov <= 0.0f) {
+ return;
+ }
+ int f = (int)(cov * (float)p.a + 0.5f);
+ if (f >= 256) {
+ *px = p.rgb;
+ }
+ else if (f > 0) {
+ *px = blend(*px, p.rgb, (uint32_t)f);
+ }
+}
+
+/* Integer bbox [x0,x1) x [y0,y1) clipped; returns 0 when empty. */
+static int clip_box(const BuiRaster *r, float fx0, float fy0, float fx1, float fy1, int *x0, int *y0,
+ int *x1, int *y1)
+{
+ if (!(fx1 > fx0) || !(fy1 > fy0)) {
+ return 0;
+ }
+ /* Guard against NaN / huge values before converting to int. */
+ fx0 = clampf(fx0, -1e6f, 1e6f);
+ fy0 = clampf(fy0, -1e6f, 1e6f);
+ fx1 = clampf(fx1, -1e6f, 1e6f);
+ fy1 = clampf(fy1, -1e6f, 1e6f);
+ *x0 = clampi((int)floorf(fx0), r->cx0, r->cx1);
+ *y0 = clampi((int)floorf(fy0), r->cy0, r->cy1);
+ *x1 = clampi((int)ceilf(fx1), r->cx0, r->cx1);
+ *y1 = clampi((int)ceilf(fy1), r->cy0, r->cy1);
+ return *x1 > *x0 && *y1 > *y0;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Lifetime / frame
+ * \{ */
+
+static void raster_reset_clip(BuiRaster *r)
+{
+ r->cx0 = 0;
+ r->cy0 = 0;
+ r->cx1 = r->w;
+ r->cy1 = r->h;
+}
+
+static void raster_alloc(BuiRaster *r, int w, int h)
+{
+ free(r->pix);
+ free(r->prev);
+ r->w = w > 0 ? w : 1;
+ r->h = h > 0 ? h : 1;
+ r->pix = (uint32_t *)calloc((size_t)r->w * r->h, sizeof(uint32_t));
+ r->prev = (uint32_t *)calloc((size_t)r->w * r->h, sizeof(uint32_t));
+ r->full_damage = 1;
+ raster_reset_clip(r);
+}
+
+static void sink_begin(void *u, int w, int h)
+{
+ BUI_raster_begin_frame((BuiRaster *)u, w, h);
+}
+static void sink_scissor(void *u, int x, int y, int w, int h)
+{
+ BUI_raster_set_clip((BuiRaster *)u, x, y, w, h);
+}
+static void sink_tris(void *u, const float (*co)[2], const float (*col)[4], int n)
+{
+ BUI_raster_triangles((BuiRaster *)u, co, col, n);
+}
+static void sink_lines(void *u, const float (*co)[2], const float (*col)[4], int n)
+{
+ for (int i = 0; i + 1 < n; i += 2) {
+ BUI_raster_line((BuiRaster *)u, co[i][0], co[i][1], co[i + 1][0], co[i + 1][1], 1.0f, col[i]);
+ }
+}
+static void sink_points(void *u, const float (*co)[2], const float (*col)[4], int n, float size)
+{
+ BUI_raster_points((BuiRaster *)u, co, col, n, size);
+}
+static void sink_text(void *u, float x, float y, const char *text, float size, const float rgba[4])
+{
+ BUI_raster_text((BuiRaster *)u, x, y, text, (int)strlen(text), size, rgba);
+}
+static void sink_end(void *u)
+{
+ BUI_raster_end_frame((BuiRaster *)u);
+}
+
+BuiRaster *BUI_raster_create(int width, int height)
+{
+ BuiRaster *r = (BuiRaster *)calloc(1, sizeof(BuiRaster));
+ if (!r) {
+ return NULL;
+ }
+ raster_alloc(r, width, height);
+ r->sink.user = r;
+ r->sink.begin_frame = sink_begin;
+ r->sink.scissor = sink_scissor;
+ r->sink.triangles = sink_tris;
+ r->sink.lines = sink_lines;
+ r->sink.points = sink_points;
+ r->sink.text = sink_text;
+ r->sink.end_frame = sink_end;
+ return r;
+}
+
+void BUI_raster_free(BuiRaster *r)
+{
+ if (!r) {
+ return;
+ }
+ free(r->pix);
+ free(r->prev);
+ free(r->damage);
+ free(r);
+}
+
+const BuiGpuSink *BUI_raster_sink(BuiRaster *r)
+{
+ return &r->sink;
+}
+
+void BUI_raster_begin_frame(BuiRaster *r, int width, int height)
+{
+ if (width > 0 && height > 0 && (width != r->w || height != r->h)) {
+ raster_alloc(r, width, height);
+ }
+ raster_reset_clip(r);
+}
+
+static void damage_push(BuiRaster *r, int x, int y, int w, int h)
+{
+ /* Merge with the previous rect when it is the same column span directly
+ * above (common for tall widgets), keeping uploads few and large. */
+ if (r->damage_len > 0) {
+ int *last = r->damage[r->damage_len - 1];
+ if (last[0] == x && last[2] == w && last[1] + last[3] == y) {
+ last[3] += h;
+ return;
+ }
+ }
+ if (r->damage_len == r->damage_cap) {
+ int cap = r->damage_cap ? r->damage_cap * 2 : 64;
+ int(*nd)[4] = (int(*)[4])realloc(r->damage, sizeof(int[4]) * (size_t)cap);
+ if (!nd) {
+ return;
+ }
+ r->damage = nd;
+ r->damage_cap = cap;
+ }
+ int *d = r->damage[r->damage_len++];
+ d[0] = x;
+ d[1] = y;
+ d[2] = w;
+ d[3] = h;
+}
+
+void BUI_raster_end_frame(BuiRaster *r)
+{
+ r->damage_len = 0;
+ const size_t total = (size_t)r->w * r->h;
+ if (r->full_damage) {
+ damage_push(r, 0, 0, r->w, r->h);
+ memcpy(r->prev, r->pix, total * sizeof(uint32_t));
+ r->full_damage = 0;
+ return;
+ }
+ for (int ty = 0; ty < r->h; ty += TILE_H) {
+ const int th = (ty + TILE_H <= r->h) ? TILE_H : r->h - ty;
+ int run_x = -1;
+ /* One step past the last tile acts as a clean sentinel that closes a
+ * run touching the right edge (for any width, not just multiples of
+ * TILE_W — otherwise right-edge changes were never reported). */
+ for (int tx = 0; tx < r->w + TILE_W; tx += TILE_W) {
+ int dirty = 0;
+ if (tx < r->w) {
+ const int tw = (tx + TILE_W <= r->w) ? TILE_W : r->w - tx;
+ for (int y = ty; y < ty + th; y++) {
+ const size_t o = (size_t)y * r->w + tx;
+ if (memcmp(r->pix + o, r->prev + o, (size_t)tw * sizeof(uint32_t)) != 0) {
+ dirty = 1;
+ break;
+ }
+ }
+ }
+ if (dirty && run_x < 0) {
+ run_x = tx;
+ }
+ else if (!dirty && run_x >= 0) {
+ const int end = tx < r->w ? tx : r->w;
+ damage_push(r, run_x, ty, end - run_x, th);
+ for (int y = ty; y < ty + th; y++) {
+ const size_t o = (size_t)y * r->w + run_x;
+ memcpy(r->prev + o, r->pix + o, (size_t)(end - run_x) * sizeof(uint32_t));
+ }
+ run_x = -1;
+ }
+ }
+ }
+}
+
+int BUI_raster_width(const BuiRaster *r)
+{
+ return r->w;
+}
+int BUI_raster_height(const BuiRaster *r)
+{
+ return r->h;
+}
+const uint32_t *BUI_raster_pixels(const BuiRaster *r)
+{
+ return r->pix;
+}
+
+int BUI_raster_damage(const BuiRaster *r, const int (**r_rects)[4])
+{
+ *r_rects = (const int(*)[4])r->damage;
+ return r->damage_len;
+}
+
+void BUI_raster_invalidate(BuiRaster *r)
+{
+ r->full_damage = 1;
+}
+
+void BUI_raster_set_clip(BuiRaster *r, int x, int y, int w, int h)
+{
+ if (w <= 0 || h <= 0) {
+ raster_reset_clip(r);
+ return;
+ }
+ r->cx0 = clampi(x, 0, r->w);
+ r->cy0 = clampi(y, 0, r->h);
+ r->cx1 = clampi(x + w, 0, r->w);
+ r->cy1 = clampi(y + h, 0, r->h);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Primitives
+ * \{ */
+
+void BUI_raster_fill_rect(BuiRaster *r, float x, float y, float w, float h, const float rgba[4])
+{
+ int x0, y0, x1, y1;
+ if (!clip_box(r, x, y, x + w, y + h, &x0, &y0, &x1, &y1)) {
+ return;
+ }
+ const Paint p = paint_from(rgba);
+ if (p.a <= 0) {
+ return;
+ }
+ const float fx0 = x, fx1 = x + w, fy0 = y, fy1 = y + h;
+ for (int py = y0; py < y1; py++) {
+ const float cy = fminf(fy1, (float)py + 1.0f) - fmaxf(fy0, (float)py);
+ if (cy <= 0.0f) {
+ continue;
+ }
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ /* fully covered interior span */
+ const int ix0 = clampi((int)ceilf(fx0), x0, x1);
+ const int ix1 = clampi((int)floorf(fx1), x0, x1);
+ for (int px = x0; px < ix0 && px < x1; px++) {
+ const float cx = fminf(fx1, (float)px + 1.0f) - fmaxf(fx0, (float)px);
+ put_cov(row + px, p, cx * cy);
+ }
+ if (cy >= 1.0f && p.a >= 256) {
+ for (int px = ix0; px < ix1; px++) {
+ row[px] = p.rgb;
+ }
+ }
+ else {
+ const int f = (int)(cy * (float)p.a + 0.5f);
+ if (f >= 256) {
+ for (int px = ix0; px < ix1; px++) {
+ row[px] = p.rgb;
+ }
+ }
+ else if (f > 0) {
+ for (int px = ix0; px < ix1; px++) {
+ row[px] = blend(row[px], p.rgb, (uint32_t)f);
+ }
+ }
+ }
+ /* trailing partial column(s); when the rect sits inside one pixel the
+ * leading loop already covered it (ix1 < ix0). */
+ for (int px = (ix1 > ix0 ? ix1 : ix0); px < x1; px++) {
+ const float cx = fminf(fx1, (float)px + 1.0f) - fmaxf(fx0, (float)px);
+ put_cov(row + px, p, cx * cy);
+ }
+ }
+}
+
+void BUI_raster_frame_rect(
+ BuiRaster *r, float x, float y, float w, float h, float t, const float rgba[4])
+{
+ if (t <= 0.0f || w <= 0.0f || h <= 0.0f) {
+ return;
+ }
+ if (t * 2.0f >= w || t * 2.0f >= h) {
+ BUI_raster_fill_rect(r, x, y, w, h, rgba);
+ return;
+ }
+ /* Non-overlapping sides so translucent borders blend once. */
+ BUI_raster_fill_rect(r, x, y, w, t, rgba);
+ BUI_raster_fill_rect(r, x, y + h - t, w, t, rgba);
+ BUI_raster_fill_rect(r, x, y + t, t, h - 2.0f * t, rgba);
+ BUI_raster_fill_rect(r, x + w - t, y + t, t, h - 2.0f * t, rgba);
+}
+
+void BUI_raster_round_rect(
+ BuiRaster *r, float x, float y, float w, float h, float radius, const float rgba[4])
+{
+ if (w <= 0.0f || h <= 0.0f) {
+ return;
+ }
+ const float hw = w * 0.5f, hh = h * 0.5f;
+ float rad = fminf(radius, fminf(hw, hh));
+ if (rad <= 0.25f) {
+ BUI_raster_fill_rect(r, x, y, w, h, rgba);
+ return;
+ }
+ int x0, y0, x1, y1;
+ if (!clip_box(r, x, y, x + w, y + h, &x0, &y0, &x1, &y1)) {
+ return;
+ }
+ const Paint p = paint_from(rgba);
+ if (p.a <= 0) {
+ return;
+ }
+ const float cx = x + hw, cy = y + hh;
+ const float bx = hw - rad, by = hh - rad;
+ const float rin = rad - 0.5f; /* coverage is exactly 1 inside this radius */
+ for (int py = y0; py < y1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const float qy = fabsf((float)py + 0.5f - cy) - by;
+ /* Half-width (from cx) of this row's fully covered span: the interior
+ * is filled directly; the SDF only runs on the anti-aliased rim. */
+ float ih = -1.0f;
+ if (rin > 0.0f) {
+ if (qy <= 0.0f) {
+ ih = bx + rin;
+ }
+ else if (qy < rin) {
+ ih = bx + sqrtf(rin * rin - qy * qy);
+ }
+ }
+ int sa = x1, sb = x0; /* solid span [sa, sb) */
+ if (ih >= 0.0f) {
+ sa = clampi((int)ceilf(cx - ih - 0.5f), x0, x1);
+ sb = clampi((int)floorf(cx + ih - 0.5f) + 1, x0, x1);
+ if (sb > sa) {
+ if (p.a >= 256) {
+ for (int px = sa; px < sb; px++) {
+ row[px] = p.rgb;
+ }
+ }
+ else {
+ for (int px = sa; px < sb; px++) {
+ row[px] = blend(row[px], p.rgb, (uint32_t)p.a);
+ }
+ }
+ }
+ else {
+ sa = x1;
+ sb = x0;
+ }
+ }
+ for (int px = x0; px < x1; px++) {
+ if (px == sa) {
+ px = sb - 1; /* skip the solid span */
+ continue;
+ }
+ const float qx = fabsf((float)px + 0.5f - cx) - bx;
+ float d;
+ if (qx <= 0.0f && qy <= 0.0f) {
+ d = fmaxf(qx, qy) - rad;
+ if (d <= -0.5f) {
+ if (p.a >= 256) {
+ row[px] = p.rgb;
+ }
+ else {
+ row[px] = blend(row[px], p.rgb, (uint32_t)p.a);
+ }
+ continue;
+ }
+ }
+ else {
+ const float mx = fmaxf(qx, 0.0f), my = fmaxf(qy, 0.0f);
+ d = sqrtf(mx * mx + my * my) + fminf(fmaxf(qx, qy), 0.0f) - rad;
+ }
+ put_cov(row + px, p, clampf(0.5f - d, 0.0f, 1.0f));
+ }
+ }
+}
+
+void BUI_raster_circle(
+ BuiRaster *r, float cx, float cy, float radius, float line_width, const float rgba[4])
+{
+ if (radius <= 0.0f) {
+ return;
+ }
+ const float ext = radius + (line_width > 0.0f ? line_width : 0.0f) + 1.0f;
+ int x0, y0, x1, y1;
+ if (!clip_box(r, cx - ext, cy - ext, cx + ext, cy + ext, &x0, &y0, &x1, &y1)) {
+ return;
+ }
+ const Paint p = paint_from(rgba);
+ if (p.a <= 0) {
+ return;
+ }
+ const float half_lw = line_width * 0.5f;
+ for (int py = y0; py < y1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const float dy = (float)py + 0.5f - cy;
+ for (int px = x0; px < x1; px++) {
+ const float dx = (float)px + 0.5f - cx;
+ const float dist = sqrtf(dx * dx + dy * dy);
+ float cov;
+ if (line_width > 0.0f) {
+ cov = clampf(half_lw - fabsf(dist - radius) + 0.5f, 0.0f, 1.0f);
+ }
+ else {
+ cov = clampf(radius - dist + 0.5f, 0.0f, 1.0f);
+ }
+ put_cov(row + px, p, cov);
+ }
+ }
+}
+
+void BUI_raster_line(
+ BuiRaster *r, float x1, float y1, float x2, float y2, float width, const float rgba[4])
+{
+ if (width <= 0.0f) {
+ width = 1.0f;
+ }
+ /* Axis-aligned lines are pixel-exact spans (crisp, like GL lines on the
+ * pixel grid). Integer coords address the pixel to the right/below. */
+ if (y1 == y2) {
+ const float xa = fminf(x1, x2), xb = fmaxf(x1, x2);
+ BUI_raster_fill_rect(r, xa, y1 - (width - 1.0f) * 0.5f, fmaxf(xb - xa, 1.0f), width, rgba);
+ return;
+ }
+ if (x1 == x2) {
+ const float ya = fminf(y1, y2), yb = fmaxf(y1, y2);
+ BUI_raster_fill_rect(r, x1 - (width - 1.0f) * 0.5f, ya, width, fmaxf(yb - ya, 1.0f), rgba);
+ return;
+ }
+ /* Diagonal: anti-aliased capsule between pixel centers. */
+ const float ax = x1 + 0.5f, ay = y1 + 0.5f, bx = x2 + 0.5f, by = y2 + 0.5f;
+ const float hw = width * 0.5f;
+ int ix0, iy0, ix1, iy1;
+ if (!clip_box(r, fminf(ax, bx) - hw - 1.0f, fminf(ay, by) - hw - 1.0f,
+ fmaxf(ax, bx) + hw + 1.0f, fmaxf(ay, by) + hw + 1.0f, &ix0, &iy0, &ix1, &iy1))
+ {
+ return;
+ }
+ const Paint p = paint_from(rgba);
+ if (p.a <= 0) {
+ return;
+ }
+ const float vx = bx - ax, vy = by - ay;
+ const float len2 = vx * vx + vy * vy;
+ for (int py = iy0; py < iy1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const float wy = (float)py + 0.5f - ay;
+ for (int px = ix0; px < ix1; px++) {
+ const float wx = (float)px + 0.5f - ax;
+ const float t = clampf((wx * vx + wy * vy) / len2, 0.0f, 1.0f);
+ const float ex = wx - vx * t, ey = wy - vy * t;
+ const float d = sqrtf(ex * ex + ey * ey) - hw;
+ put_cov(row + px, p, clampf(0.5f - d, 0.0f, 1.0f));
+ }
+ }
+}
+
+void BUI_raster_ellipse(BuiRaster *r,
+ float cx,
+ float cy,
+ float rx,
+ float ry,
+ float line_width,
+ const float rgba[4])
+{
+ rx = fabsf(rx);
+ ry = fabsf(ry);
+ if (rx <= 0.0f || ry <= 0.0f) {
+ return;
+ }
+ if (fabsf(rx - ry) < 1e-3f) {
+ BUI_raster_circle(r, cx, cy, rx, line_width, rgba);
+ return;
+ }
+ const float ext = (line_width > 0.0f ? line_width : 0.0f) + 1.0f;
+ int x0, y0, x1, y1;
+ if (!clip_box(r, cx - rx - ext, cy - ry - ext, cx + rx + ext, cy + ry + ext, &x0, &y0, &x1,
+ &y1))
+ {
+ return;
+ }
+ const Paint p = paint_from(rgba);
+ if (p.a <= 0) {
+ return;
+ }
+ const float half_lw = line_width * 0.5f;
+ for (int py = y0; py < y1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const float dy = ((float)py + 0.5f - cy) / ry;
+ for (int px = x0; px < x1; px++) {
+ const float dx = ((float)px + 0.5f - cx) / rx;
+ /* First-order distance: (|p/r| - 1) / |grad| — accurate near the edge,
+ * which is all anti-aliasing needs. */
+ const float k = sqrtf(dx * dx + dy * dy);
+ const float gx = dx / rx, gy = dy / ry;
+ const float g = sqrtf(gx * gx + gy * gy);
+ const float d = g > 0.0f ? (k - 1.0f) * k / g : -fminf(rx, ry);
+ float cov;
+ if (line_width > 0.0f) {
+ cov = clampf(half_lw - fabsf(d) + 0.5f, 0.0f, 1.0f);
+ }
+ else {
+ cov = clampf(0.5f - d, 0.0f, 1.0f);
+ }
+ put_cov(row + px, p, cov);
+ }
+ }
+}
+
+/* Signed distance to a rounded box with a per-corner radius mask. Pixel
+ * center (sx, sy); box center (cx, cy), half size (hw, hh). */
+static inline float sd_widget_box(
+ float sx, float sy, float cx, float cy, float hw, float hh, float rad, int corners)
+{
+ const float px = sx - cx, py = sy - cy;
+ int bit;
+ if (py < 0.0f) {
+ bit = px < 0.0f ? BUI_CORNER_TOP_LEFT : BUI_CORNER_TOP_RIGHT;
+ }
+ else {
+ bit = px < 0.0f ? BUI_CORNER_BOTTOM_LEFT : BUI_CORNER_BOTTOM_RIGHT;
+ }
+ const float r = (corners & bit) ? rad : 0.0f;
+ const float qx = fabsf(px) - (hw - r), qy = fabsf(py) - (hh - r);
+ /* Straight edges need no sqrt; only true corner pixels do. */
+ if (qx <= 0.0f || qy <= 0.0f) {
+ return fmaxf(qx, qy) - r;
+ }
+ return sqrtf(qx * qx + qy * qy) - r;
+}
+
+void BUI_raster_widget(BuiRaster *r,
+ float x,
+ float y,
+ float w,
+ float h,
+ float radius,
+ int corners,
+ const float inner_top[4],
+ const float inner_bottom[4],
+ const float outline[4],
+ float outline_width,
+ const float emboss[4])
+{
+ if (w <= 0.0f || h <= 0.0f) {
+ return;
+ }
+ const float hw = w * 0.5f, hh = h * 0.5f;
+ const float rad = clampf(radius, 0.0f, fminf(hw, hh));
+ const float cx = x + hw, cy = y + hh;
+ const float ow = outline ? fmaxf(outline_width, 0.0f) : 0.0f;
+ const int has_emboss = emboss && emboss[3] > 0.0f;
+ int x0, y0, x1, y1;
+ if (!clip_box(r, x - 1.0f, y - 1.0f, x + w + 1.0f, y + h + (has_emboss ? 2.0f : 1.0f), &x0, &y0,
+ &x1, &y1))
+ {
+ return;
+ }
+ const float *top = inner_top ? inner_top : inner_bottom;
+ const float *bot = inner_bottom ? inner_bottom : inner_top;
+ const int gradient = top && bot && memcmp(top, bot, sizeof(float[4])) != 0;
+ Paint p_inner = top ? paint_from(top) : (Paint){0, 0};
+ const Paint p_out = outline ? paint_from(outline) : (Paint){0, 0};
+ const Paint p_emb = has_emboss ? paint_from(emboss) : (Paint){0, 0};
+ /* Fully covered interior margin: no SDF needed farther than this from
+ * every edge (skips sqrt for the bulk of each widget). */
+ const float safe = rad + ow + 1.0f;
+
+ for (int py = y0; py < y1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const float sy = (float)py + 0.5f;
+ if (gradient) {
+ const float t = clampf((sy - y) / h, 0.0f, 1.0f);
+ float c[4];
+ for (int k = 0; k < 4; k++) {
+ c[k] = top[k] + (bot[k] - top[k]) * t;
+ }
+ p_inner = paint_from(c);
+ }
+ const int row_inside = (sy - y) >= safe && (y + h - sy) >= safe;
+ /* Interior span of this row: filled directly, no per-pixel SDF. */
+ int sa = x1, sb = x1;
+ if (row_inside) {
+ sa = clampi((int)ceilf(x + safe - 0.5f), x0, x1);
+ sb = clampi((int)floorf(x + w - safe - 0.5f) + 1, x0, x1);
+ if (sb <= sa) {
+ sa = sb = x1;
+ }
+ else if (top) {
+ if (p_inner.a >= 256) {
+ for (int px = sa; px < sb; px++) {
+ row[px] = p_inner.rgb;
+ }
+ }
+ else if (p_inner.a > 0) {
+ for (int px = sa; px < sb; px++) {
+ row[px] = blend(row[px], p_inner.rgb, (uint32_t)p_inner.a);
+ }
+ }
+ }
+ }
+ for (int px = x0; px < x1; px++) {
+ if (px == sa) {
+ px = sb - 1; /* skip the interior span */
+ continue;
+ }
+ const float sx = (float)px + 0.5f;
+ const float d = sd_widget_box(sx, sy, cx, cy, hw, hh, rad, corners);
+ const float cov = clampf(0.5f - d, 0.0f, 1.0f);
+ if (has_emboss && sy > cy) {
+ /* Emboss: the same shape shifted 1px down, visible only outside. */
+ const float de = sd_widget_box(sx, sy - 1.0f, cx, cy, hw, hh, rad, corners);
+ const float ecov = clampf(0.5f - de, 0.0f, 1.0f) - cov;
+ if (ecov > 0.0f) {
+ put_cov(row + px, p_emb, ecov);
+ }
+ }
+ if (cov <= 0.0f) {
+ continue;
+ }
+ if (top) {
+ put_cov(row + px, p_inner, cov);
+ }
+ if (ow > 0.0f) {
+ /* Outline band: inside the edge, `ow` pixels wide. */
+ const float inner_cov = clampf(0.5f - (d + ow), 0.0f, 1.0f);
+ const float band = cov - inner_cov;
+ if (band > 0.0f) {
+ put_cov(row + px, p_out, band);
+ }
+ }
+ }
+ }
+}
+
+/* Blender's widget base (GPU_SHADER_2D_WIDGET_BASE) in software: the same
+ * parameters interface_widgets.cc feeds the shader. Outer shape `rect`/`rad`,
+ * inner shape `rect` inset by `pixelsize` with `radi`; the band between them
+ * is the outline, the outer shape shifted down by one pixel (bottom half
+ * only) is the emboss. */
+void BUI_raster_widget_base(BuiRaster *r, const BuiWidgetBase *p)
+{
+ const float x = p->rect[0], y = p->rect[1], w = p->rect[2], h = p->rect[3];
+ if (w <= 0.0f || h <= 0.0f) {
+ return;
+ }
+ const float px1 = p->pixelsize > 0.0f ? p->pixelsize : 1.0f;
+ const float hw = w * 0.5f, hh = h * 0.5f, cx = x + hw, cy = y + hh;
+ const float rad = clampf(p->rad, 0.0f, fminf(hw, hh));
+ const float hwi = hw - px1, hhi = hh - px1;
+ const float radi = clampf(p->radi, 0.0f, fmaxf(0.0f, fminf(hwi, hhi)));
+ const int has_inner = p->inner1[3] > 0.0f || p->inner2[3] > 0.0f || p->alpha_checker;
+ const int has_outline = p->outline[3] > 0.0f;
+ const int has_emboss = p->emboss[3] > 0.0f;
+ if (!has_inner && !has_outline && !has_emboss) {
+ return;
+ }
+ int x0, y0, x1, y1;
+ if (!clip_box(r, x - 1.0f, y - 1.0f, x + w + 1.0f, y + h + px1 + 1.0f, &x0, &y0, &x1, &y1)) {
+ return;
+ }
+ const int gradient = memcmp(p->inner1, p->inner2, sizeof(float[4])) != 0;
+ const int per_pixel_inner = p->alpha_checker || (gradient && p->shade_horizontal);
+ const Paint p_out = paint_from(p->outline);
+ const Paint p_emb = paint_from(p->emboss);
+ Paint p_in = paint_from(p->inner1);
+ /* Columns farther than this from the left/right edges never see a corner:
+ * there the distance field only depends on the row (computed once). */
+ const float cornerw = fmaxf(rad, radi) + px1 + 1.0f;
+ const int ma = clampi((int)ceilf(x + cornerw - 0.5f), x0, x1);
+ const int mb = clampi((int)floorf(x + w - cornerw - 0.5f) + 1, ma, x1);
+
+ for (int py = y0; py < y1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const float sy = (float)py + 0.5f;
+ if (gradient && !p->shade_horizontal) {
+ const float t = clampf((sy - (y + px1)) / fmaxf(1.0f, h - 2.0f * px1), 0.0f, 1.0f);
+ float c[4];
+ for (int k = 0; k < 4; k++) {
+ c[k] = p->inner1[k] + (p->inner2[k] - p->inner1[k]) * t;
+ }
+ p_in = paint_from(c);
+ }
+ /* -- middle columns: row-constant coverage -- */
+ int span_a = ma, span_b = mb;
+ if (per_pixel_inner) {
+ span_a = span_b = x1; /* rare: checker / horizontal shading -> exact path */
+ }
+ if (span_a < span_b) {
+ const float ay = fabsf(sy - cy);
+ const float co = clampf(0.5f - (ay - hh), 0.0f, 1.0f);
+ const float ci = fminf(co, clampf(0.5f - (ay - hhi), 0.0f, 1.0f));
+ float ec = 0.0f;
+ if (has_emboss && sy > cy) {
+ ec = clampf(0.5f - (fabsf(sy - px1 - cy) - hh), 0.0f, 1.0f) - co;
+ }
+ const float band = has_outline ? co - ci : 0.0f;
+ const int fill_inner = has_inner && ci > 0.0f;
+ if (!(ec > 0.0f) && !(band > 0.0f) && fill_inner && ci >= 1.0f && p_in.a >= 256) {
+ for (int i = span_a; i < span_b; i++) {
+ row[i] = p_in.rgb; /* opaque interior: plain store */
+ }
+ }
+ else if (ec > 0.0f || band > 0.0f || fill_inner) {
+ const int fe = (int)(ec * (float)p_emb.a + 0.5f);
+ const int fi = fill_inner ? (int)(ci * (float)p_in.a + 0.5f) : 0;
+ const int fo = (int)(band * (float)p_out.a + 0.5f);
+ for (int i = span_a; i < span_b; i++) {
+ uint32_t d = row[i];
+ if (fe > 0) {
+ d = fe >= 256 ? p_emb.rgb : blend(d, p_emb.rgb, (uint32_t)fe);
+ }
+ if (fi > 0) {
+ d = fi >= 256 ? p_in.rgb : blend(d, p_in.rgb, (uint32_t)fi);
+ }
+ if (fo > 0) {
+ d = fo >= 256 ? p_out.rgb : blend(d, p_out.rgb, (uint32_t)fo);
+ }
+ row[i] = d;
+ }
+ }
+ }
+ /* -- corner columns (and everything on the exact path): full SDF -- */
+ for (int px = x0; px < x1; px++) {
+ if (px == span_a && span_a < span_b) {
+ px = span_b - 1;
+ continue;
+ }
+ const float sx = (float)px + 0.5f;
+ const float d = sd_widget_box(sx, sy, cx, cy, hw, hh, rad, p->corners);
+ const float co = clampf(0.5f - d, 0.0f, 1.0f);
+ if (has_emboss && sy > cy) {
+ const float de = sd_widget_box(sx, sy - px1, cx, cy, hw, hh, rad, p->corners);
+ const float ec = clampf(0.5f - de, 0.0f, 1.0f) - co;
+ if (ec > 0.0f) {
+ put_cov(row + px, p_emb, ec);
+ }
+ }
+ if (co <= 0.0f) {
+ continue;
+ }
+ const float di = sd_widget_box(sx, sy, cx, cy, hwi, hhi, radi, p->corners);
+ const float ci = fminf(co, clampf(0.5f - di, 0.0f, 1.0f));
+ if (has_inner && ci > 0.0f) {
+ if (p->alpha_checker) {
+ /* checkerColorAndSize: 100/255 and 160/255, 8 px cells */
+ const int cell = ((int)((sx - x) / 8.0f) + (int)((sy - y) / 8.0f)) & 1;
+ const float g = cell ? 160.0f / 255.0f : 100.0f / 255.0f;
+ const float gc[4] = {g, g, g, 1.0f};
+ put_cov(row + px, paint_from(gc), ci);
+ }
+ Paint pi = p_in;
+ if (gradient && p->shade_horizontal) {
+ const float t = clampf((sx - (x + px1)) / fmaxf(1.0f, w - 2.0f * px1), 0.0f, 1.0f);
+ float c[4];
+ for (int k = 0; k < 4; k++) {
+ c[k] = p->inner1[k] + (p->inner2[k] - p->inner1[k]) * t;
+ }
+ pi = paint_from(c);
+ }
+ put_cov(row + px, pi, ci);
+ }
+ if (has_outline && co - ci > 0.0f) {
+ put_cov(row + px, p_out, co - ci);
+ }
+ }
+ }
+}
+
+void BUI_raster_image(BuiRaster *r,
+ float x,
+ float y,
+ float w,
+ float h,
+ const uint32_t *argb,
+ int iw,
+ int ih,
+ float alpha)
+{
+ int x0, y0, x1, y1;
+ if (!argb || iw <= 0 || ih <= 0 || !clip_box(r, x, y, x + w, y + h, &x0, &y0, &x1, &y1)) {
+ return;
+ }
+ const int ga = (int)(clampf(alpha, 0.0f, 1.0f) * 256.0f + 0.5f);
+ for (int py = y0; py < y1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const int sy = clampi((int)(((float)py + 0.5f - y) * ih / h), 0, ih - 1);
+ const uint32_t *src = argb + (size_t)sy * iw;
+ for (int px = x0; px < x1; px++) {
+ const int sx = clampi((int)(((float)px + 0.5f - x) * iw / w), 0, iw - 1);
+ const uint32_t c = src[sx];
+ const int a = (int)((c >> 24) * ga) >> 8;
+ if (a >= 255) {
+ row[px] = c & 0xFFFFFFu;
+ }
+ else if (a > 0) {
+ row[px] = blend(row[px], c & 0xFFFFFFu, (uint32_t)(a + (a >> 7)));
+ }
+ }
+ }
+}
+
+void BUI_raster_end_frame_region(BuiRaster *r, int rx, int ry, int rw, int rh)
+{
+ /* Like end_frame, but only compares tiles touching the region that was
+ * redrawn: the rest of the frame is known to be unchanged. */
+ if (r->full_damage || rw <= 0 || rh <= 0) {
+ BUI_raster_end_frame(r);
+ return;
+ }
+ r->damage_len = 0;
+ const int tx0 = clampi(rx, 0, r->w) / TILE_W * TILE_W;
+ const int ty0 = clampi(ry, 0, r->h) / TILE_H * TILE_H;
+ const int tx1 = clampi(rx + rw, 0, r->w), ty1 = clampi(ry + rh, 0, r->h);
+ for (int ty = ty0; ty < ty1; ty += TILE_H) {
+ const int th = (ty + TILE_H <= r->h) ? TILE_H : r->h - ty;
+ int run_x = -1;
+ for (int tx = tx0; tx < tx1 + TILE_W; tx += TILE_W) {
+ int dirty = 0;
+ if (tx < tx1) {
+ const int tw = (tx + TILE_W <= r->w) ? TILE_W : r->w - tx;
+ for (int y = ty; y < ty + th; y++) {
+ const size_t o = (size_t)y * r->w + tx;
+ if (memcmp(r->pix + o, r->prev + o, (size_t)tw * sizeof(uint32_t)) != 0) {
+ dirty = 1;
+ break;
+ }
+ }
+ }
+ if (dirty && run_x < 0) {
+ run_x = tx;
+ }
+ else if (!dirty && run_x >= 0) {
+ const int end = tx < r->w ? tx : r->w;
+ damage_push(r, run_x, ty, end - run_x, th);
+ for (int y = ty; y < ty + th; y++) {
+ const size_t o = (size_t)y * r->w + run_x;
+ memcpy(r->prev + o, r->pix + o, (size_t)(end - run_x) * sizeof(uint32_t));
+ }
+ run_x = -1;
+ }
+ }
+ }
+}
+
+void BUI_raster_shadow(
+ BuiRaster *r, float x, float y, float w, float h, float radius, float size, float alpha)
+{
+ if (w <= 0.0f || h <= 0.0f || size <= 0.0f || alpha <= 0.0f) {
+ return;
+ }
+ int x0, y0, x1, y1;
+ if (!clip_box(r, x - size, y - size * 0.5f, x + w + size, y + h + size * 1.5f, &x0, &y0, &x1,
+ &y1))
+ {
+ return;
+ }
+ const float hw = w * 0.5f, hh = h * 0.5f;
+ const float rad = clampf(radius, 0.0f, fminf(hw, hh));
+ /* Light comes from above: the shadow sits slightly lower. */
+ const float cx = x + hw, cy = y + hh + size * 0.25f;
+ const Paint black = {0x000000u, 256};
+ for (int py = y0; py < y1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const float sy = (float)py + 0.5f;
+ for (int px = x0; px < x1; px++) {
+ const float sx = (float)px + 0.5f;
+ const float d = sd_widget_box(sx, sy, cx, cy, hw, hh, rad, BUI_CORNER_ALL);
+ /* Only outside the box itself (the popup covers the inside). */
+ const float dbox = sd_widget_box(sx, sy, x + hw, y + hh, hw, hh, rad, BUI_CORNER_ALL);
+ if (dbox <= -0.5f || d >= size) {
+ continue;
+ }
+ float t = 1.0f - clampf(d / size, 0.0f, 1.0f);
+ t = t * t * (3.0f - 2.0f * t); /* smoothstep falloff */
+ put_cov(row + px, black, t * alpha * clampf(0.5f + dbox, 0.0f, 1.0f));
+ }
+ }
+}
+
+#define POLY_SUBSAMPLES 4
+
+static int cmp_float(const void *a, const void *b)
+{
+ const float fa = *(const float *)a, fb = *(const float *)b;
+ return (fa > fb) - (fa < fb);
+}
+
+void BUI_raster_polygon(BuiRaster *r, const float (*pts)[2], int n, const float rgba[4])
+{
+ if (n < 3) {
+ return;
+ }
+ float minx = pts[0][0], maxx = pts[0][0], miny = pts[0][1], maxy = pts[0][1];
+ for (int i = 1; i < n; i++) {
+ minx = fminf(minx, pts[i][0]);
+ maxx = fmaxf(maxx, pts[i][0]);
+ miny = fminf(miny, pts[i][1]);
+ maxy = fmaxf(maxy, pts[i][1]);
+ }
+ int x0, y0, x1, y1;
+ if (!clip_box(r, minx, miny, maxx, maxy, &x0, &y0, &x1, &y1)) {
+ return;
+ }
+ const Paint p = paint_from(rgba);
+ if (p.a <= 0) {
+ return;
+ }
+ const int span = x1 - x0;
+ float *cov = (float *)calloc((size_t)span + 1, sizeof(float));
+ float *xs = (float *)malloc(sizeof(float) * (size_t)n);
+ if (!cov || !xs) {
+ free(cov);
+ free(xs);
+ return;
+ }
+ const float sub_w = 1.0f / POLY_SUBSAMPLES;
+ for (int py = y0; py < y1; py++) {
+ memset(cov, 0, sizeof(float) * ((size_t)span + 1));
+ int any = 0;
+ for (int s = 0; s < POLY_SUBSAMPLES; s++) {
+ const float sy = (float)py + ((float)s + 0.5f) * sub_w;
+ int nx = 0;
+ for (int i = 0, j = n - 1; i < n; j = i++) {
+ const float ay = pts[j][1], by = pts[i][1];
+ if ((ay <= sy && by > sy) || (by <= sy && ay > sy)) {
+ const float t = (sy - ay) / (by - ay);
+ xs[nx++] = pts[j][0] + t * (pts[i][0] - pts[j][0]);
+ }
+ }
+ if (nx < 2) {
+ continue;
+ }
+ qsort(xs, (size_t)nx, sizeof(float), cmp_float);
+ /* Even-odd spans with fractional horizontal coverage at the ends. */
+ for (int k = 0; k + 1 < nx; k += 2) {
+ const float a = fmaxf(xs[k], (float)x0), b = fminf(xs[k + 1], (float)x1);
+ if (b <= a) {
+ continue;
+ }
+ any = 1;
+ const int ia = (int)floorf(a), ib = (int)floorf(b);
+ if (ia == ib) {
+ cov[ia - x0] += (b - a) * sub_w;
+ continue;
+ }
+ cov[ia - x0] += ((float)ia + 1.0f - a) * sub_w;
+ for (int x = ia + 1; x < ib; x++) {
+ cov[x - x0] += sub_w;
+ }
+ if (ib < x1) {
+ cov[ib - x0] += (b - (float)ib) * sub_w;
+ }
+ }
+ }
+ if (!any) {
+ continue;
+ }
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ for (int x = 0; x < span; x++) {
+ put_cov(row + x0 + x, p, fminf(cov[x], 1.0f));
+ }
+ }
+ free(cov);
+ free(xs);
+}
+
+static inline float edge_fn(float ax, float ay, float bx, float by, float px, float py)
+{
+ return (bx - ax) * (py - ay) - (by - ay) * (px - ax);
+}
+
+static inline int is_top_left(float ax, float ay, float bx, float by)
+{
+ /* For counter-clockwise (in y-down space: positive area) winding. */
+ return (ay == by && bx < ax) || (by > ay);
+}
+
+void BUI_raster_triangles(BuiRaster *r,
+ const float (*co)[2],
+ const float (*col)[4],
+ int count)
+{
+ for (int i = 0; i + 2 < count; i += 3) {
+ float v[3][2] = {{co[i][0], co[i][1]}, {co[i + 1][0], co[i + 1][1]}, {co[i + 2][0], co[i + 2][1]}};
+ const float *c[3] = {col[i], col[i + 1], col[i + 2]};
+ float area = edge_fn(v[0][0], v[0][1], v[1][0], v[1][1], v[2][0], v[2][1]);
+ if (area == 0.0f || area != area) {
+ continue;
+ }
+ if (area < 0.0f) {
+ float tv[2] = {v[1][0], v[1][1]};
+ v[1][0] = v[2][0];
+ v[1][1] = v[2][1];
+ v[2][0] = tv[0];
+ v[2][1] = tv[1];
+ const float *tc = c[1];
+ c[1] = c[2];
+ c[2] = tc;
+ area = -area;
+ }
+ int x0, y0, x1, y1;
+ if (!clip_box(r, fminf(v[0][0], fminf(v[1][0], v[2][0])), fminf(v[0][1], fminf(v[1][1], v[2][1])),
+ fmaxf(v[0][0], fmaxf(v[1][0], v[2][0])), fmaxf(v[0][1], fmaxf(v[1][1], v[2][1])),
+ &x0, &y0, &x1, &y1))
+ {
+ continue;
+ }
+ const int flat = memcmp(c[0], c[1], sizeof(float[4])) == 0 &&
+ memcmp(c[0], c[2], sizeof(float[4])) == 0;
+ const Paint flat_p = paint_from(c[0]);
+ const int tl0 = is_top_left(v[1][0], v[1][1], v[2][0], v[2][1]);
+ const int tl1 = is_top_left(v[2][0], v[2][1], v[0][0], v[0][1]);
+ const int tl2 = is_top_left(v[0][0], v[0][1], v[1][0], v[1][1]);
+ const float inv_area = 1.0f / area;
+ for (int py = y0; py < y1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const float sy = (float)py + 0.5f;
+ for (int px = x0; px < x1; px++) {
+ const float sx = (float)px + 0.5f;
+ const float w0 = edge_fn(v[1][0], v[1][1], v[2][0], v[2][1], sx, sy);
+ const float w1 = edge_fn(v[2][0], v[2][1], v[0][0], v[0][1], sx, sy);
+ const float w2 = edge_fn(v[0][0], v[0][1], v[1][0], v[1][1], sx, sy);
+ if ((w0 < 0.0f || (w0 == 0.0f && !tl0)) || (w1 < 0.0f || (w1 == 0.0f && !tl1)) ||
+ (w2 < 0.0f || (w2 == 0.0f && !tl2)))
+ {
+ continue;
+ }
+ if (flat) {
+ put_cov(row + px, flat_p, 1.0f);
+ }
+ else {
+ float rgba[4];
+ const float b0 = w0 * inv_area, b1 = w1 * inv_area, b2 = w2 * inv_area;
+ for (int k = 0; k < 4; k++) {
+ rgba[k] = c[0][k] * b0 + c[1][k] * b1 + c[2][k] * b2;
+ }
+ put_cov(row + px, paint_from(rgba), 1.0f);
+ }
+ }
+ }
+ }
+}
+
+void BUI_raster_points(BuiRaster *r,
+ const float (*co)[2],
+ const float (*col)[4],
+ int count,
+ float size)
+{
+ const float rad = fmaxf(0.5f, size * 0.5f);
+ for (int i = 0; i < count; i++) {
+ BUI_raster_circle(r, co[i][0], co[i][1], rad, 0.0f, col[i]);
+ }
+}
+
+/* -------------------------------------------------------------------- */
+/** \name Color widgets (HSV wheel, gradients, lit sphere)
+ * \{ */
+
+static void hsv_to_rgb_f(float h, float s, float v, float out[3])
+{
+ h = h - floorf(h);
+ const float h6 = h * 6.0f;
+ const float r = clampf(fabsf(h6 - 3.0f) - 1.0f, 0.0f, 1.0f);
+ const float g = clampf(2.0f - fabsf(h6 - 2.0f), 0.0f, 1.0f);
+ const float b = clampf(2.0f - fabsf(h6 - 4.0f), 0.0f, 1.0f);
+ out[0] = ((r - 1.0f) * s + 1.0f) * v;
+ out[1] = ((g - 1.0f) * s + 1.0f) * v;
+ out[2] = ((b - 1.0f) * s + 1.0f) * v;
+}
+
+void BUI_raster_hsv_circle(BuiRaster *r, float cx, float cy, float radius, float value)
+{
+ int x0, y0, x1, y1;
+ if (radius <= 0.0f ||
+ !clip_box(r, cx - radius - 1, cy - radius - 1, cx + radius + 1, cy + radius + 1, &x0, &y0,
+ &x1, &y1))
+ {
+ return;
+ }
+ const float inv_2pi = 0.15915494309189535f;
+ for (int py = y0; py < y1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const float dy = (float)py + 0.5f - cy;
+ for (int px = x0; px < x1; px++) {
+ const float dx = (float)px + 0.5f - cx;
+ const float dist = sqrtf(dx * dx + dy * dy);
+ const float cov = clampf(radius - dist + 0.5f, 0.0f, 1.0f);
+ if (cov <= 0.0f) {
+ continue;
+ }
+ /* Blender's wheel (ui_hsvcircle_vals_from_pos): hue from the angle
+ * measured from "up", red at the bottom; saturation = distance. */
+ const float hue = atan2f(dx, -dy) * inv_2pi + 0.5f;
+ float rgba[4] = {0, 0, 0, 1.0f};
+ hsv_to_rgb_f(hue, fminf(dist / radius, 1.0f), value, rgba);
+ put_cov(row + px, paint_from(rgba), cov);
+ }
+ }
+}
+
+void BUI_raster_gradient(BuiRaster *r,
+ float x,
+ float y,
+ float w,
+ float h,
+ const float tl[4],
+ const float tr[4],
+ const float br[4],
+ const float bl[4])
+{
+ int x0, y0, x1, y1;
+ if (!clip_box(r, x, y, x + w, y + h, &x0, &y0, &x1, &y1)) {
+ return;
+ }
+ for (int py = y0; py < y1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const float v = clampf(((float)py + 0.5f - y) / h, 0.0f, 1.0f);
+ float left[4], right[4];
+ for (int k = 0; k < 4; k++) {
+ left[k] = tl[k] + (bl[k] - tl[k]) * v;
+ right[k] = tr[k] + (br[k] - tr[k]) * v;
+ }
+ for (int px = x0; px < x1; px++) {
+ const float u = clampf(((float)px + 0.5f - x) / w, 0.0f, 1.0f);
+ float c[4];
+ for (int k = 0; k < 4; k++) {
+ c[k] = left[k] + (right[k] - left[k]) * u;
+ }
+ put_cov(row + px, paint_from(c), 1.0f);
+ }
+ }
+}
+
+void BUI_raster_sphere(
+ BuiRaster *r, float cx, float cy, float radius, const float light[3], const float rgba[4])
+{
+ int x0, y0, x1, y1;
+ if (radius <= 0.0f ||
+ !clip_box(r, cx - radius - 1, cy - radius - 1, cx + radius + 1, cy + radius + 1, &x0, &y0,
+ &x1, &y1))
+ {
+ return;
+ }
+ float L[3] = {light[0], light[1], light[2]};
+ const float len = sqrtf(L[0] * L[0] + L[1] * L[1] + L[2] * L[2]);
+ if (len > 0.0f) {
+ L[0] /= len;
+ L[1] /= len;
+ L[2] /= len;
+ }
+ else {
+ L[2] = 1.0f;
+ }
+ /* Half vector for a viewer looking down -z. */
+ float H[3] = {L[0], L[1], L[2] + 1.0f};
+ const float hl = sqrtf(H[0] * H[0] + H[1] * H[1] + H[2] * H[2]);
+ if (hl > 0.0f) {
+ H[0] /= hl;
+ H[1] /= hl;
+ H[2] /= hl;
+ }
+ for (int py = y0; py < y1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const float ny = -((float)py + 0.5f - cy) / radius; /* up is +y */
+ for (int px = x0; px < x1; px++) {
+ const float nx = ((float)px + 0.5f - cx) / radius;
+ const float d2 = nx * nx + ny * ny;
+ const float cov = clampf((1.0f - sqrtf(d2)) * radius + 0.5f, 0.0f, 1.0f);
+ if (cov <= 0.0f) {
+ continue;
+ }
+ const float nz = sqrtf(fmaxf(0.0f, 1.0f - d2));
+ const float diff = fmaxf(0.0f, nx * L[0] + ny * L[1] + nz * L[2]);
+ float spec = fmaxf(0.0f, nx * H[0] + ny * H[1] + nz * H[2]);
+ spec = spec * spec;
+ spec = spec * spec;
+ spec = spec * spec * spec * spec; /* ^32 */
+ float c[4];
+ for (int k = 0; k < 3; k++) {
+ c[k] = rgba[k] * (0.12f + 0.88f * diff) + 0.6f * spec;
+ }
+ c[3] = rgba[3];
+ put_cov(row + px, paint_from(c), cov);
+ }
+ }
+}
+
+/** \} */
+
+void BUI_raster_set_font(BuiRaster *r, const char *family, int flags)
+{
+ if (!family) {
+ family = "";
+ }
+ strncpy(r->font_family, family, sizeof(r->font_family) - 1);
+ r->font_family[sizeof(r->font_family) - 1] = '\0';
+ r->font_flags = flags;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Native text + present (Win32 GDI)
+ * \{ */
+
+#ifdef _WIN32
+# ifndef WIN32_LEAN_AND_MEAN
+# define WIN32_LEAN_AND_MEAN
+# endif
+# include <windows.h>
+
+typedef struct FontSlot {
+ char family[64];
+ int px;
+ int flags;
+ HFONT font;
+ int ascent;
+ int height;
+} FontSlot;
+
+# define MAX_FONTS 48
+static FontSlot g_fonts[MAX_FONTS];
+static int g_font_count = 0;
+static HDC g_dc = NULL;
+
+typedef struct TextRun {
+ uint64_t hash;
+ int font;
+ int len;
+ char *text;
+ float advance;
+ /* mask, built lazily on first draw */
+ int built;
+ int mw, mh, ox; /* ox: left padding baked into the mask */
+ uint8_t *mask;
+} TextRun;
+
+# define RUN_CAP 8192 /* power of two */
+# define RUN_MAX_FILL 6000
+static TextRun *g_runs = NULL;
+static int g_run_count = 0;
+
+static void runs_flush(void)
+{
+ if (!g_runs) {
+ return;
+ }
+ for (int i = 0; i < RUN_CAP; i++) {
+ free(g_runs[i].text);
+ free(g_runs[i].mask);
+ }
+ memset(g_runs, 0, sizeof(TextRun) * RUN_CAP);
+ g_run_count = 0;
+}
+
+static void fonts_flush(void)
+{
+ for (int i = 0; i < g_font_count; i++) {
+ DeleteObject(g_fonts[i].font);
+ }
+ g_font_count = 0;
+ runs_flush(); /* runs reference font slots */
+}
+
+static HDC text_dc(void)
+{
+ if (!g_dc) {
+ g_dc = CreateCompatibleDC(NULL);
+ SetBkMode(g_dc, TRANSPARENT);
+ SetTextAlign(g_dc, TA_LEFT | TA_TOP | TA_NOUPDATECP);
+ }
+ return g_dc;
+}
+
+static int font_get(const char *family, int flags, float size)
+{
+ if (!family || !family[0] || strcmp(family, "TkDefaultFont") == 0) {
+ family = "Segoe UI";
+ }
+ int px = (int)(size + 0.5f);
+ if (px < 1) {
+ px = 1;
+ }
+ if (px > 512) {
+ px = 512;
+ }
+ for (int i = 0; i < g_font_count; i++) {
+ if (g_fonts[i].px == px && g_fonts[i].flags == flags &&
+ strcmp(g_fonts[i].family, family) == 0)
+ {
+ return i;
+ }
+ }
+ if (g_font_count == MAX_FONTS) {
+ fonts_flush();
+ }
+ wchar_t wfam[64];
+ if (MultiByteToWideChar(CP_UTF8, 0, family, -1, wfam, 64) == 0) {
+ wcscpy(wfam, L"Segoe UI");
+ }
+ HFONT font = CreateFontW(-px, 0, 0, 0, (flags & BUI_FONT_BOLD) ? FW_BOLD : FW_NORMAL,
+ (flags & BUI_FONT_ITALIC) ? TRUE : FALSE,
+ (flags & BUI_FONT_UNDERLINE) ? TRUE : FALSE, FALSE, DEFAULT_CHARSET,
+ OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,
+ DEFAULT_PITCH | FF_DONTCARE, wfam);
+ if (!font) {
+ return -1;
+ }
+ FontSlot *s = &g_fonts[g_font_count];
+ strncpy(s->family, family, sizeof(s->family) - 1);
+ s->family[sizeof(s->family) - 1] = '\0';
+ s->px = px;
+ s->flags = flags;
+ s->font = font;
+ HDC dc = text_dc();
+ HGDIOBJ old = SelectObject(dc, font);
+ TEXTMETRICW tm;
+ GetTextMetricsW(dc, &tm);
+ SelectObject(dc, old);
+ s->ascent = tm.tmAscent;
+ s->height = tm.tmHeight;
+ return g_font_count++;
+}
+
+static uint64_t run_hash(int font, const char *s, int len)
+{
+ uint64_t h = 1469598103934665603ull ^ (uint64_t)(font * 2654435761u);
+ for (int i = 0; i < len; i++) {
+ h ^= (uint8_t)s[i];
+ h *= 1099511628211ull;
+ }
+ return h ? h : 1;
+}
+
+static wchar_t *to_wide(const char *s, int len, int *r_n)
+{
+ int n = MultiByteToWideChar(CP_UTF8, 0, s, len, NULL, 0);
+ wchar_t *w = (wchar_t *)malloc(sizeof(wchar_t) * (size_t)(n + 1));
+ if (!w) {
+ *r_n = 0;
+ return NULL;
+ }
+ MultiByteToWideChar(CP_UTF8, 0, s, len, w, n);
+ w[n] = 0;
+ *r_n = n;
+ return w;
+}
+
+static TextRun *run_get(int font, const char *s, int len)
+{
+ if (!g_runs) {
+ g_runs = (TextRun *)calloc(RUN_CAP, sizeof(TextRun));
+ if (!g_runs) {
+ return NULL;
+ }
+ }
+ const uint64_t h = run_hash(font, s, len);
+ int idx = (int)(h & (RUN_CAP - 1));
+ for (;;) {
+ TextRun *e = &g_runs[idx];
+ if (e->hash == 0) {
+ break;
+ }
+ if (e->hash == h && e->font == font && e->len == len && memcmp(e->text, s, (size_t)len) == 0) {
+ return e;
+ }
+ idx = (idx + 1) & (RUN_CAP - 1);
+ }
+ if (g_run_count >= RUN_MAX_FILL) {
+ runs_flush();
+ return run_get(font, s, len);
+ }
+ TextRun *e = &g_runs[idx];
+ e->text = (char *)malloc((size_t)len + 1);
+ if (!e->text) {
+ return NULL;
+ }
+ memcpy(e->text, s, (size_t)len);
+ e->text[len] = 0;
+ e->hash = h;
+ e->font = font;
+ e->len = len;
+ g_run_count++;
+
+ int wn;
+ wchar_t *w = to_wide(s, len, &wn);
+ HDC dc = text_dc();
+ HGDIOBJ old = SelectObject(dc, g_fonts[font].font);
+ SIZE sz = {0, 0};
+ if (w && wn > 0) {
+ GetTextExtentPoint32W(dc, w, wn, &sz);
+ }
+ SelectObject(dc, old);
+ free(w);
+ e->advance = (float)sz.cx;
+ return e;
+}
+
+static void run_build(TextRun *e)
+{
+ e->built = 1;
+ const FontSlot *fs = &g_fonts[e->font];
+ int wn;
+ wchar_t *w = to_wide(e->text, e->len, &wn);
+ if (!w || wn == 0 || e->advance <= 0.0f) {
+ free(w);
+ return;
+ }
+ const int pad = 2 + fs->px / 4; /* bearings / italic overhang */
+ const int mw = (int)e->advance + pad * 2;
+ const int mh = fs->height + 1;
+ BITMAPINFO bmi;
+ memset(&bmi, 0, sizeof(bmi));
+ bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+ bmi.bmiHeader.biWidth = mw;
+ bmi.bmiHeader.biHeight = -mh;
+ bmi.bmiHeader.biPlanes = 1;
+ bmi.bmiHeader.biBitCount = 32;
+ bmi.bmiHeader.biCompression = BI_RGB;
+ void *bits = NULL;
+ HDC dc = text_dc();
+ HBITMAP bmp = CreateDIBSection(dc, &bmi, DIB_RGB_COLORS, &bits, NULL, 0);
+ if (!bmp || !bits) {
+ free(w);
+ return;
+ }
+ memset(bits, 0, (size_t)mw * mh * 4);
+ HGDIOBJ old_bmp = SelectObject(dc, bmp);
+ HGDIOBJ old_font = SelectObject(dc, fs->font);
+ SetTextColor(dc, RGB(255, 255, 255));
+ TextOutW(dc, pad, 0, w, wn);
+ GdiFlush();
+ e->mask = (uint8_t *)malloc((size_t)mw * mh);
+ if (e->mask) {
+ const uint32_t *src = (const uint32_t *)bits;
+ for (int i = 0; i < mw * mh; i++) {
+ /* grayscale AA: channels match; take green (perceptual) */
+ e->mask[i] = (uint8_t)((src[i] >> 8) & 0xFF);
+ }
+ e->mw = mw;
+ e->mh = mh;
+ e->ox = pad;
+ }
+ SelectObject(dc, old_font);
+ SelectObject(dc, old_bmp);
+ DeleteObject(bmp);
+ free(w);
+}
+
+int BUI_text_native(void)
+{
+ return 1;
+}
+
+int BUI_text_measure(
+ const char *family, int flags, float size, const char *utf8, int len, float *r_width)
+{
+ *r_width = 0.0f;
+ if (len <= 0) {
+ return 1;
+ }
+ const int f = font_get(family, flags, size);
+ if (f < 0) {
+ return 0;
+ }
+ TextRun *e = run_get(f, utf8, len);
+ if (!e) {
+ return 0;
+ }
+ *r_width = e->advance;
+ return 1;
+}
+
+int BUI_raster_text(BuiRaster *r,
+ float x,
+ float y,
+ const char *utf8,
+ int len,
+ float size,
+ const float rgba[4])
+{
+ if (len <= 0) {
+ return 1;
+ }
+ const int f = font_get(r->font_family, r->font_flags, size);
+ if (f < 0) {
+ return 0;
+ }
+ TextRun *e = run_get(f, utf8, len);
+ if (!e) {
+ return 0;
+ }
+ if (!e->built) {
+ run_build(e);
+ }
+ if (!e->mask) {
+ return 1; /* whitespace-only or empty */
+ }
+ const Paint p = paint_from(rgba);
+ if (p.a <= 0) {
+ return 1;
+ }
+ const int dx = (int)floorf(x + 0.5f) - e->ox;
+ const int dy = (int)floorf(y + 0.5f) - g_fonts[f].ascent;
+ const int x0 = clampi(dx, r->cx0, r->cx1), x1 = clampi(dx + e->mw, r->cx0, r->cx1);
+ const int y0 = clampi(dy, r->cy0, r->cy1), y1 = clampi(dy + e->mh, r->cy0, r->cy1);
+ for (int py = y0; py < y1; py++) {
+ uint32_t *row = r->pix + (size_t)py * r->w;
+ const uint8_t *m = e->mask + (size_t)(py - dy) * e->mw - dx;
+ for (int px = x0; px < x1; px++) {
+ const uint32_t cov = m[px];
+ if (cov == 0) {
+ continue;
+ }
+ const uint32_t fac = ((uint32_t)p.a * (cov + (cov >> 7))) >> 8;
+ if (fac >= 256) {
+ row[px] = p.rgb;
+ }
+ else if (fac > 0) {
+ row[px] = blend(row[px], p.rgb, fac);
+ }
+ }
+ }
+ return 1;
+}
+
+int BUI_raster_present_native(BuiRaster *r, void *window_handle, int full)
+{
+ HWND hwnd = (HWND)window_handle;
+ if (!hwnd || !IsWindow(hwnd)) {
+ return 0;
+ }
+ HDC hdc = GetDC(hwnd);
+ if (!hdc) {
+ return 0;
+ }
+ BITMAPINFO bmi;
+ memset(&bmi, 0, sizeof(bmi));
+ bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+ bmi.bmiHeader.biWidth = r->w;
+ bmi.bmiHeader.biPlanes = 1;
+ bmi.bmiHeader.biBitCount = 32;
+ bmi.bmiHeader.biCompression = BI_RGB;
+
+ int whole[1][4] = {{0, 0, r->w, r->h}};
+ const int(*rects)[4] = full ? (const int(*)[4])whole : (const int(*)[4])r->damage;
+ const int n = full ? 1 : r->damage_len;
+ /* Each rect is copied into its own tight top-down DIB and blitted whole
+ * (src origin 0,0, all scanlines). Sub-rect source offsets into a
+ * top-down DIB are interpreted inconsistently by GDI, which left partial
+ * updates on screen stale. */
+ uint32_t *tmp = NULL;
+ size_t tmp_cap = 0;
+ for (int i = 0; i < n; i++) {
+ const int rx = rects[i][0], ry = rects[i][1], rw = rects[i][2], rh = rects[i][3];
+ if (rw <= 0 || rh <= 0) {
+ continue;
+ }
+ const uint32_t *bits = r->pix;
+ if (!(rx == 0 && rw == r->w)) {
+ const size_t need = (size_t)rw * rh;
+ if (need > tmp_cap) {
+ uint32_t *nt = (uint32_t *)realloc(tmp, need * sizeof(uint32_t));
+ if (!nt) {
+ continue;
+ }
+ tmp = nt;
+ tmp_cap = need;
+ }
+ for (int row = 0; row < rh; row++) {
+ memcpy(tmp + (size_t)row * rw, r->pix + (size_t)(ry + row) * r->w + rx,
+ (size_t)rw * sizeof(uint32_t));
+ }
+ bits = tmp;
+ }
+ else {
+ bits = r->pix + (size_t)ry * r->w; /* full-width band is contiguous */
+ }
+ bmi.bmiHeader.biWidth = rw;
+ bmi.bmiHeader.biHeight = -rh;
+ SetDIBitsToDevice(hdc, rx, ry, (DWORD)rw, (DWORD)rh, 0, 0, 0, (UINT)rh, bits, &bmi,
+ DIB_RGB_COLORS);
+ }
+ free(tmp);
+ GdiFlush();
+ ReleaseDC(hwnd, hdc);
+ return 1;
+}
+
+#else /* !_WIN32 */
+
+int BUI_text_native(void)
+{
+ return 0;
+}
+
+int BUI_text_measure(
+ const char *family, int flags, float size, const char *utf8, int len, float *r_width)
+{
+ (void)family;
+ (void)flags;
+ (void)size;
+ (void)utf8;
+ (void)len;
+ *r_width = 0.0f;
+ return 0;
+}
+
+int BUI_raster_text(BuiRaster *r,
+ float x,
+ float y,
+ const char *utf8,
+ int len,
+ float size,
+ const float rgba[4])
+{
+ (void)r;
+ (void)x;
+ (void)y;
+ (void)utf8;
+ (void)len;
+ (void)size;
+ (void)rgba;
+ return 0;
+}
+
+int BUI_raster_present_native(BuiRaster *r, void *window_handle, int full)
+{
+ (void)r;
+ (void)window_handle;
+ (void)full;
+ return 0;
+}
+
+#endif
+
+/** \} */
diff --git a/kit/CMakeLists.txt b/kit/CMakeLists.txt
new file mode 100644
index 0000000..6963cdc
--- /dev/null
+++ b/kit/CMakeLists.txt
@@ -0,0 +1,30 @@
+# bui_kit - Blender's interface as a retained-mode C runtime: nodes, layout,
+# input handling (interface_handlers.cc rules) and widget drawing ported from
+# interface_widgets.cc, rendered into a BuiRaster with damage tracking.
+#
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+add_library(bui_kit STATIC
+ intern/kit_core.c
+ intern/kit_draw.c
+ intern/kit_icons_data.c
+ intern/kit_widgets.c
+ intern/kit_views.c
+ intern/kit_menus.c
+ intern/kit_color.c
+ intern/kit_frame.c
+ intern/kit_textarea.c
+ intern/kit_window.c
+)
+add_library(bui::kit ALIAS bui_kit)
+target_include_directories(bui_kit PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
+target_include_directories(bui_kit PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/intern)
+# bui_core: Blender's color math and UTF-8 cursor stepping; bui_gpu: raster.
+target_link_libraries(bui_kit PUBLIC bui::gpu bui::core)
+if(NOT MSVC)
+ target_compile_options(bui_kit PRIVATE -O2)
+ target_link_libraries(bui_kit PRIVATE m)
+endif()
+if(WIN32)
+ target_link_libraries(bui_kit PRIVATE user32 gdi32)
+endif()
diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.h
new file mode 100644
index 0000000..5bfb735
--- /dev/null
+++ b/kit/include/BUI_kit.h
@@ -0,0 +1,350 @@
+/* BUI kit: Blender's interface as a retained-mode C runtime.
+ *
+ * A tree of nodes (layouts, buttons, fields, menus, views, editors), one
+ * input context per window, and a renderer that draws Blender's widgets —
+ * ported from editors/interface/interface_widgets.cc — into a BuiRaster.
+ *
+ * Rendering is damage driven: every state change marks only the node's
+ * rectangle dirty, and a frame redraws and diffs just those regions, so an
+ * idle UI costs nothing and a hover or a scrub costs microseconds.
+ *
+ * Hosts (Python, Qt, a native window) only forward input, present the
+ * raster and receive callbacks through BKHost.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#include "GPU_raster.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct BKNode BKNode;
+typedef struct BKContext BKContext;
+typedef struct BKTreeItem BKTreeItem;
+
+/* Modifier / button state bits for input calls. */
+enum { BK_SHIFT = 1, BK_CTRL = 2, BK_ALT = 4, BK_BUTTON1 = 8 };
+
+/* Mouse cursors requested through BKHost.set_cursor. */
+enum {
+ BK_CURSOR_DEFAULT = 0,
+ BK_CURSOR_EW, /* Blender's horizontal arrows over number fields */
+ BK_CURSOR_NS,
+ BK_CURSOR_TEXT,
+ BK_CURSOR_CROSSHAIR, /* eyedropper, color areas */
+ BK_CURSOR_HAND,
+ BK_CURSOR_MOVE, /* panel grip */
+ BK_CURSOR_NONE, /* hidden: continuous grab while scrubbing */
+};
+
+/* Callback kinds delivered through BKHost.emit. */
+enum {
+ BK_EV_CHANGE = 1, /* the node's value changed */
+ BK_EV_CLICK, /* button pressed */
+ BK_EV_CALL, /* menu item / hotkey: call `ref` */
+ BK_EV_RENAME, /* list/tree rename: a = row/item index, text via BK_get_str("edit") */
+ BK_EV_ACTIVATE, /* grid view double-click / Return: a = index */
+ BK_EV_TOGGLE, /* tree toggle column: a = column, b = new value, item = ref */
+ BK_EV_BROWSE, /* path field browse button */
+ /* Raw events, for nodes with the "events" property (Tk bind, Qt event
+ * handlers): a, b = position relative to the node. */
+ BK_EV_PRESS,
+ BK_EV_RELEASE,
+ BK_EV_DOUBLE,
+ BK_EV_MOTION,
+ BK_EV_ENTER,
+ BK_EV_LEAVE,
+ BK_EV_KEY, /* ref = "text keysym" (UTF-8), a = mods */
+ BK_EV_WHEEL, /* a = delta */
+ BK_EV_SUBMIT, /* text field confirmed (Return) */
+ BK_EV_VIEW, /* scrolled view changed (nodes with "viewevents") */
+ BK_EV_SCROLL, /* scrollbar request: a = 0 moveto (b = fraction), 1 units, 2 pages (b = count) */
+ BK_EV_CONFIGURE, /* geometry changed ("events" nodes): a = width, b = height */
+ BK_EV_KEYRELEASE /* ref = "\tkeysym", a = mods */
+};
+
+typedef struct BKHost {
+ void *data;
+ void (*request)(void *data); /* schedule a render */
+ void (*set_cursor)(void *data, int cursor);
+ void (*warp)(void *data, int x, int y); /* move the pointer */
+ char *(*clipboard_get)(void *data); /* malloc'd UTF-8 or NULL */
+ void (*clipboard_set)(void *data, const char *text);
+ void (*schedule)(void *data, int ms, int timer); /* call BK_timer(timer) later */
+ void (*emit)(void *data, BKNode *node, int kind, void *ref, double a, double b);
+} BKHost;
+
+/* Reference hooks for host objects attached to nodes/items/callbacks
+ * (Python INCREF/DECREF). Optional. */
+void BK_set_ref_hooks(void (*retain)(void *ref), void (*release)(void *ref));
+
+/* -- global look ------------------------------------------------------------ */
+void BK_set_scale(float scale); /* Blender's resolution scale (1 = 20 px widgets) */
+float BK_scale(void);
+int BK_unit(void); /* U.widget_unit in pixels */
+void BK_set_font(const char *family);
+int BK_icon_id(const char *name); /* 0 when unknown */
+int BK_icon_count(void);
+const char *BK_icon_name(int id);
+
+/* -- nodes -------------------------------------------------------------------- */
+/* Types: column row grid box panel tabs sidetabs scroll label separator
+ * progress button toggle checkbox decorator text search hotkey number slider
+ * dropdown enum swatch popover menubutton menubar list tree gridview ramp
+ * curve normal histogram */
+BKNode *BK_node_new(const char *type);
+void BK_node_free(BKNode *node);
+const char *BK_node_type(const BKNode *node);
+void BK_node_set_ref(BKNode *node, void *ref); /* host object (not retained) */
+void *BK_node_ref(const BKNode *node);
+int BK_node_add(BKNode *parent, BKNode *child, int index); /* index -1: append */
+void BK_node_remove(BKNode *parent, BKNode *child);
+int BK_node_child_count(const BKNode *node);
+BKNode *BK_node_child(const BKNode *node, int i);
+BKNode *BK_node_parent(const BKNode *node);
+void BK_node_rect(const BKNode *node, int r_rect[4]);
+void BK_node_natural(BKNode *node, int r_size[2]);
+void BK_node_invalidate(BKNode *node); /* redraw */
+void BK_node_relayout(BKNode *node); /* size/structure changed */
+
+/* Properties by name (see kit_props in kit_core.c for the list). Return 0 when
+ * the key is unknown for this node. */
+int BK_set_num(BKNode *node, const char *key, double value);
+int BK_set_str(BKNode *node, const char *key, const char *value);
+int BK_set_color(BKNode *node, const char *key, const float rgba[4]);
+int BK_set_strs(BKNode *node, const char *key, const char *const *values, int n);
+double BK_get_num(BKNode *node, const char *key);
+const char *BK_get_str(BKNode *node, const char *key);
+int BK_get_color(BKNode *node, const char *key, float r_rgba[4]);
+int BK_strs_count(BKNode *node, const char *key);
+const char *BK_strs_get(BKNode *node, const char *key, int i);
+/* Link number fields edited together with Alt (vector fields). */
+void BK_link_fields(BKNode *const *fields, int n);
+
+/* Color ramp / curve / histogram data. */
+int BK_ramp_count(BKNode *ramp);
+void BK_ramp_get(BKNode *ramp, int i, float *r_pos, float r_rgba[4]);
+void BK_ramp_set(BKNode *ramp, const float *pos, const float (*rgba)[4], int n);
+int BK_ramp_active(BKNode *ramp);
+void BK_ramp_evaluate(BKNode *ramp, float t, float r_rgba[4]);
+int BK_curve_count(BKNode *curve, int channel);
+void BK_curve_get(BKNode *curve, int channel, int i, float r_xy[2]);
+void BK_curve_set(BKNode *curve, int channel, const float (*xy)[2], int n);
+float BK_curve_evaluate(BKNode *curve, int channel, float x);
+void BK_ramp_set_active_color(BKNode *ramp, const float rgba[4]);
+void BK_histogram_set(BKNode *hist, const float *bins, int n, int channels);
+/* Grid view preview colors (alpha 0 = use the item's icon). */
+void BK_gridview_set_colors(BKNode *grid, const float (*colors)[4], int n);
+
+/* Tree items (owned by their host ref; trees retain the refs). */
+BKTreeItem *BK_tree_item_new(const char *label, int icon);
+void BK_tree_item_free(BKTreeItem *item);
+void BK_tree_item_set_ref(BKTreeItem *item, void *ref);
+void *BK_tree_item_ref(const BKTreeItem *item);
+void BK_tree_item_add(BKTreeItem *parent, BKTreeItem *child);
+void BK_tree_item_clear(BKTreeItem *parent); /* detach (and release) all children */
+void BK_tree_item_set(BKTreeItem *item, const char *key, double value);
+double BK_tree_item_get(const BKTreeItem *item, const char *key);
+void BK_tree_item_set_label(BKTreeItem *item, const char *label);
+const char *BK_tree_item_label(const BKTreeItem *item);
+int BK_tree_item_child_count(const BKTreeItem *item);
+BKTreeItem *BK_tree_item_child(const BKTreeItem *item, int i);
+void BK_tree_set_roots(BKNode *tree, BKTreeItem *const *roots, int n);
+BKTreeItem *BK_tree_selected(BKNode *tree);
+void BK_tree_select(BKNode *tree, BKTreeItem *item);
+int BK_tree_row_count(BKNode *tree);
+BKTreeItem *BK_tree_row(BKNode *tree, int row);
+void BK_tree_row_rect(BKNode *tree, int row, int r_rect[4]);
+
+/* Menus. A spec array describes items; nested submenus via `sub`. */
+typedef struct BKMenuSpec {
+ const char *text; /* NULL or "-" = separator */
+ int icon;
+ const char *shortcut;
+ int checked; /* -1 none, 0/1 checkbox */
+ int enabled;
+ void *ref; /* callable for BK_EV_CALL (retained while open) */
+ const struct BKMenuSpec *sub;
+ int nsub;
+ void (*fn)(void *data); /* C callback (built-in menus), used when set */
+ void *data;
+} BKMenuSpec;
+void BK_menubutton_set_items(BKNode *button, const BKMenuSpec *items, int n);
+void BK_open_menu(BKContext *ctx,
+ BKNode *owner,
+ const BKMenuSpec *items,
+ int n,
+ const char *title,
+ int at_x,
+ int at_y);
+void BK_open_pie(BKContext *ctx, const BKMenuSpec *items, int n, const char *title);
+
+/* -- geometry managers (children of a "frame") ------------------------------------
+ * Tk's pack / grid / place, also used for Qt layouts. Keys (numbers):
+ * pack: side (0 top, 1 bottom, 2 left, 3 right), fill (1 x, 2 y, 3 both),
+ * expand, anchor (BK_ANCHOR_*), padx0 padx1 pady0 pady1 ipadx ipady
+ * grid: row column rowspan columnspan sticky (BK_ANCHOR_* bits) + pads
+ * place: x y relx rely width height relwidth relheight anchor
+ * Any manager: reqwidth / reqheight override the natural size (Tk width=). */
+enum { BK_GEOM_NONE = 0, BK_GEOM_PACK, BK_GEOM_GRID, BK_GEOM_PLACE };
+enum { BK_ANCHOR_N = 1, BK_ANCHOR_S = 2, BK_ANCHOR_W = 4, BK_ANCHOR_E = 8 };
+void BK_geom_set_manager(BKNode *child, int manager);
+int BK_geom_manager(const BKNode *child);
+void BK_geom_set(BKNode *child, const char *key, double value);
+double BK_geom_get(const BKNode *child, const char *key);
+/* Frame grid weights (Tk columnconfigure / Qt setColumnStretch). */
+void BK_frame_grid_weight(BKNode *frame, int column_axis, int index, double weight, int minsize);
+
+/* -- canvas (Tk Canvas, QPainter) -------------------------------------------------- */
+enum { BK_ITEM_RECT, BK_ITEM_OVAL, BK_ITEM_LINE, BK_ITEM_POLYGON, BK_ITEM_TEXT, BK_ITEM_ARC,
+ BK_ITEM_IMAGE, BK_ITEM_ROUNDRECT };
+typedef struct BKCanvasItem {
+ int id, type;
+ const float *coords; /* x0 y0 x1 y1 ... in canvas space */
+ int ncoords;
+ float fill[4], outline[4]; /* alpha 0 = none */
+ float width, radius, size; /* line width, corner radius, text size (0 = UI) */
+ float start, extent; /* arcs, degrees */
+ const char *text;
+ int anchor; /* BK_ANCHOR_* bits, 0 = center */
+ const unsigned char *rgba; /* images: iw * ih RGBA pixels */
+ int iw, ih;
+ int hidden;
+} BKCanvasItem;
+void BK_canvas_set_item(BKNode *canvas, const BKCanvasItem *item); /* insert or replace by id */
+void BK_canvas_delete(BKNode *canvas, int id); /* id < 0: all */
+void BK_canvas_raise(BKNode *canvas, int id, int to_top);
+int BK_canvas_count(BKNode *canvas);
+
+/* Images on labels/buttons (RGBA). */
+void BK_node_set_image(BKNode *node, const unsigned char *rgba, int w, int h);
+
+/* -- text area (multi-line) -----------------------------------------------------------
+ * Text via BK_set_str/get_str("value"); edits are byte offsets. */
+void BK_textarea_insert(BKNode *n, int offset, const char *text);
+void BK_textarea_delete(BKNode *n, int start, int end);
+int BK_textarea_caret(BKNode *n);
+void BK_textarea_set_caret(BKNode *n, int offset);
+int BK_textarea_selection(BKNode *n, int *r_start, int *r_end);
+void BK_textarea_set_selection(BKNode *n, int start, int end);
+/* Colored spans (Text tags / syntax highlight): start/end offsets + RGBA. */
+/* Styled ranges (Tk text tags): foreground and/or background color. */
+typedef struct BKTextSpan {
+ int start, end; /* byte offsets */
+ float fg[4], bg[4];
+ int has_fg, has_bg;
+} BKTextSpan;
+void BK_textarea_set_spans(BKNode *n, const BKTextSpan *spans, int count);
+int BK_textarea_index_at(BKNode *n, int x, int y); /* window coordinates -> byte offset */
+void BK_textarea_see(BKNode *n, int offset);
+
+/* -- tree columns ------------------------------------------------------------------------ */
+void BK_tree_item_set_values(BKTreeItem *item, const char *const *values, int n);
+/* Column headers via BK_set_strs(tree, "headers", ...). */
+
+/* -- undo (Blender's Ctrl+Z / Ctrl+Shift+Z over UI value edits) ----------------------------- */
+int BK_undo(BKContext *ctx);
+int BK_redo(BKContext *ctx);
+int BK_undo_depth(BKContext *ctx, int *r_redo);
+
+/* -- animation (panel open/close) --------------------------------------------------------------
+ * While BK_animating() is non-zero the host should keep rendering frames. */
+int BK_animating(BKContext *ctx);
+void BK_set_animations(int enabled);
+
+/* -- context ------------------------------------------------------------------- */
+BKContext *BK_context_new(BKNode *root);
+void BK_context_free(BKContext *ctx);
+void BK_context_set_host(BKContext *ctx, const BKHost *host);
+void BK_context_set_header(BKContext *ctx, BKNode *header); /* fixed top bar */
+BKNode *BK_context_root(BKContext *ctx);
+
+/* Render into `r` (w x h). Redraws only damaged regions unless `full`.
+ * Returns the number of redrawn regions (0 = nothing changed). */
+int BK_render(BKContext *ctx, BuiRaster *r, int w, int h, int full);
+int BK_needs_render(BKContext *ctx);
+
+/* Input; each returns non-zero when something changed. */
+int BK_press(BKContext *ctx, int x, int y, int mods);
+int BK_release(BKContext *ctx, int x, int y, int mods);
+int BK_motion(BKContext *ctx, int x, int y, int mods);
+int BK_wheel(BKContext *ctx, int x, int y, int delta, int mods);
+int BK_key(BKContext *ctx, const char *text, const char *keysym, int mods);
+int BK_context_menu(BKContext *ctx, int x, int y, int mods);
+/* Raw-only input for host bindings (Tk's <KeyRelease>, <Button-2>, <ButtonRelease-3>):
+ * forwarded to "events" nodes, no widget behavior. */
+int BK_key_release(BKContext *ctx, const char *keysym, int mods);
+int BK_button(BKContext *ctx, int x, int y, int button, int release, int mods);
+void BK_timer(BKContext *ctx, int timer);
+void BK_bind(BKContext *ctx, const char *combo, void *ref); /* "ctrl+s" -> BK_EV_CALL */
+void BK_close_popups(BKContext *ctx);
+void BK_set_pointer(BKContext *ctx, int x, int y);
+
+/* Introspection (tests, tools). */
+int BK_cursor(BKContext *ctx);
+BKNode *BK_hover(BKContext *ctx);
+BKNode *BK_focus(BKContext *ctx);
+/* Give a text-editing node keyboard focus (starts editing, like a click);
+ * NULL ends the current edit. Other nodes are ignored. */
+void BK_focus_node(BKContext *ctx, BKNode *n);
+char *BK_clipboard_get(BKContext *ctx); /* malloc'd UTF-8 or NULL */
+void BK_clipboard_set(BKContext *ctx, const char *text);
+int BK_modal_active(BKContext *ctx);
+int BK_tooltip_visible(BKContext *ctx);
+int BK_popup_count(BKContext *ctx);
+BKNode *BK_popup(BKContext *ctx, int i);
+BKNode *BK_popup_owner(BKContext *ctx, int i);
+/* Menu popups: visible rows and their rects. */
+int BK_menu_row_count(BKNode *menu);
+const char *BK_menu_row_text(BKNode *menu, int i);
+void BK_menu_row_rect(BKNode *menu, int i, int r_rect[4]);
+/* Color picker popup parts: "area", "strip", "tabs", "slider0".."slider2",
+ * "alpha", "hex", "dropper". */
+BKNode *BK_picker_part(BKNode *picker, const char *name);
+
+/* -- native window host (Win32; BK_window_supported() is 0 elsewhere) -----------------
+ * The window owns a raster, drives the context (input -> render -> present
+ * without leaving C) and installs the host services (cursor, warp,
+ * clipboard, tooltip timer); BKHost.emit set before is kept for callbacks. */
+typedef struct BKWindow BKWindow;
+typedef struct BKWindowCallbacks {
+ void *data;
+ void (*on_timer)(void *data, BKWindow *win, int id); /* BK_window_timer fired */
+ int (*on_close)(void *data, BKWindow *win); /* return 0 to keep it open */
+} BKWindowCallbacks;
+int BK_window_supported(void);
+BKWindow *BK_window_new(BKContext *ctx, const char *title, int width, int height);
+void BK_window_free(BKWindow *win);
+void BK_window_set_callbacks(BKWindow *win, const BKWindowCallbacks *cb);
+void BK_window_show(BKWindow *win);
+void BK_window_close(BKWindow *win);
+int BK_window_is_open(BKWindow *win);
+void BK_window_set_title(BKWindow *win, const char *title);
+void BK_window_set_size(BKWindow *win, int width, int height); /* logical pixels */
+void BK_window_get_size(BKWindow *win, int *r_width, int *r_height);
+BuiRaster *BK_window_raster(BKWindow *win);
+int BK_window_frames(BKWindow *win);
+void BK_window_render_now(BKWindow *win);
+int BK_window_timer(BKWindow *win, int ms); /* one-shot; returns its id */
+void BK_window_cancel_timer(BKWindow *win, int id);
+void *BK_window_handle(BKWindow *win); /* HWND */
+/* Window-manager requests (Tk's wm): "pos" (x, y), "minsize"/"maxsize" (w, h),
+ * "resizable" (w, h), "topmost" (a), "alpha" (a), "override" (a), "state"
+ * (0 normal, 1 iconic, 2 withdrawn, 3 zoomed), "lift", "lower", "focus". */
+void BK_window_wm(BKWindow *win, const char *key, double a, double b);
+/* Queries: "pos", "state", "screen" (w, h), "pointer" (x, y), "scale". */
+int BK_window_wm_get(BKWindow *win, const char *key, double *r_a, double *r_b);
+/* Message loop: run until every window is closed (or BK_window_quit). */
+void BK_window_run(void);
+int BK_window_pump(void); /* handle pending messages; returns open windows */
+void BK_window_quit(void);
+void BK_window_set_stop_check(int (*stop)(void)); /* polled after each message */
+
+/* Evaluate Blender-style number input ("2*pi", "1/3 + 2^2"). */
+int BK_eval_number(const char *expr, double *r_value);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/kit/intern/kit_color.c b/kit/intern/kit_color.c
new file mode 100644
index 0000000..d907c6f
--- /dev/null
+++ b/kit/intern/kit_color.c
@@ -0,0 +1,1371 @@
+/* Color picker, eyedropper, color ramp, curve mapping, normal ball and
+ * histogram.
+ *
+ * The picker follows interface_region_color_picker.cc: an HSV wheel (or
+ * SV square + hue strip) with a value strip, RGB/HSV/HSL sliders, alpha,
+ * hex and an eyedropper; it keeps its own HSV so hue survives grays. The
+ * wheel geometry and cursor come from interface_widgets.cc
+ * (hsvcircle_vals_from_pos / hsvcircle_pos_from_vals / hsv_cursor).
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "kit_intern.h"
+
+/* Blender's color conversions (blenlib, linked from bui_core). */
+void hsv_to_rgb_v(const float hsv[3], float r_rgb[3]);
+void rgb_to_hsv_v(const float rgb[3], float r_hsv[3]);
+void rgb_to_hsl_v(const float rgb[3], float r_hsl[3]);
+void hsl_to_rgb_v(const float hsl[3], float r_rgb[3]);
+
+#ifndef M_PI
+# define M_PI 3.14159265358979323846
+#endif
+
+static int u(void)
+{
+ return bk_unit();
+}
+
+/* -------------------------------------------------------------------- */
+/** \name Color picker popup
+ * \{ */
+
+typedef struct PickerData {
+ BKPopupPlace place;
+ BKNode *swatch;
+ float hsv[3];
+ float alpha;
+ bool square;
+ BKNode *area, *strip, *tabs, *sl[3], *alpha_sl, *hex, *dropper;
+} PickerData;
+
+#define PICKER(n) ((PickerData *)(n)->ext)
+
+static void picker_rgba(const PickerData *p, float r_rgba[4])
+{
+ hsv_to_rgb_v(p->hsv, r_rgba);
+ r_rgba[3] = p->alpha;
+}
+
+static void picker_sync(BKNode *picker)
+{
+ PickerData *p = PICKER(picker);
+ float rgba[4];
+ picker_rgba(p, rgba);
+ const int mode = (int)p->tabs->value; /* 0 RGB, 1 HSV, 2 HSL */
+ float vals[3];
+ static const char *names[3][3] = {{"R", "G", "B"}, {"H", "S", "V"}, {"H", "S", "L"}};
+ if (mode == 0) {
+ memcpy(vals, rgba, sizeof(vals));
+ }
+ else if (mode == 1) {
+ memcpy(vals, p->hsv, sizeof(vals));
+ }
+ else {
+ float hsl[3];
+ rgb_to_hsl_v(rgba, hsl);
+ vals[0] = hsl[1] == 0.0f ? p->hsv[0] : hsl[0];
+ vals[1] = hsl[1];
+ vals[2] = hsl[2];
+ }
+ for (int i = 0; i < 3; i++) {
+ bk_set_text(&p->sl[i]->label, names[mode][i]);
+ p->sl[i]->value = vals[i];
+ bk_invalidate(p->sl[i]);
+ }
+ p->alpha_sl->value = p->alpha;
+ char hex[16];
+ snprintf(hex, sizeof(hex), "#%02X%02X%02X", bk_iround(rgba[0] * 255), bk_iround(rgba[1] * 255),
+ bk_iround(rgba[2] * 255));
+ bk_set_text(&p->hex->text, hex);
+ bk_invalidate(picker);
+}
+
+static void picker_apply(BKNode *picker)
+{
+ PickerData *p = PICKER(picker);
+ float rgba[4];
+ picker_rgba(p, rgba);
+ BK_set_color(p->swatch, "set_value", rgba);
+ picker_sync(picker);
+}
+
+static void picker_set_hsv(BKNode *picker, float h, float s, float v)
+{
+ PickerData *p = PICKER(picker);
+ p->hsv[0] = h;
+ p->hsv[1] = BK_CLAMP(s, 0.0f, 1.0f);
+ p->hsv[2] = BK_CLAMP(v, 0.0f, 1.0f);
+ picker_apply(picker);
+}
+
+static void picker_set_rgb(BKNode *picker, const float rgb[3])
+{
+ PickerData *p = PICKER(picker);
+ float hsv[3];
+ rgb_to_hsv_v(rgb, hsv);
+ if (hsv[1] == 0.0f) {
+ hsv[0] = p->hsv[0]; /* keep hue through grays (color_picker_rgb_to_hsv_compat) */
+ }
+ if (hsv[2] == 0.0f) {
+ hsv[1] = p->hsv[1];
+ }
+ picker_set_hsv(picker, hsv[0], hsv[1], hsv[2]);
+}
+
+static void picker_slider_changed(BKNode *slider, void *data)
+{
+ BKNode *picker = (BKNode *)data;
+ PickerData *p = PICKER(picker);
+ const float a = (float)p->sl[0]->value, b = (float)p->sl[1]->value, c = (float)p->sl[2]->value;
+ const int mode = (int)p->tabs->value;
+ if (mode == 0) {
+ const float rgb[3] = {a, b, c};
+ picker_set_rgb(picker, rgb);
+ }
+ else if (mode == 1) {
+ picker_set_hsv(picker, a, b, c);
+ }
+ else {
+ const float hsl[3] = {a, b, c};
+ float rgb[3];
+ hsl_to_rgb_v(hsl, rgb);
+ picker_set_rgb(picker, rgb);
+ }
+}
+
+static void picker_alpha_changed(BKNode *slider, void *data)
+{
+ BKNode *picker = (BKNode *)data;
+ PICKER(picker)->alpha = (float)slider->value;
+ picker_apply(picker);
+}
+
+static void picker_tabs_changed(BKNode *tabs, void *data)
+{
+ picker_sync((BKNode *)data);
+}
+
+static void picker_hex_changed(BKNode *hex, void *data)
+{
+ BKNode *picker = (BKNode *)data;
+ float c[4];
+ if (bk_parse_hex(hex->text ? hex->text : "", c, PICKER(picker)->alpha)) {
+ picker_set_rgb(picker, c);
+ }
+ else {
+ picker_sync(picker);
+ }
+}
+
+static void picker_eyedropper_pick(void *data, const float rgb[3])
+{
+ picker_set_rgb((BKNode *)data, rgb);
+}
+
+static void picker_dropper_clicked(BKNode *button, void *data)
+{
+ BKContext *ctx = bk_ctx(button);
+ if (ctx) {
+ bk_eyedropper_start(ctx, picker_eyedropper_pick, data);
+ }
+}
+
+static int area_h(void)
+{
+ return bk_iround(7.5f * u());
+}
+
+static void picker_measure(BKNode *n, int *rw, int *rh)
+{
+ PickerData *p = PICKER(n);
+ const int uu = u(), pad = 2 * bk_iround(0.2f * uu);
+ int rows = 5 + ((p->swatch->flags & NF_ALPHA) ? 1 : 0); /* tabs, 3 sliders, (alpha), hex */
+ int h = area_h() + (int)(1.0f * uu) + rows * uu;
+ if (p->square) {
+ h += (int)(1.2f * uu);
+ }
+ *rw = 10 * uu + 2 * pad;
+ *rh = h + 2 * pad;
+}
+
+static void picker_arrange(BKNode *n)
+{
+ PickerData *p = PICKER(n);
+ const int uu = u(), pad = 2 * bk_iround(0.2f * uu), iw = n->w - 2 * pad;
+ int y = n->y + pad;
+ const int ah = area_h();
+ if (p->square) {
+ bk_arrange(p->area, n->x + pad, y, iw, ah);
+ y += ah + (int)(0.3f * uu);
+ bk_arrange(p->strip, n->x + pad, y, iw, (int)(0.8f * uu));
+ y += (int)(0.8f * uu);
+ }
+ else {
+ const int sw = bk_iround(0.9f * uu), gap = bk_iround(0.5f * uu);
+ bk_arrange(p->area, n->x + pad + (iw - sw - gap - ah) / 2, y, ah, ah);
+ bk_arrange(p->strip, n->x + pad + iw - sw, y, sw, ah);
+ y += ah;
+ }
+ y += (int)(0.4f * uu);
+ bk_arrange(p->tabs, n->x + pad, y, iw, uu);
+ y += uu + (int)(0.2f * uu);
+ BKNode *col[4] = {p->sl[0], p->sl[1], p->sl[2], p->alpha_sl};
+ const int ncol = (p->swatch->flags & NF_ALPHA) ? 4 : 3;
+ p->alpha_sl->flags = (ncol == 4) ? (p->alpha_sl->flags | NF_VISIBLE) :
+ (p->alpha_sl->flags & ~NF_VISIBLE);
+ for (int i = 0; i < ncol; i++) {
+ col[i]->corners = (i == 0 ? (CNR_TL | CNR_TR) : 0) | (i == ncol - 1 ? (CNR_BL | CNR_BR) : 0);
+ bk_arrange(col[i], n->x + pad, y, iw, uu);
+ y += uu;
+ }
+ y += (int)(0.2f * uu);
+ bk_arrange(p->hex, n->x + pad, y, iw - uu - (int)(0.2f * uu), uu);
+ bk_arrange(p->dropper, n->x + pad + iw - uu, y, uu, uu);
+}
+
+static void picker_draw(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ bk_widget_menu_back(&r, CNR_ALL);
+}
+
+static void picker_free(BKNode *n)
+{
+ free(n->ext);
+}
+
+const BKClass bk_cls_picker = {.name = "picker",
+ .flags = CLS_INTERACTIVE | CLS_POPUP,
+ .free_ext = picker_free,
+ .measure = picker_measure,
+ .arrange = picker_arrange,
+ .draw = picker_draw};
+
+static BKNode *picker_child(BKNode *picker, const BKClass *cls)
+{
+ BKNode *c = bk_node_new_cls(cls);
+ bk_node_add(picker, c);
+ return c;
+}
+
+BKNode *bk_picker_new(BKNode *swatch)
+{
+ BKNode *n = bk_node_new_cls(&bk_cls_picker);
+ PickerData *p = (PickerData *)calloc(1, sizeof(PickerData));
+ p->place.at_x = p->place.at_y = -100000;
+ p->place.side_x = p->place.side_y = p->place.side_xl = -100000;
+ p->swatch = swatch;
+ p->square = (swatch->flags & NF_SQUARE) != 0;
+ rgb_to_hsv_v(swatch->color, p->hsv);
+ p->alpha = swatch->color[3];
+ n->ext = p;
+ p->area = picker_child(n, p->square ? &bk_cls_hsv_square : &bk_cls_hsv_circle);
+ p->strip = picker_child(n, p->square ? &bk_cls_hue_strip : &bk_cls_value_strip);
+ p->area->ext = n;
+ p->strip->ext = n;
+ p->tabs = picker_child(n, &bk_cls_enum);
+ const char *modes[3] = {"RGB", "HSV", "HSL"};
+ BK_set_strs(p->tabs, "items", modes, 3);
+ p->tabs->value = 1; /* HSV */
+ p->tabs->on_change = picker_tabs_changed;
+ p->tabs->on_change_data = n;
+ for (int i = 0; i < 3; i++) {
+ p->sl[i] = picker_child(n, &bk_cls_slider);
+ p->sl[i]->step = 0.01;
+ p->sl[i]->on_change = picker_slider_changed;
+ p->sl[i]->on_change_data = n;
+ }
+ p->alpha_sl = picker_child(n, &bk_cls_slider);
+ bk_set_text(&p->alpha_sl->label, "A");
+ p->alpha_sl->step = 0.01;
+ p->alpha_sl->on_change = picker_alpha_changed;
+ p->alpha_sl->on_change_data = n;
+ p->hex = picker_child(n, &bk_cls_text);
+ bk_set_text(&p->hex->label, "Hex");
+ p->hex->on_change = picker_hex_changed;
+ p->hex->on_change_data = n;
+ p->dropper = picker_child(n, &bk_cls_button);
+ p->dropper->icon = bk_icons_lookup("EYEDROPPER");
+ bk_set_text(&p->dropper->desc, "Sample a color from the window");
+ p->dropper->on_click = picker_dropper_clicked;
+ p->dropper->on_click_data = n;
+ picker_sync(n);
+ return n;
+}
+
+BKNode *BK_picker_part(BKNode *picker, const char *name)
+{
+ if (picker->cls != &bk_cls_picker) {
+ return NULL;
+ }
+ PickerData *p = PICKER(picker);
+ if (strcmp(name, "area") == 0) {
+ return p->area;
+ }
+ if (strcmp(name, "strip") == 0) {
+ return p->strip;
+ }
+ if (strcmp(name, "tabs") == 0) {
+ return p->tabs;
+ }
+ if (strncmp(name, "slider", 6) == 0) {
+ const int i = atoi(name + 6);
+ return (i >= 0 && i < 3) ? p->sl[i] : NULL;
+ }
+ if (strcmp(name, "alpha") == 0) {
+ return p->alpha_sl;
+ }
+ if (strcmp(name, "hex") == 0) {
+ return p->hex;
+ }
+ if (strcmp(name, "dropper") == 0) {
+ return p->dropper;
+ }
+ return NULL;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Picker parts: HSV wheel, SV square, hue strip, value strip
+ * \{ */
+
+static BKNode *part_picker(const BKNode *n)
+{
+ return (BKNode *)n->ext; /* the picker popup that owns this part */
+}
+
+static void hsv_cursor(float x, float y, const BKNode *part)
+{
+ /* interface_widgets.cc hsv_cursor(): a disc of the current color, 12 px
+ * (20 px while pressed), outlines whose alpha follows the value. */
+ const PickerData *p = PICKER(part_picker(part));
+ float rgba[4];
+ picker_rgba(p, rgba);
+ const float radius = ((bk_pressed(part) ? 20.0f : 12.0f) * bk_scale_fac + bk_px()) * 0.5f;
+ const float v = p->hsv[2];
+ const float bg[4] = {0, 0, 0, v / 2.0f};
+ const float fg[4] = {1, 1, 1, BK_MIN(1.0f - v + 0.2f, 0.8f)};
+ const float col[4] = {rgba[0], rgba[1], rgba[2], 1.0f};
+ bk_circle(x, y, radius + 1, bg);
+ bk_circle(x, y, radius, fg);
+ bk_circle(x, y, radius - 1, col);
+}
+
+static int part_drag(BKNode *n, BKEvent *e);
+
+static int part_press(BKNode *n, BKEvent *e)
+{
+ return part_drag(n, e);
+}
+
+static int part_wheel(BKNode *n, BKEvent *e)
+{
+ /* Blender: wheel over the picker changes the value */
+ BKNode *picker = part_picker(n);
+ if (!picker) {
+ return 0;
+ }
+ PickerData *p = PICKER(picker);
+ picker_set_hsv(picker, p->hsv[0], p->hsv[1], p->hsv[2] + 0.05f * e->delta);
+ return 1;
+}
+
+static void circle_geom(const BKNode *n, float *cx, float *cy, float *r)
+{
+ *r = BK_MIN(n->w, n->h) * 0.5f - 1.0f;
+ *cx = n->x + n->w * 0.5f;
+ *cy = n->y + n->h * 0.5f;
+}
+
+static int part_drag(BKNode *n, BKEvent *e)
+{
+ BKNode *picker = part_picker(n);
+ if (!picker) {
+ return 0;
+ }
+ PickerData *p = PICKER(picker);
+ if (n->cls == &bk_cls_hsv_circle) {
+ /* hsvcircle_vals_from_pos: hue from the angle (red at the bottom),
+ * saturation from the distance; y is flipped for screen space */
+ float cx, cy, r;
+ circle_geom(n, &cx, &cy, &r);
+ const float dx = e->x - cx, dy = cy - e->y;
+ float hue = atan2f(dx, dy) / (2.0f * (float)M_PI) + 0.5f;
+ hue -= floorf(hue);
+ const float dist = sqrtf(dx * dx + dy * dy) / BK_MAX(1.0f, r);
+ picker_set_hsv(picker, hue, BK_MIN(1.0f, dist), p->hsv[2]);
+ }
+ else if (n->cls == &bk_cls_hsv_square) {
+ const float s = (e->x - n->x) / (float)BK_MAX(1, n->w);
+ const float v = 1.0f - (e->y - n->y) / (float)BK_MAX(1, n->h);
+ picker_set_hsv(picker, p->hsv[0], s, v);
+ }
+ else if (n->cls == &bk_cls_hue_strip) {
+ const float h = BK_CLAMP((e->x - n->x) / (float)BK_MAX(1, n->w), 0.0f, 0.9999f);
+ picker_set_hsv(picker, h, p->hsv[1], p->hsv[2]);
+ }
+ else {
+ const float v = 1.0f - (e->y - n->y) / (float)BK_MAX(1, n->h);
+ picker_set_hsv(picker, p->hsv[0], p->hsv[1], v);
+ }
+ return 1;
+}
+
+static void outline_rect(const BKNode *n)
+{
+ BuiWidgetBase wb = {{(float)n->x, (float)n->y, (float)n->w, (float)n->h}, 0, 0, CNR_ALL};
+ bk_rgba(bk_theme.regular.outline, wb.outline);
+ wb.pixelsize = 1.0f;
+ BUI_raster_widget_base(bk_draw.r, &wb);
+}
+
+static void hsv_rgba(float h, float s, float v, float out[4])
+{
+ const float hsv[3] = {h - floorf(h), s, v};
+ hsv_to_rgb_v(hsv, out);
+ out[3] = 1.0f;
+}
+
+static void hsv_circle_draw(BKNode *n)
+{
+ BKNode *picker = part_picker(n);
+ if (!picker) {
+ return;
+ }
+ PickerData *p = PICKER(picker);
+ float cx, cy, r;
+ circle_geom(n, &cx, &cy, &r);
+ BUI_raster_hsv_circle(bk_draw.r, cx, cy, r, p->hsv[2]);
+ float oc[4];
+ bk_rgba(bk_theme.regular.outline, oc);
+ bk_ring(cx, cy, r, oc, 1.0f);
+ /* hsvcircle_pos_from_vals: ang = 2 pi h + pi/2, (cos(-ang), sin(-ang)) */
+ const float ang = 2.0f * (float)M_PI * p->hsv[0] + (float)M_PI_2;
+ const float rad = BK_CLAMP(p->hsv[1], 0.0f, 1.0f) * r;
+ hsv_cursor(cx + cosf(-ang) * rad, cy - sinf(-ang) * rad, n);
+}
+
+static void hsv_square_draw(BKNode *n)
+{
+ BKNode *picker = part_picker(n);
+ if (!picker) {
+ return;
+ }
+ PickerData *p = PICKER(picker);
+ float hue[4];
+ hsv_rgba(p->hsv[0], 1, 1, hue);
+ const float white[4] = {1, 1, 1, 1}, black[4] = {0, 0, 0, 1};
+ BUI_raster_gradient(bk_draw.r, n->x, n->y, n->w, n->h, white, hue, black, black);
+ outline_rect(n);
+ hsv_cursor(n->x + p->hsv[1] * n->w, n->y + (1.0f - p->hsv[2]) * n->h, n);
+}
+
+static void hue_strip_draw(BKNode *n)
+{
+ BKNode *picker = part_picker(n);
+ if (!picker) {
+ return;
+ }
+ const float seg = n->w / 6.0f;
+ for (int i = 0; i < 6; i++) {
+ float a[4], b[4];
+ hsv_rgba(i / 6.0f, 1, 1, a);
+ hsv_rgba((i + 1) / 6.0f, 1, 1, b);
+ const int x0 = bk_iround(n->x + i * seg), x1 = bk_iround(n->x + (i + 1) * seg);
+ BUI_raster_gradient(bk_draw.r, x0, n->y, x1 - x0, n->h, a, b, b, a);
+ }
+ outline_rect(n);
+ hsv_cursor(n->x + PICKER(picker)->hsv[0] * n->w, n->y + n->h * 0.5f, n);
+}
+
+static void value_strip_draw(BKNode *n)
+{
+ BKNode *picker = part_picker(n);
+ if (!picker) {
+ return;
+ }
+ PickerData *p = PICKER(picker);
+ float top[4];
+ hsv_rgba(p->hsv[0], p->hsv[1], 1, top);
+ const float black[4] = {0, 0, 0, 1};
+ BUI_raster_gradient(bk_draw.r, n->x, n->y, n->w, n->h, top, top, black, black);
+ outline_rect(n);
+ hsv_cursor(n->x + n->w * 0.5f, n->y + (1.0f - p->hsv[2]) * n->h, n);
+}
+
+#define PART_CLASS(name_, draw_) \
+ {.name = name_, .flags = CLS_INTERACTIVE, .cursor = BK_CURSOR_CROSSHAIR, .draw = draw_, \
+ .press = part_press, .drag = part_drag, .wheel = part_wheel}
+
+const BKClass bk_cls_hsv_circle = PART_CLASS("hsv_circle", hsv_circle_draw);
+const BKClass bk_cls_hsv_square = PART_CLASS("hsv_square", hsv_square_draw);
+const BKClass bk_cls_hue_strip = PART_CLASS("hue_strip", hue_strip_draw);
+const BKClass bk_cls_value_strip = PART_CLASS("value_strip", value_strip_draw);
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Eyedropper (modal: the next click samples the window)
+ * \{ */
+
+typedef struct EyedropperData {
+ void (*pick)(void *data, const float rgb[3]);
+ void *data;
+} EyedropperData;
+
+static int eyedropper_press(BKNode *n, BKEvent *e)
+{
+ BKContext *ctx = bk_ctx(n);
+ EyedropperData d = *(EyedropperData *)n->ext;
+ float rgb[3];
+ bool ok = false;
+ if (ctx && ctx->raster) {
+ const int w = BUI_raster_width(ctx->raster), h = BUI_raster_height(ctx->raster);
+ if (e->x >= 0 && e->y >= 0 && e->x < w && e->y < h) {
+ const uint32_t px = BUI_raster_pixels(ctx->raster)[(size_t)e->y * w + e->x];
+ rgb[0] = ((px >> 16) & 255) / 255.0f;
+ rgb[1] = ((px >> 8) & 255) / 255.0f;
+ rgb[2] = (px & 255) / 255.0f;
+ ok = true;
+ }
+ }
+ if (ctx) {
+ bk_end_modal(ctx); /* frees n */
+ }
+ if (ok) {
+ d.pick(d.data, rgb);
+ }
+ return 1;
+}
+
+static void eyedropper_free(BKNode *n)
+{
+ free(n->ext);
+}
+
+const BKClass bk_cls_eyedropper = {.name = "eyedropper",
+ .cursor = BK_CURSOR_CROSSHAIR,
+ .free_ext = eyedropper_free,
+ .press = eyedropper_press};
+
+void bk_eyedropper_start(BKContext *ctx, void (*pick)(void *data, const float rgb[3]), void *data)
+{
+ BKNode *n = bk_node_new_cls(&bk_cls_eyedropper);
+ EyedropperData *d = (EyedropperData *)calloc(1, sizeof(EyedropperData));
+ d->pick = pick;
+ d->data = data;
+ n->ext = d;
+ bk_begin_modal(ctx, n);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Color ramp band (ui_draw_but_COLORBAND)
+ * \{ */
+
+#define RAMP_MAX 32
+enum { INTERP_LINEAR, INTERP_EASE, INTERP_BSPLINE, INTERP_CONSTANT };
+
+typedef struct RampData {
+ float pos[RAMP_MAX];
+ float col[RAMP_MAX][4];
+ int n, active, interp, drag;
+} RampData;
+
+#define RAMP(n) ((RampData *)(n)->ext)
+
+static void ramp_sorted(const RampData *d, int *order)
+{
+ for (int i = 0; i < d->n; i++) {
+ order[i] = i;
+ }
+ for (int i = 1; i < d->n; i++) { /* insertion sort by position */
+ const int k = order[i];
+ int j = i - 1;
+ while (j >= 0 && d->pos[order[j]] > d->pos[k]) {
+ order[j + 1] = order[j];
+ j--;
+ }
+ order[j + 1] = k;
+ }
+}
+
+void BK_ramp_evaluate(BKNode *n, float t, float out[4])
+{
+ RampData *d = RAMP(n);
+ if (!d->n) {
+ out[0] = out[1] = out[2] = 0;
+ out[3] = 1;
+ return;
+ }
+ int order[RAMP_MAX];
+ ramp_sorted(d, order);
+ if (t <= d->pos[order[0]]) {
+ memcpy(out, d->col[order[0]], sizeof(float[4]));
+ return;
+ }
+ for (int i = 0; i + 1 < d->n; i++) {
+ const int a = order[i], b = order[i + 1];
+ if (t <= d->pos[b]) {
+ if (d->interp == INTERP_CONSTANT) {
+ memcpy(out, d->col[a], sizeof(float[4]));
+ return;
+ }
+ float f = (t - d->pos[a]) / BK_MAX(1e-9f, d->pos[b] - d->pos[a]);
+ if (d->interp != INTERP_LINEAR) {
+ f = f * f * (3 - 2 * f);
+ }
+ for (int k = 0; k < 4; k++) {
+ out[k] = d->col[a][k] + (d->col[b][k] - d->col[a][k]) * f;
+ }
+ return;
+ }
+ }
+ memcpy(out, d->col[order[d->n - 1]], sizeof(float[4]));
+}
+
+static void ramp_init(BKNode *n)
+{
+ RampData *d = (RampData *)calloc(1, sizeof(RampData));
+ d->n = 2;
+ d->pos[1] = 1.0f;
+ d->col[0][3] = 1.0f;
+ d->col[1][0] = d->col[1][1] = d->col[1][2] = d->col[1][3] = 1.0f;
+ d->drag = -1;
+ n->ext = d;
+}
+
+static void ramp_free(BKNode *n)
+{
+ free(n->ext);
+}
+
+static void ramp_changed(BKNode *n)
+{
+ bk_invalidate(n);
+ bk_emit(n, BK_EV_CHANGE, NULL, RAMP(n)->active, 0);
+}
+
+static int ramp_add(BKNode *n, float pos)
+{
+ RampData *d = RAMP(n);
+ if (d->n == RAMP_MAX) {
+ return d->active;
+ }
+ float c[4];
+ BK_ramp_evaluate(n, pos, c);
+ d->pos[d->n] = pos;
+ memcpy(d->col[d->n], c, sizeof(c));
+ d->active = d->n++;
+ ramp_changed(n);
+ return d->active;
+}
+
+static void ramp_remove(BKNode *n)
+{
+ RampData *d = RAMP(n);
+ if (d->n <= 1) {
+ return;
+ }
+ const int a = d->active;
+ memmove(d->pos + a, d->pos + a + 1, sizeof(float) * (size_t)(d->n - a - 1));
+ memmove(d->col + a, d->col + a + 1, sizeof(float[4]) * (size_t)(d->n - a - 1));
+ d->n--;
+ int order[RAMP_MAX];
+ ramp_sorted(d, order);
+ d->active = order[0];
+ ramp_changed(n);
+}
+
+static int band_h(void)
+{
+ return bk_iround(1.1f * u());
+}
+
+static float ramp_pos_at(const BKNode *n, int x)
+{
+ return BK_CLAMP((x - n->x) / (float)BK_MAX(1, n->w), 0.0f, 1.0f);
+}
+
+static int ramp_press(BKNode *n, BKEvent *e)
+{
+ RampData *d = RAMP(n);
+ const float pos = ramp_pos_at(n, e->x);
+ if (EV_CTRL(e) || !d->n) { /* Ctrl+click: add a stop */
+ d->drag = ramp_add(n, pos);
+ return 1;
+ }
+ int best = 0;
+ for (int i = 1; i < d->n; i++) {
+ if (fabsf(d->pos[i] - pos) < fabsf(d->pos[best] - pos)) {
+ best = i;
+ }
+ }
+ d->active = best;
+ d->drag = best;
+ ramp_changed(n);
+ return 1;
+}
+
+static int ramp_drag(BKNode *n, BKEvent *e)
+{
+ RampData *d = RAMP(n);
+ if (d->drag < 0) {
+ return 0;
+ }
+ float pos = ramp_pos_at(n, e->x);
+ if (EV_CTRL(e)) {
+ pos = floorf(pos * 10.0f + 0.5f) / 10.0f;
+ }
+ d->pos[d->drag] = pos;
+ ramp_changed(n);
+ return 1;
+}
+
+static int ramp_release(BKNode *n, BKEvent *e)
+{
+ RAMP(n)->drag = -1;
+ return 1;
+}
+
+static int ramp_key(BKNode *n, BKEvent *e)
+{
+ if ((bk_keysym_is(e->keysym, "Delete") || bk_keysym_is(e->keysym, "x")) && !EV_CTRL(e)) {
+ ramp_remove(n);
+ return 1;
+ }
+ return 0;
+}
+
+static void ramp_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = 6 * u();
+ *rh = bk_iround(1.6f * u());
+}
+
+static void ramp_draw(BKNode *n)
+{
+ RampData *d = RAMP(n);
+ const int bh = band_h();
+ bk_checker(n->x, n->y, n->w, bh);
+ /* draw the band in thin vertical slices: exact for every interpolation */
+ const int slice = 2;
+ for (int x = 0; x < n->w; x += slice) {
+ float c0[4], c1[4];
+ BK_ramp_evaluate(n, (x + 0.5f) / n->w, c0);
+ BK_ramp_evaluate(n, BK_MIN(n->w, x + slice + 0.5f) / n->w, c1);
+ if (d->interp == INTERP_CONSTANT) {
+ memcpy(c1, c0, sizeof(c0));
+ }
+ BUI_raster_gradient(bk_draw.r, n->x + x, n->y, BK_MIN(slice, n->w - x), bh, c0, c1, c1, c0);
+ }
+ outline_rect(&(BKNode){.x = n->x, .y = n->y, .w = n->w, .h = bh});
+ const float uu = (float)u();
+ int order[RAMP_MAX];
+ ramp_sorted(d, order);
+ for (int k = 0; k < d->n; k++) {
+ const int i = order[k];
+ const float sx = floorf(n->x + d->pos[i] * n->w + 0.5f);
+ const bool active = i == d->active;
+ const float dark[4] = {0, 0, 0, 0.6f}, white[4] = {1, 1, 1, 1}, black[4] = {0, 0, 0, 0.8f};
+ bk_fill_f(sx - 1, n->y, 3, bh, dark);
+ bk_fill_f(sx, n->y, 1, bh, active ? white : black);
+ const float ty = n->y + bh + 1, ts = 0.28f * uu;
+ const float tri[3][2] = {{sx - ts, ty + ts * 1.6f}, {sx + ts, ty + ts * 1.6f}, {sx, ty}};
+ const float frame[4] = {active ? 1.0f : 0.1f, active ? 1.0f : 0.1f, active ? 1.0f : 0.1f, 1};
+ bk_polygon(tri, 3, frame);
+ const float inner[3][2] = {
+ {sx - ts * 0.55f, ty + ts * 1.35f}, {sx + ts * 0.55f, ty + ts * 1.35f}, {sx, ty + ts * 0.5f}};
+ const float c[4] = {d->col[i][0], d->col[i][1], d->col[i][2], 1};
+ bk_polygon(inner, 3, c);
+ }
+}
+
+static int ramp_set_num(BKNode *n, const char *key, double v)
+{
+ RampData *d = RAMP(n);
+ if (strcmp(key, "interpolation") == 0) {
+ d->interp = BK_CLAMP((int)v, 0, 3);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "active") == 0) {
+ d->active = BK_CLAMP((int)v, 0, BK_MAX(0, d->n - 1));
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "active_pos") == 0 && d->n) {
+ d->pos[d->active] = BK_CLAMP((float)v, 0.0f, 1.0f);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "add") == 0) {
+ ramp_add(n, (float)v);
+ return 1;
+ }
+ if (strcmp(key, "remove") == 0) {
+ ramp_remove(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int ramp_get_num(BKNode *n, const char *key, double *r)
+{
+ RampData *d = RAMP(n);
+ if (strcmp(key, "interpolation") == 0) {
+ *r = d->interp;
+ return 1;
+ }
+ if (strcmp(key, "active") == 0) {
+ *r = d->active;
+ return 1;
+ }
+ if (strcmp(key, "count") == 0) {
+ *r = d->n;
+ return 1;
+ }
+ return 0;
+}
+
+static int ramp_color_set(BKNode *n, const float c[4])
+{
+ RampData *d = RAMP(n);
+ if (!d->n) {
+ return 0;
+ }
+ memcpy(d->col[d->active], c, sizeof(float[4]));
+ bk_invalidate(n);
+ return 1;
+}
+
+const BKClass bk_cls_ramp = {.name = "ramp",
+ .flags = CLS_INTERACTIVE,
+ .init = ramp_init,
+ .free_ext = ramp_free,
+ .measure = ramp_measure,
+ .draw = ramp_draw,
+ .press = ramp_press,
+ .drag = ramp_drag,
+ .release = ramp_release,
+ .key = ramp_key,
+ .set_num = ramp_set_num,
+ .get_num = ramp_get_num};
+
+int BK_ramp_count(BKNode *n)
+{
+ return RAMP(n)->n;
+}
+
+void BK_ramp_get(BKNode *n, int i, float *pos, float rgba[4])
+{
+ RampData *d = RAMP(n);
+ if (i >= 0 && i < d->n) {
+ *pos = d->pos[i];
+ memcpy(rgba, d->col[i], sizeof(float[4]));
+ }
+}
+
+void BK_ramp_set(BKNode *n, const float *pos, const float (*rgba)[4], int count)
+{
+ RampData *d = RAMP(n);
+ d->n = BK_MIN(count, RAMP_MAX);
+ for (int i = 0; i < d->n; i++) {
+ d->pos[i] = BK_CLAMP(pos[i], 0.0f, 1.0f);
+ memcpy(d->col[i], rgba[i], sizeof(float[4]));
+ }
+ d->active = 0;
+ bk_invalidate(n);
+}
+
+int BK_ramp_active(BKNode *n)
+{
+ return RAMP(n)->active;
+}
+
+void BK_ramp_set_active_color(BKNode *n, const float rgba[4])
+{
+ ramp_color_set(n, rgba);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Curve mapping (ui_draw_but_CURVE)
+ * \{ */
+
+#define CURVE_MAX_PTS 64
+
+typedef struct CurveData {
+ float pts[4][CURVE_MAX_PTS][2];
+ int npts[4];
+ int nchannels, channel, selected, drag;
+} CurveData;
+
+#define CURVE(n) ((CurveData *)(n)->ext)
+
+static const float g_channel_colors[4][4] = {
+ {0.9f, 0.9f, 0.9f, 1}, {0.95f, 0.35f, 0.35f, 1}, {0.4f, 0.85f, 0.4f, 1}, {0.45f, 0.55f, 1, 1}};
+
+/* Sort points by x, then evaluate with Fritsch-Carlson monotone tangents
+ * (smooth, never overshoots; like Blender's auto-clamped handles). */
+static int curve_sorted(const CurveData *d, int ch, float out[][2])
+{
+ const int n = d->npts[ch];
+ memcpy(out, d->pts[ch], sizeof(float[2]) * (size_t)n);
+ for (int i = 1; i < n; i++) {
+ float p[2] = {out[i][0], out[i][1]};
+ int j = i - 1;
+ while (j >= 0 && out[j][0] > p[0]) {
+ out[j + 1][0] = out[j][0];
+ out[j + 1][1] = out[j][1];
+ j--;
+ }
+ out[j + 1][0] = p[0];
+ out[j + 1][1] = p[1];
+ }
+ return n;
+}
+
+static float curve_eval(const CurveData *d, int ch, float x)
+{
+ float p[CURVE_MAX_PTS][2];
+ const int n = curve_sorted(d, ch, p);
+ if (n == 0) {
+ return x;
+ }
+ if (x <= p[0][0]) {
+ return p[0][1];
+ }
+ if (x >= p[n - 1][0] || n < 2) {
+ return p[n - 1][1];
+ }
+ float dd[CURVE_MAX_PTS] = {0}, m[CURVE_MAX_PTS];
+ for (int i = 0; i + 1 < n; i++) {
+ dd[i] = (p[i + 1][1] - p[i][1]) / BK_MAX(1e-9f, p[i + 1][0] - p[i][0]);
+ }
+ m[0] = dd[0];
+ m[n - 1] = dd[n - 2];
+ for (int i = 1; i + 1 < n; i++) {
+ m[i] = (dd[i - 1] + dd[i]) * 0.5f;
+ }
+ for (int i = 0; i + 1 < n; i++) {
+ if (dd[i] == 0.0f) {
+ m[i] = m[i + 1] = 0.0f;
+ }
+ else {
+ const float a = m[i] / dd[i], b = m[i + 1] / dd[i], s = a * a + b * b;
+ if (s > 9.0f) {
+ const float t = 3.0f / sqrtf(s);
+ m[i] = t * a * dd[i];
+ m[i + 1] = t * b * dd[i];
+ }
+ }
+ }
+ for (int i = 0; i + 1 < n; i++) {
+ if (x <= p[i + 1][0]) {
+ const float h = BK_MAX(1e-9f, p[i + 1][0] - p[i][0]), t = (x - p[i][0]) / h;
+ const float t2 = t * t, t3 = t2 * t;
+ return (2 * t3 - 3 * t2 + 1) * p[i][1] + (t3 - 2 * t2 + t) * h * m[i] +
+ (-2 * t3 + 3 * t2) * p[i + 1][1] + (t3 - t2) * h * m[i + 1];
+ }
+ }
+ return p[n - 1][1];
+}
+
+static void curve_init(BKNode *n)
+{
+ CurveData *d = (CurveData *)calloc(1, sizeof(CurveData));
+ d->nchannels = 1;
+ for (int c = 0; c < 4; c++) {
+ d->npts[c] = 2;
+ d->pts[c][1][0] = d->pts[c][1][1] = 1.0f;
+ }
+ d->selected = d->drag = -1;
+ n->ext = d;
+ n->height_units = 8.0f;
+}
+
+static void curve_free(BKNode *n)
+{
+ free(n->ext);
+}
+
+static void curve_to_px(const BKNode *n, float x, float y, float *sx, float *sy)
+{
+ *sx = n->x + x * n->w;
+ *sy = n->y + (1.0f - y) * n->h;
+}
+
+static void curve_changed(BKNode *n)
+{
+ bk_invalidate(n);
+ bk_emit(n, BK_EV_CHANGE, NULL, CURVE(n)->channel, 0);
+}
+
+static int curve_press(BKNode *n, BKEvent *e)
+{
+ CurveData *d = CURVE(n);
+ const int ch = d->channel;
+ int near = -1;
+ float best = 0.45f * u();
+ for (int i = 0; i < d->npts[ch]; i++) {
+ float sx, sy;
+ curve_to_px(n, d->pts[ch][i][0], d->pts[ch][i][1], &sx, &sy);
+ const float dist = hypotf(sx - e->x, sy - e->y);
+ if (dist < best) {
+ near = i;
+ best = dist;
+ }
+ }
+ if (near < 0) {
+ const float fx = BK_CLAMP((e->x - n->x) / (float)BK_MAX(1, n->w), 0.0f, 1.0f);
+ const float fy = BK_CLAMP(1.0f - (e->y - n->y) / (float)BK_MAX(1, n->h), 0.0f, 1.0f);
+ float cx, cy;
+ curve_to_px(n, fx, curve_eval(d, ch, fx), &cx, &cy);
+ const bool on_curve = fabsf(cy - e->y) < 0.5f * u();
+ if ((on_curve || EV_CTRL(e)) && d->npts[ch] < CURVE_MAX_PTS) {
+ /* click the curve (or Ctrl+click anywhere) adds a point */
+ near = d->npts[ch]++;
+ d->pts[ch][near][0] = fx;
+ d->pts[ch][near][1] = on_curve ? curve_eval(d, ch, fx) : fy;
+ curve_changed(n);
+ }
+ }
+ d->selected = near;
+ d->drag = near;
+ bk_invalidate(n);
+ return 1;
+}
+
+static int curve_drag(BKNode *n, BKEvent *e)
+{
+ CurveData *d = CURVE(n);
+ if (d->drag < 0) {
+ return 0;
+ }
+ float fx = BK_CLAMP((e->x - n->x) / (float)BK_MAX(1, n->w), 0.0f, 1.0f);
+ float fy = BK_CLAMP(1.0f - (e->y - n->y) / (float)BK_MAX(1, n->h), 0.0f, 1.0f);
+ if (EV_CTRL(e)) { /* snap to the grid */
+ fx = floorf(fx * 8.0f + 0.5f) / 8.0f;
+ fy = floorf(fy * 8.0f + 0.5f) / 8.0f;
+ }
+ d->pts[d->channel][d->drag][0] = fx;
+ d->pts[d->channel][d->drag][1] = fy;
+ curve_changed(n);
+ return 1;
+}
+
+static int curve_release(BKNode *n, BKEvent *e)
+{
+ CURVE(n)->drag = -1;
+ return 1;
+}
+
+static void curve_remove_selected(BKNode *n)
+{
+ CurveData *d = CURVE(n);
+ const int ch = d->channel, s = d->selected;
+ if (s >= 0 && d->npts[ch] > 2) {
+ memmove(d->pts[ch][s], d->pts[ch][s + 1], sizeof(float[2]) * (size_t)(d->npts[ch] - s - 1));
+ d->npts[ch]--;
+ d->selected = -1;
+ curve_changed(n);
+ }
+}
+
+static int curve_key(BKNode *n, BKEvent *e)
+{
+ if ((bk_keysym_is(e->keysym, "Delete") || bk_keysym_is(e->keysym, "x")) && !EV_CTRL(e)) {
+ curve_remove_selected(n);
+ return 1;
+ }
+ return 0;
+}
+
+static void curve_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = 6 * u();
+ *rh = (int)(n->height_units * u());
+}
+
+static void curve_draw(BKNode *n)
+{
+ CurveData *d = CURVE(n);
+ const float back[4] = {0.16f, 0.16f, 0.16f, 1};
+ bk_roundbox(n->x, n->y, n->w, n->h, bk_widget_radius(&bk_theme.regular), CNR_ALL, back);
+ bk_clip_push(n->x, n->y, n->w, n->h);
+ for (int k = 1; k < 8; k++) {
+ const float g[4] = {1, 1, 1, (k % 2 == 0) ? 0.1f : 0.05f};
+ bk_fill_f(floorf(n->x + n->w * k / 8.0f + 0.5f), n->y, 1, n->h, g);
+ bk_fill_f(n->x, floorf(n->y + n->h * k / 8.0f + 0.5f), n->w, 1, g);
+ }
+ for (int pass = 0; pass < 2; pass++) {
+ for (int ch = 0; ch < d->nchannels; ch++) {
+ const bool current = ch == d->channel;
+ if ((pass == 0) == current) {
+ continue; /* other channels first, dimmed */
+ }
+ float col[4];
+ memcpy(col, g_channel_colors[d->nchannels > 1 ? ch : 0], sizeof(col));
+ if (!current) {
+ col[3] = 0.25f;
+ }
+ float px, py;
+ curve_to_px(n, 0, curve_eval(d, ch, 0), &px, &py);
+ const int steps = 96;
+ for (int i = 1; i <= steps; i++) {
+ const float x = i / (float)steps;
+ float sx, sy;
+ curve_to_px(n, x, curve_eval(d, ch, x), &sx, &sy);
+ bk_line(px, py, sx, sy, col, current ? BK_MAX(1.2f, 0.08f * u()) : 1.0f);
+ px = sx;
+ py = sy;
+ }
+ }
+ }
+ const int ch = d->channel;
+ const float r = 0.17f * u();
+ for (int i = 0; i < d->npts[ch]; i++) {
+ float sx, sy;
+ curve_to_px(n, d->pts[ch][i][0], d->pts[ch][i][1], &sx, &sy);
+ const float black[4] = {0, 0, 0, 1}, sel[4] = {1, 1, 1, 1}, grey[4] = {0.55f, 0.55f, 0.55f, 1};
+ bk_circle(sx, sy, r + 1, black);
+ bk_circle(sx, sy, r, i == d->selected ? sel : grey);
+ }
+ bk_clip_pop();
+ outline_rect(n);
+}
+
+static int curve_set_num(BKNode *n, const char *key, double v)
+{
+ CurveData *d = CURVE(n);
+ if (strcmp(key, "channels") == 0) {
+ d->nchannels = BK_CLAMP((int)v, 1, 4);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "channel") == 0) {
+ d->channel = BK_CLAMP((int)v, 0, d->nchannels - 1);
+ d->selected = -1;
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "remove_selected") == 0) {
+ curve_remove_selected(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int curve_get_num(BKNode *n, const char *key, double *r)
+{
+ CurveData *d = CURVE(n);
+ if (strcmp(key, "channel") == 0) {
+ *r = d->channel;
+ return 1;
+ }
+ if (strcmp(key, "selected") == 0) {
+ *r = d->selected;
+ return 1;
+ }
+ return 0;
+}
+
+const BKClass bk_cls_curve = {.name = "curve",
+ .flags = CLS_INTERACTIVE,
+ .init = curve_init,
+ .free_ext = curve_free,
+ .measure = curve_measure,
+ .draw = curve_draw,
+ .press = curve_press,
+ .drag = curve_drag,
+ .release = curve_release,
+ .key = curve_key,
+ .set_num = curve_set_num,
+ .get_num = curve_get_num};
+
+int BK_curve_count(BKNode *n, int ch)
+{
+ return CURVE(n)->npts[BK_CLAMP(ch, 0, 3)];
+}
+
+void BK_curve_get(BKNode *n, int ch, int i, float xy[2])
+{
+ CurveData *d = CURVE(n);
+ ch = BK_CLAMP(ch, 0, 3);
+ if (i >= 0 && i < d->npts[ch]) {
+ xy[0] = d->pts[ch][i][0];
+ xy[1] = d->pts[ch][i][1];
+ }
+}
+
+void BK_curve_set(BKNode *n, int ch, const float (*xy)[2], int count)
+{
+ CurveData *d = CURVE(n);
+ ch = BK_CLAMP(ch, 0, 3);
+ d->npts[ch] = BK_MIN(count, CURVE_MAX_PTS);
+ memcpy(d->pts[ch], xy, sizeof(float[2]) * (size_t)d->npts[ch]);
+ d->selected = -1;
+ bk_invalidate(n);
+}
+
+float BK_curve_evaluate(BKNode *n, int ch, float x)
+{
+ return curve_eval(CURVE(n), BK_CLAMP(ch, 0, 3), x);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Normal ball (UNITVEC) and histogram
+ * \{ */
+
+static void normal_init(BKNode *n)
+{
+ n->color[0] = n->color[1] = 0;
+ n->color[2] = 1;
+ n->height_units = 4.0f;
+}
+
+static void normal_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = *rh = (int)(n->height_units * u());
+}
+
+static void normal_geom(const BKNode *n, float *cx, float *cy, float *r)
+{
+ *r = BK_MIN(n->w, n->h) * 0.5f - 2.0f;
+ *cx = n->x + n->w * 0.5f;
+ *cy = n->y + n->h * 0.5f;
+}
+
+static int normal_aim(BKNode *n, BKEvent *e)
+{
+ float cx, cy, r;
+ normal_geom(n, &cx, &cy, &r);
+ float nx = (e->x - cx) / r, ny = -(e->y - cy) / r;
+ const float d = hypotf(nx, ny);
+ if (d > 1.0f) {
+ nx /= d;
+ ny /= d;
+ }
+ const float v[4] = {nx, ny, sqrtf(BK_MAX(0.0f, 1.0f - nx * nx - ny * ny)), 1};
+ memcpy(n->color, v, sizeof(v));
+ bk_invalidate(n);
+ bk_emit(n, BK_EV_CHANGE, NULL, 0, 0);
+ return 1;
+}
+
+static void normal_draw(BKNode *n)
+{
+ float cx, cy, r;
+ normal_geom(n, &cx, &cy, &r);
+ const float rim[4] = {0.1f, 0.1f, 0.1f, 1};
+ bk_circle(cx, cy, r + 1.5f, rim);
+ const float base[4] = {0.75f, 0.75f, 0.75f, 1}, dis[4] = {0.4f, 0.4f, 0.4f, 1};
+ BUI_raster_sphere(bk_draw.r, cx, cy, r, n->color, NODE_ENABLED(n) ? base : dis);
+ if (bk_hovered(n)) {
+ float c[4];
+ bk_rgba_alpha(bk_theme.text, 0.4f, c);
+ bk_ring(cx, cy, r + 1.5f, c, 1.0f);
+ }
+}
+
+const BKClass bk_cls_normal = {.name = "normal",
+ .flags = CLS_INTERACTIVE,
+ .cursor = BK_CURSOR_CROSSHAIR,
+ .init = normal_init,
+ .measure = normal_measure,
+ .draw = normal_draw,
+ .press = normal_aim,
+ .drag = normal_aim};
+
+typedef struct HistData {
+ float *bins;
+ int n, channels;
+} HistData;
+
+static void hist_init(BKNode *n)
+{
+ n->ext = calloc(1, sizeof(HistData));
+ n->height_units = 5.0f;
+}
+
+static void hist_free(BKNode *n)
+{
+ HistData *h = (HistData *)n->ext;
+ free(h->bins);
+ free(h);
+}
+
+void BK_histogram_set(BKNode *n, const float *bins, int count, int channels)
+{
+ HistData *h = (HistData *)n->ext;
+ free(h->bins);
+ channels = BK_CLAMP(channels, 1, 3);
+ h->bins = (float *)malloc(sizeof(float) * (size_t)BK_MAX(1, count * channels));
+ memcpy(h->bins, bins, sizeof(float) * (size_t)(count * channels));
+ h->n = count;
+ h->channels = channels;
+ bk_invalidate(n);
+}
+
+static void hist_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = 6 * u();
+ *rh = (int)(n->height_units * u());
+}
+
+static void hist_draw(BKNode *n)
+{
+ HistData *h = (HistData *)n->ext;
+ const float back[4] = {0.12f, 0.12f, 0.12f, 1};
+ bk_roundbox(n->x, n->y, n->w, n->h, bk_widget_radius(&bk_theme.regular), CNR_ALL, back);
+ bk_clip_push(n->x, n->y, n->w, n->h);
+ for (int k = 1; k < 4; k++) {
+ const float g[4] = {1, 1, 1, 0.06f};
+ bk_fill_f(floorf(n->x + n->w * k / 4.0f + 0.5f), n->y, 1, n->h, g);
+ bk_fill_f(n->x, floorf(n->y + n->h * k / 4.0f + 0.5f), n->w, 1, g);
+ }
+ if (h->n >= 2) {
+ float(*pts)[2] = (float(*)[2])malloc(sizeof(float[2]) * (size_t)(h->n + 2));
+ for (int ch = 0; ch < h->channels; ch++) {
+ const float *col = h->channels == 3 ? g_channel_colors[ch + 1] : g_channel_colors[0];
+ pts[0][0] = n->x;
+ pts[0][1] = n->y + n->h;
+ for (int i = 0; i < h->n; i++) {
+ const float v = BK_CLAMP(h->bins[i * h->channels + ch], 0.0f, 1.0f);
+ pts[i + 1][0] = n->x + n->w * i / (float)(h->n - 1);
+ pts[i + 1][1] = n->y + n->h * (1.0f - v);
+ }
+ pts[h->n + 1][0] = n->x + n->w;
+ pts[h->n + 1][1] = n->y + n->h;
+ const float fill[4] = {col[0], col[1], col[2], 0.35f};
+ const float line[4] = {col[0], col[1], col[2], 0.9f};
+ bk_polygon((const float(*)[2])pts, h->n + 2, fill);
+ for (int i = 1; i < h->n; i++) {
+ bk_line(pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1], line, 1.0f);
+ }
+ }
+ free(pts);
+ }
+ bk_clip_pop();
+ outline_rect(n);
+}
+
+const BKClass bk_cls_histogram = {.name = "histogram",
+ .init = hist_init,
+ .free_ext = hist_free,
+ .measure = hist_measure,
+ .draw = hist_draw};
+
+/** \} */
diff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.c
new file mode 100644
index 0000000..8a0e969
--- /dev/null
+++ b/kit/intern/kit_core.c
@@ -0,0 +1,3318 @@
+/* Kit core: nodes, properties, layout cache, input context, damage-driven
+ * rendering, text editing and number evaluation.
+ *
+ * The interaction rules follow Blender's interface_handlers.cc: drag
+ * threshold, double-click, drag-toggle, continuous grab while scrubbing
+ * (pointer hidden and warped at the window edge, restored on release),
+ * value shortcuts while hovering, tooltips after a delay.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <ctype.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#ifdef _WIN32
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+#endif
+
+#include "kit_intern.h"
+
+/* Blender's UTF-8 cursor stepping (blenlib, linked from bui_core). */
+typedef enum { STRCUR_JUMP_NONE, STRCUR_JUMP_DELIM, STRCUR_JUMP_ALL } eStrCursorJumpType;
+typedef enum { STRCUR_DIR_PREV, STRCUR_DIR_NEXT } eStrCursorJumpDirection;
+void BLI_str_cursor_step_utf8(const char *str, int str_maxlen, int *pos,
+ eStrCursorJumpDirection direction, eStrCursorJumpType jump,
+ bool use_init_step);
+void BLI_str_cursor_step_bounds_utf8(const char *str, int str_maxlen, int pos, int *r_start,
+ int *r_end);
+
+/* -------------------------------------------------------------------- */
+/** \name Utilities
+ * \{ */
+
+static void (*g_retain)(void *) = NULL;
+static void (*g_release)(void *) = NULL;
+
+void BK_set_ref_hooks(void (*retain)(void *ref), void (*release)(void *ref))
+{
+ g_retain = retain;
+ g_release = release;
+}
+void bk_retain(void *ref)
+{
+ if (ref && g_retain) {
+ g_retain(ref);
+ }
+}
+void bk_release(void *ref)
+{
+ if (ref && g_release) {
+ g_release(ref);
+ }
+}
+
+char *bk_strdup(const char *s)
+{
+ if (!s) {
+ return NULL;
+ }
+ const size_t n = strlen(s) + 1;
+ char *d = (char *)malloc(n);
+ if (d) {
+ memcpy(d, s, n);
+ }
+ return d;
+}
+
+void bk_set_text(char **dst, const char *s)
+{
+ char *d = bk_strdup(s ? s : "");
+ free(*dst);
+ *dst = d;
+}
+
+void bk_strs_free(BKStrs *s)
+{
+ for (int i = 0; i < s->n; i++) {
+ free(s->v[i]);
+ }
+ free(s->v);
+ s->v = NULL;
+ s->n = 0;
+}
+
+void bk_strs_set(BKStrs *s, const char *const *v, int n)
+{
+ bk_strs_free(s);
+ if (n <= 0) {
+ return;
+ }
+ s->v = (char **)calloc((size_t)n, sizeof(char *));
+ for (int i = 0; i < n; i++) {
+ s->v[i] = bk_strdup(v[i] ? v[i] : "");
+ }
+ s->n = n;
+}
+
+bool bk_streq(const char *a, const char *b)
+{
+ return a && b && strcmp(a, b) == 0;
+}
+
+bool bk_keysym_is(const char *keysym, const char *name)
+{
+ if (!keysym) {
+ return false;
+ }
+ for (; *keysym && *name; keysym++, name++) {
+ if (tolower((uchar)*keysym) != tolower((uchar)*name)) {
+ return false;
+ }
+ }
+ return *keysym == 0 && *name == 0;
+}
+
+double bk_time(void)
+{
+#ifdef _WIN32
+ static LARGE_INTEGER freq;
+ LARGE_INTEGER now;
+ if (!freq.QuadPart) {
+ QueryPerformanceFrequency(&freq);
+ }
+ QueryPerformanceCounter(&now);
+ return (double)now.QuadPart / (double)freq.QuadPart;
+#else
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec + ts.tv_nsec * 1e-9;
+#endif
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Nodes
+ * \{ */
+
+static int g_gen = 1; /* layout generation for the natural-size cache */
+
+static const BKClass *const g_classes[] = {
+ &bk_cls_column, &bk_cls_row, &bk_cls_grid, &bk_cls_box,
+ &bk_cls_panel, &bk_cls_tabs, &bk_cls_sidetabs, &bk_cls_scroll, &bk_cls_scrollbar,
+ &bk_cls_label, &bk_cls_separator, &bk_cls_progress, &bk_cls_button,
+ &bk_cls_toggle, &bk_cls_checkbox, &bk_cls_decorator, &bk_cls_text,
+ &bk_cls_search, &bk_cls_hotkey, &bk_cls_number, &bk_cls_slider,
+ &bk_cls_dropdown, &bk_cls_enum, &bk_cls_swatch, &bk_cls_popover,
+ &bk_cls_menubutton, &bk_cls_menubar, &bk_cls_list, &bk_cls_tree,
+ &bk_cls_gridview, &bk_cls_ramp, &bk_cls_curve, &bk_cls_normal,
+ &bk_cls_histogram, &bk_cls_frame, &bk_cls_radio, &bk_cls_canvas,
+ &bk_cls_textarea, &bk_cls_image,
+};
+
+const BKClass *bk_class_find(const char *name)
+{
+ for (size_t i = 0; i < sizeof(g_classes) / sizeof(g_classes[0]); i++) {
+ if (strcmp(g_classes[i]->name, name) == 0) {
+ return g_classes[i];
+ }
+ }
+ return NULL;
+}
+
+BKNode *bk_node_new_cls(const BKClass *cls)
+{
+ BKNode *n = (BKNode *)calloc(1, sizeof(BKNode));
+ n->cls = cls;
+ n->flags = NF_VISIBLE | NF_ENABLED | NF_EMBOSS;
+ n->weight = 1.0f;
+ n->corners = CNR_ALL;
+ n->precision = 3;
+ n->step = 0.1;
+ n->vmin = 0.0;
+ n->vmax = 1.0;
+ n->hot = -1;
+ n->rename_row = -1;
+ n->spacing = -1;
+ n->rows = 5;
+ n->split = 0.4f;
+ n->color[3] = 1.0f;
+ n->nat_gen = 0;
+ if (cls->init) {
+ cls->init(n);
+ }
+ return n;
+}
+
+BKNode *BK_node_new(const char *type)
+{
+ const BKClass *cls = bk_class_find(type);
+ return cls ? bk_node_new_cls(cls) : NULL;
+}
+
+const char *BK_node_type(const BKNode *n)
+{
+ return n->cls->name;
+}
+
+static void node_detach(BKNode *child)
+{
+ BKNode *p = child->parent;
+ if (!p) {
+ return;
+ }
+ BKContext *ctx = bk_ctx(child);
+ if (ctx) {
+ bk_forget(ctx, child);
+ bk_relayout(p);
+ }
+ for (int i = 0; i < p->nkids; i++) {
+ if (p->kids[i] == child) {
+ memmove(p->kids + i, p->kids + i + 1, sizeof(BKNode *) * (size_t)(p->nkids - i - 1));
+ p->nkids--;
+ break;
+ }
+ }
+ child->parent = NULL;
+}
+
+void BK_node_free(BKNode *n)
+{
+ if (!n) {
+ return;
+ }
+ if (n->parent) {
+ node_detach(n);
+ }
+ if (n->ctx_root) {
+ n->ctx_root->root = NULL;
+ }
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ c->parent = NULL;
+ if (c->ref) {
+ bk_release(c->ref); /* host owns it */
+ }
+ else {
+ BK_node_free(c); /* C-owned (built by a composite) */
+ }
+ }
+ free(n->kids);
+ if (n->cls->free_ext) {
+ n->cls->free_ext(n);
+ }
+ free(n->text);
+ free(n->label);
+ free(n->desc);
+ free(n->placeholder);
+ free(n->suffix);
+ bk_strs_free(&n->items);
+ free(n->marks);
+ bk_strs_free(&n->item_icons_s);
+ bk_strs_free(&n->shortcuts);
+ free(n->item_icons);
+ free(n->linked);
+ free(n->linked_start);
+ bk_te_free(n->edit);
+ free(n->geom);
+ bk_image_free((BKImage *)n->image);
+ free(n);
+}
+
+void BK_node_set_ref(BKNode *n, void *ref)
+{
+ n->ref = ref;
+}
+void *BK_node_ref(const BKNode *n)
+{
+ return n->ref;
+}
+
+void bk_node_add(BKNode *parent, BKNode *child)
+{
+ BK_node_add(parent, child, -1);
+}
+
+int BK_node_add(BKNode *parent, BKNode *child, int index)
+{
+ if (!parent || !child || child == parent) {
+ return 0;
+ }
+ if (child->parent) {
+ void *ref = child->ref;
+ bk_retain(ref); /* keep alive across the move */
+ BK_node_remove(child->parent, child);
+ BK_node_add(parent, child, index);
+ bk_release(ref);
+ return 1;
+ }
+ if (parent->nkids == parent->capkids) {
+ parent->capkids = parent->capkids ? parent->capkids * 2 : 4;
+ parent->kids = (BKNode **)realloc(parent->kids, sizeof(BKNode *) * (size_t)parent->capkids);
+ }
+ if (index < 0 || index > parent->nkids) {
+ index = parent->nkids;
+ }
+ memmove(parent->kids + index + 1, parent->kids + index,
+ sizeof(BKNode *) * (size_t)(parent->nkids - index));
+ parent->kids[index] = child;
+ parent->nkids++;
+ child->parent = parent;
+ bk_retain(child->ref);
+ bk_relayout(parent);
+ return 1;
+}
+
+void BK_node_remove(BKNode *parent, BKNode *child)
+{
+ if (!child || child->parent != parent) {
+ return;
+ }
+ node_detach(child);
+ bk_release(child->ref);
+}
+
+int BK_node_child_count(const BKNode *n)
+{
+ return n->nkids;
+}
+BKNode *BK_node_child(const BKNode *n, int i)
+{
+ return (i >= 0 && i < n->nkids) ? n->kids[i] : NULL;
+}
+BKNode *BK_node_parent(const BKNode *n)
+{
+ return n->parent;
+}
+void BK_node_rect(const BKNode *n, int r[4])
+{
+ r[0] = n->x;
+ r[1] = n->y;
+ r[2] = n->w;
+ r[3] = n->h;
+}
+void BK_node_natural(BKNode *n, int r[2])
+{
+ bk_natural(n, &r[0], &r[1]);
+}
+void BK_node_invalidate(BKNode *n)
+{
+ bk_invalidate(n);
+}
+void BK_node_relayout(BKNode *n)
+{
+ bk_relayout(n);
+}
+
+BKContext *bk_ctx(const BKNode *n)
+{
+ while (n) {
+ if (n->ctx_root) {
+ return n->ctx_root;
+ }
+ n = n->parent;
+ }
+ return NULL;
+}
+
+BKRect bk_node_rect(const BKNode *n)
+{
+ return bk_rect(n->x, n->y, n->w, n->h);
+}
+
+void bk_invalidate(BKNode *n)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (!ctx) {
+ return;
+ }
+ int m = 3;
+ for (const BKNode *p = n; p; p = p->parent) {
+ if (p->cls->flags & CLS_POPUP) {
+ m = (int)(bk_theme.menu_shadow_width * bk_scale_fac) + 6;
+ break;
+ }
+ }
+ bk_ctx_dirty_rect(ctx, bk_rect(n->x - m, n->y - m, n->w + 2 * m, n->h + 2 * m));
+}
+
+void bk_relayout(BKNode *n)
+{
+ g_gen++;
+ BKContext *ctx = bk_ctx(n);
+ if (ctx) {
+ ctx->layout_dirty = true;
+ bk_ctx_request(ctx);
+ }
+}
+
+void bk_natural(BKNode *n, int *r_w, int *r_h)
+{
+ if (n->nat_gen != g_gen) {
+ int w = 4 * bk_unit(), h = bk_unit();
+ if (n->cls->measure) {
+ const float saved = bk_text_scale;
+ bk_text_scale = n->font_scale > 0.0f ? n->font_scale : 1.0f;
+ n->cls->measure(n, &w, &h);
+ if (bk_text_scale > 1.0f) { /* taller text needs a taller widget */
+ h = BK_MAX(h, (int)(h * bk_text_scale + 0.5f));
+ }
+ bk_text_scale = saved;
+ }
+ if (n->geom) { /* explicit requested size (Tk width=/height=, Qt fixed size) */
+ if (n->geom->reqw > 0) {
+ w = n->geom->reqw;
+ }
+ if (n->geom->reqh > 0) {
+ h = n->geom->reqh;
+ }
+ }
+ n->nat_w = w;
+ n->nat_h = h;
+ n->nat_gen = g_gen;
+ }
+ *r_w = n->nat_w;
+ *r_h = n->nat_h;
+}
+
+int bk_configure_pending;
+
+void bk_arrange(BKNode *n, int x, int y, int w, int h)
+{
+ if ((n->flags & NF_EVENTS) && (n->x != x || n->y != y || n->w != w || n->h != h)) {
+ n->flags |= NF_CONFIGURED; /* reported after layout (Tk's <Configure>) */
+ bk_configure_pending = 1;
+ }
+ n->x = x;
+ n->y = y;
+ n->w = w;
+ n->h = h;
+ if (n->cls->arrange) {
+ n->cls->arrange(n);
+ }
+}
+
+void bk_draw_tree(BKNode *n)
+{
+ if (!NODE_VISIBLE(n)) {
+ return;
+ }
+ if (n->cls->draw_tree) {
+ n->cls->draw_tree(n);
+ return;
+ }
+ /* Skip whole subtrees outside the redrawn region (children stay inside
+ * their parent's rect; emboss/outlines spill by a pixel or two). */
+ BKRect r = bk_rect(n->x - 3, n->y - 3, n->w + 6, n->h + 6);
+ if (!bk_clip_visible(&r)) {
+ return;
+ }
+ if (n->cls->draw) {
+ const float saved = bk_text_scale;
+ bk_text_scale = n->font_scale > 0.0f ? n->font_scale : 1.0f;
+ n->cls->draw(n);
+ bk_text_scale = saved;
+ }
+ for (int i = 0; i < n->nkids; i++) {
+ bk_draw_tree(n->kids[i]);
+ }
+}
+
+bool bk_contains(const BKNode *n, int x, int y)
+{
+ return x >= n->x && x < n->x + n->w && y >= n->y && y < n->y + n->h;
+}
+
+BKNode *bk_hit(BKNode *n, int x, int y)
+{
+ if (!NODE_VISIBLE(n) || !bk_contains(n, x, y)) {
+ return NULL;
+ }
+ if (n->cls->hit) {
+ return n->cls->hit(n, x, y);
+ }
+ for (int i = n->nkids - 1; i >= 0; i--) {
+ BKNode *f = bk_hit(n->kids[i], x, y);
+ if (f) {
+ return f;
+ }
+ }
+ return ((n->cls->flags & CLS_INTERACTIVE) || (n->flags & NF_EVENTS)) ? n : NULL;
+}
+
+bool bk_hovered(const BKNode *n)
+{
+ const BKContext *ctx = bk_ctx(n);
+ return ctx && ctx->hover == n && NODE_ENABLED(n);
+}
+
+bool bk_pressed(const BKNode *n)
+{
+ const BKContext *ctx = bk_ctx(n);
+ return ctx && ctx->grab == n && ctx->hover == n;
+}
+
+void bk_emit(BKNode *n, int kind, void *ref, double a, double b)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (ctx && ctx->host.emit) {
+ ctx->host.emit(ctx->host.data, n, kind, ref, a, b);
+ }
+}
+
+void bk_changed(BKNode *n)
+{
+ bk_invalidate(n);
+ if (n->on_change) {
+ n->on_change(n, n->on_change_data);
+ }
+ bk_emit(n, BK_EV_CHANGE, NULL, n->value, 0);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Values & shortcuts
+ * \{ */
+
+double bk_clamp_value(const BKNode *n, double v)
+{
+ if (n->flags & NF_HAS_MIN && v < n->vmin) {
+ v = n->vmin;
+ }
+ if (n->flags & NF_HAS_MAX && v > n->vmax) {
+ v = n->vmax;
+ }
+ if (n->flags & NF_INTEGER) {
+ v = floor(v + 0.5);
+ }
+ return v;
+}
+
+void bk_set_value_silent(BKNode *n, double v)
+{
+ v = bk_clamp_value(n, v);
+ if (v != n->value) {
+ n->value = v;
+ bk_invalidate(n);
+ }
+}
+
+void bk_set_value(BKNode *n, double v)
+{
+ v = bk_clamp_value(n, v);
+ if (v != n->value) {
+ bk_undo_record(n, 0);
+ n->value = v;
+ bk_changed(n);
+ }
+}
+
+char *bk_clipboard_get(BKContext *ctx);
+void bk_clipboard_set(BKContext *ctx, const char *s);
+
+static void vc_copy(void *data)
+{
+ BKNode *n = (BKNode *)data;
+ char buf[256];
+ if (n->cls->to_text && n->cls->to_text(n, buf, sizeof(buf))) {
+ bk_clipboard_set(bk_ctx(n), buf);
+ }
+}
+
+static void vc_paste(void *data)
+{
+ BKNode *n = (BKNode *)data;
+ char *s = bk_clipboard_get(bk_ctx(n));
+ if (s) {
+ /* trim */
+ char *b = s;
+ while (*b && isspace((uchar)*b)) {
+ b++;
+ }
+ size_t l = strlen(b);
+ while (l && isspace((uchar)b[l - 1])) {
+ b[--l] = 0;
+ }
+ if (n->cls->from_text) {
+ n->cls->from_text(n, b);
+ }
+ free(s);
+ }
+}
+
+static void vc_reset(void *data)
+{
+ BKNode *n = (BKNode *)data;
+ if (n->cls->reset) {
+ n->cls->reset(n, false);
+ }
+}
+
+int bk_value_context_items(BKNode *n, BKMenuSpec *items, int max)
+{
+ if (max < 4) {
+ return 0;
+ }
+ memset(items, 0, sizeof(BKMenuSpec) * 4);
+ items[0] = (BKMenuSpec){"Copy Value", bk_icons_lookup("COPYDOWN"), "Ctrl C", -1, 1};
+ items[0].fn = vc_copy;
+ items[0].data = n;
+ items[1] = (BKMenuSpec){"Paste Value", bk_icons_lookup("PASTEDOWN"), "Ctrl V", -1, 1};
+ items[1].fn = vc_paste;
+ items[1].data = n;
+ items[2] = (BKMenuSpec){"-", 0, NULL, -1, 1};
+ items[3] = (BKMenuSpec){"Reset to Default Value", bk_icons_lookup("LOOP_BACK"), "Backspace",
+ -1, 1};
+ items[3].fn = vc_reset;
+ items[3].data = n;
+ return 4;
+}
+
+int bk_value_key(BKNode *n, BKEvent *e)
+{
+ const BKClass *c = n->cls;
+ if (EV_CTRL(e) && EV_ALT(e)) {
+ return 0; /* Ctrl+Alt+C/V: whole vector, handled by the parent */
+ }
+ if (EV_CTRL(e) && bk_keysym_is(e->keysym, "c")) {
+ vc_copy(n);
+ return 1;
+ }
+ if (EV_CTRL(e) && bk_keysym_is(e->keysym, "v")) {
+ vc_paste(n);
+ return 1;
+ }
+ if (bk_keysym_is(e->keysym, "BackSpace")) {
+ if (c->reset) {
+ c->reset(n, true);
+ }
+ return 1;
+ }
+ if (bk_keysym_is(e->keysym, "minus") || bk_keysym_is(e->keysym, "KP_Subtract")) {
+ if (c->negate) {
+ c->negate(n);
+ return 1;
+ }
+ return 0;
+ }
+ if (bk_keysym_is(e->keysym, "Return") || bk_keysym_is(e->keysym, "KP_Enter")) {
+ if (c->activate) {
+ c->activate(n);
+ }
+ return 1;
+ }
+ return 0;
+}
+
+int bk_value_wheel(BKNode *n, BKEvent *e)
+{
+ if (EV_CTRL(e) && n->cls->step) {
+ n->cls->step(n, e->delta > 0 ? 1 : -1);
+ return 1;
+ }
+ return 0;
+}
+
+void bk_begin_edit(BKNode *n, const char *text, bool select_all)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (ctx && ctx->focus && ctx->focus != n) {
+ BKNode *f = ctx->focus;
+ ctx->focus = NULL;
+ if (f->cls->finish_edit) {
+ f->cls->finish_edit(f, true);
+ }
+ }
+ bk_te_free(n->edit);
+ n->edit = bk_te_new(text, select_all);
+ memcpy(n->edit->mask, n->mask, sizeof(n->mask));
+ if (ctx) {
+ ctx->focus = n;
+ ctx->cursor = -1; /* re-evaluate (text cursor) */
+ }
+ bk_invalidate(n);
+}
+
+static void end_edit(BKContext *ctx, bool confirm)
+{
+ BKNode *f = ctx->focus;
+ ctx->focus = NULL;
+ if (f) {
+ if (f->cls->finish_edit) {
+ f->cls->finish_edit(f, confirm);
+ }
+ bk_te_free(f->edit);
+ f->edit = NULL;
+ bk_invalidate(f);
+ }
+}
+
+int bk_edit_key(BKNode *n, BKEvent *e)
+{
+ BKContext *ctx = bk_ctx(n);
+ const int res = bk_te_key(n->edit, ctx, e->text, e->keysym, e->mods);
+ if ((res == TE_CONFIRM || res == TE_CANCEL) && ctx) {
+ end_edit(ctx, res == TE_CONFIRM);
+ }
+ else if ((res == TE_NEXT || res == TE_PREV) && ctx) {
+ end_edit(ctx, true);
+ bk_edit_next(n, res == TE_NEXT ? 1 : -1);
+ }
+ bk_invalidate(n);
+ return 1;
+}
+
+void BK_link_fields(BKNode *const *fields, int n)
+{
+ for (int i = 0; i < n; i++) {
+ BKNode *f = fields[i];
+ free(f->linked);
+ free(f->linked_start);
+ f->linked = (BKNode **)calloc((size_t)BK_MAX(1, n - 1), sizeof(BKNode *));
+ f->linked_start = (double *)calloc((size_t)BK_MAX(1, n - 1), sizeof(double));
+ f->nlinked = 0;
+ for (int j = 0; j < n; j++) {
+ if (j != i) {
+ f->linked[f->nlinked++] = fields[j];
+ }
+ }
+ }
+ if (n > 0 && fields[0]->parent) {
+ fields[0]->parent->flags |= NF_VECTOR;
+ }
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Properties
+ * \{ */
+
+static int str_align(const char *s)
+{
+ if (bk_streq(s, "right")) {
+ return BK_ALIGN_RIGHT;
+ }
+ if (bk_streq(s, "center")) {
+ return BK_ALIGN_CENTER;
+ }
+ return BK_ALIGN_LEFT;
+}
+
+static const struct {
+ const char *key;
+ unsigned flag;
+ bool relayout;
+} g_flag_props[] = {
+ {"visible", NF_VISIBLE, true}, {"enabled", NF_ENABLED, false},
+ {"align", NF_ALIGN, true}, {"emboss", NF_EMBOSS, false},
+ {"vertical", NF_VERTICAL, true}, {"icon_only", NF_ICON_ONLY, true},
+ {"collapsed", NF_COLLAPSED, true}, {"integer", NF_INTEGER, false},
+ {"live", NF_LIVE, false}, {"alpha", NF_ALPHA, false},
+ {"square", NF_SQUARE, false}, {"directory", NF_DIRECTORY, false},
+ {"line", NF_LINE, false}, {"bold", NF_BOLD, true},
+ {"events", NF_EVENTS, false}, {"nopropagate", NF_NOPROPAGATE, true},
+ {"viewevents", NF_VIEWEVENTS, false}, {"noscrollbar", NF_NOSCROLLBAR, true},
+};
+
+static int g_view_watchers; /* > 0 once any node asked for view events */
+
+/* Scrolled views (Tk's xview/yview): the class reports first/visible/total
+ * in its own units; fractions, moveto, scrolling by units and change
+ * notification are shared here. */
+static void view_of(BKNode *n, int axis, int *first, int *vis, int *total)
+{
+ *first = 0;
+ *vis = *total = 1;
+ if (n->cls->view) {
+ n->cls->view(n, axis, first, vis, total);
+ }
+ *total = BK_MAX(1, *total);
+ *vis = BK_CLAMP(*vis, 1, *total);
+}
+
+void bk_view_fractions(BKNode *n, int axis, float *r_first, float *r_last)
+{
+ int first, vis, total;
+ view_of(n, axis, &first, &vis, &total);
+ *r_first = BK_CLAMP((float)first / total, 0.0f, 1.0f);
+ *r_last = BK_CLAMP((float)(first + vis) / total, 0.0f, 1.0f);
+}
+
+static void view_set_first(BKNode *n, int axis, int first)
+{
+ int cur, vis, total;
+ view_of(n, axis, &cur, &vis, &total);
+ first = BK_CLAMP(first, 0, total - vis);
+ if (n->cls->set_view && first != cur) {
+ n->cls->set_view(n, axis, first);
+ bk_invalidate(n);
+ }
+}
+
+static int view_set_num(BKNode *n, const char *key, double v)
+{
+ const int axis = key[0] == 'x';
+ int first, vis, total;
+ if (strcmp(key + 1, "view") == 0) { /* moveto fraction */
+ view_of(n, axis, &first, &vis, &total);
+ view_set_first(n, axis, (int)floor(v * total + 0.5));
+ return 1;
+ }
+ if (strcmp(key + 1, "scroll") == 0) { /* by units */
+ view_of(n, axis, &first, &vis, &total);
+ view_set_first(n, axis, first + (int)v);
+ return 1;
+ }
+ return 0;
+}
+
+static int view_get_num(BKNode *n, const char *key, double *r_v)
+{
+ const int axis = key[0] == 'x';
+ if (strcmp(key + 1, "first") == 0 || strcmp(key + 1, "last") == 0) {
+ float a, b;
+ bk_view_fractions(n, axis, &a, &b);
+ *r_v = key[1] == 'f' ? a : b;
+ return 1;
+ }
+ if (strcmp(key + 1, "total") == 0 || strcmp(key + 1, "visible") == 0) {
+ int first, vis, total;
+ view_of(n, axis, &first, &vis, &total);
+ *r_v = key[1] == 't' ? total : vis;
+ return 1;
+ }
+ return 0;
+}
+
+typedef struct Notify {
+ BKNode *node;
+ int kind;
+} Notify;
+
+static void notify_collect(BKNode *n, Notify *out, int *count, int max)
+{
+ if (*count >= max) {
+ return;
+ }
+ if (n->flags & NF_CONFIGURED) {
+ n->flags &= ~NF_CONFIGURED;
+ out[(*count)++] = (Notify){n, BK_EV_CONFIGURE};
+ }
+ if ((n->flags & NF_VIEWEVENTS) && *count < max) {
+ float f[4];
+ bk_view_fractions(n, 0, &f[0], &f[1]);
+ bk_view_fractions(n, 1, &f[2], &f[3]);
+ if (memcmp(f, n->view_seen, sizeof(f)) != 0) {
+ memcpy(n->view_seen, f, sizeof(f));
+ out[(*count)++] = (Notify){n, BK_EV_VIEW};
+ }
+ }
+ for (int i = 0; i < n->nkids; i++) {
+ notify_collect(n->kids[i], out, count, max);
+ }
+}
+
+/* Tell the host what layout and input changed: a widget's geometry (Tk's
+ * <Configure>) and scrolled views (Tk's x/yscrollcommand). One shared pass
+ * after input and after layout. */
+void bk_views_check(BKContext *ctx)
+{
+ if ((!g_view_watchers && !bk_configure_pending) || !ctx->root) {
+ return;
+ }
+ bk_configure_pending = 0;
+ Notify changed[128];
+ int count = 0;
+ notify_collect(ctx->root, changed, &count, 128);
+ for (int i = 0; i < count; i++) { /* after the walk: callbacks may edit the tree */
+ BKNode *n = changed[i].node;
+ bk_emit(n, changed[i].kind, NULL, changed[i].kind == BK_EV_CONFIGURE ? n->w : 0,
+ changed[i].kind == BK_EV_CONFIGURE ? n->h : 0);
+ }
+}
+
+int BK_set_num(BKNode *n, const char *key, double v)
+{
+ if (n->cls->set_num && n->cls->set_num(n, key, v)) {
+ return 1;
+ }
+ if ((key[0] == 'x' || key[0] == 'y') && view_set_num(n, key, v)) {
+ return 1;
+ }
+ if (strcmp(key, "viewevents") == 0 && v != 0) {
+ g_view_watchers++;
+ }
+ for (size_t i = 0; i < sizeof(g_flag_props) / sizeof(g_flag_props[0]); i++) {
+ if (strcmp(key, g_flag_props[i].key) == 0) {
+ if (v != 0) {
+ n->flags |= g_flag_props[i].flag;
+ }
+ else {
+ n->flags &= ~g_flag_props[i].flag;
+ }
+ if (g_flag_props[i].relayout) {
+ bk_relayout(n);
+ }
+ bk_invalidate(n);
+ if (strcmp(key, "enabled") == 0 || strcmp(key, "visible") == 0) {
+ BKContext *ctx = bk_ctx(n);
+ if (ctx && !(n->flags & g_flag_props[i].flag)) {
+ bk_forget(ctx, n);
+ }
+ }
+ return 1;
+ }
+ }
+ if (strcmp(key, "value") == 0) {
+ if (n->cls == &bk_cls_tabs || n->cls == &bk_cls_sidetabs) {
+ n->current = (int)v;
+ bk_relayout(n);
+ }
+ else {
+ bk_set_value_silent(n, v);
+ }
+ return 1;
+ }
+ if (strcmp(key, "set_value") == 0) { /* notifying setter */
+ bk_set_value(n, v);
+ return 1;
+ }
+ if (strcmp(key, "default") == 0) {
+ n->defval = v;
+ return 1;
+ }
+ if (strcmp(key, "min") == 0) {
+ n->vmin = v;
+ n->flags |= NF_HAS_MIN;
+ return 1;
+ }
+ if (strcmp(key, "max") == 0) {
+ n->vmax = v;
+ n->flags |= NF_HAS_MAX;
+ return 1;
+ }
+ if (strcmp(key, "step") == 0) {
+ n->step = v;
+ return 1;
+ }
+ if (strcmp(key, "precision") == 0) {
+ n->precision = (int)v;
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "weight") == 0) {
+ n->weight = (float)v;
+ bk_relayout(n);
+ return 1;
+ }
+ if (strcmp(key, "factor") == 0) {
+ n->factor = v;
+ bk_relayout(n);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "spacing") == 0) {
+ n->spacing = (int)v;
+ bk_relayout(n);
+ return 1;
+ }
+ if (strcmp(key, "padding") == 0) {
+ n->padding = (int)v;
+ bk_relayout(n);
+ return 1;
+ }
+ if (strcmp(key, "columns") == 0) {
+ n->columns = (int)v;
+ bk_relayout(n);
+ return 1;
+ }
+ if (strcmp(key, "rows") == 0) {
+ n->rows = (int)v;
+ bk_relayout(n);
+ return 1;
+ }
+ if (strcmp(key, "tile") == 0) {
+ n->tile = (float)v;
+ bk_relayout(n);
+ return 1;
+ }
+ if (strcmp(key, "height") == 0) {
+ n->height_units = (float)v;
+ bk_relayout(n);
+ return 1;
+ }
+ if (strcmp(key, "split") == 0) {
+ n->split = (float)v;
+ bk_relayout(n);
+ return 1;
+ }
+ if (strcmp(key, "scroll") == 0) {
+ n->scroll = (int)v;
+ bk_relayout(n);
+ return 1;
+ }
+ if (strcmp(key, "scroll_x") == 0) {
+ n->scroll_x = (int)v;
+ bk_relayout(n);
+ return 1;
+ }
+ if (strcmp(key, "selmode") == 0) {
+ n->selmode = (int)v;
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "font_scale") == 0) {
+ n->font_scale = (float)v;
+ bk_relayout(n);
+ return 1;
+ }
+ if (strcmp(key, "cursor") == 0) { /* < 0: back to the class cursor */
+ n->cursor_override = v < 0 ? 0 : (int)v + 1;
+ return 1;
+ }
+ if (strcmp(key, "current") == 0) {
+ n->current = (int)v;
+ bk_relayout(n);
+ return 1;
+ }
+ if (strcmp(key, "icon") == 0) {
+ n->icon = (int)v;
+ bk_relayout(n);
+ return 1;
+ }
+ return 0;
+}
+
+double BK_get_num(BKNode *n, const char *key)
+{
+ double cv;
+ if (n->cls->get_num && n->cls->get_num(n, key, &cv)) {
+ return cv;
+ }
+ for (size_t i = 0; i < sizeof(g_flag_props) / sizeof(g_flag_props[0]); i++) {
+ if (strcmp(key, g_flag_props[i].key) == 0) {
+ return (n->flags & g_flag_props[i].flag) ? 1.0 : 0.0;
+ }
+ }
+ if (strcmp(key, "value") == 0) {
+ if (n->cls == &bk_cls_tabs || n->cls == &bk_cls_sidetabs) {
+ return n->current;
+ }
+ return n->value;
+ }
+ if (strcmp(key, "default") == 0) {
+ return n->defval;
+ }
+ if (strcmp(key, "min") == 0) {
+ return n->vmin;
+ }
+ if (strcmp(key, "max") == 0) {
+ return n->vmax;
+ }
+ if (strcmp(key, "step") == 0) {
+ return n->step;
+ }
+ if (strcmp(key, "factor") == 0) {
+ return n->factor;
+ }
+ if (strcmp(key, "weight") == 0) {
+ return n->weight;
+ }
+ if (strcmp(key, "scroll") == 0) {
+ return n->scroll;
+ }
+ if (strcmp(key, "scroll_x") == 0) {
+ return n->scroll_x;
+ }
+ if ((key[0] == 'x' || key[0] == 'y') && view_get_num(n, key, &cv)) {
+ return cv;
+ }
+ if (strcmp(key, "current") == 0) {
+ return n->current;
+ }
+ if (strcmp(key, "tile") == 0) {
+ return n->tile;
+ }
+ if (strcmp(key, "height") == 0) {
+ return n->height_units;
+ }
+ if (strcmp(key, "hot") == 0) {
+ return n->hot;
+ }
+ if (strcmp(key, "editing") == 0) {
+ return n->edit != NULL || n->dragmode == 99;
+ }
+ if (strcmp(key, "corners") == 0) {
+ return n->corners;
+ }
+ if (strcmp(key, "rename_row") == 0) {
+ return n->rename_row;
+ }
+ return 0.0;
+}
+
+/* A field being edited shows a programmatic text change (Tk's entry.delete /
+ * insert, validatecommand rejecting a keystroke). */
+static void edit_follow_text(BKNode *n)
+{
+ BKTextEdit *te = n->edit;
+ const char *s = n->text ? n->text : "";
+ if (!te || strcmp(te->text, s) == 0) {
+ return;
+ }
+ const int caret = te->caret;
+ BKTextEdit *fresh = bk_te_new(s, false);
+ memcpy(fresh->mask, te->mask, sizeof(te->mask));
+ fresh->caret = BK_MIN(caret, fresh->len);
+ fresh->anchor = -1;
+ bk_te_free(te);
+ n->edit = fresh;
+}
+
+int BK_set_str(BKNode *n, const char *key, const char *v)
+{
+ if (strcmp(key, "text") == 0 || strcmp(key, "title") == 0) {
+ bk_set_text(&n->text, v);
+ bk_relayout(n);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "value") == 0 && n->cls == &bk_cls_textarea) {
+ return bk_textarea_set_text(n, v);
+ }
+ if (strcmp(key, "value") == 0) { /* string-valued nodes */
+ bk_set_text(&n->text, v);
+ edit_follow_text(n);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "set_value") == 0) {
+ if (!bk_streq(n->text, v)) {
+ bk_undo_record(n, 1);
+ bk_set_text(&n->text, v);
+ edit_follow_text(n);
+ bk_changed(n);
+ }
+ return 1;
+ }
+ if (strcmp(key, "label") == 0) {
+ bk_set_text(&n->label, v);
+ bk_relayout(n);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "description") == 0) {
+ bk_set_text(&n->desc, v);
+ return 1;
+ }
+ if (strcmp(key, "placeholder") == 0) {
+ bk_set_text(&n->placeholder, v);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "mask") == 0) { /* one UTF-8 character, "" = plain */
+ memset(n->mask, 0, sizeof(n->mask));
+ strncpy(n->mask, v ? v : "", sizeof(n->mask) - 1);
+ if (n->edit) {
+ memcpy(n->edit->mask, n->mask, sizeof(n->mask));
+ }
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "suffix") == 0) {
+ bk_set_text(&n->suffix, v);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "icon") == 0) {
+ n->icon = bk_icons_lookup(v);
+ bk_relayout(n);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "icon_on") == 0) {
+ n->icon_on = bk_icons_lookup(v);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "text_align") == 0) {
+ n->align = str_align(v);
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+const char *BK_get_str(BKNode *n, const char *key)
+{
+ if (strcmp(key, "value") == 0 && n->cls == &bk_cls_textarea) {
+ return bk_textarea_text(n);
+ }
+ if (strcmp(key, "text") == 0 || strcmp(key, "value") == 0 || strcmp(key, "title") == 0) {
+ return n->text ? n->text : "";
+ }
+ if (strcmp(key, "label") == 0) {
+ return n->label ? n->label : "";
+ }
+ if (strcmp(key, "description") == 0) {
+ return n->desc ? n->desc : "";
+ }
+ if (strcmp(key, "edit") == 0) {
+ return n->edit ? n->edit->text : "";
+ }
+ if (strcmp(key, "type") == 0) {
+ return n->cls->name;
+ }
+ return "";
+}
+
+int BK_set_color(BKNode *n, const char *key, const float c[4])
+{
+ if (strcmp(key, "color") == 0 || strcmp(key, "value") == 0) {
+ for (int k = 0; k < 4; k++) { /* normals keep their sign */
+ n->color[k] = n->cls == &bk_cls_normal ? c[k] : BK_CLAMP(c[k], 0.0f, 1.0f);
+ }
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "bg") == 0) { /* frames / canvases */
+ memcpy(n->color, c, sizeof(float[4]));
+ n->flags = c[3] > 0 ? (n->flags | NF_HAS_BG) : (n->flags & ~NF_HAS_BG);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "set_value") == 0) {
+ float v[4];
+ for (int k = 0; k < 4; k++) {
+ v[k] = BK_CLAMP(c[k], 0.0f, 1.0f);
+ }
+ if (memcmp(v, n->color, sizeof(v)) != 0) {
+ bk_undo_record(n, 2);
+ memcpy(n->color, v, sizeof(v));
+ bk_changed(n);
+ }
+ return 1;
+ }
+ if (strcmp(key, "text_color") == 0) {
+ for (int k = 0; k < 4; k++) {
+ n->color_text[k] = (uchar)(BK_CLAMP(c[k], 0.0f, 1.0f) * 255.0f + 0.5f);
+ }
+ n->has_color_text = true;
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+int BK_get_color(BKNode *n, const char *key, float r[4])
+{
+ if (strcmp(key, "color") == 0 || strcmp(key, "value") == 0) {
+ memcpy(r, n->color, sizeof(float[4]));
+ return 1;
+ }
+ return 0;
+}
+
+int BK_set_strs(BKNode *n, const char *key, const char *const *v, int count)
+{
+ if (strcmp(key, "headers") == 0) { /* tree/table column headers */
+ bk_strs_set(&n->shortcuts, v, count);
+ bk_relayout(n);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "items") == 0) {
+ bk_strs_set(&n->items, v, count);
+ if (n->value >= count) {
+ n->value = count > 0 ? count - 1 : 0;
+ }
+ bk_relayout(n);
+ bk_invalidate(n);
+ return 1;
+ }
+ if (strcmp(key, "icons") == 0) {
+ bk_strs_set(&n->item_icons_s, v, count);
+ free(n->item_icons);
+ n->item_icons = (int *)calloc((size_t)BK_MAX(1, count), sizeof(int));
+ for (int i = 0; i < count; i++) {
+ n->item_icons[i] = bk_icons_lookup(v[i]);
+ }
+ if (n->cls == &bk_cls_tree) {
+ bk_tree_columns_from_icons(n); /* (off, on) icon pairs per toggle column */
+ }
+ bk_relayout(n);
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+int BK_strs_count(BKNode *n, const char *key)
+{
+ return strcmp(key, "items") == 0 ? n->items.n : 0;
+}
+
+const char *BK_strs_get(BKNode *n, const char *key, int i)
+{
+ if (strcmp(key, "items") == 0 && i >= 0 && i < n->items.n) {
+ return n->items.v[i];
+ }
+ return "";
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Context: damage, popups, services
+ * \{ */
+
+BKContext *BK_context_new(BKNode *root)
+{
+ BKContext *ctx = (BKContext *)calloc(1, sizeof(BKContext));
+ ctx->root = root;
+ ctx->cursor = BK_CURSOR_DEFAULT;
+ ctx->layout_dirty = true;
+ ctx->full_dirty = true;
+ if (root) {
+ root->ctx_root = ctx;
+ }
+ return ctx;
+}
+
+void BK_context_free(BKContext *ctx)
+{
+ if (!ctx) {
+ return;
+ }
+ BK_close_popups(ctx);
+ for (int i = 0; i < ctx->nkeys; i++) {
+ bk_release(ctx->keys[i].ref);
+ }
+ if (ctx->root) {
+ ctx->root->ctx_root = NULL;
+ }
+ if (ctx->header) {
+ ctx->header->ctx_root = NULL;
+ }
+ free(ctx);
+}
+
+void BK_context_set_host(BKContext *ctx, const BKHost *host)
+{
+ ctx->host = *host;
+}
+
+void BK_context_set_header(BKContext *ctx, BKNode *header)
+{
+ if (ctx->header) {
+ ctx->header->ctx_root = NULL;
+ }
+ ctx->header = header;
+ if (header) {
+ header->ctx_root = ctx;
+ }
+ ctx->layout_dirty = true;
+}
+
+BKNode *BK_context_root(BKContext *ctx)
+{
+ return ctx->root;
+}
+
+void bk_ctx_request(BKContext *ctx)
+{
+ if (ctx->host.request) {
+ ctx->host.request(ctx->host.data);
+ }
+}
+
+static bool rect_overlap(const BKRect *a, const BKRect *b)
+{
+ return a->xmin < b->xmax && b->xmin < a->xmax && a->ymin < b->ymax && b->ymin < a->ymax;
+}
+
+static void rect_union(BKRect *a, const BKRect *b)
+{
+ a->xmin = BK_MIN(a->xmin, b->xmin);
+ a->ymin = BK_MIN(a->ymin, b->ymin);
+ a->xmax = BK_MAX(a->xmax, b->xmax);
+ a->ymax = BK_MAX(a->ymax, b->ymax);
+}
+
+void bk_ctx_dirty_rect(BKContext *ctx, BKRect r)
+{
+ if (r.xmax <= r.xmin || r.ymax <= r.ymin) {
+ return;
+ }
+ bk_ctx_request(ctx);
+ if (ctx->full_dirty) {
+ return;
+ }
+ for (int i = 0; i < ctx->ndirty; i++) {
+ if (rect_overlap(&ctx->dirty[i], &r)) {
+ rect_union(&ctx->dirty[i], &r);
+ return;
+ }
+ }
+ if (ctx->ndirty == BK_MAX_DIRTY) {
+ for (int i = 1; i < ctx->ndirty; i++) {
+ rect_union(&ctx->dirty[0], &ctx->dirty[i]);
+ }
+ rect_union(&ctx->dirty[0], &r);
+ ctx->ndirty = 1;
+ return;
+ }
+ ctx->dirty[ctx->ndirty++] = r;
+}
+
+static bool is_within(const BKNode *n, const BKNode *subtree)
+{
+ for (; n; n = n->parent) {
+ if (n == subtree) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static void undo_forget(BKContext *ctx, BKNode *subtree);
+
+void bk_forget(BKContext *ctx, BKNode *subtree)
+{
+ undo_forget(ctx, subtree);
+ for (int i = ctx->nanim - 1; i >= 0; i--) {
+ if (is_within(ctx->anim[i], subtree)) {
+ ctx->anim[i] = ctx->anim[--ctx->nanim];
+ }
+ }
+ for (int i = 0; i < ctx->nmulti; i++) {
+ if (is_within(ctx->multi[i], subtree)) {
+ ctx->nmulti = 0;
+ break;
+ }
+ }
+ if (ctx->hover && is_within(ctx->hover, subtree)) {
+ ctx->hover = NULL;
+ }
+ if (ctx->grab && is_within(ctx->grab, subtree)) {
+ ctx->grab = NULL;
+ }
+ if (ctx->focus && is_within(ctx->focus, subtree)) {
+ BKNode *f = ctx->focus;
+ ctx->focus = NULL;
+ bk_te_free(f->edit);
+ f->edit = NULL;
+ }
+ if (ctx->modal && is_within(ctx->modal, subtree)) {
+ ctx->modal = NULL;
+ }
+ if (ctx->tip_node && is_within(ctx->tip_node, subtree)) {
+ ctx->tip_node = NULL;
+ ctx->tip_shown = 0;
+ }
+ if (ctx->last_click_node && is_within(ctx->last_click_node, subtree)) {
+ ctx->last_click_node = NULL;
+ }
+ /* popups owned by the subtree */
+ for (int i = 0; i < ctx->npopups; i++) {
+ if (ctx->popups[i]->parent && is_within(ctx->popups[i]->parent, subtree)) {
+ bk_close_popups_after(ctx, i > 0 ? ctx->popups[i - 1] : NULL);
+ break;
+ }
+ }
+}
+
+int bk_popup_index(BKContext *ctx, const BKNode *popup)
+{
+ for (int i = 0; i < ctx->npopups; i++) {
+ if (ctx->popups[i] == popup) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+bool bk_owns_popup(BKContext *ctx, const BKNode *owner)
+{
+ if (!ctx) {
+ return false;
+ }
+ for (int i = 0; i < ctx->npopups; i++) {
+ if (ctx->popups[i]->parent == owner) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static void free_popup(BKNode *p)
+{
+ if (p->cls == &bk_cls_menu || p->cls == &bk_cls_pie) {
+ bk_menu_on_close(p);
+ }
+ p->parent = NULL;
+ BK_node_free(p);
+}
+
+void bk_close_popups_after(BKContext *ctx, BKNode *after)
+{
+ const int keep = after ? bk_popup_index(ctx, after) + 1 : 0;
+ while (ctx->npopups > keep) {
+ BKNode *p = ctx->popups[--ctx->npopups];
+ bk_invalidate(p);
+ /* clear references into the popup before freeing it */
+ if (ctx->hover && is_within(ctx->hover, p)) {
+ ctx->hover = NULL;
+ }
+ if (ctx->grab && is_within(ctx->grab, p)) {
+ ctx->grab = NULL;
+ }
+ if (ctx->focus && is_within(ctx->focus, p)) {
+ BKNode *f = ctx->focus;
+ ctx->focus = NULL;
+ bk_te_free(f->edit);
+ f->edit = NULL;
+ }
+ if (ctx->tip_node && is_within(ctx->tip_node, p)) {
+ ctx->tip_node = NULL;
+ ctx->tip_shown = 0;
+ }
+ if (ctx->last_click_node && is_within(ctx->last_click_node, p)) {
+ ctx->last_click_node = NULL;
+ }
+ if (ctx->modal && is_within(ctx->modal, p)) {
+ ctx->modal = NULL;
+ }
+ /* The popover panel's body belongs to its owner, not the popup. */
+ if (p->cls == &bk_cls_popover_panel && p->nkids) {
+ BKNode *body = p->kids[0];
+ p->nkids = 0;
+ body->parent = p->parent;
+ }
+ BKNode *owner = p->parent;
+ free_popup(p);
+ if (owner) {
+ bk_invalidate(owner);
+ }
+ }
+ ctx->layout_dirty = ctx->layout_dirty; /* no relayout needed */
+ bk_ctx_request(ctx);
+}
+
+void BK_close_popups(BKContext *ctx)
+{
+ bk_close_popups_after(ctx, NULL);
+}
+
+void bk_open_popup(BKContext *ctx, BKNode *popup, BKNode *owner, BKNode *parent_popup)
+{
+ if (!parent_popup) { /* opened from inside a popup: nest under it */
+ for (const BKNode *nd = owner; nd && !parent_popup; nd = nd->parent) {
+ if (bk_popup_index(ctx, nd) >= 0) {
+ parent_popup = (BKNode *)nd;
+ }
+ }
+ }
+ if (parent_popup && bk_popup_index(ctx, parent_popup) >= 0) {
+ bk_close_popups_after(ctx, parent_popup);
+ }
+ else {
+ BK_close_popups(ctx);
+ }
+ if (ctx->npopups == BK_MAX_POPUPS) {
+ BK_node_free(popup);
+ return;
+ }
+ popup->parent = owner ? owner : ctx->root;
+ ctx->popups[ctx->npopups++] = popup;
+ ctx->tip_serial++;
+ if (ctx->tip_shown) {
+ ctx->tip_shown = 0;
+ bk_ctx_dirty_rect(ctx, ctx->tip_rect);
+ }
+ if (ctx->win_w > 0) {
+ bk_popup_place(popup, ctx->win_w, ctx->win_h);
+ }
+ bk_invalidate(popup);
+ if (owner) {
+ bk_invalidate(owner);
+ }
+}
+
+int BK_popup_count(BKContext *ctx)
+{
+ return ctx->npopups;
+}
+BKNode *BK_popup(BKContext *ctx, int i)
+{
+ return (i >= 0 && i < ctx->npopups) ? ctx->popups[i] : NULL;
+}
+BKNode *BK_popup_owner(BKContext *ctx, int i)
+{
+ return (i >= 0 && i < ctx->npopups) ? ctx->popups[i]->parent : NULL;
+}
+
+void bk_start_drag_toggle(BKContext *ctx, int group, int value)
+{
+ ctx->dt_group = group;
+ ctx->dt_value = value;
+ ctx->dt_active = 1;
+}
+
+static void update_cursor(BKContext *ctx);
+
+void bk_begin_modal(BKContext *ctx, BKNode *tool)
+{
+ if (!tool->parent) {
+ tool->parent = ctx->root;
+ }
+ ctx->modal = tool;
+ update_cursor(ctx);
+ bk_ctx_request(ctx);
+}
+
+void bk_end_modal(BKContext *ctx)
+{
+ BKNode *m = ctx->modal;
+ ctx->modal = NULL;
+ if (m) {
+ m->parent = NULL;
+ BK_node_free(m);
+ }
+ update_cursor(ctx);
+ bk_ctx_request(ctx);
+}
+
+static char *g_clipboard = NULL; /* fallback when the host has none */
+
+char *bk_clipboard_get(BKContext *ctx)
+{
+ if (ctx && ctx->host.clipboard_get) {
+ char *s = ctx->host.clipboard_get(ctx->host.data);
+ if (s) {
+ return s;
+ }
+ }
+ return bk_strdup(g_clipboard ? g_clipboard : "");
+}
+
+void bk_clipboard_set(BKContext *ctx, const char *s)
+{
+ bk_set_text(&g_clipboard, s);
+ if (ctx && ctx->host.clipboard_set) {
+ ctx->host.clipboard_set(ctx->host.data, s);
+ }
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Rendering
+ * \{ */
+
+static void layout(BKContext *ctx)
+{
+ g_gen++;
+ const int w = ctx->win_w, h = ctx->win_h;
+ int hw = 0, hh = 0;
+ if (ctx->header) {
+ bk_natural(ctx->header, &hw, &hh);
+ }
+ ctx->header_h = hh;
+ int cw = 0, ch = 0;
+ if (ctx->root) {
+ bk_natural(ctx->root, &cw, &ch);
+ }
+ ctx->content_h = ch;
+ const int view_h = h - hh;
+ ctx->scroll = BK_CLAMP(ctx->scroll, 0, BK_MAX(0, ch - view_h));
+ if (ctx->root) {
+ bk_arrange(ctx->root, 0, hh - ctx->scroll, w, BK_MAX(ch, view_h));
+ }
+ if (ctx->header) {
+ bk_arrange(ctx->header, 0, 0, w, hh);
+ }
+ for (int i = 0; i < ctx->npopups; i++) {
+ bk_popup_place(ctx->popups[i], w, h);
+ }
+ ctx->layout_dirty = false;
+}
+
+static void tooltip_rect(BKContext *ctx, BKRect *r_rect)
+{
+ const BKNode *n = ctx->tip_node;
+ const char *desc = n && n->desc ? n->desc : "";
+ const int u = bk_unit(), p = bk_pad();
+ int lines = 1;
+ float w = 0.0f;
+ const char *s = desc;
+ while (1) {
+ const char *nl = strchr(s, '\n');
+ const int len = nl ? (int)(nl - s) : (int)strlen(s);
+ w = BK_MAX(w, bk_text_width(s, len, false));
+ if (!nl) {
+ break;
+ }
+ lines++;
+ s = nl + 1;
+ }
+ const int tw = (int)w + 2 * p, th = lines * u + p / 2;
+ int tx = BK_MAX(0, BK_MIN(ctx->tip_x - tw / 4, ctx->win_w - tw));
+ int ty = ctx->tip_y + (int)(0.9f * u);
+ if (ty + th > ctx->win_h) {
+ ty = BK_MAX(0, ctx->tip_y - th - (int)(0.4f * u));
+ }
+ *r_rect = bk_rect(tx, ty, tw, th);
+}
+
+static void draw_tooltip(BKContext *ctx)
+{
+ if (!ctx->tip_shown || !ctx->tip_node || !ctx->tip_node->desc) {
+ return;
+ }
+ const BKRect r = ctx->tip_rect;
+ bk_widget_tooltip_back(&r);
+ const int u = bk_unit(), p = bk_pad();
+ const char *s = ctx->tip_node->desc;
+ int line = 0;
+ while (1) {
+ const char *nl = strchr(s, '\n');
+ const int len = nl ? (int)(nl - s) : (int)strlen(s);
+ BKRect lr = bk_rect(r.xmin, r.ymin + p / 4 + line * u, bk_rw(&r), u);
+ uchar c[4];
+ memcpy(c, bk_theme.tooltip.text, 4);
+ if (line > 0) {
+ c[3] = (uchar)(c[3] * 0.65f); /* details are dimmer than the title */
+ }
+ char buf[256];
+ const int bl = BK_MIN(len, 255);
+ memcpy(buf, s, (size_t)bl);
+ buf[bl] = 0;
+ bk_text_in(&lr, buf, c, BK_ALIGN_LEFT, false);
+ if (!nl) {
+ break;
+ }
+ s = nl + 1;
+ line++;
+ }
+}
+
+static void draw_region(BKContext *ctx, const BKRect *rect)
+{
+ const int w = ctx->win_w, h = ctx->win_h;
+ bk_clip_reset(w, h);
+ bk_clip_push(rect->xmin, rect->ymin, bk_rw(rect), bk_rh(rect));
+ bk_fill(rect->xmin, rect->ymin, bk_rw(rect), bk_rh(rect), bk_theme.region_bg);
+ const int top = ctx->header_h, view_h = h - top;
+ bk_clip_push(0, top, w, view_h);
+ if (ctx->root) {
+ bk_draw_tree(ctx->root);
+ }
+ bk_clip_pop();
+ if (ctx->header) {
+ bk_draw_tree(ctx->header);
+ }
+ if (ctx->content_h > view_h) { /* region scrollbar */
+ const int sb = BK_MAX(2, (int)(0.15f * bk_unit()));
+ const float th = BK_MAX((float)bk_unit(), (float)view_h * view_h / ctx->content_h);
+ const float ty = top + (view_h - th) * ctx->scroll / (float)(ctx->content_h - view_h);
+ float c[4];
+ bk_rgba(bk_theme.scroll.item, c);
+ bk_roundbox(w - sb - 2, ty, sb, th, sb * 0.5f, CNR_ALL, c);
+ }
+ for (int i = 0; i < ctx->npopups; i++) {
+ bk_draw_tree(ctx->popups[i]);
+ }
+ draw_tooltip(ctx);
+ bk_clip_reset(w, h);
+}
+
+int BK_needs_render(BKContext *ctx)
+{
+ return ctx->layout_dirty || ctx->full_dirty || ctx->ndirty > 0;
+}
+
+static void anim_step(BKContext *ctx);
+
+int BK_render(BKContext *ctx, BuiRaster *r, int w, int h, int full)
+{
+ bk_draw.r = r;
+ ctx->raster = r;
+ anim_step(ctx);
+ if (w != ctx->win_w || h != ctx->win_h || BUI_raster_width(r) != w ||
+ BUI_raster_height(r) != h)
+ {
+ ctx->win_w = w;
+ ctx->win_h = h;
+ ctx->layout_dirty = true;
+ }
+ if (full || ctx->layout_dirty) {
+ ctx->full_dirty = true;
+ }
+ if (ctx->layout_dirty) {
+ layout(ctx);
+ }
+ bk_views_check(ctx);
+ if (ctx->layout_dirty) { /* a scroll command changed the layout */
+ layout(ctx);
+ }
+ if (!ctx->full_dirty && ctx->ndirty == 0) {
+ return 0;
+ }
+ BUI_raster_begin_frame(r, w, h);
+ int regions;
+ if (ctx->full_dirty) {
+ const BKRect all = bk_rect(0, 0, w, h);
+ draw_region(ctx, &all);
+ BUI_raster_end_frame(r);
+ regions = 1;
+ }
+ else {
+ BKRect bbox = ctx->dirty[0];
+ for (int i = 0; i < ctx->ndirty; i++) {
+ BKRect d = ctx->dirty[i];
+ d.xmin = BK_MAX(d.xmin, 0);
+ d.ymin = BK_MAX(d.ymin, 0);
+ d.xmax = BK_MIN(d.xmax, w);
+ d.ymax = BK_MIN(d.ymax, h);
+ if (d.xmax > d.xmin && d.ymax > d.ymin) {
+ draw_region(ctx, &d);
+ }
+ rect_union(&bbox, &ctx->dirty[i]);
+ }
+ BUI_raster_end_frame_region(r, bbox.xmin, bbox.ymin, bk_rw(&bbox), bk_rh(&bbox));
+ regions = ctx->ndirty;
+ }
+ ctx->full_dirty = false;
+ ctx->ndirty = 0;
+ return regions;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Input
+ * \{ */
+
+#define DOUBLE_CLICK_S 0.35
+#define DOUBLE_CLICK_PX 4
+#define TOOLTIP_DELAY_MS 600
+
+static BKNode *hit_all(BKContext *ctx, int x, int y)
+{
+ for (int i = ctx->npopups - 1; i >= 0; i--) {
+ if (bk_contains(ctx->popups[i], x, y)) {
+ return bk_hit(ctx->popups[i], x, y);
+ }
+ }
+ if (ctx->header && bk_contains(ctx->header, x, y)) {
+ return bk_hit(ctx->header, x, y);
+ }
+ if (y < ctx->header_h) {
+ return NULL;
+ }
+ return ctx->root ? bk_hit(ctx->root, x, y) : NULL;
+}
+
+static BKEvent make_event(BKContext *ctx, BKNode *target, int x, int y, int mods)
+{
+ BKEvent e;
+ memset(&e, 0, sizeof(e));
+ e.x = x;
+ e.y = y;
+ e.mods = mods;
+ if (target) {
+ e.lx = x - target->x;
+ e.ly = y - target->y;
+ e.inside = bk_contains(target, x, y);
+ }
+ e.dx = x - ctx->press_x;
+ e.dy = y - ctx->press_y;
+ e.dragged = ctx->dragging;
+ e.text = "";
+ e.keysym = "";
+ return e;
+}
+
+static int hide_tooltip(BKContext *ctx)
+{
+ ctx->tip_serial++;
+ if (ctx->tip_shown) {
+ ctx->tip_shown = 0;
+ bk_ctx_dirty_rect(ctx, bk_rect(ctx->tip_rect.xmin - 12, ctx->tip_rect.ymin - 12,
+ bk_rw(&ctx->tip_rect) + 24, bk_rh(&ctx->tip_rect) + 24));
+ return 1;
+ }
+ return 0;
+}
+
+static void arm_tooltip(BKContext *ctx, BKNode *target, int x, int y)
+{
+ ctx->tip_serial++;
+ if (!target || !target->desc || !target->desc[0] || !ctx->host.schedule) {
+ return;
+ }
+ ctx->tip_node = target;
+ ctx->tip_x = x;
+ ctx->tip_y = y;
+ ctx->host.schedule(ctx->host.data, TOOLTIP_DELAY_MS, ctx->tip_serial);
+}
+
+void BK_timer(BKContext *ctx, int timer)
+{
+ if (timer == ctx->tip_serial && ctx->tip_node && ctx->hover == ctx->tip_node && !ctx->grab &&
+ !ctx->tip_shown)
+ {
+ ctx->tip_shown = 1;
+ tooltip_rect(ctx, &ctx->tip_rect);
+ bk_ctx_dirty_rect(ctx, bk_rect(ctx->tip_rect.xmin - 12, ctx->tip_rect.ymin - 12,
+ bk_rw(&ctx->tip_rect) + 24, bk_rh(&ctx->tip_rect) + 24));
+ }
+}
+
+static void set_hover(BKContext *ctx, BKNode *n)
+{
+ if (n == ctx->hover) {
+ return;
+ }
+ BKNode *old = ctx->hover;
+ ctx->hover = n;
+ if (old) {
+ if (old->cls->leave) {
+ old->cls->leave(old);
+ }
+ bk_invalidate(old);
+ bk_event(old, BK_EV_LEAVE, 0, NULL);
+ }
+ if (n) {
+ bk_invalidate(n);
+ bk_event(n, BK_EV_ENTER, 0, NULL);
+ }
+}
+
+static void update_cursor(BKContext *ctx)
+{
+ int name;
+ if (ctx->modal) {
+ name = ctx->modal->cls->cursor ? ctx->modal->cls->cursor : BK_CURSOR_CROSSHAIR;
+ }
+ else if (ctx->grab && ctx->dragging && ctx->grab->cls->drag_cursor) {
+ name = ctx->grab->cls->drag_cursor;
+ }
+ else {
+ BKNode *n = ctx->grab ? ctx->grab : ctx->hover;
+ name = BK_CURSOR_DEFAULT;
+ if (n && n->cursor_override) {
+ name = n->cursor_override - 1;
+ }
+ else if (n && NODE_ENABLED(n)) {
+ name = n->cls->cursor_at ? n->cls->cursor_at(n, ctx->pointer_x, ctx->pointer_y) :
+ n->cls->cursor;
+ }
+ }
+ if (name != ctx->cursor) {
+ ctx->cursor = name;
+ if (ctx->host.set_cursor) {
+ ctx->host.set_cursor(ctx->host.data, name);
+ }
+ }
+}
+
+static bool continuous(BKContext *ctx)
+{
+ return ctx->host.warp && ctx->grab && ctx->dragging &&
+ ctx->grab->cls->drag_cursor == BK_CURSOR_NONE;
+}
+
+static void wrap_pointer(BKContext *ctx, int x, int y)
+{
+ const int e = 12, w = ctx->win_w, h = ctx->win_h;
+ if (w <= 2 * e || h <= 2 * e) {
+ return;
+ }
+ if (x > e && x < w - e && y > e && y < h - e) {
+ return;
+ }
+ int px = ctx->press_x - ctx->off_x, py = ctx->press_y - ctx->off_y;
+ px = BK_CLAMP(px, e + 1, w - e - 1);
+ py = BK_CLAMP(py, e + 1, h - e - 1);
+ ctx->off_x += x - px;
+ ctx->off_y += y - py;
+ ctx->skip_x = px;
+ ctx->skip_y = py;
+ ctx->has_skip = true;
+ ctx->host.warp(ctx->host.data, px, py);
+}
+
+void BK_set_pointer(BKContext *ctx, int x, int y)
+{
+ ctx->pointer_x = x;
+ ctx->pointer_y = y;
+}
+
+static int in_BK_motion(BKContext *ctx, int x, int y, int mods)
+{
+ if (ctx->has_skip) {
+ ctx->has_skip = false;
+ if (x == ctx->skip_x && y == ctx->skip_y) {
+ return 0; /* the warp we caused */
+ }
+ }
+ ctx->pointer_x = x;
+ ctx->pointer_y = y;
+ int changed = hide_tooltip(ctx);
+ if (ctx->modal) {
+ BKEvent e = make_event(ctx, ctx->modal, x, y, mods);
+ if (ctx->modal->cls->move) {
+ changed |= ctx->modal->cls->move(ctx->modal, &e);
+ }
+ update_cursor(ctx);
+ return changed;
+ }
+ if (ctx->grab) {
+ const int vx = x + ctx->off_x, vy = y + ctx->off_y;
+ const int threshold = BK_MAX(3, (int)(0.15f * bk_unit()));
+ if (!ctx->dragging &&
+ (abs(vx - ctx->press_x) > threshold || abs(vy - ctx->press_y) > threshold))
+ {
+ ctx->dragging = true;
+ update_cursor(ctx);
+ }
+ if (ctx->dragging) {
+ BKEvent e = make_event(ctx, ctx->grab, vx, vy, mods);
+ if (ctx->grab->cls->drag) {
+ changed |= ctx->grab->cls->drag(ctx->grab, &e);
+ }
+ if (ctx->grab) {
+ bk_event(ctx->grab, BK_EV_MOTION, mods, &e);
+ }
+ }
+ if (!ctx->grab) { /* the drag handler may have closed things */
+ return 1;
+ }
+ BKNode *under = hit_all(ctx, x, y);
+ if (ctx->dt_active && under && under->cls->drag_group == ctx->dt_group &&
+ NODE_ENABLED(under) && under != ctx->grab)
+ {
+ if ((int)(under->value != 0) != ctx->dt_value) { /* Blender: drag across toggles */
+ if (under->cls->drag_group == DRAG_GROUP_PANEL) {
+ if (!bk_anim_running(under)) {
+ under->anim = (under->flags & NF_COLLAPSED) ? 0.0f : 1.0f;
+ }
+ under->flags = ctx->dt_value ? (under->flags & ~NF_COLLAPSED) :
+ (under->flags | NF_COLLAPSED);
+ under->value = ctx->dt_value;
+ bk_anim_start(under);
+ bk_relayout(under);
+ }
+ else {
+ bk_set_value(under, ctx->dt_value);
+ }
+ changed = 1;
+ }
+ }
+ if (under != ctx->hover) {
+ set_hover(ctx, under);
+ changed = 1;
+ }
+ if (continuous(ctx)) {
+ wrap_pointer(ctx, x, y);
+ }
+ return changed;
+ }
+ BKNode *under = hit_all(ctx, x, y);
+ if (under != ctx->hover) {
+ set_hover(ctx, under);
+ changed = 1;
+ }
+ if (under) {
+ BKEvent e = make_event(ctx, under, x, y, mods);
+ if (under->cls->move) {
+ changed |= under->cls->move(under, &e);
+ }
+ bk_event(under, BK_EV_MOTION, mods, &e);
+ }
+ arm_tooltip(ctx, under, x, y);
+ update_cursor(ctx);
+ return changed;
+}
+
+static int in_BK_press(BKContext *ctx, int x, int y, int mods)
+{
+ hide_tooltip(ctx);
+ ctx->pointer_x = x;
+ ctx->pointer_y = y;
+ ctx->press_x = x;
+ ctx->press_y = y;
+ ctx->dragging = false;
+ ctx->off_x = ctx->off_y = 0;
+ if (ctx->modal) {
+ BKEvent e = make_event(ctx, ctx->modal, x, y, mods);
+ if (ctx->modal->cls->press) {
+ ctx->modal->cls->press(ctx->modal, &e);
+ }
+ update_cursor(ctx);
+ return 1;
+ }
+ if (ctx->npopups) {
+ bool inside = false;
+ for (int i = 0; i < ctx->npopups; i++) {
+ inside |= bk_contains(ctx->popups[i], x, y);
+ }
+ if (!inside) {
+ BK_close_popups(ctx); /* Blender: an outside click only closes menus */
+ ctx->hover = NULL;
+ update_cursor(ctx);
+ return 1;
+ }
+ }
+ BKNode *target = hit_all(ctx, x, y);
+ if (ctx->focus && target != ctx->focus) {
+ end_edit(ctx, true);
+ }
+ set_hover(ctx, target);
+ if (!target || !NODE_ENABLED(target)) {
+ ctx->grab = NULL; /* disabled components get no drags either */
+ return 1;
+ }
+ ctx->grab = target;
+ ctx->interaction++;
+ bk_invalidate(target);
+ BKEvent e = make_event(ctx, target, x, y, mods);
+ const double now = bk_time();
+ if (ctx->last_click_node == target && now - ctx->last_click_t < DOUBLE_CLICK_S &&
+ abs(x - ctx->last_click_x) <= DOUBLE_CLICK_PX && abs(y - ctx->last_click_y) <= DOUBLE_CLICK_PX)
+ {
+ ctx->last_click_node = NULL;
+ bk_event(target, BK_EV_DOUBLE, mods, &e);
+ if (target->cls->dbl) {
+ target->cls->dbl(target, &e);
+ }
+ else if (target->cls->press) {
+ target->cls->press(target, &e);
+ }
+ }
+ else {
+ ctx->last_click_t = now;
+ ctx->last_click_node = target;
+ ctx->last_click_x = x;
+ ctx->last_click_y = y;
+ bk_event(target, BK_EV_PRESS, mods, &e);
+ if (target->cls->press) {
+ target->cls->press(target, &e);
+ }
+ }
+ update_cursor(ctx);
+ return 1;
+}
+
+static int in_BK_release(BKContext *ctx, int x, int y, int mods)
+{
+ if (ctx->modal) {
+ BKEvent e = make_event(ctx, ctx->modal, x, y, mods);
+ if (ctx->modal->cls->release) {
+ ctx->modal->cls->release(ctx->modal, &e);
+ }
+ return 1;
+ }
+ const bool was_continuous = continuous(ctx);
+ const int vx = x + ctx->off_x, vy = y + ctx->off_y;
+ BKNode *grab = ctx->grab;
+ ctx->dt_active = 0;
+ if (grab && NODE_ENABLED(grab)) {
+ BKEvent e = make_event(ctx, grab, vx, vy, mods);
+ if (grab->cls->release) {
+ grab->cls->release(grab, &e);
+ }
+ if (ctx->grab == grab) {
+ bk_event(grab, BK_EV_RELEASE, mods, &e);
+ }
+ }
+ /* The handler may have closed (freed) popups; that clears ctx->grab when
+ * it pointed into them, so re-read it. */
+ grab = ctx->grab;
+ ctx->grab = NULL;
+ if (grab) {
+ bk_invalidate(grab);
+ }
+ if (ctx->dragging && bk_popup_index(ctx, grab) < 0) {
+ /* Blender: press a menu button, drag onto an item, release to pick. */
+ for (int i = ctx->npopups - 1; i >= 0; i--) {
+ BKNode *p = ctx->popups[i];
+ if (bk_contains(p, x, y) && p != grab) {
+ BKEvent e = make_event(ctx, p, x, y, mods);
+ if (p->cls->release) {
+ p->cls->release(p, &e);
+ }
+ break;
+ }
+ }
+ }
+ ctx->dragging = false;
+ if (was_continuous) {
+ /* Blender puts the pointer back where the drag began. */
+ ctx->skip_x = ctx->press_x;
+ ctx->skip_y = ctx->press_y;
+ ctx->has_skip = true;
+ ctx->host.warp(ctx->host.data, ctx->press_x, ctx->press_y);
+ x = ctx->press_x;
+ y = ctx->press_y;
+ }
+ ctx->off_x = ctx->off_y = 0;
+ ctx->pointer_x = x;
+ ctx->pointer_y = y;
+ set_hover(ctx, hit_all(ctx, x, y));
+ update_cursor(ctx);
+ return 1;
+}
+
+static void raw_event(BKNode *n, int kind, int mods, const BKEvent *e, int button);
+
+static int in_BK_context_menu(BKContext *ctx, int x, int y, int mods)
+{
+ hide_tooltip(ctx);
+ if (ctx->modal) {
+ bk_end_modal(ctx);
+ return 1;
+ }
+ if (ctx->focus) {
+ end_edit(ctx, true);
+ }
+ BKNode *under = hit_all(ctx, x, y);
+ if (under && (under->flags & NF_EVENTS)) { /* <Button-3> bindings see it first */
+ BKEvent e = make_event(ctx, under, x, y, mods);
+ raw_event(under, BK_EV_PRESS, mods, &e, 3);
+ }
+ bool in_popup = false;
+ for (int i = 0; i < ctx->npopups; i++) {
+ in_popup |= bk_contains(ctx->popups[i], x, y);
+ }
+ BKNode *target = hit_all(ctx, x, y);
+ if (!in_popup) {
+ BK_close_popups(ctx);
+ }
+ for (BKNode *n = target; n; n = n->parent) {
+ if (!NODE_ENABLED(n) || bk_popup_index(ctx, n) >= 0) {
+ continue;
+ }
+ BKMenuSpec items[16];
+ int count = 0;
+ if (n->cls->context_items) {
+ count = n->cls->context_items(n, items, 16);
+ }
+ else if (n->cls->flags & CLS_VALUE) {
+ count = bk_value_context_items(n, items, 16);
+ }
+ if (count > 0) {
+ if (in_popup) {
+ BK_close_popups(ctx);
+ }
+ BK_open_menu(ctx, n, items, count, n->label && n->label[0] ? n->label : NULL, x, y);
+ return 1;
+ }
+ }
+ return 1;
+}
+
+static int key_mods_match(int mods, const BKKeyBinding *k)
+{
+ return (mods & (BK_SHIFT | BK_CTRL | BK_ALT)) == k->mods;
+}
+
+/* Blender: Ctrl+Z / Ctrl+Shift+Z (and Ctrl+Y) undo/redo UI edits */
+static int undo_key(BKContext *ctx, const char *keysym, int mods)
+{
+ if ((mods & BK_CTRL) && bk_keysym_is(keysym, "z")) {
+ return (mods & BK_SHIFT) ? BK_redo(ctx) : BK_undo(ctx);
+ }
+ if ((mods & BK_CTRL) && bk_keysym_is(keysym, "y")) {
+ return BK_redo(ctx);
+ }
+ return 0;
+}
+
+static int in_BK_key(BKContext *ctx, const char *text, const char *keysym, int mods)
+{
+ hide_tooltip(ctx);
+ BKEvent e = make_event(ctx, NULL, ctx->pointer_x, ctx->pointer_y, mods);
+ e.text = text ? text : "";
+ e.keysym = keysym ? keysym : "";
+ ctx->interaction++;
+ for (BKNode *n = ctx->focus ? ctx->focus : ctx->hover; n; n = n->parent) {
+ if (n->flags & NF_EVENTS) { /* Tk/Qt key bindings see the key first */
+ bk_event(n, BK_EV_KEY, mods, &e);
+ break;
+ }
+ }
+ if (ctx->modal) {
+ if (bk_keysym_is(e.keysym, "Escape")) {
+ bk_end_modal(ctx);
+ }
+ return 1;
+ }
+ if (ctx->focus) {
+ BKNode *f = ctx->focus;
+ if (f->cls->key && f->cls->key(f, &e)) {
+ return 1;
+ }
+ return undo_key(ctx, e.keysym, mods);
+ }
+ if (ctx->npopups) {
+ BKNode *top = ctx->popups[ctx->npopups - 1];
+ if (top->cls->key && top->cls->key(top, &e)) {
+ return 1;
+ }
+ if (bk_keysym_is(e.keysym, "Escape")) {
+ bk_close_popups_after(ctx, ctx->npopups > 1 ? ctx->popups[ctx->npopups - 2] : NULL);
+ return 1;
+ }
+ return 0;
+ }
+ for (BKNode *n = ctx->hover; n; n = n->parent) { /* bubble up to a handler */
+ if (!NODE_ENABLED(n)) {
+ continue;
+ }
+ if (n->cls->key) {
+ e.lx = e.x - n->x;
+ e.ly = e.y - n->y;
+ if (n->cls->key(n, &e)) {
+ return 1;
+ }
+ }
+ else if ((n->cls->flags & CLS_VALUE) && bk_value_key(n, &e)) {
+ return 1;
+ }
+ }
+ for (int i = 0; i < ctx->nkeys; i++) {
+ if (key_mods_match(mods, &ctx->keys[i]) && bk_keysym_is(e.keysym, ctx->keys[i].keysym)) {
+ if (ctx->host.emit) {
+ ctx->host.emit(ctx->host.data, NULL, BK_EV_CALL, ctx->keys[i].ref, 0, 0);
+ }
+ return 1;
+ }
+ }
+ return undo_key(ctx, e.keysym, mods);
+}
+
+static BKNode *deepest(BKNode *n, int x, int y)
+{
+ if (!NODE_VISIBLE(n) || !bk_contains(n, x, y)) {
+ return NULL;
+ }
+ for (int i = n->nkids - 1; i >= 0; i--) {
+ BKNode *f = deepest(n->kids[i], x, y);
+ if (f) {
+ return f;
+ }
+ }
+ return n;
+}
+
+static int in_BK_wheel(BKContext *ctx, int x, int y, int delta, int mods)
+{
+ hide_tooltip(ctx);
+ BKNode *target = hit_all(ctx, x, y);
+ if (!target && ctx->root && y >= ctx->header_h) {
+ target = deepest(ctx->root, x, y); /* non-interactive area: let containers scroll */
+ }
+ for (BKNode *n = target; n; n = n->parent) {
+ if (!NODE_ENABLED(n)) {
+ continue;
+ }
+ BKEvent e = make_event(ctx, n, x, y, mods);
+ e.delta = delta;
+ if (n == target) {
+ bk_event(n, BK_EV_WHEEL, mods, &e);
+ }
+ if (n->cls->wheel ? n->cls->wheel(n, &e) :
+ ((n->cls->flags & CLS_VALUE) && bk_value_wheel(n, &e)))
+ {
+ return 1;
+ }
+ }
+ /* scroll the region */
+ const int view_h = ctx->win_h - ctx->header_h;
+ if (ctx->content_h > view_h && !ctx->npopups) {
+ const int ns = BK_CLAMP(ctx->scroll - delta * 2 * bk_unit(), 0, ctx->content_h - view_h);
+ if (ns != ctx->scroll) {
+ ctx->scroll = ns;
+ ctx->layout_dirty = true;
+ bk_ctx_request(ctx);
+ return 1;
+ }
+ }
+ return 0;
+}
+
+void BK_bind(BKContext *ctx, const char *combo, void *ref)
+{
+ if (ctx->nkeys == BK_MAX_KEYS) {
+ return;
+ }
+ BKKeyBinding *k = &ctx->keys[ctx->nkeys++];
+ memset(k, 0, sizeof(*k));
+ const char *s = combo;
+ while (1) {
+ const char *plus = strchr(s, '+');
+ if (!plus) {
+ break;
+ }
+ const int len = (int)(plus - s);
+ if (len == 4 && strncmp(s, "ctrl", 4) == 0) {
+ k->mods |= BK_CTRL;
+ }
+ else if (len == 5 && strncmp(s, "shift", 5) == 0) {
+ k->mods |= BK_SHIFT;
+ }
+ else if (len == 3 && strncmp(s, "alt", 3) == 0) {
+ k->mods |= BK_ALT;
+ }
+ s = plus + 1;
+ }
+ strncpy(k->keysym, s, sizeof(k->keysym) - 1);
+ k->ref = ref;
+ bk_retain(ref);
+}
+
+int BK_cursor(BKContext *ctx)
+{
+ return ctx->cursor;
+}
+BKNode *BK_hover(BKContext *ctx)
+{
+ return ctx->hover;
+}
+BKNode *BK_focus(BKContext *ctx)
+{
+ return ctx->focus;
+}
+
+void BK_focus_node(BKContext *ctx, BKNode *n)
+{
+ if (!n) {
+ if (ctx->focus) {
+ end_edit(ctx, true);
+ }
+ return;
+ }
+ if (n == ctx->focus || !NODE_ENABLED(n)) {
+ return;
+ }
+ if (n->cls == &bk_cls_textarea) {
+ if (ctx->focus) {
+ end_edit(ctx, true);
+ }
+ ctx->focus = n;
+ bk_invalidate(n);
+ }
+ else if ((n->cls == &bk_cls_text || n->cls == &bk_cls_search || n->cls == &bk_cls_number) &&
+ n->cls->activate)
+ {
+ n->cls->activate(n);
+ }
+}
+
+char *BK_clipboard_get(BKContext *ctx)
+{
+ return bk_clipboard_get(ctx);
+}
+
+void BK_clipboard_set(BKContext *ctx, const char *text)
+{
+ bk_clipboard_set(ctx, text);
+}
+int BK_modal_active(BKContext *ctx)
+{
+ return ctx->modal != NULL;
+}
+int BK_tooltip_visible(BKContext *ctx)
+{
+ return ctx->tip_shown;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Text editing (Blender's text button: ui_textedit_*)
+ * \{ */
+
+BKTextEdit *bk_te_new(const char *text, bool select_all)
+{
+ BKTextEdit *te = (BKTextEdit *)calloc(1, sizeof(BKTextEdit));
+ te->len = text ? (int)strlen(text) : 0;
+ te->cap = te->len + 64;
+ te->text = (char *)malloc((size_t)te->cap);
+ memcpy(te->text, text ? text : "", (size_t)te->len + 1);
+ te->caret = te->len;
+ te->anchor = select_all ? 0 : -1;
+ return te;
+}
+
+void bk_te_free(BKTextEdit *te)
+{
+ if (te) {
+ free(te->text);
+ free(te);
+ }
+}
+
+static bool te_selection(const BKTextEdit *te, int *a, int *b)
+{
+ if (te->anchor < 0 || te->anchor == te->caret) {
+ return false;
+ }
+ *a = BK_MIN(te->anchor, te->caret);
+ *b = BK_MAX(te->anchor, te->caret);
+ return true;
+}
+
+static void te_delete(BKTextEdit *te, int a, int b)
+{
+ memmove(te->text + a, te->text + b, (size_t)(te->len - b + 1));
+ te->len -= b - a;
+ te->caret = a;
+ te->anchor = -1;
+}
+
+static bool te_delete_selection(BKTextEdit *te)
+{
+ int a, b;
+ if (!te_selection(te, &a, &b)) {
+ return false;
+ }
+ te_delete(te, a, b);
+ return true;
+}
+
+static void te_insert(BKTextEdit *te, const char *s)
+{
+ te_delete_selection(te);
+ int n = (int)strlen(s);
+ if (te->len + n + 1 > te->cap) {
+ te->cap = te->len + n + 64;
+ te->text = (char *)realloc(te->text, (size_t)te->cap);
+ }
+ memmove(te->text + te->caret + n, te->text + te->caret, (size_t)(te->len - te->caret + 1));
+ memcpy(te->text + te->caret, s, (size_t)n);
+ /* no line breaks in single-line fields */
+ for (int i = 0; i < n; i++) {
+ if (te->text[te->caret + i] == '\n' || te->text[te->caret + i] == '\r') {
+ te->text[te->caret + i] = ' ';
+ }
+ }
+ te->len += n;
+ te->caret += n;
+ te->anchor = -1;
+}
+
+static void te_move(BKTextEdit *te, int to, bool extend)
+{
+ if (extend) {
+ if (te->anchor < 0) {
+ te->anchor = te->caret;
+ }
+ }
+ else {
+ te->anchor = -1;
+ }
+ te->caret = BK_CLAMP(to, 0, te->len);
+}
+
+static int te_step(BKTextEdit *te, int pos, bool next, bool word)
+{
+ BLI_str_cursor_step_utf8(te->text, te->len, &pos, next ? STRCUR_DIR_NEXT : STRCUR_DIR_PREV,
+ word ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE, true);
+ return pos;
+}
+
+int bk_te_key(BKTextEdit *te, BKContext *ctx, const char *text, const char *ks, int mods)
+{
+ const bool ctrl = mods & BK_CTRL, shift = mods & BK_SHIFT;
+ if (bk_keysym_is(ks, "ISO_Left_Tab")) { /* X11's Shift+Tab */
+ return TE_PREV;
+ }
+ if (bk_keysym_is(ks, "Tab")) {
+ return (mods & BK_SHIFT) ? TE_PREV : TE_NEXT; /* Blender: Tab edits the next field */
+ }
+ if (bk_keysym_is(ks, "Return") || bk_keysym_is(ks, "KP_Enter")) {
+ return TE_CONFIRM;
+ }
+ if (bk_keysym_is(ks, "Escape")) {
+ return TE_CANCEL;
+ }
+ int a, b;
+ const bool has_sel = te_selection(te, &a, &b);
+ if (ctrl && (bk_keysym_is(ks, "a") || bk_keysym_is(ks, "c") || bk_keysym_is(ks, "x") ||
+ bk_keysym_is(ks, "v")))
+ {
+ if (bk_keysym_is(ks, "a")) {
+ te->anchor = 0;
+ te->caret = te->len;
+ }
+ else if ((bk_keysym_is(ks, "c") || bk_keysym_is(ks, "x")) && has_sel) {
+ char *sel = (char *)malloc((size_t)(b - a + 1));
+ memcpy(sel, te->text + a, (size_t)(b - a));
+ sel[b - a] = 0;
+ bk_clipboard_set(ctx, sel);
+ free(sel);
+ if (bk_keysym_is(ks, "x")) {
+ te_delete_selection(te);
+ }
+ }
+ else if (bk_keysym_is(ks, "v")) {
+ char *clip = bk_clipboard_get(ctx);
+ if (clip) {
+ te_insert(te, clip);
+ free(clip);
+ }
+ }
+ return TE_CHANGED;
+ }
+ if (bk_keysym_is(ks, "Left")) {
+ if (has_sel && !shift) {
+ te_move(te, a, false);
+ }
+ else {
+ te_move(te, te_step(te, te->caret, false, ctrl), shift);
+ }
+ return TE_CHANGED;
+ }
+ if (bk_keysym_is(ks, "Right")) {
+ if (has_sel && !shift) {
+ te_move(te, b, false);
+ }
+ else {
+ te_move(te, te_step(te, te->caret, true, ctrl), shift);
+ }
+ return TE_CHANGED;
+ }
+ if (bk_keysym_is(ks, "Home") || bk_keysym_is(ks, "Up")) {
+ te_move(te, 0, shift);
+ return TE_CHANGED;
+ }
+ if (bk_keysym_is(ks, "End") || bk_keysym_is(ks, "Down")) {
+ te_move(te, te->len, shift);
+ return TE_CHANGED;
+ }
+ if (bk_keysym_is(ks, "BackSpace")) {
+ if (!te_delete_selection(te) && te->caret > 0) {
+ te_delete(te, te_step(te, te->caret, false, ctrl), te->caret);
+ }
+ return TE_CHANGED;
+ }
+ if (bk_keysym_is(ks, "Delete")) {
+ if (!te_delete_selection(te) && te->caret < te->len) {
+ const int c = te->caret;
+ te_delete(te, c, te_step(te, c, true, ctrl));
+ }
+ return TE_CHANGED;
+ }
+ if (text && (uchar)text[0] >= 0x20 && text[0] != 0x7f && !ctrl) {
+ te_insert(te, text);
+ return TE_CHANGED;
+ }
+ return TE_NONE;
+}
+
+int bk_te_index_at(BKTextEdit *te, float px)
+{
+ px += te->scroll;
+ float prev = 0.0f;
+ int i = 0;
+ while (i < te->len) {
+ int nx = i;
+ BLI_str_cursor_step_utf8(te->text, te->len, &nx, STRCUR_DIR_NEXT, STRCUR_JUMP_NONE, true);
+ const float w = bk_masked_width(te->text, nx, te->mask, false);
+ if (px < (prev + w) * 0.5f) {
+ return i;
+ }
+ prev = w;
+ i = nx;
+ }
+ return te->len;
+}
+
+void bk_te_click(BKTextEdit *te, float px, bool extend)
+{
+ te_move(te, bk_te_index_at(te, px), extend);
+}
+
+void bk_te_drag(BKTextEdit *te, float px)
+{
+ if (te->anchor < 0) {
+ te->anchor = te->caret;
+ }
+ te->caret = bk_te_index_at(te, px);
+}
+
+void bk_te_select_word(BKTextEdit *te, int index)
+{
+ int a, b;
+ BLI_str_cursor_step_bounds_utf8(te->text, te->len, BK_CLAMP(index, 0, te->len), &a, &b);
+ if (a == b) {
+ te->anchor = 0;
+ te->caret = te->len;
+ }
+ else {
+ te->anchor = a;
+ te->caret = b;
+ }
+}
+
+void bk_te_draw(BKTextEdit *te, const BKRect *rect, const uchar color[4])
+{
+ const int p = bk_pad();
+ const float inner = BK_MAX(1.0f, (float)(bk_rw(rect) - 2 * p));
+ const float caret_px = bk_masked_width(te->text, te->caret, te->mask, false);
+ if (caret_px - te->scroll > inner) {
+ te->scroll = caret_px - inner;
+ }
+ else if (caret_px - te->scroll < 0) {
+ te->scroll = caret_px;
+ }
+ const float tx = rect->xmin + p - te->scroll;
+ const int h = bk_rh(rect);
+ bk_clip_push(rect->xmin + 1, rect->ymin, bk_rw(rect) - 2, h);
+ int a, b;
+ if (te_selection(te, &a, &b)) {
+ const float sx = tx + bk_masked_width(te->text, a, te->mask, false);
+ const float sw = bk_masked_width(te->text, b, te->mask, false) -
+ bk_masked_width(te->text, a, te->mask, false);
+ const float m = 0.15f * h;
+ bk_fill(sx, rect->ymin + m, sw, h - 2 * m, bk_theme.selection);
+ }
+ if (te->mask[0]) {
+ char buf[1024];
+ bk_text(tx, bk_text_baseline(rect), buf, bk_mask_text(te->text, te->len, te->mask, buf,
+ sizeof(buf)),
+ color, false);
+ }
+ else {
+ bk_text(tx, bk_text_baseline(rect), te->text, te->len, color, false);
+ }
+ const float m = 0.2f * h;
+ bk_fill(floorf(tx + caret_px), rect->ymin + m, BK_MAX(1.0f, floorf(0.1f * bk_unit() + 0.5f)),
+ h - 2 * m, bk_theme.cursor);
+ bk_clip_pop();
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Number expressions ("2*pi", "1/3+2^2")
+ * \{ */
+
+typedef struct Parser {
+ const char *s;
+ bool err;
+} Parser;
+
+static void skip_ws(Parser *p)
+{
+ while (*p->s == ' ' || *p->s == '\t') {
+ p->s++;
+ }
+}
+
+static double parse_expr(Parser *p);
+
+static double parse_atom(Parser *p)
+{
+ skip_ws(p);
+ if (*p->s == '(') {
+ p->s++;
+ const double v = parse_expr(p);
+ skip_ws(p);
+ if (*p->s == ')') {
+ p->s++;
+ }
+ else {
+ p->err = true;
+ }
+ return v;
+ }
+ if (isalpha((uchar)*p->s)) {
+ char name[16];
+ int n = 0;
+ while (isalnum((uchar)*p->s) && n < 15) {
+ name[n++] = *p->s++;
+ }
+ name[n] = 0;
+ if (strcmp(name, "pi") == 0) {
+ return 3.14159265358979323846;
+ }
+ if (strcmp(name, "tau") == 0) {
+ return 6.28318530717958647692;
+ }
+ if (strcmp(name, "e") == 0) {
+ return 2.71828182845904523536;
+ }
+ /* functions */
+ skip_ws(p);
+ if (*p->s == '(') {
+ const double a = parse_atom(p);
+ if (strcmp(name, "sqrt") == 0) {
+ return sqrt(a);
+ }
+ if (strcmp(name, "sin") == 0) {
+ return sin(a);
+ }
+ if (strcmp(name, "cos") == 0) {
+ return cos(a);
+ }
+ if (strcmp(name, "tan") == 0) {
+ return tan(a);
+ }
+ if (strcmp(name, "abs") == 0) {
+ return fabs(a);
+ }
+ if (strcmp(name, "radians") == 0) {
+ return a * 3.14159265358979323846 / 180.0;
+ }
+ if (strcmp(name, "degrees") == 0) {
+ return a * 180.0 / 3.14159265358979323846;
+ }
+ }
+ p->err = true;
+ return 0.0;
+ }
+ char *end;
+ const double v = strtod(p->s, &end);
+ if (end == p->s) {
+ p->err = true;
+ return 0.0;
+ }
+ p->s = end;
+ return v;
+}
+
+static double parse_unary(Parser *p);
+
+static double parse_power(Parser *p)
+{
+ const double base = parse_atom(p);
+ skip_ws(p);
+ if ((p->s[0] == '*' && p->s[1] == '*') || p->s[0] == '^') {
+ p->s += p->s[0] == '^' ? 1 : 2;
+ return pow(base, parse_unary(p)); /* right associative */
+ }
+ return base;
+}
+
+static double parse_unary(Parser *p)
+{
+ skip_ws(p);
+ if (*p->s == '-') {
+ p->s++;
+ return -parse_unary(p);
+ }
+ if (*p->s == '+') {
+ p->s++;
+ return parse_unary(p);
+ }
+ return parse_power(p);
+}
+
+static double parse_term(Parser *p)
+{
+ double v = parse_unary(p);
+ while (!p->err) {
+ skip_ws(p);
+ const char c = *p->s;
+ if (c == '*' && p->s[1] != '*') {
+ p->s++;
+ v *= parse_unary(p);
+ }
+ else if (c == '/' && p->s[1] == '/') {
+ p->s += 2;
+ const double d = parse_unary(p);
+ if (d == 0.0) {
+ p->err = true;
+ return 0.0;
+ }
+ v = floor(v / d);
+ }
+ else if (c == '/') {
+ p->s++;
+ const double d = parse_unary(p);
+ if (d == 0.0) {
+ p->err = true;
+ return 0.0;
+ }
+ v /= d;
+ }
+ else if (c == '%') {
+ p->s++;
+ const double d = parse_unary(p);
+ if (d == 0.0) {
+ p->err = true;
+ return 0.0;
+ }
+ v = fmod(v, d);
+ }
+ else {
+ break;
+ }
+ }
+ return v;
+}
+
+static double parse_expr(Parser *p)
+{
+ double v = parse_term(p);
+ while (!p->err) {
+ skip_ws(p);
+ if (*p->s == '+') {
+ p->s++;
+ v += parse_term(p);
+ }
+ else if (*p->s == '-') {
+ p->s++;
+ v -= parse_term(p);
+ }
+ else {
+ break;
+ }
+ }
+ return v;
+}
+
+int BK_eval_number(const char *expr, double *r_value)
+{
+ Parser p = {expr, false};
+ const double v = parse_expr(&p);
+ skip_ws(&p);
+ if (p.err || *p.s != 0 || !isfinite(v)) {
+ return 0;
+ }
+ *r_value = v;
+ return 1;
+}
+
+/** \} */
+
+/* Public input entry points: mark the input scope (undo grouping) and report
+ * the view changes the event caused (scrollbars follow). */
+#define INPUT_ENTRY(call) \
+ ctx->in_input++; \
+ const int r = call; \
+ ctx->in_input--; \
+ bk_views_check(ctx); \
+ return r
+
+int BK_press(BKContext *ctx, int x, int y, int mods)
+{
+ INPUT_ENTRY(in_BK_press(ctx, x, y, mods));
+}
+
+int BK_release(BKContext *ctx, int x, int y, int mods)
+{
+ INPUT_ENTRY(in_BK_release(ctx, x, y, mods));
+}
+
+int BK_motion(BKContext *ctx, int x, int y, int mods)
+{
+ INPUT_ENTRY(in_BK_motion(ctx, x, y, mods));
+}
+
+int BK_wheel(BKContext *ctx, int x, int y, int delta, int mods)
+{
+ INPUT_ENTRY(in_BK_wheel(ctx, x, y, delta, mods));
+}
+
+int BK_key(BKContext *ctx, const char *text, const char *keysym, int mods)
+{
+ INPUT_ENTRY(in_BK_key(ctx, text, keysym, mods));
+}
+
+int BK_context_menu(BKContext *ctx, int x, int y, int mods)
+{
+ INPUT_ENTRY(in_BK_context_menu(ctx, x, y, mods));
+}
+
+int BK_key_release(BKContext *ctx, const char *keysym, int mods)
+{
+ BKEvent e = make_event(ctx, NULL, ctx->pointer_x, ctx->pointer_y, mods);
+ e.text = "";
+ e.keysym = keysym ? keysym : "";
+ for (BKNode *n = ctx->focus ? ctx->focus : ctx->hover; n; n = n->parent) {
+ if (n->flags & NF_EVENTS) {
+ char buf[96];
+ snprintf(buf, sizeof(buf), "\t%s", e.keysym);
+ bk_emit(n, BK_EV_KEYRELEASE, buf, mods, 0);
+ return 1;
+ }
+ }
+ return 0;
+}
+
+int BK_button(BKContext *ctx, int x, int y, int button, int release, int mods)
+{
+ BKNode *under = hit_all(ctx, x, y);
+ if (!under || !(under->flags & NF_EVENTS)) {
+ return 0;
+ }
+ BKEvent e = make_event(ctx, under, x, y, mods);
+ raw_event(under, release ? BK_EV_RELEASE : BK_EV_PRESS, mods, &e, button);
+ return 1;
+}
+
+/* -------------------------------------------------------------------- */
+/** \name Raw events, undo, animation, Tab order
+ * \{ */
+
+/* Raw events for host bindings (Tk's bind). Pointer events carry
+ * "state button" in `ref` so hosts can match <Control-Button-3> etc. */
+static void raw_event(BKNode *n, int kind, int mods, const BKEvent *e, int button)
+{
+ if (!(n->flags & NF_EVENTS)) {
+ return;
+ }
+ char buf[128];
+ if (kind == BK_EV_KEY && e) {
+ snprintf(buf, sizeof(buf), "%s\t%s", e->text ? e->text : "", e->keysym ? e->keysym : "");
+ bk_emit(n, kind, buf, mods, 0);
+ return;
+ }
+ snprintf(buf, sizeof(buf), "%d %d", mods, button);
+ if (kind == BK_EV_WHEEL && e) {
+ bk_emit(n, kind, buf, e->delta, 0);
+ return;
+ }
+ bk_emit(n, kind, buf, e ? e->x - n->x : 0, e ? e->y - n->y : 0);
+}
+
+void bk_event(BKNode *n, int kind, int mods, const BKEvent *e)
+{
+ raw_event(n, kind, mods, e, 1);
+}
+
+static const char *node_text(BKNode *n)
+{
+ return n->cls == &bk_cls_textarea ? bk_textarea_text(n) : (n->text ? n->text : "");
+}
+
+static void undo_entry_free(BKUndo *u)
+{
+ free(u->t[0]);
+ free(u->t[1]);
+ memset(u, 0, sizeof(*u));
+}
+
+void bk_undo_record(BKNode *n, int kind)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (!ctx || !ctx->in_input || ctx->in_undo) {
+ return;
+ }
+ for (const BKNode *p = n; p; p = p->parent) {
+ if (p->cls->flags & CLS_POPUP) {
+ return; /* popup internals (picker sliders): the owner records */
+ }
+ }
+ if (ctx->undo_pos > 0) {
+ const BKUndo *top = &ctx->undo[ctx->undo_pos - 1];
+ const int span = kind == 1 ? 24 : 0; /* a typing burst is one step */
+ if (top->node == n && ctx->interaction - top->interaction <= span) {
+ return; /* same interaction: keep the first "before" */
+ }
+ }
+ for (int i = ctx->undo_pos; i < ctx->nundo; i++) {
+ undo_entry_free(&ctx->undo[i]); /* drop the redo tail */
+ }
+ ctx->nundo = ctx->undo_pos;
+ if (ctx->nundo == BK_MAX_UNDO) {
+ undo_entry_free(&ctx->undo[0]);
+ memmove(ctx->undo, ctx->undo + 1, sizeof(BKUndo) * (BK_MAX_UNDO - 1));
+ memset(&ctx->undo[BK_MAX_UNDO - 1], 0, sizeof(BKUndo));
+ ctx->nundo--;
+ }
+ BKUndo *u = &ctx->undo[ctx->nundo++];
+ memset(u, 0, sizeof(*u));
+ u->node = n;
+ u->kind = kind;
+ u->interaction = ctx->interaction;
+ if (kind == 0) {
+ u->v[0] = n->value;
+ }
+ else if (kind == 1) {
+ u->t[0] = bk_strdup(node_text(n));
+ }
+ else {
+ memcpy(u->c[0], n->color, sizeof(float[4]));
+ }
+ ctx->undo_pos = ctx->nundo;
+}
+
+static void undo_capture(BKUndo *u, int slot)
+{
+ BKNode *n = u->node;
+ if (u->kind == 0) {
+ u->v[slot] = n->value;
+ }
+ else if (u->kind == 1) {
+ free(u->t[slot]);
+ u->t[slot] = bk_strdup(node_text(n));
+ }
+ else {
+ memcpy(u->c[slot], n->color, sizeof(float[4]));
+ }
+}
+
+static void undo_apply(BKContext *ctx, BKUndo *u, int slot)
+{
+ BKNode *n = u->node;
+ ctx->in_undo = 1;
+ if (u->kind == 0) {
+ bk_set_value(n, u->v[slot]);
+ }
+ else if (u->kind == 1) {
+ if (n->cls == &bk_cls_textarea) {
+ bk_textarea_set_text(n, u->t[slot]);
+ bk_emit(n, BK_EV_CHANGE, NULL, 0, 0);
+ }
+ else {
+ BK_set_str(n, "set_value", u->t[slot] ? u->t[slot] : "");
+ }
+ }
+ else {
+ BK_set_color(n, "set_value", u->c[slot]);
+ }
+ ctx->in_undo = 0;
+}
+
+int BK_undo(BKContext *ctx)
+{
+ if (ctx->undo_pos == 0) {
+ return 0;
+ }
+ const int group = ctx->undo[ctx->undo_pos - 1].interaction;
+ while (ctx->undo_pos > 0 && ctx->undo[ctx->undo_pos - 1].interaction == group) {
+ BKUndo *u = &ctx->undo[--ctx->undo_pos];
+ undo_capture(u, 1);
+ undo_apply(ctx, u, 0);
+ }
+ return 1;
+}
+
+int BK_redo(BKContext *ctx)
+{
+ if (ctx->undo_pos >= ctx->nundo) {
+ return 0;
+ }
+ const int group = ctx->undo[ctx->undo_pos].interaction;
+ while (ctx->undo_pos < ctx->nundo && ctx->undo[ctx->undo_pos].interaction == group) {
+ undo_apply(ctx, &ctx->undo[ctx->undo_pos++], 1);
+ }
+ return 1;
+}
+
+int BK_undo_depth(BKContext *ctx, int *r_redo)
+{
+ if (r_redo) {
+ *r_redo = ctx->nundo - ctx->undo_pos;
+ }
+ return ctx->undo_pos;
+}
+
+static void undo_forget(BKContext *ctx, BKNode *subtree)
+{
+ int w = 0;
+ const int pos = ctx->undo_pos;
+ int new_pos = pos;
+ for (int i = 0; i < ctx->nundo; i++) {
+ if (is_within(ctx->undo[i].node, subtree)) {
+ undo_entry_free(&ctx->undo[i]);
+ if (i < pos) {
+ new_pos--;
+ }
+ continue;
+ }
+ if (w != i) {
+ ctx->undo[w] = ctx->undo[i];
+ memset(&ctx->undo[i], 0, sizeof(BKUndo));
+ }
+ w++;
+ }
+ ctx->nundo = w;
+ ctx->undo_pos = BK_MIN(new_pos, w);
+}
+
+static int g_animations = 1;
+#define ANIM_SECONDS 0.12
+
+void BK_set_animations(int enabled)
+{
+ g_animations = enabled != 0;
+}
+
+int BK_animating(BKContext *ctx)
+{
+ return ctx->nanim > 0;
+}
+
+void bk_anim_start(BKNode *n)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (!ctx || !g_animations) {
+ n->anim = (n->flags & NF_COLLAPSED) ? 0.0f : 1.0f;
+ return;
+ }
+ for (int i = 0; i < ctx->nanim; i++) {
+ if (ctx->anim[i] == n) {
+ return; /* already running: it just reverses direction */
+ }
+ }
+ if (ctx->nanim < BK_MAX_ANIM) {
+ if (!ctx->nanim) {
+ ctx->anim_t = bk_time();
+ }
+ ctx->anim[ctx->nanim++] = n;
+ bk_ctx_request(ctx);
+ }
+}
+
+static void anim_step(BKContext *ctx)
+{
+ if (!ctx->nanim) {
+ return;
+ }
+ const double now = bk_time();
+ const float step = (float)((now - ctx->anim_t) / ANIM_SECONDS);
+ ctx->anim_t = now;
+ for (int i = ctx->nanim - 1; i >= 0; i--) {
+ BKNode *n = ctx->anim[i];
+ const float target = (n->flags & NF_COLLAPSED) ? 0.0f : 1.0f;
+ if (n->anim < target) {
+ n->anim = BK_MIN(target, n->anim + step);
+ }
+ else {
+ n->anim = BK_MAX(target, n->anim - step);
+ }
+ if (n->anim == target) {
+ ctx->anim[i] = ctx->anim[--ctx->nanim];
+ }
+ }
+ g_gen++;
+ ctx->layout_dirty = true;
+}
+
+/* Tab / Shift+Tab: the next editable field in tree order (Blender's
+ * ui_textedit_next_but), wrapping around. */
+static bool is_editable(const BKNode *n)
+{
+ return n->cls == &bk_cls_number || n->cls == &bk_cls_slider || n->cls == &bk_cls_text ||
+ n->cls == &bk_cls_search;
+}
+
+static void collect_editable(BKNode *n, BKNode **out, int *count, int max)
+{
+ if (!NODE_VISIBLE(n) || *count >= max) {
+ return;
+ }
+ if (n->cls == &bk_cls_panel && (n->flags & NF_COLLAPSED)) {
+ return;
+ }
+ if (is_editable(n) && NODE_ENABLED(n)) {
+ out[(*count)++] = n;
+ }
+ for (int i = 0; i < n->nkids; i++) {
+ collect_editable(n->kids[i], out, count, max);
+ }
+}
+
+BKNode *bk_next_editable(BKNode *from, int dir)
+{
+ BKNode *top = from;
+ while (top->parent) {
+ top = top->parent;
+ }
+ BKNode *list[512];
+ int count = 0, at = -1;
+ collect_editable(top, list, &count, 512);
+ for (int i = 0; i < count; i++) {
+ if (list[i] == from) {
+ at = i;
+ }
+ }
+ if (at < 0 || count < 2) {
+ return NULL;
+ }
+ return list[(at + dir + count) % count];
+}
+
+BKNode *bk_hit_at(BKContext *ctx, int x, int y)
+{
+ return hit_all(ctx, x, y);
+}
+
+/** \} */
+
+bool bk_anim_running(const BKNode *n)
+{
+ const BKContext *ctx = bk_ctx(n);
+ if (!ctx) {
+ return false;
+ }
+ for (int i = 0; i < ctx->nanim; i++) {
+ if (ctx->anim[i] == n) {
+ return true;
+ }
+ }
+ return false;
+}
+
+void bk_edit_next(BKNode *from, int dir)
+{
+ BKNode *next = bk_next_editable(from, dir);
+ if (next && next->cls->activate) {
+ next->cls->activate(next);
+ }
+}
diff --git a/kit/intern/kit_draw.c b/kit/intern/kit_draw.c
new file mode 100644
index 0000000..07002a7
--- /dev/null
+++ b/kit/intern/kit_draw.c
@@ -0,0 +1,1376 @@
+/* Drawing: Blender's default theme, the widget base and the widget draw
+ * functions, ported from editors/interface/interface_widgets.cc (same names,
+ * same math, same shape tables), rendered into a BuiRaster. Screen space is
+ * y-down, so Blender's "ymin" (bottom) is our ymax.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "kit_icons_data.h"
+#include "kit_intern.h"
+
+/* Blender's color math (blenlib, linked from bui_core). */
+void rgb_to_hsl_v(const float rgb[3], float r_hsl[3]);
+void hsl_to_rgb_v(const float hsl[3], float r_rgb[3]);
+
+/* -------------------------------------------------------------------- */
+/** \name Theme: Blender 4.x defaults (userdef_default_theme.c, ThemeUI)
+ * \{ */
+
+#define RGBA(v) {(uchar)((v) >> 24), (uchar)((v) >> 16), (uchar)((v) >> 8), (uchar)(v)}
+#define WCOL(outline_, outline_sel_, inner_, inner_sel_, item_, text_, text_sel_, round_) \
+ {RGBA(outline_), RGBA(outline_sel_), RGBA(inner_), RGBA(inner_sel_), RGBA(item_), \
+ RGBA(text_), RGBA(text_sel_), 0, 0, 0, round_}
+
+BKTheme bk_theme = {
+ /* regular */ WCOL(0x3d3d3dff, 0x656565ff, 0x545454ff, 0x4772b3ff, 0x191919ff, 0xe6e6e6ff,
+ 0xffffffff, 0.2f),
+ /* tool */ WCOL(0x3d3d3dff, 0x656565ff, 0x545454ff, 0x4772b3ff, 0x191919ff, 0xe6e6e6ff,
+ 0xffffffff, 0.2f),
+ /* toggle */ WCOL(0x3d3d3dff, 0x656565ff, 0x545454ff, 0x4772b3ff, 0x191919ff, 0xe6e6e6ff,
+ 0xffffffff, 0.2f),
+ /* radio */ WCOL(0x3d3d3dff, 0x656565ff, 0x545454ff, 0x4772b3ff, 0xffffffff, 0xe6e6e6ff,
+ 0xffffffff, 0.2f),
+ /* option */ WCOL(0x3d3d3dff, 0x656565ff, 0x545454ff, 0x4772b3ff, 0xffffffff, 0xe6e6e6ff,
+ 0xffffffff, 0.3f),
+ /* text */ WCOL(0x3d3d3dff, 0x656565ff, 0x1d1d1dff, 0x181818ff, 0x4772b3ff, 0xe6e6e6ff,
+ 0xffffffff, 0.2f),
+ /* num */ WCOL(0x3d3d3dff, 0x656565ff, 0x545454ff, 0x656565ff, 0xe6e6e6ff, 0xe6e6e6ff,
+ 0xffffffff, 0.2f),
+ /* numslider */ WCOL(0x3d3d3dff, 0x656565ff, 0x545454ff, 0x999999ff, 0x4772b3ff,
+ 0xe6e6e6ff, 0xffffffff, 0.2f),
+ /* menu */ WCOL(0x3d3d3dff, 0x656565ff, 0x282828ff, 0x303030ff, 0xe6e6e6ff, 0xe6e6e6ff,
+ 0xffffffff, 0.2f),
+ /* pulldown */ WCOL(0x3d3d3d00, 0x3d3d3d00, 0x00000000, 0x4772b3ff, 0xffffffff,
+ 0xd9d9d9ff, 0xffffffff, 0.2f),
+ /* menu_back */ WCOL(0x242424ff, 0x242424ff, 0x181818efu, 0x2d2d2dff, 0x656565ff,
+ 0xa5a5a5ff, 0xffffffff, 0.25f),
+ /* menu_item */ WCOL(0x00000000, 0x00000000, 0x00000000, 0x4772b3ff, 0xffffff8f,
+ 0xe6e6e6ff, 0xffffffff, 0.2f),
+ /* list_item */ WCOL(0x00000000, 0x00000000, 0x00000000, 0x334d80ff, 0x4772b3ff,
+ 0xe6e6e6ff, 0xffffffff, 0.2f),
+ /* box */ WCOL(0x3d3d3dff, 0x656565ff, 0x282828ff, 0x4772b3ff, 0x191919ff, 0xe6e6e6ff,
+ 0xffffffff, 0.2f),
+ /* scroll */ WCOL(0x00000000, 0x00000000, 0x00000000, 0x646464b4, 0x545454ff, 0xe6e6e6ff,
+ 0xffffffff, 0.5f),
+ /* progress */ WCOL(0x3d3d3dff, 0x656565ff, 0x1d1d1dff, 0x4772b3ff, 0x4772b3ff,
+ 0xe6e6e6ff, 0xffffffff, 0.2f),
+ /* tooltip */ WCOL(0x3d3d3dff, 0x3d3d3dff, 0x1d1d1dff, 0x1d1d1dff, 0x1d1d1dff, 0xe6e6e6ff,
+ 0xffffffff, 0.25f),
+ /* tab */ WCOL(0x1d1d1dff, 0x1d1d1dff, 0x2a2a2aff, 0x3d3d3dff, 0x28292dff, 0x989898ff,
+ 0xffffffff, 0.2f),
+ /* pie_menu */ WCOL(0x0a0a0aff, 0x0a0a0aff, 0x181818ffu, 0x4772b3ff, 0x4772b3ff,
+ 0xd9d9d9ff, 0xffffffff, 0.5f),
+ RGBA(0x303030ff), /* region_bg */
+ RGBA(0x181818ff), /* header_bg (top bar) */
+ RGBA(0x1d1d1dff), /* tabs_bg (navigation bar) */
+ RGBA(0x3d3d3dff), /* panel_header */
+ RGBA(0x3d3d3dff), /* panel_back */
+ RGBA(0x0000001fu), /* panel_sub_back */
+ RGBA(0xffffff0du), /* panel_outline */
+ RGBA(0xe6e6e6ff), /* text */
+ RGBA(0xffffffff), /* text_hi */
+ RGBA(0x00000026u), /* widget_emboss */
+ RGBA(0x71a8ffff), /* text cursor */
+ RGBA(0x4772b380u), /* text selection */
+ 0.4f, /* menu_shadow_fac */
+ 6, /* menu_shadow_width */
+ 0.4f, /* panel_roundness */
+};
+
+float bk_scale_fac = 1.0f;
+static char g_font_family[64] = "";
+
+void BK_set_scale(float scale)
+{
+ bk_scale_fac = BK_CLAMP(scale, 0.5f, 4.0f);
+}
+float BK_scale(void)
+{
+ return bk_scale_fac;
+}
+int BK_unit(void)
+{
+ return bk_unit();
+}
+void BK_set_font(const char *family)
+{
+ strncpy(g_font_family, family ? family : "", sizeof(g_font_family) - 1);
+}
+
+int bk_unit(void)
+{
+ return (int)floorf(20.0f * bk_scale_fac + 0.5f); /* U.widget_unit */
+}
+float bk_px(void)
+{
+ return bk_scale_fac >= 1.5f ? 2.0f : 1.0f; /* U.pixelsize */
+}
+float bk_text_scale = 1.0f;
+
+float bk_font_size(void)
+{
+ return floorf(11.0f * bk_scale_fac * bk_text_scale + 0.5f); /* UI_DEFAULT_TEXT_POINTS */
+}
+
+/* Password fields: every UTF-8 character shows as `mask`. */
+int bk_mask_text(const char *s, int len, const char *mask, char *buf, int size)
+{
+ const int ml = (int)strlen(mask);
+ int out = 0;
+ for (int i = 0; i < len; i++) {
+ if (((unsigned char)s[i] & 0xC0) != 0x80 && out + ml < size) {
+ memcpy(buf + out, mask, (size_t)ml);
+ out += ml;
+ }
+ }
+ buf[out] = 0;
+ return out;
+}
+
+float bk_masked_width(const char *s, int len, const char *mask, bool bold)
+{
+ if (!mask || !mask[0]) {
+ return bk_text_width(s, len, bold);
+ }
+ char buf[1024];
+ return bk_text_width(buf, bk_mask_text(s, len, mask, buf, sizeof(buf)), bold);
+}
+int bk_pad(void)
+{
+ return (int)floorf(0.4f * bk_unit() + 0.5f); /* UI_TEXT_MARGIN_X */
+}
+int bk_iround(float v)
+{
+ return (int)floorf(v + 0.5f);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Clip stack & primitives
+ * \{ */
+
+BKDraw bk_draw;
+static int g_clip_stack[32][4];
+static int g_clip_n = 0;
+
+static void clip_apply(void)
+{
+ const int *c = bk_draw.clip;
+ BUI_raster_set_clip(bk_draw.r, c[0], c[1], BK_MAX(1, c[2] - c[0]), BK_MAX(1, c[3] - c[1]));
+ if (c[2] <= c[0] || c[3] <= c[1]) {
+ BUI_raster_set_clip(bk_draw.r, -10, -10, 1, 1); /* empty */
+ }
+}
+
+void bk_clip_reset(int w, int h)
+{
+ g_clip_n = 0;
+ bk_draw.clip[0] = 0;
+ bk_draw.clip[1] = 0;
+ bk_draw.clip[2] = w;
+ bk_draw.clip[3] = h;
+ clip_apply();
+}
+
+void bk_clip_push(int x, int y, int w, int h)
+{
+ if (g_clip_n < 32) {
+ memcpy(g_clip_stack[g_clip_n], bk_draw.clip, sizeof(int[4]));
+ }
+ g_clip_n++;
+ int *c = bk_draw.clip;
+ c[0] = BK_MAX(c[0], x);
+ c[1] = BK_MAX(c[1], y);
+ c[2] = BK_MIN(c[2], x + w);
+ c[3] = BK_MIN(c[3], y + h);
+ clip_apply();
+}
+
+void bk_clip_pop(void)
+{
+ if (g_clip_n > 0) {
+ g_clip_n--;
+ if (g_clip_n < 32) {
+ memcpy(bk_draw.clip, g_clip_stack[g_clip_n], sizeof(int[4]));
+ }
+ }
+ clip_apply();
+}
+
+bool bk_clip_visible(const BKRect *r)
+{
+ const int *c = bk_draw.clip;
+ return r->xmax > c[0] && r->xmin < c[2] && r->ymax > c[1] && r->ymin < c[3];
+}
+
+void bk_rgba(const uchar c[4], float o[4])
+{
+ o[0] = c[0] / 255.0f;
+ o[1] = c[1] / 255.0f;
+ o[2] = c[2] / 255.0f;
+ o[3] = c[3] / 255.0f;
+}
+
+void bk_rgba_alpha(const uchar c[4], float alpha, float o[4])
+{
+ bk_rgba(c, o);
+ o[3] *= alpha;
+}
+
+void bk_fill(float x, float y, float w, float h, const uchar c[4])
+{
+ float f[4];
+ bk_rgba(c, f);
+ BUI_raster_fill_rect(bk_draw.r, x, y, w, h, f);
+}
+
+void bk_fill_f(float x, float y, float w, float h, const float c[4])
+{
+ BUI_raster_fill_rect(bk_draw.r, x, y, w, h, c);
+}
+
+void bk_roundbox(float x, float y, float w, float h, float rad, int corners, const float c[4])
+{
+ BuiWidgetBase p = {{x, y, w, h}, rad, rad, corners};
+ memcpy(p.inner1, c, sizeof(float[4]));
+ memcpy(p.inner2, c, sizeof(float[4]));
+ memcpy(p.outline, c, sizeof(float[4]));
+ p.pixelsize = 1.0f;
+ BUI_raster_widget_base(bk_draw.r, &p);
+}
+
+void bk_shadow(const BKRect *r, float rad)
+{
+ /* widget_softshadow(): inset by the outline, Blender's shadow width/alpha */
+ const float px = bk_px();
+ BUI_raster_shadow(bk_draw.r, r->xmin + px, r->ymin + px, bk_rw(r) - 2 * px,
+ bk_rh(r) - 2 * px, rad, bk_theme.menu_shadow_width * bk_scale_fac,
+ bk_theme.menu_shadow_fac);
+}
+
+void bk_line(float x0, float y0, float x1, float y1, const float c[4], float width)
+{
+ BUI_raster_line(bk_draw.r, x0, y0, x1, y1, width, c);
+}
+
+void bk_circle(float cx, float cy, float rad, const float c[4])
+{
+ BUI_raster_circle(bk_draw.r, cx, cy, rad, 0.0f, c);
+}
+
+void bk_ring(float cx, float cy, float rad, const float c[4], float width)
+{
+ BUI_raster_ellipse(bk_draw.r, cx, cy, rad, rad, width, c);
+}
+
+void bk_polygon(const float (*pts)[2], int n, const float c[4])
+{
+ BUI_raster_polygon(bk_draw.r, pts, n, c);
+}
+
+void bk_checker(float x, float y, float w, float h)
+{
+ /* UI_ALPHA_CHECKER_DARK / LIGHT, 8 px cells (scaled) */
+ const float dark[4] = {100 / 255.0f, 100 / 255.0f, 100 / 255.0f, 1.0f};
+ const float light[4] = {160 / 255.0f, 160 / 255.0f, 160 / 255.0f, 1.0f};
+ const float cell = floorf(8.0f * bk_scale_fac + 0.5f);
+ bk_fill_f(x, y, w, h, dark);
+ for (float yy = y; yy < y + h; yy += cell) {
+ const int row = (int)((yy - y) / cell);
+ for (float xx = x + ((row & 1) ? cell : 0); xx < x + w; xx += 2 * cell) {
+ bk_fill_f(xx, yy, fminf(cell, x + w - xx), fminf(cell, y + h - yy), light);
+ }
+ }
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Color utilities (interface_widgets.cc)
+ * \{ */
+
+static void color_blend_v3_v3(uchar cp[3], const uchar cpstate[3], const float fac)
+{
+ if (fac != 0.0f) {
+ cp[0] = (uchar)((1.0f - fac) * cp[0] + fac * cpstate[0]);
+ cp[1] = (uchar)((1.0f - fac) * cp[1] + fac * cpstate[1]);
+ cp[2] = (uchar)((1.0f - fac) * cp[2] + fac * cpstate[2]);
+ }
+}
+
+static void color_blend_v4_v4v4(uchar r_col[4], const uchar col1[4], const uchar col2[4],
+ const float fac)
+{
+ const int faci = (int)BK_CLAMP(fac * 255.0f + 0.5f, 0.0f, 255.0f);
+ const int facm = 255 - faci;
+ for (int k = 0; k < 4; k++) {
+ r_col[k] = (uchar)((faci * col1[k] + facm * col2[k]) / 256);
+ }
+}
+
+static int srgb_to_grayscale_byte(const uchar c[3])
+{
+ /* BLI srgb_to_grayscale_byte: Rec.709 luma weights */
+ return (int)((255 * 0 + 54 * c[0] + 182 * c[1] + 19 * c[2]) / 255);
+}
+
+static void color_mul_hsl_v3(uchar ch[3], float h_factor, float s_factor, float l_factor)
+{
+ float rgb[3] = {ch[0] / 255.0f, ch[1] / 255.0f, ch[2] / 255.0f}, hsl[3];
+ rgb_to_hsl_v(rgb, hsl);
+ hsl[0] *= h_factor;
+ hsl[1] *= s_factor;
+ hsl[2] *= l_factor;
+ hsl_to_rgb_v(hsl, rgb);
+ for (int k = 0; k < 3; k++) {
+ ch[k] = (uchar)BK_CLAMP(rgb[k] * 255.0f + 0.5f, 0.0f, 255.0f);
+ }
+}
+
+static void shadecolors4(const uchar *color, short shadetop, short shadedown, uchar r_top[4],
+ uchar r_down[4])
+{
+ for (int k = 0; k < 3; k++) {
+ r_top[k] = (uchar)BK_CLAMP(color[k] + shadetop, 0, 255);
+ r_down[k] = (uchar)BK_CLAMP(color[k] + shadedown, 0, 255);
+ }
+ r_top[3] = r_down[3] = color[3];
+}
+
+void bk_widget_active_color(BKWCol *wcol)
+{
+ const bool dark = srgb_to_grayscale_byte(wcol->text) > srgb_to_grayscale_byte(wcol->inner);
+ color_mul_hsl_v3(wcol->inner, 1.0f, 1.15f, dark ? 1.2f : 1.1f);
+ color_blend_v4_v4v4(wcol->outline, wcol->outline, wcol->outline_sel, 0.5f);
+ color_mul_hsl_v3(wcol->outline_sel, 1.0f, 1.15f, 1.15f);
+ color_mul_hsl_v3(wcol->text, 1.0f, 1.15f, dark ? 1.25f : 0.8f);
+}
+
+static void widget_color_disabled(BKWCol *w)
+{
+ const float f = 0.5f; /* widget_alpha_factor() */
+ w->outline[3] = (uchar)(w->outline[3] * f);
+ w->outline_sel[3] = (uchar)(w->outline_sel[3] * f);
+ w->inner[3] = (uchar)(w->inner[3] * f);
+ w->inner_sel[3] = (uchar)(w->inner_sel[3] * f);
+ w->item[3] = (uchar)(w->item[3] * f);
+ w->text[3] = (uchar)(w->text[3] * f);
+ w->text_sel[3] = (uchar)(w->text_sel[3] * f);
+}
+
+void bk_widget_state(BKWCol *wcol, const BKWCol *theme, int state)
+{
+ *wcol = *theme;
+ if (state & ST_DISABLED) {
+ widget_color_disabled(wcol);
+ }
+ if (state & ST_SELECT) {
+ memcpy(wcol->inner, wcol->inner_sel, 4);
+ memcpy(wcol->outline, wcol->outline_sel, 4);
+ memcpy(wcol->text, wcol->text_sel, 3);
+ const short t = wcol->shadetop;
+ wcol->shadetop = wcol->shadedown;
+ wcol->shadedown = t;
+ }
+ else {
+ if (state & ST_ACTIVE_DEFAULT) {
+ memcpy(wcol->inner, wcol->inner_sel, 4);
+ memcpy(wcol->outline, wcol->outline_sel, 4);
+ memcpy(wcol->text, wcol->text_sel, 4);
+ }
+ if (state & ST_HOVER) {
+ bk_widget_active_color(wcol);
+ }
+ }
+}
+
+void bk_widget_state_menu_item(BKWCol *wcol, const BKWCol *theme, int state)
+{
+ *wcol = *theme;
+ if ((state & ST_DISABLED) && (state & ST_HOVER)) {
+ wcol->text[3] = 128;
+ color_blend_v3_v3(wcol->inner, wcol->text, 0.5f);
+ wcol->inner[3] = 64;
+ }
+ else if (state & ST_DISABLED) {
+ wcol->text[3] = 128;
+ }
+ else if (state & (ST_ACTIVE_DEFAULT | ST_SELECT)) {
+ memcpy(wcol->inner, wcol->inner_sel, 4);
+ memcpy(wcol->outline, wcol->outline_sel, 4);
+ memcpy(wcol->text, wcol->text_sel, 4);
+ }
+ else if (state & ST_HOVER) {
+ color_blend_v3_v3(wcol->inner, wcol->text, 0.2f);
+ color_blend_v3_v3(wcol->outline, wcol->outline_sel, 0.5f);
+ memcpy(wcol->text, wcol->text_sel, 3);
+ wcol->inner[3] = 255;
+ wcol->text[3] = 255;
+ }
+}
+
+float bk_widget_radius(const BKWCol *wcol)
+{
+ return wcol->roundness * bk_unit(); /* widget_radius_from_zoom */
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Widget base: round_box_edges, shape presets, widgetbase_draw
+ * \{ */
+
+enum { TRIA_NONE, TRIA_ARROWS, TRIA_SCROLL, TRIA_MENU, TRIA_CHECK, TRIA_DASH };
+
+typedef struct WidgetTrias {
+ int type;
+ float center[2], size;
+ int npoly; /* outline polygons */
+ int nv[2];
+ float v[2][16][2]; /* screen-space polygon outlines */
+} WidgetTrias;
+
+typedef struct WidgetBase {
+ BuiWidgetBase p;
+ bool draw_inner, draw_outline, draw_emboss;
+ WidgetTrias tria1, tria2;
+} WidgetBase;
+
+static const float g_shape_preset_number_arrow_vert[3][2] = {
+ {-0.352077f, 0.532607f}, {-0.352077f, -0.549313f}, {0.330000f, -0.008353f}};
+static const float g_shape_preset_scroll_circle_vert[16][2] = {
+ {0.382684f, 0.923879f}, {0.000001f, 1.000000f}, {-0.382683f, 0.923880f},
+ {-0.707107f, 0.707107f}, {-0.923879f, 0.382684f}, {-1.000000f, 0.000000f},
+ {-0.923880f, -0.382684f}, {-0.707107f, -0.707107f}, {-0.382683f, -0.923880f},
+ {0.000000f, -1.000000f}, {0.382684f, -0.923880f}, {0.707107f, -0.707107f},
+ {0.923880f, -0.382684f}, {1.000000f, -0.000000f}, {0.923880f, 0.382683f},
+ {0.707107f, 0.707107f}};
+static const float g_shape_preset_menu_arrow_vert[6][2] = {
+ {-0.33f, 0.16f}, {0.33f, 0.16f}, {0, 0.82f}, {0, -0.82f}, {-0.33f, -0.16f}, {0.33f, -0.16f}};
+static const float g_shape_preset_checkmark_vert[6][2] = {
+ {-0.578579f, 0.253369f}, {-0.392773f, 0.412794f}, {-0.004241f, -0.328551f},
+ {-0.003001f, 0.034320f}, {1.055313f, 0.864744f}, {0.866408f, 1.026895f}};
+/* Outline order of the checkmark's 4 triangles {3,2,4},{3,4,5},{1,0,3},{0,2,3}. */
+static const int g_checkmark_outline[6] = {0, 2, 4, 5, 3, 1};
+
+static void widget_init(WidgetBase *wtb)
+{
+ memset(wtb, 0, sizeof(*wtb));
+ wtb->draw_inner = wtb->draw_outline = wtb->draw_emboss = true;
+ wtb->p.pixelsize = bk_px();
+}
+
+static void round_box_edges(WidgetBase *wt, int roundboxalign, const BKRect *rect, float rad)
+{
+ const float px = bk_px();
+ float radi = rad - px;
+ const int hnum = ((roundboxalign & (CNR_TL | CNR_TR)) == (CNR_TL | CNR_TR) ||
+ (roundboxalign & (CNR_BR | CNR_BL)) == (CNR_BR | CNR_BL)) ?
+ 1 :
+ 2;
+ const int vnum = ((roundboxalign & (CNR_TL | CNR_BL)) == (CNR_TL | CNR_BL) ||
+ (roundboxalign & (CNR_TR | CNR_BR)) == (CNR_TR | CNR_BR)) ?
+ 1 :
+ 2;
+ const int minsize = BK_MIN(bk_rw(rect) * hnum, bk_rh(rect) * vnum);
+ if (2.0f * rad > minsize) {
+ rad = 0.5f * minsize;
+ }
+ if (2.0f * (radi + 1.0f) > minsize) {
+ radi = 0.5f * minsize - px;
+ }
+ wt->p.rect[0] = (float)rect->xmin;
+ wt->p.rect[1] = (float)rect->ymin;
+ wt->p.rect[2] = (float)bk_rw(rect);
+ wt->p.rect[3] = (float)bk_rh(rect);
+ wt->p.rad = rad;
+ wt->p.radi = BK_MAX(0.0f, radi);
+ wt->p.corners = roundboxalign;
+}
+
+/* Map a preset vertex (Blender's y-up local space) to the screen. */
+static void tria_vert(float *out, float cx, float cy, float sx, float sy, const float v[2], int i1,
+ int i2)
+{
+ out[0] = sx * v[i1] + cx;
+ out[1] = cy - sy * v[i2];
+}
+
+static void shape_preset_init_trias_ex(WidgetTrias *tria, const BKRect *rect, float triasize,
+ char where, const float (*verts)[2], int verts_tot)
+{
+ int i1 = 0, i2 = 1;
+ const float minsize = (where == 'r' || where == 'l') ? bk_rh(rect) : bk_rw(rect);
+ float centx = rect->xmin + 0.4f * minsize;
+ float centy = rect->ymax - 0.5f * minsize; /* Blender: ymin(bottom) + 0.5 * minsize */
+ float sizex, sizey;
+ sizex = sizey = -0.5f * triasize * minsize;
+ if (where == 'r') {
+ centx = rect->xmax - 0.4f * minsize;
+ sizex = -sizex;
+ }
+ else if (where == 't') {
+ centx = rect->xmin + 0.5f * minsize;
+ centy = rect->ymin + 0.5f * minsize;
+ sizey = -sizey;
+ i2 = 0;
+ i1 = 1;
+ }
+ else if (where == 'b') {
+ centx = rect->xmin + 0.5f * minsize;
+ sizex = -sizex;
+ i2 = 0;
+ i1 = 1;
+ }
+ tria->npoly = 1;
+ tria->nv[0] = verts_tot;
+ for (int a = 0; a < verts_tot; a++) {
+ tria_vert(tria->v[0][a], centx, centy, sizex, sizey, verts[a], i1, i2);
+ }
+}
+
+static void shape_preset_init_number_arrows(WidgetTrias *tria, const BKRect *rect,
+ float triasize, char where)
+{
+ tria->type = TRIA_ARROWS;
+ shape_preset_init_trias_ex(tria, rect, triasize, where, g_shape_preset_number_arrow_vert, 3);
+}
+
+static void shape_preset_init_scroll_circle(WidgetTrias *tria, const BKRect *rect,
+ float triasize, char where)
+{
+ tria->type = TRIA_SCROLL;
+ shape_preset_init_trias_ex(tria, rect, triasize, where, g_shape_preset_scroll_circle_vert, 16);
+}
+
+static void shape_preset_trias_from_rect_menu(WidgetTrias *tria, const BKRect *rect)
+{
+ const float width = bk_rw(rect), height = bk_rh(rect);
+ if ((width / height) < 0.5f) {
+ return; /* too narrow */
+ }
+ tria->type = TRIA_MENU;
+ float centx = rect->xmin + 0.52f * height;
+ const float centy = rect->ymin + 0.5f * height;
+ const float size = 0.4f * height;
+ if (width > height * 1.1f) {
+ centx = rect->xmax - 0.32f * height; /* wider buttons: align tighter right */
+ }
+ /* Blender 4.x draws the menu indicator as a down chevron at this spot. */
+ tria->center[0] = centx;
+ tria->center[1] = centy;
+ tria->size = size;
+ (void)g_shape_preset_menu_arrow_vert;
+}
+
+static void draw_menu_chevron(const WidgetTrias *t, const float c[4])
+{
+ const float s = t->size * 0.42f, lw = BK_MAX(1.2f, 0.075f * bk_unit());
+ const float cx = t->center[0], cy = t->center[1];
+ BUI_raster_line(bk_draw.r, cx - s, cy - s * 0.4f, cx, cy + s * 0.5f, lw, c);
+ BUI_raster_line(bk_draw.r, cx, cy + s * 0.5f, cx + s, cy - s * 0.4f, lw, c);
+}
+
+static void shape_preset_trias_from_rect_checkmark(WidgetTrias *tria, const BKRect *rect)
+{
+ tria->type = TRIA_CHECK;
+ const float h = bk_rh(rect);
+ const float centx = rect->xmin + 0.5f * h, centy = rect->ymax - 0.5f * h, size = 0.5f * h;
+ tria->npoly = 1;
+ tria->nv[0] = 6;
+ for (int a = 0; a < 6; a++) {
+ tria_vert(tria->v[0][a], centx, centy, size, size,
+ g_shape_preset_checkmark_vert[g_checkmark_outline[a]], 0, 1);
+ }
+}
+
+static void shape_preset_trias_from_rect_dash(WidgetTrias *tria, const BKRect *rect)
+{
+ tria->type = TRIA_DASH;
+ const float h = bk_rh(rect);
+ const float cx = rect->xmin + 0.5f * h, cy = rect->ymin + 0.5f * h, s = 0.5f * h;
+ const float hw = 0.5f * s, hh = 0.1f * s;
+ tria->npoly = 1;
+ tria->nv[0] = 4;
+ const float q[4][2] = {{cx - hw, cy - hh}, {cx + hw, cy - hh}, {cx + hw, cy + hh}, {cx - hw, cy + hh}};
+ memcpy(tria->v[0], q, sizeof(q));
+}
+
+static void draw_trias(const WidgetTrias *t, const float color[4])
+{
+ for (int k = 0; k < t->npoly; k++) {
+ if (t->nv[k] >= 3) {
+ BUI_raster_polygon(bk_draw.r, (const float(*)[2])t->v[k], t->nv[k], color);
+ }
+ }
+}
+
+static void widgetbase_draw_ex(WidgetBase *wtb, const BKWCol *wcol, const float *color_override,
+ bool alpha_checker)
+{
+ BuiWidgetBase *p = &wtb->p;
+ memset(p->inner1, 0, sizeof(float[4]) * 4);
+ if (color_override) {
+ memcpy(p->inner1, color_override, sizeof(float[4]));
+ memcpy(p->inner2, color_override, sizeof(float[4]));
+ }
+ else if (wtb->draw_inner) {
+ if (wcol->shaded == 0) {
+ bk_rgba(wcol->inner, p->inner1);
+ bk_rgba(wcol->inner, p->inner2);
+ }
+ else {
+ uchar top[4], down[4];
+ shadecolors4(wcol->inner, wcol->shadetop, wcol->shadedown, top, down);
+ bk_rgba(top, p->inner1);
+ bk_rgba(down, p->inner2);
+ }
+ }
+ if (wtb->draw_outline) {
+ bk_rgba(wcol->outline, p->outline);
+ }
+ /* Emboss only if the outline is not fully transparent (it looks like a gap). */
+ if (wtb->draw_emboss && wcol->outline[3] != 0) {
+ bk_rgba(bk_theme.emboss, p->emboss);
+ }
+ p->alpha_checker = alpha_checker;
+ BUI_raster_widget_base(bk_draw.r, p);
+ if (wtb->tria1.type != TRIA_NONE || wtb->tria2.npoly) {
+ float tc[4];
+ bk_rgba(wcol->item, tc);
+ if (wtb->tria1.type == TRIA_MENU) {
+ draw_menu_chevron(&wtb->tria1, tc);
+ }
+ draw_trias(&wtb->tria1, tc);
+ draw_trias(&wtb->tria2, tc);
+ }
+}
+
+static void widgetbase_draw(WidgetBase *wtb, const BKWCol *wcol)
+{
+ widgetbase_draw_ex(wtb, wcol, NULL, false);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Widget types (interface_widgets.cc)
+ * \{ */
+
+#define NUM_BUT_PADDING_FACTOR 0.425f
+
+static void swap_shade(BKWCol *w)
+{
+ const short t = w->shadetop;
+ w->shadetop = w->shadedown;
+ w->shadedown = t;
+}
+
+void bk_widget_but(BKWCol *wcol, BKRect *rect, int state, int corners)
+{
+ WidgetBase wtb;
+ widget_init(&wtb);
+ round_box_edges(&wtb, corners, rect, bk_widget_radius(wcol));
+ wtb.draw_emboss = !(state & ST_ALIGN_DOWN);
+ if (state & ST_NO_EMBOSS) {
+ wtb.draw_outline = wtb.draw_emboss = false;
+ if (!(state & (ST_HOVER | ST_SELECT))) {
+ wtb.draw_inner = false;
+ }
+ }
+ widgetbase_draw(&wtb, wcol);
+}
+
+void bk_widget_numbut(BKWCol *wcol, BKRect *rect, int state, int corners)
+{
+ const float rad = bk_widget_radius(wcol);
+ const float px = bk_px();
+ const int handle_width = BK_MIN(bk_rw(rect) / 3, (int)(bk_rh(rect) * 0.7f));
+ if (state & ST_SELECT) {
+ swap_shade(wcol);
+ }
+ WidgetBase wtb;
+ widget_init(&wtb);
+ round_box_edges(&wtb, corners, rect, rad);
+
+ if ((state & ST_HOVER) && !(state & ST_TEXT_INPUT)) {
+ BKWCol wcol_zone;
+ WidgetBase wtb_zone;
+ BKRect rz;
+
+ /* left arrow zone */
+ widget_init(&wtb_zone);
+ wtb_zone.draw_outline = wtb_zone.draw_emboss = false;
+ wcol_zone = *wcol;
+ memcpy(wcol_zone.item, wcol->text, 3);
+ if (state & ST_HOVER_LEFT) {
+ bk_widget_active_color(&wcol_zone);
+ }
+ rz = *rect;
+ rz.xmax = rect->xmin + handle_width + (int)px;
+ round_box_edges(&wtb_zone, corners & ~(CNR_TR | CNR_BR), &rz, rad);
+ shape_preset_init_number_arrows(&wtb_zone.tria1, &rz, 0.6f, 'l');
+ widgetbase_draw(&wtb_zone, &wcol_zone);
+
+ /* right arrow zone */
+ widget_init(&wtb_zone);
+ wtb_zone.draw_outline = wtb_zone.draw_emboss = false;
+ wcol_zone = *wcol;
+ memcpy(wcol_zone.item, wcol->text, 3);
+ if (state & ST_HOVER_RIGHT) {
+ bk_widget_active_color(&wcol_zone);
+ }
+ rz = *rect;
+ rz.xmin = rect->xmax - handle_width - (int)px;
+ round_box_edges(&wtb_zone, corners & ~(CNR_TL | CNR_BL), &rz, rad);
+ shape_preset_init_number_arrows(&wtb_zone.tria1, &rz, 0.6f, 'r');
+ widgetbase_draw(&wtb_zone, &wcol_zone);
+
+ /* middle highlight zone */
+ widget_init(&wtb_zone);
+ wtb_zone.draw_outline = wtb_zone.draw_emboss = false;
+ wcol_zone = *wcol;
+ memcpy(wcol_zone.item, wcol->text, 3);
+ if (!(state & (ST_HOVER_LEFT | ST_HOVER_RIGHT))) {
+ bk_widget_active_color(&wcol_zone);
+ }
+ rz = *rect;
+ rz.xmin = rect->xmin + handle_width - (int)px;
+ rz.xmax = rect->xmax - handle_width + (int)px;
+ round_box_edges(&wtb_zone, 0, &rz, 0);
+ widgetbase_draw(&wtb_zone, &wcol_zone);
+
+ /* outline */
+ wtb.draw_inner = false;
+ wtb.draw_emboss = !(state & ST_ALIGN_DOWN);
+ widgetbase_draw(&wtb, wcol);
+ }
+ else {
+ wtb.draw_emboss = !(state & ST_ALIGN_DOWN);
+ widgetbase_draw(&wtb, wcol);
+ }
+ if (!(state & ST_TEXT_INPUT)) {
+ const int text_padding = (int)(NUM_BUT_PADDING_FACTOR * bk_rh(rect));
+ rect->xmin += text_padding;
+ rect->xmax -= text_padding;
+ }
+}
+
+void bk_widget_numslider(BKWCol *wcol, BKRect *rect, int state, int corners, float factor)
+{
+ WidgetBase wtb, wtb1;
+ widget_init(&wtb);
+ widget_init(&wtb1);
+ const float rad = bk_widget_radius(wcol);
+ round_box_edges(&wtb, corners, rect, rad);
+ wtb.draw_outline = false;
+ wtb.draw_emboss = !(state & ST_ALIGN_DOWN);
+ widgetbase_draw(&wtb, wcol);
+
+ if (!(state & ST_TEXT_INPUT)) {
+ int corners_slider = corners;
+ uchar outline[3];
+ memcpy(outline, wcol->outline, 3);
+ memcpy(wcol->outline, wcol->item, 3);
+ memcpy(wcol->inner, wcol->item, 3);
+ if (!(state & ST_SELECT)) {
+ swap_shade(wcol);
+ }
+ BKRect rect1 = *rect;
+ float factor_discard = 1.0f;
+ factor = BK_CLAMP(factor, 0.0f, 1.0f);
+ const float width = (float)bk_rw(rect);
+ const float factor_ui = factor * width;
+ const float min_width = 2.0f * rad;
+ if (factor_ui > width - rad) {
+ factor_discard = factor; /* left + middle + right */
+ }
+ else if (factor_ui > min_width) {
+ corners_slider &= ~(CNR_TR | CNR_BR); /* left + middle */
+ rect1.xmax = rect1.xmin + (int)factor_ui;
+ }
+ else {
+ corners_slider &= ~(CNR_TR | CNR_BR); /* left part */
+ rect1.xmax = rect1.xmin + (int)min_width;
+ factor_discard = factor_ui / min_width;
+ }
+ round_box_edges(&wtb1, corners_slider, &rect1, rad);
+ wtb1.draw_outline = false;
+ wtb1.draw_emboss = false;
+ /* alpha_discard: keep the left `factor_discard` of the slider shape */
+ bk_clip_push(rect1.xmin, rect1.ymin - 1, (int)ceilf(bk_rw(&rect1) * factor_discard),
+ bk_rh(&rect1) + 2);
+ widgetbase_draw(&wtb1, wcol);
+ bk_clip_pop();
+ memcpy(wcol->outline, outline, 3);
+ if (!(state & ST_SELECT)) {
+ swap_shade(wcol);
+ }
+ }
+ /* outline */
+ wtb.draw_outline = true;
+ wtb.draw_inner = false;
+ wtb.draw_emboss = false;
+ widgetbase_draw(&wtb, wcol);
+ if (!(state & ST_TEXT_INPUT)) {
+ const int text_padding = (int)(NUM_BUT_PADDING_FACTOR * bk_rh(rect));
+ rect->xmax -= text_padding;
+ rect->xmin += text_padding;
+ }
+}
+
+void bk_widget_textbut(BKWCol *wcol, BKRect *rect, int state, int corners)
+{
+ if (state & ST_SELECT) {
+ swap_shade(wcol);
+ }
+ WidgetBase wtb;
+ widget_init(&wtb);
+ round_box_edges(&wtb, corners, rect, bk_widget_radius(wcol));
+ wtb.draw_emboss = !(state & ST_ALIGN_DOWN);
+ widgetbase_draw(&wtb, wcol);
+}
+
+void bk_widget_menubut(BKWCol *wcol, BKRect *rect, int state, int corners)
+{
+ WidgetBase wtb;
+ widget_init(&wtb);
+ round_box_edges(&wtb, corners, rect, bk_widget_radius(wcol));
+ shape_preset_trias_from_rect_menu(&wtb.tria1, rect);
+ if (state & ST_NO_EMBOSS) {
+ wtb.draw_inner = wtb.draw_outline = wtb.draw_emboss = false;
+ }
+ wtb.draw_emboss = wtb.draw_emboss && !(state & ST_ALIGN_DOWN);
+ widgetbase_draw(&wtb, wcol);
+ /* text space, arrows are about 0.6 height of button */
+ rect->xmax -= (6 * bk_rh(rect)) / 10;
+}
+
+void bk_widget_optionbut(BKWCol *wcol, BKRect *rect, int state)
+{
+ BKRect rt = *rect;
+ WidgetBase wtb;
+ widget_init(&wtb);
+ rt.xmax = rt.xmin + bk_rh(&rt); /* square */
+ /* smaller: BLI_rcti_resize + translate so the left edge stays */
+ const int delta = (int)((bk_rh(&rt) - 2 * bk_px()) / 6);
+ rt.xmin += delta;
+ rt.xmax -= delta;
+ rt.ymin += delta;
+ rt.ymax -= delta;
+ rt.xmin -= delta;
+ rt.xmax -= delta;
+ if (state & ST_INDETERMINATE) {
+ color_blend_v4_v4v4(wcol->inner, wcol->inner, wcol->inner_sel, 0.75f);
+ }
+ const float rad = wcol->roundness * bk_rh(&rt); /* widget_radius_from_rcti */
+ round_box_edges(&wtb, CNR_ALL, &rt, rad);
+ if (state & ST_INDETERMINATE) {
+ shape_preset_trias_from_rect_dash(&wtb.tria1, &rt);
+ }
+ else if (state & ST_SELECT) {
+ shape_preset_trias_from_rect_checkmark(&wtb.tria1, &rt);
+ }
+ widgetbase_draw(&wtb, wcol);
+ rect->xmin = rt.xmax + (int)(delta * 0.9f); /* text space */
+}
+
+void bk_widget_pulldownbut(BKWCol *wcol, BKRect *rect, int state, int corners)
+{
+ if (state & ST_HOVER) {
+ WidgetBase wtb;
+ memcpy(wcol->inner, wcol->inner_sel, 4);
+ memcpy(wcol->text, wcol->text_sel, 3);
+ widget_init(&wtb);
+ round_box_edges(&wtb, corners, rect, bk_widget_radius(wcol));
+ widgetbase_draw(&wtb, wcol);
+ }
+}
+
+void bk_widget_menu_itembut(BKWCol *wcol, BKRect *rect)
+{
+ WidgetBase wtb;
+ widget_init(&wtb);
+ const int padding = (int)(0.125f * bk_unit()); /* padding on the sides */
+ rect->xmin += padding;
+ rect->xmax -= padding;
+ round_box_edges(&wtb, CNR_ALL, rect, bk_widget_radius(wcol));
+ widgetbase_draw(&wtb, wcol);
+}
+
+void bk_widget_list_itembut(BKWCol *wcol, BKRect *rect, int state)
+{
+ WidgetBase wtb;
+ widget_init(&wtb);
+ round_box_edges(&wtb, CNR_ALL, rect, bk_widget_radius(wcol));
+ if (state & ST_HOVER) {
+ color_blend_v3_v3(wcol->inner, wcol->text, 0.2f);
+ wcol->inner[3] = (state & ST_SELECT) ? 255 : 20;
+ }
+ widgetbase_draw(&wtb, wcol);
+}
+
+void bk_widget_box(BKWCol *wcol, BKRect *rect, int corners, const uchar *color)
+{
+ WidgetBase wtb;
+ widget_init(&wtb);
+ BKWCol w = *wcol;
+ if (color && color[3]) {
+ memcpy(w.inner, color, 4);
+ }
+ round_box_edges(&wtb, corners, rect, bk_widget_radius(&w));
+ widgetbase_draw(&wtb, &w);
+}
+
+void bk_widget_progress(BKWCol *wcol, BKRect *rect, int corners, float factor)
+{
+ BKRect rect_bar = *rect;
+ WidgetBase wtb, wtb_bar;
+ widget_init(&wtb);
+ widget_init(&wtb_bar);
+ const float ofs = bk_widget_radius(wcol);
+ float w = BK_CLAMP(factor, 0.0f, 1.0f) * bk_rw(rect);
+ w = BK_MAX(w, ofs); /* ensure minimum size */
+ rect_bar.xmax = rect_bar.xmin + (int)w;
+ round_box_edges(&wtb, corners, rect, ofs);
+ round_box_edges(&wtb_bar, corners, &rect_bar, ofs);
+ widgetbase_draw(&wtb, wcol);
+ BKWCol bar = *wcol;
+ memcpy(bar.inner, bar.item, 3); /* "slider" bar color */
+ widgetbase_draw(&wtb_bar, &bar);
+}
+
+void bk_widget_swatch(BKWCol *wcol, BKRect *rect, int state, int corners, const float col_in[4])
+{
+ WidgetBase wtb;
+ widget_init(&wtb);
+ round_box_edges(&wtb, corners, rect, bk_widget_radius(wcol));
+ float col[4] = {col_in[0], col_in[1], col_in[2], col_in[3]};
+ const bool show_alpha_checkers = col[3] < 1.0f;
+ if (state & ST_DISABLED) {
+ col[3] *= 0.5f;
+ }
+ wtb.draw_emboss = !(state & ST_ALIGN_DOWN);
+ widgetbase_draw_ex(&wtb, wcol, col, show_alpha_checkers);
+}
+
+void bk_widget_scroll(BKWCol *wcol, const BKRect *rect, const BKRect *slider, bool pressed)
+{
+ WidgetBase wtb;
+ widget_init(&wtb);
+ const bool horizontal = bk_rw(rect) > bk_rh(rect);
+ const float rad = wcol->roundness * (horizontal ? bk_rh(rect) : bk_rw(rect));
+ wtb.p.shade_horizontal = !horizontal;
+ if (horizontal) {
+ swap_shade(wcol);
+ }
+ round_box_edges(&wtb, CNR_ALL, rect, rad);
+ widgetbase_draw(&wtb, wcol);
+ if (bk_rw(slider) < 2 || bk_rh(slider) < 2) {
+ return;
+ }
+ swap_shade(wcol);
+ memcpy(wcol->inner, wcol->item, 4);
+ if (wcol->shadetop > wcol->shadedown) {
+ wcol->shadetop += 20;
+ }
+ else {
+ wcol->shadedown += 20;
+ }
+ if (pressed) {
+ for (int k = 0; k < 3; k++) {
+ wcol->inner[k] = wcol->inner[k] >= 250 ? 255 : wcol->inner[k] + 5;
+ }
+ }
+ wtb.draw_emboss = false;
+ round_box_edges(&wtb, CNR_ALL, slider, rad);
+ widgetbase_draw(&wtb, wcol);
+ (void)shape_preset_init_scroll_circle;
+}
+
+void bk_widget_tab(BKWCol *wcol, BKRect *rect, int state, int corners)
+{
+ WidgetBase wtb;
+ widget_init(&wtb);
+ round_box_edges(&wtb, corners, rect, bk_widget_radius(wcol));
+ widgetbase_draw(&wtb, wcol);
+}
+
+static void widget_menu_back(const BKWCol *wcol, const BKRect *rect, int corners)
+{
+ WidgetBase wtb;
+ widget_init(&wtb);
+ const float radius = bk_widget_radius(wcol);
+ bk_shadow(rect, radius); /* widget_softshadow */
+ round_box_edges(&wtb, corners, rect, radius);
+ wtb.draw_emboss = false;
+ widgetbase_draw(&wtb, wcol);
+}
+
+void bk_widget_menu_back(const BKRect *rect, int corners)
+{
+ widget_menu_back(&bk_theme.menu_back, rect, corners);
+}
+
+void bk_widget_tooltip_back(const BKRect *rect)
+{
+ widget_menu_back(&bk_theme.tooltip, rect, CNR_ALL);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Text
+ * \{ */
+
+typedef struct MeasureSlot {
+ uint64_t hash;
+ float size;
+ float width;
+} MeasureSlot;
+#define MEASURE_SLOTS 8192
+static MeasureSlot g_measure[MEASURE_SLOTS];
+
+static uint64_t hash_str(const char *s, int len, bool bold)
+{
+ uint64_t h = 1469598103934665603ull ^ (bold ? 0x9e37 : 0);
+ for (int i = 0; i < len; i++) {
+ h = (h ^ (uchar)s[i]) * 1099511628211ull;
+ }
+ return h | 1;
+}
+
+float bk_text_width(const char *s, int len, bool bold)
+{
+ if (!s) {
+ return 0.0f;
+ }
+ if (len < 0) {
+ len = (int)strlen(s);
+ }
+ if (len == 0) {
+ return 0.0f;
+ }
+ const float size = bk_font_size();
+ const uint64_t h = hash_str(s, len, bold);
+ MeasureSlot *slot = &g_measure[h & (MEASURE_SLOTS - 1)];
+ if (slot->hash == h && slot->size == size) {
+ return slot->width;
+ }
+ float w = 0.0f;
+ if (!BUI_text_measure(g_font_family, bold ? BUI_FONT_BOLD : 0, size, s, len, &w)) {
+ w = len * size * 0.55f;
+ }
+ slot->hash = h;
+ slot->size = size;
+ slot->width = w;
+ return w;
+}
+
+float bk_text_baseline(const BKRect *rect)
+{
+ /* UI_fontstyle_draw: centered on the ascender (Inter: ~0.72 em) */
+ return rect->ymin + bk_rh(rect) * 0.5f + bk_font_size() * 0.36f;
+}
+
+void bk_text_f(float x, float baseline, const char *s, int len, const float c[4], bool bold)
+{
+ if (!s || c[3] <= 0.0f) {
+ return;
+ }
+ if (len < 0) {
+ len = (int)strlen(s);
+ }
+ if (len == 0) {
+ return;
+ }
+ BUI_raster_set_font(bk_draw.r, g_font_family, bold ? BUI_FONT_BOLD : 0);
+ BUI_raster_text(bk_draw.r, floorf(x + 0.5f), floorf(baseline + 0.5f), s, len, bk_font_size(),
+ c);
+}
+
+void bk_text(float x, float baseline, const char *s, int len, const uchar color[4], bool bold)
+{
+ float c[4];
+ bk_rgba(color, c);
+ bk_text_f(x, baseline, s, len, c, bold);
+}
+
+/* Bytes of `s` that fit in `width` with an ellipsis appended (UTF-8 safe). */
+static int fit_with_ellipsis(const char *s, float width, bool bold, bool *r_ellipsis)
+{
+ const int len = (int)strlen(s);
+ *r_ellipsis = false;
+ if (bk_text_width(s, len, bold) <= width) {
+ return len;
+ }
+ *r_ellipsis = true;
+ const float ew = bk_text_width("\xe2\x80\xa6", 3, bold);
+ int n = len;
+ while (n > 0) {
+ n--;
+ while (n > 0 && ((uchar)s[n] & 0xC0) == 0x80) {
+ n--;
+ }
+ if (bk_text_width(s, n, bold) + ew <= width) {
+ break;
+ }
+ }
+ return n;
+}
+
+float bk_line_height(void)
+{
+ return floorf(bk_font_size() * 1.45f + 0.5f);
+}
+
+float bk_text_in(const BKRect *rect, const char *s, const uchar color[4], int align, bool bold)
+{
+ if (!s || !s[0]) {
+ return 0.0f;
+ }
+ if (strchr(s, '\n')) { /* multi-line: a centered block of lines */
+ int lines = 1;
+ for (const char *c = s; *c; c++) {
+ lines += *c == '\n';
+ }
+ const float lh = bk_line_height();
+ float y = rect->ymin + (bk_rh(rect) - lines * lh) * 0.5f, widest = 0.0f;
+ for (const char *line = s;; y += lh) {
+ const char *end = strchr(line, '\n');
+ const int len = end ? (int)(end - line) : (int)strlen(line);
+ char buf[512];
+ memcpy(buf, line, (size_t)BK_MIN(len, 511));
+ buf[BK_MIN(len, 511)] = 0;
+ const BKRect lr = bk_rect(rect->xmin, (int)y, bk_rw(rect), (int)lh);
+ widest = BK_MAX(widest, bk_text_in(&lr, buf, color, align, bold));
+ if (!end) {
+ break;
+ }
+ line = end + 1;
+ }
+ return widest;
+ }
+ const int pad = bk_pad();
+ const float avail = (float)(bk_rw(rect) - 2 * pad);
+ bool ell;
+ const int n = fit_with_ellipsis(s, avail, bold, &ell);
+ char buf[512];
+ int blen = BK_MIN(n, (int)sizeof(buf) - 4);
+ memcpy(buf, s, (size_t)blen);
+ if (ell) {
+ memcpy(buf + blen, "\xe2\x80\xa6", 3);
+ blen += 3;
+ }
+ const float tw = bk_text_width(buf, blen, bold);
+ float x;
+ if (align == BK_ALIGN_LEFT) {
+ x = rect->xmin + pad;
+ }
+ else if (align == BK_ALIGN_RIGHT) {
+ x = rect->xmax - pad - tw;
+ }
+ else {
+ x = rect->xmin + (bk_rw(rect) - tw) * 0.5f;
+ }
+ bk_clip_push(rect->xmin, rect->ymin, bk_rw(rect), bk_rh(rect));
+ bk_text(x, bk_text_baseline(rect), buf, blen, color, bold);
+ bk_clip_pop();
+ return tw;
+}
+
+int bk_icon_size(void)
+{
+ return bk_iround(0.8f * bk_unit()); /* ICON_DEFAULT_HEIGHT = 16 * scale */
+}
+
+float bk_content_width(const char *s, int icon, bool bold)
+{
+ float w = (s && s[0]) ? bk_text_width(s, -1, bold) : 0.0f;
+ if (icon) {
+ w += bk_icon_size() + ((s && s[0]) ? 0.25f * bk_unit() : 0.0f);
+ }
+ return w;
+}
+
+void bk_text_icon(const BKRect *rect, const char *s, int icon, const uchar color[4], int align,
+ bool enabled)
+{
+ if (!icon) {
+ bk_text_in(rect, s, color, align, false);
+ return;
+ }
+ const float u = (float)bk_unit();
+ const float is = (float)bk_icon_size();
+ const float alpha = enabled ? 1.0f : 0.5f;
+ if (!s || !s[0]) {
+ bk_icon(icon, rect->xmin + bk_rw(rect) * 0.5f, rect->ymin + bk_rh(rect) * 0.5f, NULL, alpha,
+ 0);
+ return;
+ }
+ const float tw = BK_MIN(bk_text_width(s, -1, false), bk_rw(rect) - is - 2.0f * bk_pad());
+ float ix;
+ if (align == BK_ALIGN_CENTER) {
+ ix = rect->xmin + (bk_rw(rect) - (is + 0.25f * u + tw)) * 0.5f;
+ }
+ else {
+ ix = rect->xmin + 0.2f * u;
+ }
+ bk_icon(icon, ix + is * 0.5f, rect->ymin + bk_rh(rect) * 0.5f, NULL, alpha, 0);
+ BKRect tr = *rect;
+ tr.xmin = (int)(ix + is + 0.25f * u) - bk_pad();
+ bk_text_in(&tr, s, color, BK_ALIGN_LEFT, false);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Icons & small glyphs
+ * \{ */
+
+const float *bk_icon_tint(int icon)
+{
+ if (icon <= 0 || icon >= bk_icon_def_count || !bk_icon_defs[icon].has_tint) {
+ return NULL;
+ }
+ return bk_icon_defs[icon].tint;
+}
+
+void bk_icon(int icon, float cx, float cy, const uchar *color, float alpha, float size)
+{
+ if (icon <= 0 || icon >= bk_icon_def_count) {
+ return;
+ }
+ const float s = size > 0.0f ? size : (float)bk_icon_size();
+ float c[4];
+ if (color) {
+ bk_rgba(color, c);
+ }
+ else {
+ const float *tint = bk_icon_tint(icon);
+ if (tint) {
+ memcpy(c, tint, sizeof(c));
+ }
+ else {
+ bk_rgba(bk_theme.text, c);
+ c[3] *= 0.9f;
+ }
+ }
+ c[3] *= alpha;
+ bk_icons_draw(icon, floorf(cx - s * 0.5f + 0.5f), floorf(cy - s * 0.5f + 0.5f), s, c);
+}
+
+void bk_tria(float cx, float cy, char dir, const float c[4], float size)
+{
+ /* draw_icon_tri(): 'h' right, 'v' down */
+ const float s = size > 0 ? size : 0.18f * bk_unit();
+ float p[3][2];
+ if (dir == 'h') {
+ const float q[3][2] = {{cx - s * 0.5f, cy - s}, {cx - s * 0.5f, cy + s}, {cx + s * 0.7f, cy}};
+ memcpy(p, q, sizeof(p));
+ }
+ else {
+ const float q[3][2] = {{cx - s, cy - s * 0.5f}, {cx + s, cy - s * 0.5f}, {cx, cy + s * 0.7f}};
+ memcpy(p, q, sizeof(p));
+ }
+ BUI_raster_polygon(bk_draw.r, (const float(*)[2])p, 3, c);
+}
+
+void bk_chevron_down(float cx, float cy, const uchar col[4])
+{
+ float c[4];
+ bk_rgba(col, c);
+ const float s = 0.16f * bk_unit(), lw = BK_MAX(1.2f, 0.08f * bk_unit());
+ BUI_raster_line(bk_draw.r, cx - s, cy - s * 0.45f, cx, cy + s * 0.55f, lw, c);
+ BUI_raster_line(bk_draw.r, cx, cy + s * 0.55f, cx + s, cy - s * 0.45f, lw, c);
+}
+
+int bk_icons_lookup(const char *name)
+{
+ if (!name || !name[0]) {
+ return 0;
+ }
+ for (int i = 1; i < bk_icon_def_count; i++) {
+ if (strcmp(bk_icon_defs[i].name, name) == 0) {
+ return i;
+ }
+ }
+ return 0;
+}
+
+int BK_icon_id(const char *name)
+{
+ return bk_icons_lookup(name);
+}
+int BK_icon_count(void)
+{
+ return bk_icon_def_count - 1;
+}
+const char *BK_icon_name(int id)
+{
+ return (id > 0 && id < bk_icon_def_count) ? bk_icon_defs[id].name : "";
+}
+
+void bk_icons_draw(int id, float x, float y, float s, const float color[4])
+{
+ const BKIconDef *def = &bk_icon_defs[id];
+ const float lw = BK_MAX(1.0f, s * 0.085f);
+ BuiRaster *r = bk_draw.r;
+ for (int i = 0; i < def->count; i++) {
+ const BKIconOp *op = &bk_icon_ops[def->first + i];
+ float c[4];
+ if (op->color_mode == 2) {
+ memcpy(c, op->rgba, sizeof(c));
+ c[3] *= color[3];
+ }
+ else {
+ memcpy(c, color, sizeof(c));
+ if (op->color_mode == 1) {
+ c[3] *= op->k;
+ }
+ }
+ const float *a = op->a;
+#define PX(v) (x + (v) * s)
+#define PY(v) (y + (v) * s)
+ switch (op->op) {
+ case BK_ICON_LINE:
+ BUI_raster_line(r, PX(a[0]), PY(a[1]), PX(a[2]), PY(a[3]), lw * a[4], c);
+ break;
+ case BK_ICON_POLY: {
+ float pts[32][2];
+ const int n = BK_MIN(op->npts, 32);
+ for (int k = 0; k < n; k++) {
+ pts[k][0] = PX(bk_icon_pts[op->pts_offset + k][0]);
+ pts[k][1] = PY(bk_icon_pts[op->pts_offset + k][1]);
+ }
+ BUI_raster_polygon(r, (const float(*)[2])pts, n, c);
+ break;
+ }
+ case BK_ICON_DISC:
+ BUI_raster_circle(r, PX(a[0]), PY(a[1]), a[2] * s, 0.0f, c);
+ break;
+ case BK_ICON_RING:
+ BUI_raster_ellipse(r, PX(a[0]), PY(a[1]), a[2] * s, a[3] * s, lw * a[4], c);
+ break;
+ case BK_ICON_RECT:
+ BUI_raster_fill_rect(r, PX(a[0]), PY(a[1]), a[2] * s, a[3] * s, c);
+ break;
+ case BK_ICON_FRAME:
+ BUI_raster_widget(r, PX(a[0]), PY(a[1]), a[2] * s, a[3] * s, a[4] * s, BUI_CORNER_ALL,
+ NULL, NULL, c, lw * a[5], NULL);
+ break;
+ case BK_ICON_BOX:
+ BUI_raster_round_rect(r, PX(a[0]), PY(a[1]), a[2] * s, a[3] * s, a[4] * s, c);
+ break;
+ }
+#undef PX
+#undef PY
+ }
+}
+
+/** \} */
diff --git a/kit/intern/kit_frame.c b/kit/intern/kit_frame.c
new file mode 100644
index 0000000..27cf4b2
--- /dev/null
+++ b/kit/intern/kit_frame.c
@@ -0,0 +1,1030 @@
+/* Frames with Tk's geometry managers (pack, grid, place), radio buttons,
+ * canvases (Tk Canvas / QPainter display lists) and images.
+ *
+ * The packer is Tk's ArrangePacking / ComputePackRequest (generic/tkPack.c):
+ * each child takes a parcel off one side of the remaining cavity, `expand`
+ * shares what is left, fill/anchor place the child inside its parcel. The
+ * gridder follows tkGrid.c's model (column/row minimums from the children,
+ * extra space by weight, sticky placement). Qt box/grid layouts map onto
+ * the same code.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "kit_intern.h"
+
+static int u(void)
+{
+ return bk_unit();
+}
+
+/* -------------------------------------------------------------------- */
+/** \name Geometry info
+ * \{ */
+
+static BKGeom *geom_ensure(BKNode *n)
+{
+ if (!n->geom) {
+ n->geom = (BKGeom *)calloc(1, sizeof(BKGeom));
+ n->geom->rowspan = n->geom->columnspan = 1;
+ }
+ return n->geom;
+}
+
+void BK_geom_set_manager(BKNode *n, int manager)
+{
+ geom_ensure(n)->manager = manager;
+ bk_relayout(n);
+}
+
+int BK_geom_manager(const BKNode *n)
+{
+ return n->geom ? n->geom->manager : BK_GEOM_NONE;
+}
+
+enum { HAS_W = 1, HAS_H = 2, HAS_RW = 4, HAS_RH = 8 };
+
+void BK_geom_set(BKNode *n, const char *key, double v)
+{
+ BKGeom *g = geom_ensure(n);
+ const int iv = (int)floor(v + 0.5);
+#define K(name) (strcmp(key, name) == 0)
+ if (K("side")) g->side = iv;
+ else if (K("fill")) g->fill = iv;
+ else if (K("expand")) g->expand = iv;
+ else if (K("anchor")) g->anchor = iv;
+ else if (K("padx0")) g->padx[0] = iv;
+ else if (K("padx1")) g->padx[1] = iv;
+ else if (K("pady0")) g->pady[0] = iv;
+ else if (K("pady1")) g->pady[1] = iv;
+ else if (K("ipadx")) g->ipadx = iv;
+ else if (K("ipady")) g->ipady = iv;
+ else if (K("row")) g->row = iv;
+ else if (K("column")) g->column = iv;
+ else if (K("rowspan")) g->rowspan = BK_MAX(1, iv);
+ else if (K("columnspan")) g->columnspan = BK_MAX(1, iv);
+ else if (K("sticky")) g->sticky = iv;
+ else if (K("x")) g->x = (float)v;
+ else if (K("y")) g->y = (float)v;
+ else if (K("relx")) g->relx = (float)v;
+ else if (K("rely")) g->rely = (float)v;
+ else if (K("width")) { g->width = (float)v; g->has |= HAS_W; }
+ else if (K("height")) { g->height = (float)v; g->has |= HAS_H; }
+ else if (K("relwidth")) { g->relwidth = (float)v; g->has |= HAS_RW; }
+ else if (K("relheight")) { g->relheight = (float)v; g->has |= HAS_RH; }
+ else if (K("reqwidth")) g->reqw = iv;
+ else if (K("reqheight")) g->reqh = iv;
+ else if (K("reset_place")) { g->x = g->y = g->relx = g->rely = 0; g->has = 0; }
+#undef K
+ bk_relayout(n);
+}
+
+double BK_geom_get(const BKNode *n, const char *key)
+{
+ const BKGeom *g = n->geom;
+ if (!g) {
+ return 0.0;
+ }
+#define K(name) (strcmp(key, name) == 0)
+ if (K("manager")) return g->manager;
+ if (K("side")) return g->side;
+ if (K("fill")) return g->fill;
+ if (K("expand")) return g->expand;
+ if (K("anchor")) return g->anchor;
+ if (K("row")) return g->row;
+ if (K("column")) return g->column;
+ if (K("rowspan")) return g->rowspan;
+ if (K("columnspan")) return g->columnspan;
+ if (K("sticky")) return g->sticky;
+ if (K("reqwidth")) return g->reqw;
+ if (K("reqheight")) return g->reqh;
+#undef K
+ return 0.0;
+}
+
+static void child_req(BKNode *c, int *w, int *h)
+{
+ bk_natural(c, w, h); /* honors reqwidth/reqheight */
+ if (c->geom) {
+ *w += 2 * c->geom->ipadx;
+ *h += 2 * c->geom->ipady;
+ }
+}
+
+/* Offset of a child inside spare space for an anchor (0 = center). */
+static int anchor_off(int anchor, int extra, int lo_bit, int hi_bit)
+{
+ const bool lo = anchor & lo_bit, hi = anchor & hi_bit;
+ if (lo && !hi) {
+ return 0;
+ }
+ if (hi && !lo) {
+ return extra;
+ }
+ return extra / 2;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Frame
+ * \{ */
+
+#define GRID_MAX 64
+
+typedef struct FrameData {
+ float colweight[GRID_MAX], rowweight[GRID_MAX];
+ int colmin[GRID_MAX], rowmin[GRID_MAX];
+} FrameData;
+
+static void frame_init(BKNode *n)
+{
+ n->ext = calloc(1, sizeof(FrameData));
+}
+
+static void frame_free(BKNode *n)
+{
+ free(n->ext);
+}
+
+void BK_frame_grid_weight(BKNode *n, int column_axis, int index, double weight, int minsize)
+{
+ if (n->cls != &bk_cls_frame || index < 0 || index >= GRID_MAX) {
+ return;
+ }
+ FrameData *d = (FrameData *)n->ext;
+ if (column_axis) {
+ d->colweight[index] = (float)weight;
+ d->colmin[index] = minsize;
+ }
+ else {
+ d->rowweight[index] = (float)weight;
+ d->rowmin[index] = minsize;
+ }
+ bk_relayout(n);
+}
+
+static int frame_header_h(const BKNode *n)
+{
+ return (n->text && n->text[0]) ? bk_iround(1.25f * u()) : 0;
+}
+
+static void frame_insets(const BKNode *n, int *l, int *t, int *r, int *b)
+{
+ const int p = n->padding;
+ *l = *r = *b = p;
+ *t = p + frame_header_h(n);
+}
+
+static bool managed(const BKNode *c, int manager)
+{
+ return NODE_VISIBLE(c) && c->geom && c->geom->manager == manager;
+}
+
+static int padsum(const int p[2])
+{
+ return p[0] + p[1];
+}
+
+/* Tk ComputePackRequest. */
+static void pack_request(BKNode *n, int *rw, int *rh)
+{
+ int width = 0, height = 0, maxw = 0, maxh = 0;
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!managed(c, BK_GEOM_PACK)) {
+ continue;
+ }
+ int cw, ch;
+ child_req(c, &cw, &ch);
+ const BKGeom *g = c->geom;
+ if (g->side <= 1) { /* top / bottom */
+ maxw = BK_MAX(maxw, cw + padsum(g->padx) + width);
+ height += ch + padsum(g->pady);
+ }
+ else {
+ maxh = BK_MAX(maxh, ch + padsum(g->pady) + height);
+ width += cw + padsum(g->padx);
+ }
+ }
+ *rw = BK_MAX(maxw, width);
+ *rh = BK_MAX(maxh, height);
+}
+
+static int x_expansion(BKNode *n, int from, int cavity_w)
+{
+ int num = 0, min_exp = cavity_w;
+ for (int i = from; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!managed(c, BK_GEOM_PACK)) {
+ continue;
+ }
+ int cw, ch;
+ child_req(c, &cw, &ch);
+ const int child_w = cw + padsum(c->geom->padx);
+ if (c->geom->side <= 1) {
+ if (num) {
+ min_exp = BK_MIN(min_exp, (cavity_w - child_w) / num);
+ }
+ }
+ else {
+ cavity_w -= child_w;
+ if (c->geom->expand) {
+ num++;
+ }
+ }
+ }
+ if (num) {
+ min_exp = BK_MIN(min_exp, cavity_w / num);
+ }
+ return BK_MAX(0, min_exp);
+}
+
+static int y_expansion(BKNode *n, int from, int cavity_h)
+{
+ int num = 0, min_exp = cavity_h;
+ for (int i = from; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!managed(c, BK_GEOM_PACK)) {
+ continue;
+ }
+ int cw, ch;
+ child_req(c, &cw, &ch);
+ const int child_h = ch + padsum(c->geom->pady);
+ if (c->geom->side >= 2) {
+ if (num) {
+ min_exp = BK_MIN(min_exp, (cavity_h - child_h) / num);
+ }
+ }
+ else {
+ cavity_h -= child_h;
+ if (c->geom->expand) {
+ num++;
+ }
+ }
+ }
+ if (num) {
+ min_exp = BK_MIN(min_exp, cavity_h / num);
+ }
+ return BK_MAX(0, min_exp);
+}
+
+/* Tk ArrangePacking. */
+static void do_pack(BKNode *n, int x0, int y0, int w, int h)
+{
+ int cx = x0, cy = y0, cw = w, ch = h;
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!managed(c, BK_GEOM_PACK)) {
+ continue;
+ }
+ const BKGeom *g = c->geom;
+ int rw, rh;
+ child_req(c, &rw, &rh);
+ int fx, fy, fw, fh;
+ if (g->side <= 1) {
+ fw = cw;
+ fh = rh + padsum(g->pady);
+ if (g->expand) {
+ fh += y_expansion(n, i, ch);
+ }
+ fh = BK_CLAMP(fh, 0, ch);
+ fx = cx;
+ if (g->side == 0) {
+ fy = cy;
+ cy += fh;
+ }
+ else {
+ fy = cy + ch - fh;
+ }
+ ch -= fh;
+ }
+ else {
+ fw = rw + padsum(g->padx);
+ fh = ch;
+ if (g->expand) {
+ fw += x_expansion(n, i, cw);
+ }
+ fw = BK_CLAMP(fw, 0, cw);
+ fy = cy;
+ if (g->side == 2) {
+ fx = cx;
+ cx += fw;
+ }
+ else {
+ fx = cx + cw - fw;
+ }
+ cw -= fw;
+ }
+ const int aw = BK_MAX(0, fw - padsum(g->padx)), ah = BK_MAX(0, fh - padsum(g->pady));
+ const int ww = ((g->fill & 1) || rw > aw) ? aw : rw;
+ const int hh = ((g->fill & 2) || rh > ah) ? ah : rh;
+ bk_arrange(c, fx + g->padx[0] + anchor_off(g->anchor, aw - ww, BK_ANCHOR_W, BK_ANCHOR_E),
+ fy + g->pady[0] + anchor_off(g->anchor, ah - hh, BK_ANCHOR_N, BK_ANCHOR_S), ww,
+ hh);
+ }
+}
+
+/* -- grid -- */
+
+static void grid_sizes(BKNode *n, int *colw, int *rowh, int *r_ncols, int *r_nrows)
+{
+ FrameData *d = (FrameData *)n->ext;
+ int ncols = 0, nrows = 0;
+ memset(colw, 0, sizeof(int) * GRID_MAX);
+ memset(rowh, 0, sizeof(int) * GRID_MAX);
+ /* single-span children first, then spanning ones grow the last cell */
+ for (int pass = 0; pass < 2; pass++) {
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!managed(c, BK_GEOM_GRID)) {
+ continue;
+ }
+ const BKGeom *g = c->geom;
+ const int c0 = BK_CLAMP(g->column, 0, GRID_MAX - 1), r0 = BK_CLAMP(g->row, 0, GRID_MAX - 1);
+ const int cs = BK_CLAMP(g->columnspan, 1, GRID_MAX - c0),
+ rs = BK_CLAMP(g->rowspan, 1, GRID_MAX - r0);
+ ncols = BK_MAX(ncols, c0 + cs);
+ nrows = BK_MAX(nrows, r0 + rs);
+ int cw, ch;
+ child_req(c, &cw, &ch);
+ cw += padsum(g->padx);
+ ch += padsum(g->pady);
+ if (pass == 0 && cs == 1) {
+ colw[c0] = BK_MAX(colw[c0], cw);
+ }
+ if (pass == 0 && rs == 1) {
+ rowh[r0] = BK_MAX(rowh[r0], ch);
+ }
+ if (pass == 1 && cs > 1) {
+ int sum = 0;
+ for (int k = c0; k < c0 + cs; k++) {
+ sum += colw[k];
+ }
+ if (sum < cw) {
+ colw[c0 + cs - 1] += cw - sum;
+ }
+ }
+ if (pass == 1 && rs > 1) {
+ int sum = 0;
+ for (int k = r0; k < r0 + rs; k++) {
+ sum += rowh[k];
+ }
+ if (sum < ch) {
+ rowh[r0 + rs - 1] += ch - sum;
+ }
+ }
+ }
+ }
+ for (int k = 0; k < ncols; k++) {
+ colw[k] = BK_MAX(colw[k], d->colmin[k]);
+ }
+ for (int k = 0; k < nrows; k++) {
+ rowh[k] = BK_MAX(rowh[k], d->rowmin[k]);
+ }
+ *r_ncols = ncols;
+ *r_nrows = nrows;
+}
+
+static void grid_request(BKNode *n, int *rw, int *rh)
+{
+ int colw[GRID_MAX], rowh[GRID_MAX], nc, nr;
+ grid_sizes(n, colw, rowh, &nc, &nr);
+ *rw = *rh = 0;
+ for (int k = 0; k < nc; k++) {
+ *rw += colw[k];
+ }
+ for (int k = 0; k < nr; k++) {
+ *rh += rowh[k];
+ }
+}
+
+static void distribute(int *sizes, int count, const float *weights, int extra)
+{
+ float total = 0.0f;
+ for (int k = 0; k < count; k++) {
+ total += weights[k];
+ }
+ if (extra <= 0 || total <= 0.0f) {
+ return;
+ }
+ int given = 0, last = -1;
+ for (int k = 0; k < count; k++) {
+ if (weights[k] > 0.0f) {
+ const int add = (int)(extra * weights[k] / total);
+ sizes[k] += add;
+ given += add;
+ last = k;
+ }
+ }
+ if (last >= 0) {
+ sizes[last] += extra - given; /* rounding remainder */
+ }
+}
+
+static void do_grid(BKNode *n, int x0, int y0, int w, int h)
+{
+ FrameData *d = (FrameData *)n->ext;
+ int colw[GRID_MAX], rowh[GRID_MAX], nc, nr;
+ grid_sizes(n, colw, rowh, &nc, &nr);
+ if (!nc) {
+ return;
+ }
+ int sw = 0, sh = 0;
+ for (int k = 0; k < nc; k++) {
+ sw += colw[k];
+ }
+ for (int k = 0; k < nr; k++) {
+ sh += rowh[k];
+ }
+ distribute(colw, nc, d->colweight, w - sw);
+ distribute(rowh, nr, d->rowweight, h - sh);
+ int colx[GRID_MAX + 1], rowy[GRID_MAX + 1];
+ colx[0] = x0;
+ for (int k = 0; k < nc; k++) {
+ colx[k + 1] = colx[k] + colw[k];
+ }
+ rowy[0] = y0;
+ for (int k = 0; k < nr; k++) {
+ rowy[k + 1] = rowy[k] + rowh[k];
+ }
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!managed(c, BK_GEOM_GRID)) {
+ continue;
+ }
+ const BKGeom *g = c->geom;
+ const int c0 = BK_CLAMP(g->column, 0, GRID_MAX - 1), r0 = BK_CLAMP(g->row, 0, GRID_MAX - 1);
+ const int c1 = BK_MIN(nc, c0 + g->columnspan), r1 = BK_MIN(nr, r0 + g->rowspan);
+ const int cx = colx[c0] + g->padx[0], cy = rowy[r0] + g->pady[0];
+ const int cw = BK_MAX(0, colx[c1] - colx[c0] - padsum(g->padx));
+ const int ch = BK_MAX(0, rowy[r1] - rowy[r0] - padsum(g->pady));
+ int rw, rh;
+ child_req(c, &rw, &rh);
+ const int st = g->sticky;
+ const int ww = ((st & BK_ANCHOR_W) && (st & BK_ANCHOR_E)) ? cw : BK_MIN(rw, cw);
+ const int hh = ((st & BK_ANCHOR_N) && (st & BK_ANCHOR_S)) ? ch : BK_MIN(rh, ch);
+ bk_arrange(c, cx + anchor_off(st, cw - ww, BK_ANCHOR_W, BK_ANCHOR_E),
+ cy + anchor_off(st, ch - hh, BK_ANCHOR_N, BK_ANCHOR_S), ww, hh);
+ }
+}
+
+static void do_place(BKNode *c, int x0, int y0, int pw, int ph)
+{
+ const BKGeom *g = c->geom;
+ int rw, rh;
+ child_req(c, &rw, &rh);
+ float x = g->relx * pw + g->x, y = g->rely * ph + g->y;
+ float ww = g->relwidth * pw + g->width, hh = g->relheight * ph + g->height;
+ if (!(g->has & (HAS_W | HAS_RW))) {
+ ww = (float)rw;
+ }
+ if (!(g->has & (HAS_H | HAS_RH))) {
+ hh = (float)rh;
+ }
+ /* anchor: which point of the child sits at (x, y); place defaults to nw */
+ const int a = g->anchor ? g->anchor : (BK_ANCHOR_N | BK_ANCHOR_W);
+ x -= anchor_off(a, (int)ww, BK_ANCHOR_W, BK_ANCHOR_E);
+ y -= anchor_off(a, (int)hh, BK_ANCHOR_N, BK_ANCHOR_S);
+ bk_arrange(c, x0 + (int)x, y0 + (int)y, (int)ww, (int)hh);
+}
+
+static void frame_measure(BKNode *n, int *rw, int *rh)
+{
+ int l, t, r, b;
+ frame_insets(n, &l, &t, &r, &b);
+ int pw = 0, ph = 0, gw = 0, gh = 0;
+ if (!(n->flags & NF_NOPROPAGATE)) {
+ pack_request(n, &pw, &ph);
+ grid_request(n, &gw, &gh);
+ }
+ int w = BK_MAX(pw, gw), h = BK_MAX(ph, gh);
+ if (frame_header_h(n)) {
+ w = BK_MAX(w, (int)bk_text_width(n->text, -1, false) + 2 * u());
+ }
+ *rw = w + l + r;
+ *rh = h + t + b;
+}
+
+static void frame_arrange(BKNode *n)
+{
+ int l, t, r, b;
+ frame_insets(n, &l, &t, &r, &b);
+ const int x0 = n->x + l, y0 = n->y + t;
+ const int w = BK_MAX(0, n->w - l - r), h = BK_MAX(0, n->h - t - b);
+ do_pack(n, x0, y0, w, h);
+ do_grid(n, x0, y0, w, h);
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (managed(c, BK_GEOM_PLACE)) {
+ do_place(c, x0, y0, w, h);
+ }
+ else if (!c->geom || c->geom->manager == BK_GEOM_NONE) {
+ c->x = c->y = c->w = c->h = 0; /* unmanaged: not shown (Tk) */
+ }
+ }
+}
+
+static bool shown(const BKNode *c)
+{
+ return NODE_VISIBLE(c) && c->geom && c->geom->manager != BK_GEOM_NONE;
+}
+
+static void frame_draw(BKNode *n)
+{
+ float c[4];
+ const int hh = frame_header_h(n);
+ if (hh) { /* LabelFrame / QGroupBox: a Blender panel (header + body) */
+ const float rad = bk_theme.panel_roundness * 0.5f * u();
+ bk_rgba(bk_theme.panel_back, c);
+ bk_roundbox(n->x, n->y, n->w, n->h, rad, CNR_ALL, c);
+ bk_rgba(bk_theme.panel_header, c);
+ bk_roundbox(n->x, n->y, n->w, hh, rad, CNR_TL | CNR_TR, c);
+ BKRect tr = bk_rect(n->x + (int)(0.4f * u()), n->y, n->w, hh);
+ bk_text_in(&tr, n->text, bk_theme.text, BK_ALIGN_LEFT, false);
+ }
+ else if (n->flags & NF_HAS_BG) {
+ bk_fill_f(n->x, n->y, n->w, n->h, n->color);
+ }
+}
+
+/* Shared by frames and canvases: own drawing, then managed children clipped
+ * to the widget (Tk children never spill out). */
+static void frame_draw_tree(BKNode *n)
+{
+ if (!NODE_VISIBLE(n)) {
+ return;
+ }
+ BKRect r = bk_rect(n->x - 3, n->y - 3, n->w + 6, n->h + 6);
+ if (!bk_clip_visible(&r)) {
+ return;
+ }
+ n->cls->draw(n);
+ bk_clip_push(n->x, n->y, n->w, n->h + 2); /* children never spill out (Tk) */
+ for (int i = 0; i < n->nkids; i++) {
+ if (shown(n->kids[i])) {
+ bk_draw_tree(n->kids[i]);
+ }
+ }
+ bk_clip_pop();
+}
+
+static BKNode *frame_hit(BKNode *n, int x, int y)
+{
+ for (int i = n->nkids - 1; i >= 0; i--) {
+ BKNode *c = n->kids[i];
+ if (shown(c)) {
+ BKNode *f = bk_hit(c, x, y);
+ if (f) {
+ return f;
+ }
+ }
+ }
+ return (n->flags & NF_EVENTS) ? n : NULL;
+}
+
+const BKClass bk_cls_frame = {.name = "frame",
+ .init = frame_init,
+ .free_ext = frame_free,
+ .measure = frame_measure,
+ .arrange = frame_arrange,
+ .draw = frame_draw,
+ .draw_tree = frame_draw_tree,
+ .hit = frame_hit};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Radio button
+ * \{ */
+
+static int radio_press(BKNode *n, BKEvent *e)
+{
+ if (!n->value) {
+ bk_set_value(n, 1); /* a radio only ever turns itself on */
+ }
+ return 1;
+}
+
+static void radio_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = u() + (int)bk_text_width(n->label, -1, false) + bk_pad();
+ *rh = u();
+}
+
+static void radio_draw(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ int st = NODE_ENABLED(n) ? (bk_hovered(n) ? ST_HOVER : 0) : ST_DISABLED;
+ if (n->value) {
+ st |= ST_SELECT;
+ }
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.option, st);
+ w.roundness = 0.5f; /* round option box */
+ BKRect box = r;
+ bk_widget_optionbut(&w, &box, st & ~ST_SELECT); /* no checkmark: a dot instead */
+ if (n->value) {
+ const int s = bk_rh(&r);
+ const float cx = r.xmin + s * 0.5f - (s - 2 * bk_px()) / 6.0f, cy = r.ymin + s * 0.5f;
+ float dot[4];
+ bk_rgba(w.item, dot);
+ bk_circle(cx, cy, s * 0.14f, dot);
+ }
+ uchar tc[4];
+ memcpy(tc, bk_theme.option.text, 4);
+ if (!NODE_ENABLED(n)) {
+ tc[3] /= 2;
+ }
+ box.xmin -= bk_pad() / 2;
+ bk_text_in(&box, n->label, tc, BK_ALIGN_LEFT, false);
+}
+
+static int radio_to_text(BKNode *n, char *buf, int size)
+{
+ buf[0] = n->value ? '1' : '0';
+ buf[1] = 0;
+ return 1;
+}
+
+const BKClass bk_cls_radio = {.name = "radio",
+ .flags = CLS_INTERACTIVE,
+ .measure = radio_measure,
+ .draw = radio_draw,
+ .press = radio_press,
+ .to_text = radio_to_text};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Images
+ * \{ */
+
+void bk_image_free(BKImage *img)
+{
+ if (img) {
+ free(img->argb);
+ free(img);
+ }
+}
+
+static BKImage *image_from_rgba(const unsigned char *rgba, int w, int h)
+{
+ if (!rgba || w <= 0 || h <= 0) {
+ return NULL;
+ }
+ BKImage *img = (BKImage *)calloc(1, sizeof(BKImage));
+ img->w = w;
+ img->h = h;
+ img->argb = (uint32_t *)malloc(sizeof(uint32_t) * (size_t)w * h);
+ for (int i = 0; i < w * h; i++) {
+ const unsigned char *p = rgba + 4 * (size_t)i;
+ img->argb[i] = ((uint32_t)p[3] << 24) | ((uint32_t)p[0] << 16) | ((uint32_t)p[1] << 8) | p[2];
+ }
+ return img;
+}
+
+void bk_image_draw(const BKImage *img, float x, float y, float w, float h, float alpha)
+{
+ if (img) {
+ BUI_raster_image(bk_draw.r, x, y, w, h, img->argb, img->w, img->h, alpha);
+ }
+}
+
+void BK_node_set_image(BKNode *n, const unsigned char *rgba, int w, int h)
+{
+ bk_image_free((BKImage *)n->image);
+ n->image = image_from_rgba(rgba, w, h);
+ bk_relayout(n);
+ bk_invalidate(n);
+}
+
+static void image_measure(BKNode *n, int *rw, int *rh)
+{
+ const BKImage *img = (const BKImage *)n->image;
+ *rw = img ? img->w : u();
+ *rh = img ? img->h : u();
+}
+
+static void image_draw(BKNode *n)
+{
+ const BKImage *img = (const BKImage *)n->image;
+ if (img) {
+ bk_image_draw(img, n->x + (n->w - img->w) / 2, n->y + (n->h - img->h) / 2, img->w, img->h,
+ NODE_ENABLED(n) ? 1.0f : 0.5f);
+ }
+}
+
+const BKClass bk_cls_image = {.name = "image", .measure = image_measure, .draw = image_draw};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Canvas (display list)
+ * \{ */
+
+typedef struct CItem {
+ BKCanvasItem it;
+ float *coords;
+ char *text;
+ BKImage *img;
+} CItem;
+
+typedef struct CanvasData {
+ CItem *items;
+ int n, cap;
+} CanvasData;
+
+#define CANVAS(n) ((CanvasData *)(n)->ext)
+
+static void canvas_init(BKNode *n)
+{
+ n->ext = calloc(1, sizeof(CanvasData));
+}
+
+static void citem_free(CItem *c)
+{
+ free(c->coords);
+ free(c->text);
+ bk_image_free(c->img);
+}
+
+static void canvas_free(BKNode *n)
+{
+ CanvasData *d = CANVAS(n);
+ for (int i = 0; i < d->n; i++) {
+ citem_free(&d->items[i]);
+ }
+ free(d->items);
+ free(d);
+}
+
+static int canvas_find(CanvasData *d, int id)
+{
+ for (int i = 0; i < d->n; i++) {
+ if (d->items[i].it.id == id) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+void BK_canvas_set_item(BKNode *n, const BKCanvasItem *item)
+{
+ if (n->cls != &bk_cls_canvas) {
+ return;
+ }
+ CanvasData *d = CANVAS(n);
+ int i = canvas_find(d, item->id);
+ if (i < 0) {
+ if (d->n == d->cap) {
+ d->cap = d->cap ? d->cap * 2 : 16;
+ d->items = (CItem *)realloc(d->items, sizeof(CItem) * (size_t)d->cap);
+ }
+ i = d->n++;
+ memset(&d->items[i], 0, sizeof(CItem));
+ }
+ else {
+ citem_free(&d->items[i]);
+ }
+ CItem *c = &d->items[i];
+ c->it = *item;
+ c->coords = (float *)malloc(sizeof(float) * (size_t)BK_MAX(1, item->ncoords));
+ memcpy(c->coords, item->coords, sizeof(float) * (size_t)item->ncoords);
+ c->it.coords = c->coords;
+ c->text = item->text ? bk_strdup(item->text) : NULL;
+ c->it.text = c->text;
+ c->img = image_from_rgba(item->rgba, item->iw, item->ih);
+ c->it.rgba = NULL;
+ bk_invalidate(n);
+}
+
+void BK_canvas_delete(BKNode *n, int id)
+{
+ CanvasData *d = CANVAS(n);
+ for (int i = d->n - 1; i >= 0; i--) {
+ if (id < 0 || d->items[i].it.id == id) {
+ citem_free(&d->items[i]);
+ memmove(d->items + i, d->items + i + 1, sizeof(CItem) * (size_t)(d->n - i - 1));
+ d->n--;
+ }
+ }
+ bk_invalidate(n);
+}
+
+void BK_canvas_raise(BKNode *n, int id, int to_top)
+{
+ CanvasData *d = CANVAS(n);
+ const int i = canvas_find(d, id);
+ if (i < 0) {
+ return;
+ }
+ CItem tmp = d->items[i];
+ memmove(d->items + i, d->items + i + 1, sizeof(CItem) * (size_t)(d->n - i - 1));
+ if (to_top) {
+ d->items[d->n - 1] = tmp;
+ }
+ else {
+ memmove(d->items + 1, d->items, sizeof(CItem) * (size_t)(d->n - 1));
+ d->items[0] = tmp;
+ }
+ bk_invalidate(n);
+}
+
+int BK_canvas_count(BKNode *n)
+{
+ return CANVAS(n)->n;
+}
+
+static void canvas_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = 10 * u();
+ *rh = 5 * u();
+}
+
+static void draw_polyline(const float *pts, int npts, float ox, float oy, const float c[4],
+ float width, bool closed)
+{
+ for (int k = 0; k + 1 < npts; k++) {
+ bk_line(ox + pts[2 * k], oy + pts[2 * k + 1], ox + pts[2 * k + 2], oy + pts[2 * k + 3], c,
+ width);
+ }
+ if (closed && npts > 2) {
+ bk_line(ox + pts[2 * npts - 2], oy + pts[2 * npts - 1], ox + pts[0], oy + pts[1], c, width);
+ }
+}
+
+static void canvas_item_draw(const CItem *ci, float ox, float oy)
+{
+ const BKCanvasItem *it = &ci->it;
+ if (it->hidden) {
+ return;
+ }
+ const float *p = ci->coords;
+ const float lw = it->width > 0 ? it->width : 1.0f;
+ const bool fill = it->fill[3] > 0, outline = it->outline[3] > 0;
+ BuiRaster *r = bk_draw.r;
+ switch (it->type) {
+ case BK_ITEM_RECT:
+ case BK_ITEM_ROUNDRECT: {
+ if (it->ncoords < 4) {
+ return;
+ }
+ const float x0 = BK_MIN(p[0], p[2]), y0 = BK_MIN(p[1], p[3]);
+ const float w = fabsf(p[2] - p[0]), h = fabsf(p[3] - p[1]);
+ if (it->type == BK_ITEM_ROUNDRECT || it->radius > 0) {
+ BuiWidgetBase wb = {{ox + x0, oy + y0, w, h}, it->radius, BK_MAX(0, it->radius - lw), CNR_ALL};
+ if (fill) {
+ memcpy(wb.inner1, it->fill, sizeof(float[4]));
+ memcpy(wb.inner2, it->fill, sizeof(float[4]));
+ }
+ if (outline) {
+ memcpy(wb.outline, it->outline, sizeof(float[4]));
+ }
+ wb.pixelsize = lw;
+ BUI_raster_widget_base(r, &wb);
+ }
+ else {
+ if (fill) {
+ BUI_raster_fill_rect(r, ox + x0, oy + y0, w, h, it->fill);
+ }
+ if (outline) {
+ BUI_raster_frame_rect(r, ox + x0, oy + y0, w, h, lw, it->outline);
+ }
+ }
+ break;
+ }
+ case BK_ITEM_OVAL: {
+ if (it->ncoords < 4) {
+ return;
+ }
+ const float cx = ox + (p[0] + p[2]) * 0.5f, cy = oy + (p[1] + p[3]) * 0.5f;
+ const float rx = fabsf(p[2] - p[0]) * 0.5f, ry = fabsf(p[3] - p[1]) * 0.5f;
+ if (fill) {
+ BUI_raster_ellipse(r, cx, cy, rx, ry, 0.0f, it->fill);
+ }
+ if (outline) {
+ BUI_raster_ellipse(r, cx, cy, rx, ry, lw, it->outline);
+ }
+ break;
+ }
+ case BK_ITEM_LINE: {
+ const float *c = it->fill[3] > 0 ? it->fill : it->outline;
+ draw_polyline(p, it->ncoords / 2, ox, oy, c, lw, false);
+ break;
+ }
+ case BK_ITEM_POLYGON: {
+ const int np = it->ncoords / 2;
+ if (np >= 3 && fill) {
+ float(*pts)[2] = (float(*)[2])malloc(sizeof(float[2]) * (size_t)np);
+ for (int k = 0; k < np; k++) {
+ pts[k][0] = ox + p[2 * k];
+ pts[k][1] = oy + p[2 * k + 1];
+ }
+ BUI_raster_polygon(r, (const float(*)[2])pts, np, it->fill);
+ free(pts);
+ }
+ if (outline) {
+ draw_polyline(p, np, ox, oy, it->outline, lw, true);
+ }
+ break;
+ }
+ case BK_ITEM_ARC: {
+ if (it->ncoords < 4) {
+ return;
+ }
+ /* Tk pieslice: center + points along the arc (degrees ccw from 3 o'clock) */
+ const float cx = ox + (p[0] + p[2]) * 0.5f, cy = oy + (p[1] + p[3]) * 0.5f;
+ const float rx = fabsf(p[2] - p[0]) * 0.5f, ry = fabsf(p[3] - p[1]) * 0.5f;
+ const int seg = 48;
+ float pts[50][2];
+ pts[0][0] = cx;
+ pts[0][1] = cy;
+ for (int k = 0; k <= seg; k++) {
+ const float a = (it->start + it->extent * k / seg) * 3.14159265f / 180.0f;
+ pts[k + 1][0] = cx + rx * cosf(a);
+ pts[k + 1][1] = cy - ry * sinf(a);
+ }
+ if (fill) {
+ BUI_raster_polygon(r, (const float(*)[2])pts, seg + 2, it->fill);
+ }
+ if (outline) {
+ for (int k = 1; k <= seg; k++) {
+ bk_line(pts[k][0], pts[k][1], pts[k + 1][0], pts[k + 1][1], it->outline, lw);
+ }
+ }
+ break;
+ }
+ case BK_ITEM_TEXT: {
+ if (!ci->text || it->ncoords < 2) {
+ return;
+ }
+ const float size = it->size > 0 ? it->size : bk_font_size();
+ const int len = (int)strlen(ci->text);
+ float tw = 0;
+ BUI_text_measure("", 0, size, ci->text, len, &tw);
+ float x = ox + p[0], y = oy + p[1];
+ x -= anchor_off(it->anchor, (int)tw, BK_ANCHOR_W, BK_ANCHOR_E);
+ /* y: baseline from the anchor (cap height ~0.72 em) */
+ const float asc = size * 0.72f;
+ y += asc - anchor_off(it->anchor, (int)asc, BK_ANCHOR_N, BK_ANCHOR_S);
+ const float *c = it->fill[3] > 0 ? it->fill : it->outline;
+ BUI_raster_set_font(r, "", 0);
+ BUI_raster_text(r, floorf(x + 0.5f), floorf(y + 0.5f), ci->text, len, size, c);
+ break;
+ }
+ case BK_ITEM_IMAGE: {
+ if (!ci->img || it->ncoords < 2) {
+ return;
+ }
+ const float w = (float)ci->img->w, h = (float)ci->img->h;
+ const float x = ox + p[0] - anchor_off(it->anchor, (int)w, BK_ANCHOR_W, BK_ANCHOR_E);
+ const float y = oy + p[1] - anchor_off(it->anchor, (int)h, BK_ANCHOR_N, BK_ANCHOR_S);
+ bk_image_draw(ci->img, x, y, w, h, 1.0f);
+ break;
+ }
+ }
+}
+
+static void canvas_draw(BKNode *n)
+{
+ if (n->flags & NF_HAS_BG) {
+ bk_fill_f(n->x, n->y, n->w, n->h, n->color);
+ }
+ CanvasData *d = CANVAS(n);
+ bk_clip_push(n->x, n->y, n->w, n->h);
+ const float ox = (float)(n->x - n->scroll_x), oy = (float)(n->y - n->scroll);
+ for (int i = 0; i < d->n; i++) {
+ canvas_item_draw(&d->items[i], ox, oy);
+ }
+ bk_clip_pop();
+}
+
+/* create_window: place-managed children sit at canvas coordinates, scrolled
+ * with the items. */
+static void canvas_arrange(BKNode *n)
+{
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (managed(c, BK_GEOM_PLACE)) {
+ do_place(c, n->x - n->scroll_x, n->y - n->scroll, n->w, n->h);
+ }
+ else {
+ c->x = c->y = c->w = c->h = 0;
+ }
+ }
+}
+
+const BKClass bk_cls_canvas = {.name = "canvas",
+ .init = canvas_init,
+ .free_ext = canvas_free,
+ .measure = canvas_measure,
+ .arrange = canvas_arrange,
+ .draw = canvas_draw,
+ .draw_tree = frame_draw_tree,
+ .hit = frame_hit};
+
+/** \} */
diff --git a/kit/intern/kit_icons_data.c b/kit/intern/kit_icons_data.c
new file mode 100644
index 0000000..d55e607
--- /dev/null
+++ b/kit/intern/kit_icons_data.c
@@ -0,0 +1,590 @@
+/* Generated by tools/gen_kit_icons.py from tools/kit_icons_src.py — do not edit.
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#include "kit_icons_data.h"
+
+const BKIconOp bk_icon_ops[] = {
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.1800f, 0.5000f, 0.8200f, 1.2000f, 0.0000f}, 0, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1800f, 0.5000f, 0.8200f, 0.5000f, 1.2000f, 0.0000f}, 0, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8000f, 0.1400f, 0.4200f, 0.5600f, 1.6000f, 0.0000f}, 0, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 0, 5},
+ {6, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1200f, 0.3400f, 0.5600f, 0.4200f, 0.0800f, 0.0000f}, 5, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 5, 4},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3200f, 0.2400f, 0.1000f, 0.1000f, 1.0000f, 0.0000f}, 9, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5200f, 0.2400f, 0.1000f, 0.1000f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2400f, 0.2400f, 0.7600f, 0.7600f, 1.2000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7600f, 0.2400f, 0.2400f, 0.7600f, 1.2000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.5200f, 0.4200f, 0.7400f, 1.3000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4200f, 0.7400f, 0.8200f, 0.2800f, 1.3000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.3000f, 0.8000f, 0.3000f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.5000f, 0.8000f, 0.5000f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.7000f, 0.8000f, 0.7000f, 1.1000f, 0.0000f}, 9, 0},
+ {5, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.2400f, 0.6800f, 0.5600f, 0.1000f, 1.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.4200f, 0.8400f, 0.4200f, 1.0000f, 0.0000f}, 9, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3200f, 0.5000f, 0.1800f, 0.1200f, 1.0000f, 0.0000f}, 9, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6800f, 0.5000f, 0.1800f, 0.1200f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4000f, 0.5000f, 0.6000f, 0.5000f, 1.3000f, 0.0000f}, 9, 0},
+ {5, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1400f, 0.1400f, 0.5000f, 0.5000f, 0.0600f, 1.0000f}, 9, 0},
+ {6, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3800f, 0.3800f, 0.5000f, 0.5000f, 0.0600f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.1200f, 0.8600f, 0.3200f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8600f, 0.3200f, 0.8600f, 0.7000f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8600f, 0.7000f, 0.5000f, 0.9000f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.9000f, 0.1400f, 0.7000f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1400f, 0.7000f, 0.1400f, 0.3200f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1400f, 0.3200f, 0.5000f, 0.1200f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1400f, 0.3200f, 0.5000f, 0.5200f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5200f, 0.8600f, 0.3200f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5200f, 0.5000f, 0.9000f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1400f, 0.7000f, 0.2000f, 0.5738f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.5738f, 0.2600f, 0.4625f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2600f, 0.4625f, 0.3200f, 0.3730f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3200f, 0.3730f, 0.3800f, 0.3103f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3800f, 0.3103f, 0.4400f, 0.2774f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4400f, 0.2774f, 0.5000f, 0.2750f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.2750f, 0.5600f, 0.3016f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5600f, 0.3016f, 0.6200f, 0.3536f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6200f, 0.3536f, 0.6800f, 0.4260f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6800f, 0.4260f, 0.7400f, 0.5125f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7400f, 0.5125f, 0.8000f, 0.6062f, 1.1000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8000f, 0.6062f, 0.8600f, 0.7000f, 1.1000f, 0.0000f}, 9, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.0900f, 0.0000f, 0.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.2000f, 0.8000f, 0.5000f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8000f, 0.5000f, 0.5000f, 0.8000f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.8000f, 0.2000f, 0.5000f, 1.0000f, 0.0000f}, 9, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.5000f, 0.5000f, 0.2000f, 1.0000f, 0.0000f}, 9, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 9, 4},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2500f, 0.4000f, 0.5000f, 0.6400f, 1.1000f, 0.0000f}, 13, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.6400f, 0.7500f, 0.4000f, 1.1000f, 0.0000f}, 13, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 13, 3},
+ {0, 2, 1.0000f, {0.1000f, 0.1000f, 0.1000f, 1.0000f}, {0.5000f, 0.3600f, 0.5000f, 0.6200f, 1.3000f, 0.0000f}, 16, 0},
+ {2, 2, 1.0000f, {0.1000f, 0.1000f, 0.1000f, 1.0000f}, {0.5000f, 0.7400f, 0.0500f, 0.0000f, 0.0000f, 0.0000f}, 16, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.5500f, 0.2000f, 0.8600f, 1.0000f, 0.0000f}, 16, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.8600f, 0.8000f, 0.8600f, 1.0000f, 0.0000f}, 16, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8000f, 0.8600f, 0.8000f, 0.5500f, 1.0000f, 0.0000f}, 16, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.6600f, 0.5000f, 0.1400f, 1.2000f, 0.0000f}, 16, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3200f, 0.3200f, 0.5000f, 0.1400f, 1.2000f, 0.0000f}, 16, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.1400f, 0.6800f, 0.3200f, 1.2000f, 0.0000f}, 16, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.8400f, 0.5600f, 0.4400f, 1.4000f, 0.0000f}, 16, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 16, 4},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4400f, 0.3200f, 0.6800f, 0.5600f, 1.2000f, 0.0000f}, 20, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.1200f, 0.8200f, 0.2400f, 1.0000f, 0.0000f}, 20, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8200f, 0.2400f, 0.7800f, 0.6000f, 1.0000f, 0.0000f}, 20, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7800f, 0.6000f, 0.5000f, 0.8800f, 1.0000f, 0.0000f}, 20, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.8800f, 0.2200f, 0.6000f, 1.0000f, 0.0000f}, 20, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2200f, 0.6000f, 0.1800f, 0.2400f, 1.0000f, 0.0000f}, 20, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1800f, 0.2400f, 0.5000f, 0.1200f, 1.0000f, 0.0000f}, 20, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 20, 6},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7400f, 0.2000f, 0.1000f, 0.6000f, 0.0000f, 0.0000f}, 26, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 26, 3},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2400f, 0.1000f, 0.6000f, 0.1000f, 1.0000f, 0.0000f}, 29, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6000f, 0.1000f, 0.7800f, 0.2800f, 1.0000f, 0.0000f}, 29, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7800f, 0.2800f, 0.7800f, 0.9000f, 1.0000f, 0.0000f}, 29, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7800f, 0.9000f, 0.2400f, 0.9000f, 1.0000f, 0.0000f}, 29, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2400f, 0.9000f, 0.2400f, 0.1000f, 1.0000f, 0.0000f}, 29, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6000f, 0.1000f, 0.6000f, 0.2800f, 1.0000f, 0.0000f}, 29, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6000f, 0.2800f, 0.7800f, 0.2800f, 1.0000f, 0.0000f}, 29, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 29, 6},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 35, 6},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.2000f, 0.8000f, 0.2000f, 1.3000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.2000f, 0.5000f, 0.8400f, 1.3000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.4000f, 0.1600f, 0.1600f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.1600f, 0.4000f, 0.1600f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8400f, 0.4000f, 0.8400f, 0.1600f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8400f, 0.1600f, 0.6000f, 0.1600f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.6000f, 0.1600f, 0.8400f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.8400f, 0.4000f, 0.8400f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8400f, 0.6000f, 0.8400f, 0.8400f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8400f, 0.8400f, 0.6000f, 0.8400f, 1.1000f, 0.0000f}, 41, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3600f, 0.2500f, 0.0600f, 0.0000f, 0.0000f, 0.0000f}, 41, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3600f, 0.5000f, 0.0600f, 0.0000f, 0.0000f, 0.0000f}, 41, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3600f, 0.7500f, 0.0600f, 0.0000f, 0.0000f, 0.0000f}, 41, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6400f, 0.2500f, 0.0600f, 0.0000f, 0.0000f, 0.0000f}, 41, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6400f, 0.5000f, 0.0600f, 0.0000f, 0.0000f, 0.0000f}, 41, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6400f, 0.7500f, 0.0600f, 0.0000f, 0.0000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1464f, 0.5064f, 0.1883f, 0.4691f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1883f, 0.4691f, 0.2340f, 0.4366f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2340f, 0.4366f, 0.2831f, 0.4095f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2831f, 0.4095f, 0.3349f, 0.3881f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3349f, 0.3881f, 0.3887f, 0.3725f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3887f, 0.3725f, 0.4440f, 0.3631f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4440f, 0.3631f, 0.5000f, 0.3600f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.3600f, 0.5560f, 0.3631f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5560f, 0.3631f, 0.6113f, 0.3725f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6113f, 0.3725f, 0.6651f, 0.3881f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6651f, 0.3881f, 0.7169f, 0.4095f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7169f, 0.4095f, 0.7660f, 0.4366f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7660f, 0.4366f, 0.8117f, 0.4691f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8117f, 0.4691f, 0.8536f, 0.5064f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1464f, 0.4936f, 0.1883f, 0.5309f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1883f, 0.5309f, 0.2340f, 0.5634f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2340f, 0.5634f, 0.2831f, 0.5905f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2831f, 0.5905f, 0.3349f, 0.6119f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3349f, 0.6119f, 0.3887f, 0.6275f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3887f, 0.6275f, 0.4440f, 0.6369f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4440f, 0.6369f, 0.5000f, 0.6400f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.6400f, 0.5560f, 0.6369f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5560f, 0.6369f, 0.6113f, 0.6275f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6113f, 0.6275f, 0.6651f, 0.6119f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6651f, 0.6119f, 0.7169f, 0.5905f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7169f, 0.5905f, 0.7660f, 0.5634f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7660f, 0.5634f, 0.8117f, 0.5309f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8117f, 0.5309f, 0.8536f, 0.4936f, 1.1000f, 0.0000f}, 41, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.1400f, 0.0000f, 0.0000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1170f, 0.4614f, 0.1599f, 0.5065f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1599f, 0.5065f, 0.2081f, 0.5460f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2081f, 0.5460f, 0.2609f, 0.5791f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2609f, 0.5791f, 0.3173f, 0.6054f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3173f, 0.6054f, 0.3766f, 0.6245f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3766f, 0.6245f, 0.4378f, 0.6361f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4378f, 0.6361f, 0.5000f, 0.6400f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.6400f, 0.5622f, 0.6361f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5622f, 0.6361f, 0.6234f, 0.6245f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6234f, 0.6245f, 0.6827f, 0.6054f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6827f, 0.6054f, 0.7391f, 0.5791f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7391f, 0.5791f, 0.7919f, 0.5460f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7919f, 0.5460f, 0.8401f, 0.5065f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8401f, 0.5065f, 0.8830f, 0.4614f, 1.1000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.6400f, 0.5000f, 0.7800f, 1.0000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3000f, 0.6000f, 0.2300f, 0.7200f, 1.0000f, 0.0000f}, 41, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7000f, 0.6000f, 0.7700f, 0.7200f, 1.0000f, 0.0000f}, 41, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 41, 3},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2400f, 0.4800f, 0.5200f, 0.3800f, 0.0000f, 0.0000f}, 44, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.1600f, 0.2300f, 0.2300f, 0.0000f, 0.0000f}, 44, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.6200f, 0.2300f, 0.2300f, 0.0000f, 0.0000f}, 44, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3900f, 0.3900f, 0.2300f, 0.2300f, 0.0000f, 0.0000f}, 44, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6200f, 0.1600f, 0.2300f, 0.2300f, 0.0000f, 0.0000f}, 44, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6200f, 0.6200f, 0.2300f, 0.2300f, 0.0000f, 0.0000f}, 44, 0},
+ {5, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.1600f, 0.6900f, 0.6900f, 0.0400f, 1.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.5500f, 0.2000f, 0.8600f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.8600f, 0.8000f, 0.8600f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8000f, 0.8600f, 0.8000f, 0.5500f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.1200f, 0.5000f, 0.6600f, 1.2000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3200f, 0.4800f, 0.5000f, 0.6600f, 1.2000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.6600f, 0.6800f, 0.4800f, 1.2000f, 0.0000f}, 44, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.3600f, 0.3600f, 1.0000f, 0.0000f}, 44, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.3200f, 0.0550f, 0.0000f, 0.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.4400f, 0.5000f, 0.7000f, 1.2000f, 0.0000f}, 44, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.4200f, 0.2200f, 0.0000f, 0.0000f, 0.0000f}, 44, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4000f, 0.6600f, 0.2000f, 0.1800f, 0.0000f, 0.0000f}, 44, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3600f, 0.5000f, 0.1800f, 0.1200f, 1.0000f, 0.0000f}, 44, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6400f, 0.5000f, 0.1800f, 0.1200f, 1.0000f, 0.0000f}, 44, 0},
+ {6, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2200f, 0.4600f, 0.5600f, 0.4200f, 0.0800f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6800f, 0.4600f, 0.6755f, 0.4199f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6755f, 0.4199f, 0.6622f, 0.3819f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6622f, 0.3819f, 0.6407f, 0.3478f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6407f, 0.3478f, 0.6122f, 0.3193f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6122f, 0.3193f, 0.5781f, 0.2978f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5781f, 0.2978f, 0.5401f, 0.2845f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5401f, 0.2845f, 0.5000f, 0.2800f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.2800f, 0.4599f, 0.2845f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4599f, 0.2845f, 0.4219f, 0.2978f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4219f, 0.2978f, 0.3878f, 0.3193f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3878f, 0.3193f, 0.3593f, 0.3478f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3593f, 0.3478f, 0.3378f, 0.3819f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3378f, 0.3819f, 0.3245f, 0.4199f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3245f, 0.4199f, 0.3200f, 0.4600f, 1.0000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2975f, 0.4000f, 0.3547f, 0.3301f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3547f, 0.3301f, 0.4312f, 0.2820f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4312f, 0.2820f, 0.5191f, 0.2608f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5191f, 0.2608f, 0.6091f, 0.2687f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6091f, 0.2687f, 0.6919f, 0.3048f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6919f, 0.3048f, 0.7589f, 0.3654f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7589f, 0.3654f, 0.8031f, 0.4442f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8031f, 0.4442f, 0.8199f, 0.5330f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8199f, 0.5330f, 0.8076f, 0.6225f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8076f, 0.6225f, 0.7673f, 0.7034f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7673f, 0.7034f, 0.7034f, 0.7673f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7034f, 0.7673f, 0.6225f, 0.8076f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6225f, 0.8076f, 0.5330f, 0.8199f, 1.1000f, 0.0000f}, 44, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5330f, 0.8199f, 0.4442f, 0.8031f, 1.1000f, 0.0000f}, 44, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 44, 3},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7025f, 0.4000f, 0.6453f, 0.3301f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6453f, 0.3301f, 0.5688f, 0.2820f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5688f, 0.2820f, 0.4809f, 0.2608f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4809f, 0.2608f, 0.3909f, 0.2687f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3909f, 0.2687f, 0.3081f, 0.3048f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3081f, 0.3048f, 0.2411f, 0.3654f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2411f, 0.3654f, 0.1969f, 0.4442f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1969f, 0.4442f, 0.1801f, 0.5330f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1801f, 0.5330f, 0.1924f, 0.6225f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1924f, 0.6225f, 0.2327f, 0.7034f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2327f, 0.7034f, 0.2966f, 0.7673f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2966f, 0.7673f, 0.3775f, 0.8076f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3775f, 0.8076f, 0.4670f, 0.8199f, 1.1000f, 0.0000f}, 47, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4670f, 0.8199f, 0.5558f, 0.8031f, 1.1000f, 0.0000f}, 47, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 47, 3},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.3600f, 0.0000f, 0.0000f, 0.0000f}, 50, 0},
+ {2, 2, 1.0000f, {1.0000f, 1.0000f, 1.0000f, 0.7000f}, {0.4000f, 0.4000f, 0.1000f, 0.0000f, 0.0000f, 0.0000f}, 50, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1800f, 0.5000f, 0.8200f, 0.5000f, 1.2000f, 0.0000f}, 50, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2200f, 0.8000f, 0.5800f, 0.4400f, 2.0000f, 0.0000f}, 50, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6600f, 0.3400f, 0.1600f, 0.1600f, 1.6000f, 0.0000f}, 50, 0},
+ {6, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1000f, 0.1600f, 0.3400f, 0.3000f, 0.0600f, 0.0000f}, 50, 0},
+ {6, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5600f, 0.5400f, 0.3400f, 0.3000f, 0.0600f, 0.0000f}, 50, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4400f, 0.3100f, 0.5000f, 0.3100f, 1.0000f, 0.0000f}, 50, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.3100f, 0.5000f, 0.6900f, 1.0000f, 0.0000f}, 50, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.6900f, 0.5600f, 0.6900f, 1.0000f, 0.0000f}, 50, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 50, 6},
+ {0, 2, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.4500f}, {0.1400f, 0.3200f, 0.5000f, 0.5200f, 1.0000f, 0.0000f}, 56, 0},
+ {0, 2, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.4500f}, {0.5000f, 0.5200f, 0.8600f, 0.3200f, 1.0000f, 0.0000f}, 56, 0},
+ {0, 2, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.4500f}, {0.5000f, 0.5200f, 0.5000f, 0.9000f, 1.0000f, 0.0000f}, 56, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.1700f, 0.1000f, 0.1000f, 0.0000f, 0.0000f}, 56, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3200f, 0.2200f, 0.8400f, 0.2200f, 1.0000f, 0.0000f}, 56, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3000f, 0.3600f, 0.1000f, 0.1000f, 0.0000f, 0.0000f}, 56, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4600f, 0.4100f, 0.8400f, 0.4100f, 1.0000f, 0.0000f}, 56, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3000f, 0.5500f, 0.1000f, 0.1000f, 0.0000f, 0.0000f}, 56, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4600f, 0.6000f, 0.8400f, 0.6000f, 1.0000f, 0.0000f}, 56, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.7400f, 0.1000f, 0.1000f, 0.0000f, 0.0000f}, 56, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3200f, 0.7900f, 0.8400f, 0.7900f, 1.0000f, 0.0000f}, 56, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3000f, 0.3000f, 0.1000f, 0.0000f, 0.0000f, 0.0000f}, 56, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7000f, 0.3600f, 0.0800f, 0.0000f, 0.0000f, 0.0000f}, 56, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4200f, 0.7000f, 0.1200f, 0.0000f, 0.0000f, 0.0000f}, 56, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7600f, 0.7400f, 0.0700f, 0.0000f, 0.0000f, 0.0000f}, 56, 0},
+ {5, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1800f, 0.1800f, 0.6400f, 0.7000f, 0.0600f, 1.0000f}, 56, 0},
+ {6, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3400f, 0.1000f, 0.3200f, 0.1600f, 0.0400f, 0.0000f}, 56, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2600f, 0.1800f, 0.1600f, 0.6400f, 0.0000f, 0.0000f}, 56, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5800f, 0.1800f, 0.1600f, 0.6400f, 0.0000f, 0.0000f}, 56, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.3800f, 0.1400f, 1.0000f, 0.0000f}, 56, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.1400f, 0.0000f, 0.0000f, 0.0000f}, 56, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5600f, 0.5000f, 0.9000f, 1.1000f, 0.0000f}, 56, 0},
+ {6, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3000f, 0.1200f, 0.4000f, 0.3000f, 0.0600f, 0.0000f}, 56, 0},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.4400f, 0.6000f, 0.1200f, 0.0000f, 0.0000f}, 56, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 56, 3},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7200f, 0.5000f, 0.9000f, 0.5000f, 1.8000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6556f, 0.6556f, 0.7828f, 0.7828f, 1.8000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.7200f, 0.5000f, 0.9000f, 1.8000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3444f, 0.6556f, 0.2172f, 0.7828f, 1.8000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2800f, 0.5000f, 0.1000f, 0.5000f, 1.8000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3444f, 0.3444f, 0.2172f, 0.2172f, 1.8000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.2800f, 0.5000f, 0.1000f, 1.8000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6556f, 0.3444f, 0.7828f, 0.2172f, 1.8000f, 0.0000f}, 59, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.2400f, 0.2400f, 1.6000f, 0.0000f}, 59, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.3600f, 0.3600f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.2800f, 0.5000f, 0.5000f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.6600f, 0.6000f, 1.0000f, 0.0000f}, 59, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.3600f, 0.3600f, 1.0000f, 0.0000f}, 59, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.2000f, 0.2000f, 1.0000f, 0.0000f}, 59, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.0700f, 0.0000f, 0.0000f, 0.0000f}, 59, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.3600f, 0.3600f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3966f, 0.3824f, 0.4107f, 0.3558f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4107f, 0.3558f, 0.4314f, 0.3340f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4314f, 0.3340f, 0.4573f, 0.3186f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4573f, 0.3186f, 0.4863f, 0.3109f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4863f, 0.3109f, 0.5164f, 0.3112f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5164f, 0.3112f, 0.5452f, 0.3197f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5452f, 0.3197f, 0.5707f, 0.3357f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5707f, 0.3357f, 0.5909f, 0.3580f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5909f, 0.3580f, 0.6043f, 0.3850f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6043f, 0.3850f, 0.6099f, 0.4145f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6099f, 0.4145f, 0.6072f, 0.4445f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6072f, 0.4445f, 0.5966f, 0.4726f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5966f, 0.4726f, 0.5787f, 0.4968f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5787f, 0.4968f, 0.5550f, 0.5153f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5500f, 0.5100f, 0.5000f, 0.5600f, 1.0000f, 0.0000f}, 59, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5600f, 0.5000f, 0.6200f, 1.0000f, 0.0000f}, 59, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.7200f, 0.0450f, 0.0000f, 0.0000f, 0.0000f}, 59, 0},
+ {2, 2, 1.0000f, {0.9000f, 0.2500f, 0.2500f, 1.0000f}, {0.5000f, 0.5000f, 0.3000f, 0.0000f, 0.0000f, 0.0000f}, 59, 0},
+ {6, 1, 0.3500f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1200f, 0.3400f, 0.5600f, 0.4200f, 0.0800f, 0.0000f}, 59, 0},
+ {1, 1, 0.3500f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 59, 4},
+ {3, 1, 0.3500f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3200f, 0.2400f, 0.1000f, 0.1000f, 1.0000f, 0.0000f}, 63, 0},
+ {3, 1, 0.3500f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5200f, 0.2400f, 0.1000f, 0.1000f, 1.0000f, 0.0000f}, 63, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 63, 7},
+ {1, 1, 0.3500f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 70, 7},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.2000f, 0.1000f, 0.6000f, 0.0000f, 0.0000f}, 77, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 77, 3},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4000f, 0.2500f, 0.6400f, 0.5000f, 1.1000f, 0.0000f}, 80, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6400f, 0.5000f, 0.4000f, 0.7500f, 1.1000f, 0.0000f}, 80, 0},
+ {2, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3000f, 0.6600f, 0.1400f, 0.0000f, 0.0000f, 0.0000f}, 80, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 80, 3},
+ {4, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1200f, 0.8400f, 0.7600f, 0.0600f, 0.0000f, 0.0000f}, 83, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4300f, 0.4300f, 0.2400f, 0.2400f, 1.0000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6000f, 0.6000f, 0.8400f, 0.8400f, 1.5000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2400f, 0.4800f, 0.2465f, 0.5379f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2465f, 0.5379f, 0.2657f, 0.5928f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2657f, 0.5928f, 0.2967f, 0.6421f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2967f, 0.6421f, 0.3379f, 0.6833f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3379f, 0.6833f, 0.3872f, 0.7143f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3872f, 0.7143f, 0.4421f, 0.7335f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4421f, 0.7335f, 0.5000f, 0.7400f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.7400f, 0.5579f, 0.7335f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5579f, 0.7335f, 0.6128f, 0.7143f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6128f, 0.7143f, 0.6621f, 0.6833f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6621f, 0.6833f, 0.7033f, 0.6421f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7033f, 0.6421f, 0.7343f, 0.5928f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7343f, 0.5928f, 0.7535f, 0.5379f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7535f, 0.5379f, 0.7600f, 0.4800f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2400f, 0.4800f, 0.2400f, 0.1800f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7600f, 0.4800f, 0.7600f, 0.1800f, 2.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.3000f, 0.5000f, 0.3000f, 1.1000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.5000f, 0.6500f, 0.5000f, 1.1000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2000f, 0.7000f, 0.8000f, 0.7000f, 1.1000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1600f, 0.2400f, 0.8400f, 0.2400f, 1.2000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3800f, 0.2400f, 0.4200f, 0.1200f, 1.0000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4200f, 0.1200f, 0.5800f, 0.1200f, 1.0000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5800f, 0.1200f, 0.6200f, 0.2400f, 1.0000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2400f, 0.3000f, 0.3000f, 0.8800f, 1.0000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3000f, 0.8800f, 0.7000f, 0.8800f, 1.0000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7000f, 0.8800f, 0.7600f, 0.3000f, 1.0000f, 0.0000f}, 83, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.3800f, 0.5000f, 0.7800f, 1.0000f, 0.0000f}, 83, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 83, 3},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 86, 3},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 89, 3},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 92, 3},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2800f, 0.5000f, 0.1600f, 0.1100f, 1.0000f, 0.0000f}, 95, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7200f, 0.5000f, 0.1600f, 0.1100f, 1.0000f, 0.0000f}, 95, 0},
+ {6, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.2200f, 0.4600f, 0.5600f, 0.4200f, 0.0800f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8400f, 0.3800f, 0.8360f, 0.3444f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8360f, 0.3444f, 0.8242f, 0.3106f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8242f, 0.3106f, 0.8051f, 0.2802f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.8051f, 0.2802f, 0.7798f, 0.2549f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7798f, 0.2549f, 0.7494f, 0.2358f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7494f, 0.2358f, 0.7156f, 0.2240f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.7156f, 0.2240f, 0.6800f, 0.2200f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6800f, 0.2200f, 0.6444f, 0.2240f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6444f, 0.2240f, 0.6106f, 0.2358f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6106f, 0.2358f, 0.5802f, 0.2549f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5802f, 0.2549f, 0.5549f, 0.2802f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5549f, 0.2802f, 0.5358f, 0.3106f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5358f, 0.3106f, 0.5240f, 0.3444f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5240f, 0.3444f, 0.5200f, 0.3800f, 1.0000f, 0.0000f}, 95, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4400f, 0.5600f, 0.1800f, 0.8600f, 1.1000f, 0.0000f}, 95, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 95, 4},
+ {5, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1400f, 0.2400f, 0.7200f, 0.5200f, 0.0600f, 1.0000f}, 99, 0},
+ {1, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f, 0.0000f}, 99, 3},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.3600f, 0.3600f, 1.0000f, 0.0000f}, 102, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.5000f, 0.5000f, 0.1600f, 0.3600f, 1.0000f, 0.0000f}, 102, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.1400f, 0.5000f, 0.8600f, 0.5000f, 1.0000f, 0.0000f}, 102, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4300f, 0.4300f, 0.2400f, 0.2400f, 1.0000f, 0.0000f}, 102, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6000f, 0.6000f, 0.8400f, 0.8400f, 1.5000f, 0.0000f}, 102, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4300f, 0.3200f, 0.4300f, 0.5400f, 1.0000f, 0.0000f}, 102, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3200f, 0.4300f, 0.5400f, 0.4300f, 1.0000f, 0.0000f}, 102, 0},
+ {3, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.4300f, 0.4300f, 0.2400f, 0.2400f, 1.0000f, 0.0000f}, 102, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.6000f, 0.6000f, 0.8400f, 0.8400f, 1.5000f, 0.0000f}, 102, 0},
+ {0, 0, 1.0000f, {0.0000f, 0.0000f, 0.0000f, 0.0000f}, {0.3200f, 0.4300f, 0.5400f, 0.4300f, 1.0000f, 0.0000f}, 102, 0},
+};
+const float bk_icon_pts[][2] = {
+ {0.4200f, 0.5000f},
+ {0.5000f, 0.6000f},
+ {0.3000f, 0.8600f},
+ {0.1400f, 0.8600f},
+ {0.1800f, 0.7000f},
+ {0.6800f, 0.5000f},
+ {0.9000f, 0.3600f},
+ {0.9000f, 0.7600f},
+ {0.6800f, 0.6200f},
+ {0.5000f, 0.2000f},
+ {0.8000f, 0.5000f},
+ {0.5000f, 0.8000f},
+ {0.2000f, 0.5000f},
+ {0.5000f, 0.1000f},
+ {0.9200f, 0.8600f},
+ {0.0800f, 0.8600f},
+ {0.5000f, 0.3600f},
+ {0.7200f, 0.1400f},
+ {0.8600f, 0.2800f},
+ {0.6400f, 0.5000f},
+ {0.5000f, 0.1200f},
+ {0.8200f, 0.2400f},
+ {0.7800f, 0.6000f},
+ {0.5000f, 0.8800f},
+ {0.2200f, 0.6000f},
+ {0.1800f, 0.2400f},
+ {0.1800f, 0.2000f},
+ {0.1800f, 0.8000f},
+ {0.7000f, 0.5000f},
+ {0.1000f, 0.2400f},
+ {0.4000f, 0.2400f},
+ {0.4800f, 0.3400f},
+ {0.9000f, 0.3400f},
+ {0.9000f, 0.8200f},
+ {0.1000f, 0.8200f},
+ {0.1200f, 0.1800f},
+ {0.8800f, 0.1800f},
+ {0.5800f, 0.5200f},
+ {0.5800f, 0.8400f},
+ {0.4200f, 0.7600f},
+ {0.4200f, 0.5200f},
+ {0.5000f, 0.1200f},
+ {0.8800f, 0.4800f},
+ {0.1200f, 0.4800f},
+ {0.1200f, 0.3000f},
+ {0.3600f, 0.2400f},
+ {0.2600f, 0.4800f},
+ {0.8800f, 0.3000f},
+ {0.6400f, 0.2400f},
+ {0.7400f, 0.4800f},
+ {0.5000f, 0.1200f},
+ {0.8600f, 0.3200f},
+ {0.8600f, 0.7000f},
+ {0.5000f, 0.9000f},
+ {0.1400f, 0.7000f},
+ {0.1400f, 0.3200f},
+ {0.3000f, 0.1600f},
+ {0.3000f, 0.8400f},
+ {0.8200f, 0.5000f},
+ {0.6800f, 0.5000f},
+ {0.9000f, 0.3600f},
+ {0.9000f, 0.7600f},
+ {0.6800f, 0.6200f},
+ {0.2800f, 0.1200f},
+ {0.2800f, 0.8200f},
+ {0.4500f, 0.6600f},
+ {0.5800f, 0.9000f},
+ {0.6800f, 0.8500f},
+ {0.5600f, 0.6200f},
+ {0.7800f, 0.6000f},
+ {0.2800f, 0.1200f},
+ {0.2800f, 0.8200f},
+ {0.4500f, 0.6600f},
+ {0.5800f, 0.9000f},
+ {0.6800f, 0.8500f},
+ {0.5600f, 0.6200f},
+ {0.7800f, 0.6000f},
+ {0.8200f, 0.2000f},
+ {0.8200f, 0.8000f},
+ {0.3000f, 0.5000f},
+ {0.5000f, 0.1800f},
+ {0.8200f, 0.8200f},
+ {0.5000f, 0.8200f},
+ {0.2200f, 0.3600f},
+ {0.7800f, 0.3600f},
+ {0.5000f, 0.7000f},
+ {0.6400f, 0.2200f},
+ {0.6400f, 0.7800f},
+ {0.3000f, 0.5000f},
+ {0.3600f, 0.2200f},
+ {0.3600f, 0.7800f},
+ {0.7000f, 0.5000f},
+ {0.2200f, 0.6400f},
+ {0.7800f, 0.6400f},
+ {0.5000f, 0.3000f},
+ {0.5000f, 0.1000f},
+ {0.9000f, 0.5000f},
+ {0.6000f, 0.6000f},
+ {0.4000f, 0.4000f},
+ {0.4000f, 0.3800f},
+ {0.4000f, 0.6200f},
+ {0.6200f, 0.5000f},
+};
+const BKIconDef bk_icon_defs[] = {
+ {"", 0, 0, 0, {0, 0, 0, 0}},
+ {"ADD", 0, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"BRUSH_DATA", 2, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"CAMERA_DATA", 4, 4, 1, {0.4500f, 0.7800f, 0.4000f, 1.0000f}},
+ {"CANCEL", 8, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"CHECKMARK", 10, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"COLLAPSEMENU", 12, 3, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"COLLECTION", 15, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"CONSTRAINT", 17, 3, 1, {0.4000f, 0.6200f, 0.9600f, 1.0000f}},
+ {"COPYDOWN", 20, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"CUBE", 22, 9, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"CURVE_BEZCURVE", 31, 12, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"CURVE_DATA", 31, 12, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"DECORATE", 43, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"DECORATE_ANIMATE", 44, 4, 1, {0.9500f, 0.8000f, 0.3000f, 1.0000f}},
+ {"DECORATE_KEYFRAME", 48, 1, 1, {0.9500f, 0.8000f, 0.3000f, 1.0000f}},
+ {"DOT", 43, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"DOWNARROW_HLT", 49, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"DUPLICATE", 20, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"EDITMODE_HLT", 22, 9, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"ERROR", 51, 3, 1, {0.9500f, 0.8000f, 0.3000f, 1.0000f}},
+ {"EXPORT", 54, 6, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"EYEDROPPER", 60, 3, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"FAKE_USER_OFF", 63, 6, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"FAKE_USER_ON", 69, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"FF", 70, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"FILE", 72, 7, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"FILEBROWSER", 79, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"FILE_BLANK", 72, 7, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"FILE_FOLDER", 79, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"FILTER", 80, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"FOLDER_REDIRECT", 79, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"FONT_DATA", 81, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"FULLSCREEN_ENTER", 83, 8, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"GRIP", 91, 6, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"GROUP", 15, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"HIDE_OFF", 97, 29, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"HIDE_ON", 126, 17, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"HOME", 143, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"IMAGE", 145, 6, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"IMAGE_DATA", 145, 6, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"IMPORT", 151, 6, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"INFO", 157, 3, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"KEYFRAME", 44, 4, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"KEYFRAME_HLT", 48, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"LAYER_USED", 43, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"LIGHT", 160, 2, 1, {0.4500f, 0.7800f, 0.4000f, 1.0000f}},
+ {"LIGHT_DATA", 160, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"LINKED", 162, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"LOCKED", 164, 15, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"LOOP_BACK", 179, 15, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"LOOP_FORWARDS", 194, 15, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"MATERIAL", 209, 2, 1, {0.9000f, 0.3600f, 0.3600f, 1.0000f}},
+ {"MENU_PANEL", 12, 3, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"MESH_CUBE", 22, 9, 1, {0.9300f, 0.5800f, 0.2500f, 1.0000f}},
+ {"MESH_DATA", 22, 9, 1, {0.4500f, 0.7800f, 0.4000f, 1.0000f}},
+ {"MINUS", 211, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"MODIFIER", 212, 2, 1, {0.4000f, 0.6200f, 0.9600f, 1.0000f}},
+ {"NEW", 72, 7, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"NODE", 214, 5, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"NODETREE", 214, 5, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"NODE_MATERIAL", 209, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"OBJECT_DATA", 219, 4, 1, {0.9300f, 0.5800f, 0.2500f, 1.0000f}},
+ {"OBJECT_DATAMODE", 219, 4, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"OPTIONS", 91, 6, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"OUTLINER", 223, 8, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"OUTLINER_COLLECTION", 15, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"OUTLINER_OB_LIGHT", 160, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"PANEL_CLOSE", 8, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"PARTICLES", 231, 4, 1, {0.4000f, 0.6200f, 0.9600f, 1.0000f}},
+ {"PASTEDOWN", 235, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"PAUSE", 237, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"PHYSICS", 239, 2, 1, {0.4000f, 0.6200f, 0.9600f, 1.0000f}},
+ {"PINNED", 241, 3, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"PLAY", 244, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"PLUS", 0, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"PREFERENCES", 245, 9, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"PREVIEW_RANGE", 254, 3, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"PROPERTIES", 212, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"PROP_ON", 257, 3, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"QUESTION", 260, 18, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"REC", 278, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"REDO", 194, 15, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"REMOVE", 211, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"RENDER_STILL", 4, 4, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"RESTRICT_RENDER_OFF", 4, 4, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"RESTRICT_RENDER_ON", 279, 4, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"RESTRICT_SELECT_OFF", 283, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"RESTRICT_SELECT_ON", 284, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"RESTRICT_VIEW_OFF", 97, 29, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"RESTRICT_VIEW_ON", 126, 17, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"REW", 285, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"RIGHTARROW", 287, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"SCENE", 4, 4, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"SCENE_DATA", 289, 3, 1, {0.7000f, 0.5200f, 0.9500f, 1.0000f}},
+ {"SCULPTMODE_HLT", 2, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"SEARCH", 292, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"SETTINGS", 245, 9, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"SHADING_RENDERED", 209, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"SNAP_ON", 294, 16, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"SORTALPHA", 310, 3, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"TEXT", 81, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"TEXTURE", 145, 6, 1, {0.9000f, 0.3600f, 0.3600f, 1.0000f}},
+ {"TIME", 254, 3, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"TOOL_SETTINGS", 245, 9, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"TRASH", 313, 8, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"TRIA_DOWN", 321, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"TRIA_LEFT", 322, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"TRIA_RIGHT", 323, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"TRIA_UP", 324, 1, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"UNDO", 179, 15, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"UNLINKED", 325, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"UNLOCKED", 327, 15, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"UNPINNED", 342, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"VIEWZOOM", 292, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"VIEW_CAMERA", 344, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"WORLD", 346, 3, 1, {0.9000f, 0.3600f, 0.3600f, 1.0000f}},
+ {"WORLD_DATA", 346, 3, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"X", 8, 2, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"ZOOM_IN", 349, 4, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+ {"ZOOM_OUT", 353, 3, 0, {0.0000f, 0.0000f, 0.0000f, 0.0000f}},
+};
+const int bk_icon_def_count = 121;
diff --git a/kit/intern/kit_icons_data.h b/kit/intern/kit_icons_data.h
new file mode 100644
index 0000000..8cc08e7
--- /dev/null
+++ b/kit/intern/kit_icons_data.h
@@ -0,0 +1,29 @@
+/* Vector icon tables (generated into kit_icons_data.c).
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+enum { BK_ICON_LINE, BK_ICON_POLY, BK_ICON_DISC, BK_ICON_RING, BK_ICON_RECT, BK_ICON_FRAME,
+ BK_ICON_BOX };
+
+typedef struct BKIconOp {
+ unsigned char op;
+ unsigned char color_mode; /* 0 pen, 1 pen * k alpha, 2 explicit rgba */
+ float k;
+ float rgba[4];
+ float a[6]; /* op arguments in the unit box (widths are line-width multiples) */
+ int pts_offset; /* polygon points */
+ int npts;
+} BKIconOp;
+
+typedef struct BKIconDef {
+ const char *name;
+ int first, count;
+ int has_tint;
+ float tint[4];
+} BKIconDef;
+
+extern const BKIconOp bk_icon_ops[];
+extern const float bk_icon_pts[][2];
+extern const BKIconDef bk_icon_defs[];
+extern const int bk_icon_def_count;
diff --git a/kit/intern/kit_intern.h b/kit/intern/kit_intern.h
new file mode 100644
index 0000000..a24d139
--- /dev/null
+++ b/kit/intern/kit_intern.h
@@ -0,0 +1,535 @@
+/* BUI kit internals: node/context structs, theme, drawing and class API.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "BUI_kit.h"
+
+typedef unsigned char uchar;
+
+/* -------------------------------------------------------------------- */
+/* Geometry (screen space, y down; xmax/ymax exclusive) */
+
+typedef struct BKRect {
+ int xmin, ymin, xmax, ymax;
+} BKRect;
+
+static inline int bk_rw(const BKRect *r)
+{
+ return r->xmax - r->xmin;
+}
+static inline int bk_rh(const BKRect *r)
+{
+ return r->ymax - r->ymin;
+}
+static inline BKRect bk_rect(int x, int y, int w, int h)
+{
+ BKRect r = {x, y, x + w, y + h};
+ return r;
+}
+
+/* Corner flags (Blender's CNR_*; "top" = screen top). */
+enum { CNR_TL = 1, CNR_TR = 2, CNR_BR = 4, CNR_BL = 8, CNR_ALL = 15 };
+
+/* -------------------------------------------------------------------- */
+/* Theme (Blender's uiWidgetColors / ThemeUI defaults) */
+
+typedef struct BKWCol {
+ uchar outline[4], outline_sel[4], inner[4], inner_sel[4], item[4], text[4], text_sel[4];
+ uchar shaded;
+ short shadetop, shadedown;
+ float roundness;
+} BKWCol;
+
+typedef struct BKTheme {
+ BKWCol regular, tool, toggle, radio, option, textfield, num, numslider, menu, pulldown, menu_back,
+ menu_item, list_item, box, scroll, progress, tooltip, tab, pie_menu;
+ uchar region_bg[4], header_bg[4], tabs_bg[4];
+ uchar panel_header[4], panel_back[4], panel_sub_back[4], panel_outline[4];
+ uchar text[4], text_hi[4], emboss[4], cursor[4], selection[4];
+ float menu_shadow_fac;
+ int menu_shadow_width;
+ float panel_roundness;
+} BKTheme;
+
+extern BKTheme bk_theme;
+
+/* Metrics (U.widget_unit, U.pixelsize, UI text size). */
+extern float bk_scale_fac;
+int bk_unit(void);
+float bk_px(void);
+float bk_font_size(void);
+float bk_line_height(void);
+extern float bk_text_scale; /* per-node font scale while measuring/drawing it */
+float bk_masked_width(const char *s, int len, const char *mask, bool bold);
+int bk_mask_text(const char *s, int len, const char *mask, char *buf, int size);
+int bk_pad(void); /* UI_TEXT_MARGIN_X * widget_unit */
+
+/* -------------------------------------------------------------------- */
+/* Drawing (kit_draw.c): Blender's widget base, text, icons */
+
+typedef struct BKDraw {
+ BuiRaster *r;
+ int clip[4]; /* current clip (x0, y0, x1, y1) */
+} BKDraw;
+
+extern BKDraw bk_draw; /* active frame */
+
+void bk_clip_push(int x, int y, int w, int h);
+void bk_clip_pop(void);
+void bk_clip_reset(int w, int h);
+bool bk_clip_visible(const BKRect *r);
+
+void bk_rgba(const uchar c[4], float r_out[4]);
+void bk_rgba_alpha(const uchar c[4], float alpha, float r_out[4]);
+void bk_fill(float x, float y, float w, float h, const uchar c[4]);
+void bk_fill_f(float x, float y, float w, float h, const float c[4]);
+void bk_roundbox(float x, float y, float w, float h, float rad, int corners, const float c[4]);
+void bk_shadow(const BKRect *r, float rad);
+void bk_line(float x0, float y0, float x1, float y1, const float c[4], float width);
+void bk_circle(float cx, float cy, float rad, const float c[4]);
+void bk_ring(float cx, float cy, float rad, const float c[4], float width);
+void bk_polygon(const float (*pts)[2], int n, const float c[4]);
+void bk_checker(float x, float y, float w, float h);
+
+/* Widget state flags (subset of Blender's UI_SELECT, UI_HOVER, ...). */
+enum {
+ ST_SELECT = 1 << 0,
+ ST_HOVER = 1 << 1,
+ ST_DISABLED = 1 << 2,
+ ST_TEXT_INPUT = 1 << 3,
+ ST_HOVER_LEFT = 1 << 4,
+ ST_HOVER_RIGHT = 1 << 5,
+ ST_NO_EMBOSS = 1 << 6,
+ ST_ALIGN_DOWN = 1 << 7, /* no emboss: stacked above another button */
+ ST_INDETERMINATE = 1 << 8,
+ ST_ACTIVE_DEFAULT = 1 << 9,
+};
+
+/* Apply Blender's widget_state(): theme colors adjusted for state. */
+void bk_widget_state(BKWCol *wcol, const BKWCol *theme, int state);
+void bk_widget_state_menu_item(BKWCol *wcol, const BKWCol *theme, int state);
+void bk_widget_active_color(BKWCol *wcol);
+float bk_widget_radius(const BKWCol *wcol);
+
+/* Ported widget draw functions. `rect` is narrowed to the text area like
+ * Blender's (the caller then draws text into it). */
+void bk_widget_but(BKWCol *wcol, BKRect *rect, int state, int corners);
+void bk_widget_numbut(BKWCol *wcol, BKRect *rect, int state, int corners);
+void bk_widget_numslider(BKWCol *wcol, BKRect *rect, int state, int corners, float factor);
+void bk_widget_textbut(BKWCol *wcol, BKRect *rect, int state, int corners);
+void bk_widget_menubut(BKWCol *wcol, BKRect *rect, int state, int corners);
+void bk_widget_optionbut(BKWCol *wcol, BKRect *rect, int state);
+void bk_widget_pulldownbut(BKWCol *wcol, BKRect *rect, int state, int corners);
+void bk_widget_menu_itembut(BKWCol *wcol, BKRect *rect);
+void bk_widget_list_itembut(BKWCol *wcol, BKRect *rect, int state);
+void bk_widget_box(BKWCol *wcol, BKRect *rect, int corners, const uchar *color);
+void bk_widget_progress(BKWCol *wcol, BKRect *rect, int corners, float factor);
+void bk_widget_swatch(BKWCol *wcol, BKRect *rect, int state, int corners, const float col[4]);
+void bk_widget_scroll(BKWCol *wcol, const BKRect *rect, const BKRect *slider, bool pressed);
+void bk_widget_tab(BKWCol *wcol, BKRect *rect, int state, int corners);
+void bk_widget_menu_back(const BKRect *rect, int corners);
+void bk_widget_tooltip_back(const BKRect *rect);
+
+/* Text (Blender's widget_draw_text: left/center/right in a rect, clipped
+ * with an ellipsis). */
+enum { BK_ALIGN_LEFT = 0, BK_ALIGN_CENTER = 1, BK_ALIGN_RIGHT = 2 };
+float bk_text_width(const char *s, int len, bool bold);
+float bk_text_baseline(const BKRect *rect);
+void bk_text(float x, float baseline, const char *s, int len, const uchar color[4], bool bold);
+void bk_text_f(float x, float baseline, const char *s, int len, const float c[4], bool bold);
+/* Draw `s` inside rect with alignment; returns drawn width. Ellipsizes. */
+float bk_text_in(const BKRect *rect, const char *s, const uchar color[4], int align, bool bold);
+/* Text + optional icon in rect (Blender's widget_draw_text_icon). */
+void bk_text_icon(const BKRect *rect,
+ const char *s,
+ int icon,
+ const uchar color[4],
+ int align,
+ bool enabled);
+int bk_icon_size(void);
+void bk_icon(int icon, float cx, float cy, const uchar *color, float alpha, float size);
+const float *bk_icon_tint(int icon); /* NULL: use text color */
+float bk_content_width(const char *s, int icon, bool bold);
+void bk_tria(float cx, float cy, char dir, const float c[4], float size);
+void bk_chevron_down(float cx, float cy, const uchar c[4]);
+
+/* Icons (kit_icons.c). */
+int bk_icons_lookup(const char *name);
+void bk_icons_draw(int id, float x, float y, float s, const float color[4]);
+
+/* -------------------------------------------------------------------- */
+/* Text editing (Blender's text button behavior) */
+
+typedef struct BKTextEdit {
+ char *text;
+ int len, cap;
+ int caret, anchor; /* byte offsets; anchor < 0 = no selection */
+ float scroll;
+ char mask[8]; /* shown instead of each character (password fields), "" = none */
+} BKTextEdit;
+
+enum { TE_NONE = 0, TE_CHANGED, TE_CONFIRM, TE_CANCEL, TE_NEXT, TE_PREV };
+
+BKTextEdit *bk_te_new(const char *text, bool select_all);
+void bk_te_free(BKTextEdit *te);
+int bk_te_key(BKTextEdit *te, BKContext *ctx, const char *text, const char *keysym, int mods);
+int bk_te_index_at(BKTextEdit *te, float px);
+void bk_te_click(BKTextEdit *te, float px, bool extend);
+void bk_te_drag(BKTextEdit *te, float px);
+void bk_te_select_word(BKTextEdit *te, int index);
+void bk_te_draw(BKTextEdit *te, const BKRect *rect, const uchar color[4]);
+
+/* -------------------------------------------------------------------- */
+/* Nodes */
+
+typedef struct BKEvent {
+ int x, y; /* window */
+ int lx, ly; /* relative to the node */
+ int dx, dy; /* since press */
+ int mods;
+ int delta;
+ bool inside, dragged;
+ const char *text;
+ const char *keysym;
+} BKEvent;
+
+#define EV_SHIFT(e) (((e)->mods & BK_SHIFT) != 0)
+#define EV_CTRL(e) (((e)->mods & BK_CTRL) != 0)
+#define EV_ALT(e) (((e)->mods & BK_ALT) != 0)
+
+typedef struct BKClass {
+ const char *name;
+ unsigned flags; /* CLS_* */
+ int cursor; /* hover cursor */
+ int drag_cursor; /* while dragged (BK_CURSOR_NONE = continuous grab) */
+ int drag_group; /* drag-toggle group (0 = none) */
+ void (*init)(BKNode *n);
+ void (*free_ext)(BKNode *n);
+ void (*measure)(BKNode *n, int *r_w, int *r_h);
+ void (*arrange)(BKNode *n); /* place children inside n's rect */
+ void (*draw)(BKNode *n);
+ void (*draw_tree)(BKNode *n); /* optional: replaces draw + children */
+ BKNode *(*hit)(BKNode *n, int x, int y);
+ int (*press)(BKNode *n, BKEvent *e);
+ int (*dbl)(BKNode *n, BKEvent *e);
+ int (*drag)(BKNode *n, BKEvent *e);
+ int (*release)(BKNode *n, BKEvent *e);
+ int (*move)(BKNode *n, BKEvent *e);
+ int (*leave)(BKNode *n);
+ int (*key)(BKNode *n, BKEvent *e);
+ int (*wheel)(BKNode *n, BKEvent *e);
+ int (*cursor_at)(BKNode *n, int x, int y);
+ void (*finish_edit)(BKNode *n, bool confirm);
+ int (*context_items)(BKNode *n, BKMenuSpec *items, int max);
+ /* value hooks for the shared value shortcuts (Ctrl+C/V, Backspace ...) */
+ int (*to_text)(BKNode *n, char *buf, int size);
+ int (*from_text)(BKNode *n, const char *s); /* 1 when set */
+ void (*step)(BKNode *n, int dir);
+ void (*reset)(BKNode *n, bool to_zero);
+ void (*negate)(BKNode *n);
+ void (*activate)(BKNode *n);
+ /* class-specific properties (consulted before the generic ones) */
+ int (*set_num)(BKNode *n, const char *key, double v);
+ int (*get_num)(BKNode *n, const char *key, double *r_v);
+ /* scrollable view along an axis (0 = y, 1 = x), in the class's units
+ * (rows, lines, pixels): Tk's xview/yview and scrollbars build on this */
+ void (*view)(BKNode *n, int axis, int *r_first, int *r_visible, int *r_total);
+ void (*set_view)(BKNode *n, int axis, int first);
+} BKClass;
+
+enum {
+ CLS_INTERACTIVE = 1 << 0,
+ CLS_VALUE = 1 << 1, /* has the value shortcuts and context menu */
+ CLS_POPUP = 1 << 2,
+};
+
+enum { DRAG_GROUP_TOGGLE = 1, DRAG_GROUP_PANEL = 2 };
+
+/* Node flags. */
+enum {
+ NF_VISIBLE = 1 << 0,
+ NF_ENABLED = 1 << 1,
+ NF_ALIGN = 1 << 2,
+ NF_EMBOSS = 1 << 3,
+ NF_VERTICAL = 1 << 4,
+ NF_ICON_ONLY = 1 << 5,
+ NF_COLLAPSED = 1 << 6,
+ NF_INTEGER = 1 << 7,
+ NF_LIVE = 1 << 8,
+ NF_ALPHA = 1 << 9,
+ NF_SQUARE = 1 << 10, /* color picker type */
+ NF_DIRECTORY = 1 << 11,
+ NF_LINE = 1 << 12, /* separator line */
+ NF_BOLD = 1 << 13,
+ NF_VECTOR = 1 << 14, /* column of linked number fields (Ctrl+Alt+C/V) */
+ NF_HAS_MIN = 1 << 15,
+ NF_HAS_MAX = 1 << 16,
+ NF_EVENTS = 1 << 17, /* forward raw events to the host (bind) */
+ NF_NOPROPAGATE = 1 << 18, /* frame: keep its own size (pack_propagate(False)) */
+ NF_HAS_BG = 1 << 19, /* frame/canvas: fill with `color` */
+ NF_SELECTED = 1 << 20, /* drawn selected (multi-drag set) */
+ NF_VIEWEVENTS = 1 << 21, /* emit BK_EV_VIEW when the scrolled view changes */
+ NF_NOSCROLLBAR = 1 << 22, /* an external scrollbar drives the view */
+ NF_CONFIGURED = 1 << 23, /* geometry changed since the host was told (BK_EV_CONFIGURE) */
+};
+
+typedef struct BKStrs {
+ char **v;
+ int n;
+} BKStrs;
+
+struct BKNode {
+ const BKClass *cls;
+ BKNode *parent;
+ BKNode **kids;
+ int nkids, capkids;
+ BKContext *ctx_root; /* set on a context's root (and popups) */
+ void *ref; /* host object */
+
+ int x, y, w, h;
+ int nat_w, nat_h, nat_gen;
+ float weight;
+ int corners;
+ unsigned flags;
+
+ /* common data */
+ char *text; /* label text / title / string value */
+ char *label; /* value component label */
+ char *desc; /* tooltip */
+ char *placeholder, *suffix;
+ int icon, icon_on;
+ int align; /* label alignment */
+ uchar color_text[4];
+ bool has_color_text;
+
+ /* values */
+ double value, defval, vmin, vmax, step, factor;
+ int precision;
+ float color[4];
+ BKStrs items, item_icons_s, shortcuts;
+ int *item_icons;
+ int spacing, padding, columns, rows;
+ float tile, height_units, split;
+ int hot, scroll, current;
+ int scroll_x; /* horizontal view offset (canvas) */
+ int cursor_override; /* hover cursor + 1 (0 = the class's) */
+ float font_scale; /* text size relative to the UI font (0 = 1) */
+ int selmode; /* list/tree: 0 single, 1 multiple (toggle), 2 extended (Ctrl/Shift),
+ * 3 single shown with marks (clearable) */
+ unsigned char *marks; /* list: selected rows when selmode != 0 */
+ int nmarks;
+ char mask[8]; /* text fields: password mask character (Tk's show=) */
+ float view_seen[4]; /* last reported view fractions (y0, y1, x0, x1) */
+
+ /* interaction scratch */
+ double drag_start;
+ BKNode **linked;
+ int nlinked;
+ double *linked_start;
+ BKTextEdit *edit;
+ int rename_row;
+ int dragmode;
+
+ struct BKGeom *geom; /* geometry manager info (children of frames) */
+ float anim; /* panel open fraction while animating (0..1) */
+ void *image; /* BKImage on labels/buttons */
+
+ void *ext; /* type-specific data */
+ /* internal C wiring (composites built in C, e.g. the color picker) */
+ void (*on_change)(BKNode *n, void *data);
+ void *on_change_data;
+ void (*on_click)(BKNode *n, void *data);
+ void *on_click_data;
+};
+
+#define NODE_VISIBLE(n) (((n)->flags & NF_VISIBLE) != 0)
+#define NODE_ENABLED(n) (((n)->flags & NF_ENABLED) != 0)
+
+const BKClass *bk_class_find(const char *name);
+BKNode *bk_node_new_cls(const BKClass *cls);
+void bk_node_add(BKNode *parent, BKNode *child);
+BKContext *bk_ctx(const BKNode *n);
+void bk_invalidate(BKNode *n);
+void bk_relayout(BKNode *n);
+void bk_natural(BKNode *n, int *r_w, int *r_h);
+void bk_arrange(BKNode *n, int x, int y, int w, int h);
+void bk_draw_tree(BKNode *n);
+BKNode *bk_hit(BKNode *n, int x, int y);
+bool bk_contains(const BKNode *n, int x, int y);
+BKRect bk_node_rect(const BKNode *n);
+bool bk_hovered(const BKNode *n);
+bool bk_pressed(const BKNode *n);
+void bk_emit(BKNode *n, int kind, void *ref, double a, double b);
+void bk_view_fractions(BKNode *n, int axis, float *r_first, float *r_last);
+void bk_views_check(BKContext *ctx);
+extern int bk_configure_pending;
+void bk_changed(BKNode *n); /* invalidate + emit change + C hook */
+char *bk_strdup(const char *s);
+void bk_set_text(char **dst, const char *s);
+void bk_strs_set(BKStrs *s, const char *const *v, int n);
+void bk_strs_free(BKStrs *s);
+void bk_retain(void *ref);
+void bk_release(void *ref);
+
+/* Value helpers shared by classes. */
+void bk_set_value(BKNode *n, double v); /* clamp + notify */
+void bk_set_value_silent(BKNode *n, double v);
+double bk_clamp_value(const BKNode *n, double v);
+int bk_value_key(BKNode *n, BKEvent *e); /* Blender value shortcuts */
+int bk_value_wheel(BKNode *n, BKEvent *e); /* Ctrl+Wheel */
+int bk_value_context_items(BKNode *n, BKMenuSpec *items, int max);
+void bk_begin_edit(BKNode *n, const char *text, bool select_all);
+int bk_edit_key(BKNode *n, BKEvent *e); /* routes to TextEdit, confirms/cancels */
+
+/* -------------------------------------------------------------------- */
+/* Context */
+
+#define BK_MAX_POPUPS 16
+#define BK_MAX_DIRTY 24
+#define BK_MAX_KEYS 64
+
+typedef struct BKKeyBinding {
+ int mods;
+ char keysym[32];
+ void *ref;
+} BKKeyBinding;
+
+typedef struct BKGeom {
+ int manager;
+ int side, fill, expand, anchor;
+ int padx[2], pady[2], ipadx, ipady;
+ int row, column, rowspan, columnspan, sticky;
+ float x, y, relx, rely, width, height, relwidth, relheight;
+ unsigned has; /* place: which of width/height/relwidth/relheight were given */
+ int reqw, reqh;
+} BKGeom;
+
+typedef struct BKImage {
+ int w, h;
+ uint32_t *argb; /* premultiplied-free 0xAARRGGBB */
+} BKImage;
+
+void bk_image_free(BKImage *img);
+void bk_image_draw(const BKImage *img, float x, float y, float w, float h, float alpha);
+
+/* Undo entries (BK_undo). */
+typedef struct BKUndo {
+ BKNode *node;
+ int kind; /* 0 number, 1 text, 2 color */
+ double v[2];
+ char *t[2];
+ float c[2][4];
+ int interaction;
+} BKUndo;
+
+#define BK_MAX_UNDO 128
+#define BK_MAX_MULTI 32
+#define BK_MAX_ANIM 32
+
+struct BKContext {
+ BKNode *root, *header;
+ BKHost host;
+ BKNode *hover, *grab, *focus, *modal;
+ BKNode *popups[BK_MAX_POPUPS];
+ int npopups;
+ /* tooltip */
+ BKNode *tip_node;
+ int tip_x, tip_y, tip_serial, tip_shown;
+ BKRect tip_rect;
+ /* drag-toggle */
+ int dt_group, dt_value, dt_active;
+ /* pointer */
+ bool dragging;
+ int press_x, press_y, off_x, off_y, skip_x, skip_y;
+ bool has_skip;
+ int pointer_x, pointer_y;
+ double last_click_t;
+ BKNode *last_click_node;
+ int last_click_x, last_click_y;
+ int cursor;
+ /* window / region */
+ int win_w, win_h, scroll, content_h, header_h;
+ /* damage */
+ bool layout_dirty, full_dirty;
+ BKRect dirty[BK_MAX_DIRTY];
+ int ndirty;
+ BKKeyBinding keys[BK_MAX_KEYS];
+ int nkeys;
+ BuiRaster *raster; /* last rendered frame (eyedropper sampling) */
+ /* undo */
+ BKUndo undo[BK_MAX_UNDO];
+ int nundo, undo_pos, interaction, in_input, in_undo;
+ /* multi-drag over number fields */
+ BKNode *multi[BK_MAX_MULTI];
+ double multi_start[BK_MAX_MULTI];
+ int nmulti, multi_x0;
+ /* animations */
+ BKNode *anim[BK_MAX_ANIM];
+ int nanim;
+ double anim_t;
+};
+
+void bk_undo_record(BKNode *n, int kind);
+void bk_anim_start(BKNode *n);
+BKNode *bk_next_editable(BKNode *from, int dir);
+void bk_event(BKNode *n, int kind, int mods, const BKEvent *e);
+BKNode *bk_hit_at(BKContext *ctx, int x, int y);
+bool bk_anim_running(const BKNode *n);
+void bk_edit_next(BKNode *from, int dir);
+int bk_textarea_set_text(BKNode *n, const char *s);
+const char *bk_textarea_text(BKNode *n);
+
+void bk_ctx_dirty_rect(BKContext *ctx, BKRect r);
+void bk_ctx_request(BKContext *ctx);
+void bk_open_popup(BKContext *ctx, BKNode *popup, BKNode *owner, BKNode *parent_popup);
+void bk_close_popups_after(BKContext *ctx, BKNode *after); /* NULL: all */
+bool bk_owns_popup(BKContext *ctx, const BKNode *owner);
+int bk_popup_index(BKContext *ctx, const BKNode *popup);
+void bk_start_drag_toggle(BKContext *ctx, int group, int value);
+void bk_begin_modal(BKContext *ctx, BKNode *tool);
+void bk_end_modal(BKContext *ctx);
+char *bk_clipboard_get(BKContext *ctx);
+void bk_clipboard_set(BKContext *ctx, const char *s);
+void bk_forget(BKContext *ctx, BKNode *subtree);
+double bk_time(void);
+
+/* Popup placement fields live in ext of popup nodes (kit_menus.c). */
+typedef struct BKPopupPlace {
+ int at_x, at_y; /* < -9999: below owner */
+ int side_x, side_y, side_xl; /* submenu beside a row (side_x < -9999: none) */
+} BKPopupPlace;
+void bk_popup_place(BKNode *popup, int win_w, int win_h);
+
+/* Picker / menus (kit_menus.c, kit_color.c) */
+BKNode *bk_menu_new(const BKMenuSpec *items, int n, const char *title, const char *current);
+BKNode *bk_picker_new(BKNode *swatch);
+void bk_menu_on_close(BKNode *menu);
+void bk_eyedropper_start(BKContext *ctx, void (*pick)(void *data, const float rgb[3]), void *data);
+int bk_parse_hex(const char *s, float out[4], float alpha);
+BKNode *bk_popover_panel_new(BKNode *owner, BKNode *body);
+void bk_menuspec_free(BKMenuSpec *items, int n);
+BKMenuSpec *bk_menuspec_copy(const BKMenuSpec *items, int n);
+int bk_tree_columns_from_icons(BKNode *n);
+
+/* Classes (kit_widgets.c, kit_views.c, kit_color.c, kit_menus.c) */
+extern const BKClass bk_cls_column, bk_cls_row, bk_cls_grid, bk_cls_box, bk_cls_panel,
+ bk_cls_tabs, bk_cls_sidetabs, bk_cls_scroll, bk_cls_scrollbar, bk_cls_label, bk_cls_separator,
+ bk_cls_progress, bk_cls_button, bk_cls_toggle, bk_cls_checkbox, bk_cls_decorator,
+ bk_cls_text, bk_cls_search, bk_cls_hotkey, bk_cls_number, bk_cls_slider, bk_cls_dropdown,
+ bk_cls_enum, bk_cls_swatch, bk_cls_popover, bk_cls_menubutton, bk_cls_menubar, bk_cls_list,
+ bk_cls_tree, bk_cls_gridview, bk_cls_ramp, bk_cls_curve, bk_cls_normal, bk_cls_histogram,
+ bk_cls_hsv_circle, bk_cls_hsv_square, bk_cls_hue_strip, bk_cls_value_strip, bk_cls_menu,
+ bk_cls_pie, bk_cls_popover_panel, bk_cls_picker, bk_cls_eyedropper, bk_cls_frame,
+ bk_cls_radio, bk_cls_canvas, bk_cls_textarea, bk_cls_image;
+
+/* Small utilities */
+#define BK_MIN(a, b) ((a) < (b) ? (a) : (b))
+#define BK_MAX(a, b) ((a) > (b) ? (a) : (b))
+#define BK_CLAMP(v, a, b) ((v) < (a) ? (a) : ((v) > (b) ? (b) : (v)))
+int bk_iround(float v);
+bool bk_streq(const char *a, const char *b);
+bool bk_keysym_is(const char *keysym, const char *name); /* case-insensitive */
diff --git a/kit/intern/kit_menus.c b/kit/intern/kit_menus.c
new file mode 100644
index 0000000..4810194
--- /dev/null
+++ b/kit/intern/kit_menus.c
@@ -0,0 +1,969 @@
+/* Menus (dropdown, context, menu bar, submenus, type-to-search), pie menus
+ * and popover panels; popup placement.
+ *
+ * As in Blender: menus open on press and pick on release, hovering a
+ * submenu item opens it, typing searches every item including submenus,
+ * Up/Down/Return/Right/Left navigate; pies pick by direction. Backgrounds
+ * use widget_menu_back (soft shadow + menu_back colors), rows use
+ * widget_menu_itembut with widget_state_menu_item.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <ctype.h>
+#include <math.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "kit_intern.h"
+
+static int u(void)
+{
+ return bk_unit();
+}
+
+/* -------------------------------------------------------------------- */
+/** \name Menu specs (deep copies with retained refs)
+ * \{ */
+
+static bool is_sep(const BKMenuSpec *s)
+{
+ return !s->text || strcmp(s->text, "-") == 0;
+}
+
+BKMenuSpec *bk_menuspec_copy(const BKMenuSpec *items, int n)
+{
+ if (n <= 0) {
+ return NULL;
+ }
+ BKMenuSpec *out = (BKMenuSpec *)calloc((size_t)n, sizeof(BKMenuSpec));
+ for (int i = 0; i < n; i++) {
+ out[i] = items[i];
+ out[i].text = bk_strdup(items[i].text ? items[i].text : "-");
+ out[i].shortcut = items[i].shortcut ? bk_strdup(items[i].shortcut) : NULL;
+ out[i].sub = items[i].nsub ? bk_menuspec_copy(items[i].sub, items[i].nsub) : NULL;
+ bk_retain(items[i].ref);
+ }
+ return out;
+}
+
+void bk_menuspec_free(BKMenuSpec *items, int n)
+{
+ if (!items) {
+ return;
+ }
+ for (int i = 0; i < n; i++) {
+ free((char *)items[i].text);
+ free((char *)items[i].shortcut);
+ bk_menuspec_free((BKMenuSpec *)items[i].sub, items[i].nsub);
+ bk_release(items[i].ref);
+ }
+ free(items);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Placement
+ * \{ */
+
+#define PLACE_NONE (-100000)
+
+static BKPopupPlace *popup_place_of(BKNode *p)
+{
+ return (BKPopupPlace *)p->ext; /* every popup's ext starts with BKPopupPlace */
+}
+
+static void place_init(BKPopupPlace *pl)
+{
+ pl->at_x = pl->at_y = PLACE_NONE;
+ pl->side_x = pl->side_y = pl->side_xl = PLACE_NONE;
+}
+
+void bk_popup_place(BKNode *p, int win_w, int win_h)
+{
+ if (p->cls == &bk_cls_pie) {
+ bk_arrange(p, 0, 0, win_w, win_h);
+ return;
+ }
+ BKPopupPlace *pl = popup_place_of(p);
+ int w, h;
+ bk_natural(p, &w, &h);
+ int x, y;
+ const BKNode *o = p->parent;
+ if (pl->side_x != PLACE_NONE) { /* submenu beside its row */
+ x = (pl->side_x + w <= win_w) ? pl->side_x : BK_MAX(0, pl->side_xl - w);
+ y = BK_MAX(0, BK_MIN(pl->side_y, win_h - h));
+ }
+ else if (pl->at_x != PLACE_NONE) { /* at a point (context menus) */
+ x = BK_MAX(0, BK_MIN(pl->at_x, win_w - w));
+ y = pl->at_y;
+ if (y + h > win_h) {
+ y = BK_MAX(0, y - h);
+ }
+ }
+ else { /* below the owner; flipped above when there is no room */
+ w = BK_MAX(w, o ? o->w : 0);
+ const int ox = o ? o->x : 0, oy = o ? o->y : 0, oh = o ? o->h : 0;
+ y = oy + oh;
+ if (y + h > win_h && oy - h >= 0) {
+ y = oy - h;
+ }
+ x = BK_MAX(0, BK_MIN(ox, win_w - w));
+ }
+ bk_arrange(p, x, y, w, h);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Menu
+ * \{ */
+
+static BKRect pie_item_rect_pub(BKNode *n, int i);
+
+typedef struct MenuData {
+ BKPopupPlace place;
+ BKMenuSpec *all;
+ int nall;
+ BKMenuSpec *filtered; /* search results (owned) */
+ int nfiltered;
+ char *title, *current;
+ char query[128];
+ int from_row; /* row of the parent menu that opened this submenu */
+} MenuData;
+
+#define MENU(n) ((MenuData *)(n)->ext)
+
+static BKMenuSpec *menu_items(BKNode *n, int *r_count)
+{
+ MenuData *m = MENU(n);
+ if (m->query[0]) {
+ *r_count = m->nfiltered;
+ return m->filtered;
+ }
+ *r_count = m->nall;
+ return m->all;
+}
+
+static int menu_pad(void)
+{
+ return bk_iround(0.2f * u()); /* UI_MENU_PADDING */
+}
+static int menu_sep_h(void)
+{
+ return bk_iround(0.5f * u());
+}
+static int menu_title_h(BKNode *n)
+{
+ return (MENU(n)->title || MENU(n)->query[0]) ? u() : 0;
+}
+
+static void menu_row_geom(BKNode *n, int row, int *r_y, int *r_h)
+{
+ int count;
+ BKMenuSpec *items = menu_items(n, &count);
+ int y = menu_pad() + menu_title_h(n);
+ for (int i = 0; i < count; i++) {
+ const int h = is_sep(&items[i]) ? menu_sep_h() : u();
+ if (i == row) {
+ *r_y = n->y + y;
+ *r_h = h;
+ return;
+ }
+ y += h;
+ }
+ *r_y = n->y + y;
+ *r_h = 0;
+}
+
+static int menu_row_at(BKNode *n, int y)
+{
+ int count;
+ BKMenuSpec *items = menu_items(n, &count);
+ for (int i = 0; i < count; i++) {
+ int ry, rh;
+ menu_row_geom(n, i, &ry, &rh);
+ if (y >= ry && y < ry + rh) {
+ return (!is_sep(&items[i]) && items[i].enabled) ? i : -1;
+ }
+ }
+ return -1;
+}
+
+static bool menu_has_icons(BKMenuSpec *items, int count)
+{
+ for (int i = 0; i < count; i++) {
+ if (!is_sep(&items[i]) && (items[i].icon || items[i].checked >= 0)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static void menu_measure(BKNode *n, int *rw, int *rh)
+{
+ int count;
+ BKMenuSpec *items = menu_items(n, &count);
+ const float uu = (float)u();
+ float text_w = 0, sc_w = 0;
+ bool sub = false;
+ int h = 0;
+ for (int i = 0; i < count; i++) {
+ if (is_sep(&items[i])) {
+ h += menu_sep_h();
+ continue;
+ }
+ h += u();
+ text_w = BK_MAX(text_w, bk_text_width(items[i].text, -1, false));
+ if (items[i].shortcut) {
+ sc_w = BK_MAX(sc_w, bk_text_width(items[i].shortcut, -1, false));
+ }
+ sub |= items[i].nsub > 0;
+ }
+ float w = text_w + 2 * bk_pad() + (menu_has_icons(items, count) ? bk_icon_size() + 0.3f * uu : 0);
+ w += sc_w > 0 ? sc_w + 1.5f * uu : 0;
+ w += sub ? uu : 0;
+ if (MENU(n)->title) {
+ w = BK_MAX(w, bk_text_width(MENU(n)->title, -1, false) + 2 * bk_pad());
+ }
+ w = BK_MAX(w, 6 * uu);
+ if (count == 0 && MENU(n)->query[0]) {
+ h = u(); /* "No results found" */
+ }
+ *rw = (int)w + 2 * menu_pad();
+ *rh = BK_MAX(h, u()) + menu_title_h(n) + 2 * menu_pad();
+}
+
+static int menu_child_row(BKNode *n)
+{
+ BKContext *ctx = bk_ctx(n);
+ const int k = ctx ? bk_popup_index(ctx, n) : -1;
+ if (k >= 0 && k + 1 < ctx->npopups && ctx->popups[k + 1]->parent == n) {
+ return MENU(ctx->popups[k + 1])->from_row;
+ }
+ return -1;
+}
+
+static void menu_open_sub(BKNode *n, int row)
+{
+ BKContext *ctx = bk_ctx(n);
+ int count;
+ BKMenuSpec *items = menu_items(n, &count);
+ if (!ctx || row < 0 || row >= count || !items[row].nsub || menu_child_row(n) == row) {
+ return;
+ }
+ BKNode *sub = bk_menu_new(items[row].sub, items[row].nsub, NULL, NULL);
+ int ry, rh;
+ menu_row_geom(n, row, &ry, &rh);
+ MENU(sub)->place.side_x = n->x + n->w;
+ MENU(sub)->place.side_y = ry - menu_pad();
+ MENU(sub)->place.side_xl = n->x;
+ MENU(sub)->from_row = row;
+ bk_open_popup(ctx, sub, n, n);
+}
+
+static BKNode *menu_root(BKNode *n)
+{
+ while (n->parent && n->parent->cls == &bk_cls_menu) {
+ n = n->parent;
+ }
+ return n;
+}
+
+static void menu_pick(BKNode *n, int row)
+{
+ int count;
+ BKMenuSpec *items = menu_items(n, &count);
+ if (row < 0 || row >= count || is_sep(&items[row]) || !items[row].enabled) {
+ return;
+ }
+ if (items[row].nsub) {
+ menu_open_sub(n, row);
+ return;
+ }
+ BKContext *ctx = bk_ctx(n);
+ if (!ctx) {
+ return;
+ }
+ /* take what we need before the menus (and their copies) are freed */
+ void (*fn)(void *) = items[row].fn;
+ void *data = items[row].data;
+ void *ref = items[row].ref;
+ BKNode *owner = menu_root(n)->parent;
+ bk_retain(ref);
+ BK_close_popups(ctx);
+ if (fn) {
+ fn(data);
+ }
+ else if (ref) {
+ if (ctx->host.emit) {
+ ctx->host.emit(ctx->host.data, owner, BK_EV_CALL, ref, 0, 0);
+ }
+ }
+ else if (owner && (owner->cls == &bk_cls_dropdown || owner->cls == &bk_cls_enum)) {
+ bk_set_value(owner, (double)(intptr_t)data); /* enum menu: the item index */
+ }
+ bk_release(ref);
+}
+
+static void menu_filter_walk(MenuData *m, const BKMenuSpec *items, int count, const char *path,
+ const char *q, BKMenuSpec **out, int *nout, int *cap)
+{
+ for (int i = 0; i < count; i++) {
+ const BKMenuSpec *it = &items[i];
+ if (is_sep(it)) {
+ continue;
+ }
+ char full[512];
+ if (path[0]) {
+ snprintf(full, sizeof(full), "%s \xe2\x96\xb8 %s", path, it->text);
+ }
+ else {
+ snprintf(full, sizeof(full), "%s", it->text);
+ }
+ if (it->nsub) {
+ menu_filter_walk(m, it->sub, it->nsub, full, q, out, nout, cap);
+ continue;
+ }
+ /* case-insensitive substring */
+ bool hit = false;
+ for (const char *s = it->text; *s && !hit; s++) {
+ size_t k = 0;
+ while (q[k] && s[k] && tolower((unsigned char)s[k]) == tolower((unsigned char)q[k])) {
+ k++;
+ }
+ hit = q[k] == 0;
+ }
+ if (!hit) {
+ continue;
+ }
+ if (*nout == *cap) {
+ *cap = *cap ? *cap * 2 : 16;
+ *out = (BKMenuSpec *)realloc(*out, sizeof(BKMenuSpec) * (size_t)*cap);
+ }
+ BKMenuSpec s = *it;
+ s.text = bk_strdup(full);
+ s.shortcut = it->shortcut ? bk_strdup(it->shortcut) : NULL;
+ s.sub = NULL;
+ s.nsub = 0;
+ bk_retain(s.ref);
+ (*out)[(*nout)++] = s;
+ }
+}
+
+static void menu_filter(BKNode *n)
+{
+ MenuData *m = MENU(n);
+ bk_menuspec_free(m->filtered, m->nfiltered);
+ m->filtered = NULL;
+ m->nfiltered = 0;
+ if (m->query[0]) {
+ int cap = 0;
+ menu_filter_walk(m, m->all, m->nall, "", m->query, &m->filtered, &m->nfiltered, &cap);
+ }
+ n->hot = (m->query[0] && m->nfiltered) ? 0 : -1;
+ BKContext *ctx = bk_ctx(n);
+ if (ctx) {
+ bk_close_popups_after(ctx, n);
+ bk_invalidate(n); /* old size */
+ bk_popup_place(n, ctx->win_w, ctx->win_h);
+ }
+ bk_relayout(n);
+ bk_invalidate(n);
+}
+
+static int menu_move(BKNode *n, BKEvent *e)
+{
+ const int hot = menu_row_at(n, e->y);
+ if (hot == n->hot) {
+ return 0;
+ }
+ n->hot = hot;
+ bk_invalidate(n);
+ int count;
+ BKMenuSpec *items = menu_items(n, &count);
+ if (hot >= 0 && items[hot].nsub) {
+ menu_open_sub(n, hot);
+ }
+ else if (hot >= 0 && menu_child_row(n) >= 0) {
+ bk_close_popups_after(bk_ctx(n), n);
+ }
+ return 1;
+}
+
+static int menu_press(BKNode *n, BKEvent *e)
+{
+ return 1;
+}
+
+static int menu_release(BKNode *n, BKEvent *e)
+{
+ const int row = menu_row_at(n, e->y);
+ if (bk_contains(n, e->x, e->y) && row >= 0) {
+ menu_pick(n, row);
+ }
+ return 1;
+}
+
+static void menu_step(BKNode *n, int d)
+{
+ int count;
+ BKMenuSpec *items = menu_items(n, &count);
+ int i = n->hot;
+ for (int k = 0; k < count; k++) {
+ i = i >= 0 ? (i + d + count) % count : (d > 0 ? 0 : count - 1);
+ if (!is_sep(&items[i]) && items[i].enabled) {
+ n->hot = i;
+ bk_invalidate(n);
+ return;
+ }
+ }
+}
+
+static int menu_search_key(BKNode *n, BKEvent *e)
+{
+ MenuData *m = MENU(n);
+ if (bk_keysym_is(e->keysym, "Escape") && m->query[0]) {
+ m->query[0] = 0;
+ menu_filter(n);
+ return 1;
+ }
+ if (bk_keysym_is(e->keysym, "BackSpace") && m->query[0]) {
+ size_t l = strlen(m->query);
+ do {
+ l--;
+ } while (l > 0 && ((unsigned char)m->query[l] & 0xC0) == 0x80);
+ m->query[l] = 0;
+ menu_filter(n);
+ return 1;
+ }
+ if (e->text && (unsigned char)e->text[0] >= 0x20 && !EV_CTRL(e) &&
+ strlen(m->query) + strlen(e->text) < sizeof(m->query) - 1)
+ {
+ strcat(m->query, e->text);
+ menu_filter(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int menu_key(BKNode *n, BKEvent *e)
+{
+ int count;
+ BKMenuSpec *items = menu_items(n, &count);
+ if (bk_keysym_is(e->keysym, "Down") || bk_keysym_is(e->keysym, "Up")) {
+ menu_step(n, bk_keysym_is(e->keysym, "Down") ? 1 : -1);
+ return 1;
+ }
+ if (bk_keysym_is(e->keysym, "Return") || bk_keysym_is(e->keysym, "KP_Enter")) {
+ menu_pick(n, n->hot);
+ return 1;
+ }
+ if (bk_keysym_is(e->keysym, "Right") && n->hot >= 0 && n->hot < count && items[n->hot].nsub) {
+ menu_open_sub(n, n->hot);
+ return 1;
+ }
+ if (bk_keysym_is(e->keysym, "Left") && n->parent && n->parent->cls == &bk_cls_menu) {
+ bk_close_popups_after(bk_ctx(n), n->parent);
+ return 1;
+ }
+ /* typing always searches from the top menu (Blender menu search) */
+ return menu_search_key(menu_root(n), e);
+}
+
+static void menu_check_icon(float cx, float cy, bool on)
+{
+ const int s = bk_iround(0.6f * u());
+ BKRect r = bk_rect((int)(cx - s * 0.5f), (int)(cy - s * 0.5f), s, s);
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.option, on ? ST_SELECT : 0);
+ bk_widget_optionbut(&w, &r, on ? ST_SELECT : 0);
+}
+
+static void menu_draw(BKNode *n)
+{
+ MenuData *m = MENU(n);
+ BKRect r = bk_node_rect(n);
+ bk_widget_menu_back(&r, CNR_ALL);
+ const int p = menu_pad(), th = menu_title_h(n);
+ const float uu = (float)u();
+ const BKWCol *mi = &bk_theme.menu_item;
+ if (m->query[0]) {
+ uchar ic[4];
+ memcpy(ic, mi->text, 4);
+ ic[3] = 180;
+ bk_icon(bk_icons_lookup("SEARCH"), n->x + p + 0.2f * uu + bk_icon_size() * 0.5f,
+ n->y + p + th * 0.5f, ic, 1.0f, 0);
+ BKRect qr = bk_rect(n->x + p + bk_icon_size() + (int)(0.3f * uu) - bk_pad(), n->y + p,
+ n->w - 2 * p, th);
+ bk_text_in(&qr, m->query, mi->text, BK_ALIGN_LEFT, false);
+ }
+ else if (m->title) {
+ BKRect tr = bk_rect(n->x + p, n->y + p, n->w - 2 * p, th);
+ uchar tc[4];
+ memcpy(tc, bk_theme.menu_back.text, 4);
+ bk_text_in(&tr, m->title, tc, BK_ALIGN_LEFT, false);
+ }
+ int count;
+ BKMenuSpec *items = menu_items(n, &count);
+ if (count == 0 && m->query[0]) {
+ BKRect nr = bk_rect(n->x + p, n->y + p + th, n->w - 2 * p, u());
+ uchar tc[4];
+ memcpy(tc, mi->text, 4);
+ tc[3] = 128;
+ bk_text_in(&nr, "No results found", tc, BK_ALIGN_LEFT, false);
+ }
+ const bool icons = menu_has_icons(items, count);
+ const int open_child = menu_child_row(n);
+ for (int i = 0; i < count; i++) {
+ int ry, rh;
+ menu_row_geom(n, i, &ry, &rh);
+ BKMenuSpec *it = &items[i];
+ BKRect row = bk_rect(n->x + p, ry, n->w - 2 * p, rh);
+ if (is_sep(it)) {
+ float c[4];
+ bk_rgba_alpha(mi->text, 0.15f, c);
+ bk_fill_f(row.xmin + bk_pad(), ry + rh / 2, bk_rw(&row) - 2 * bk_pad(), 1, c);
+ continue;
+ }
+ int st = it->enabled ? 0 : ST_DISABLED;
+ if ((i == n->hot || i == open_child) && it->enabled) {
+ st |= ST_HOVER;
+ }
+ if (m->current && strcmp(it->text, m->current) == 0) {
+ st |= ST_ACTIVE_DEFAULT; /* the current enum value */
+ }
+ BKWCol w;
+ bk_widget_state_menu_item(&w, mi, st);
+ BKRect wr = row;
+ if (st & (ST_HOVER | ST_ACTIVE_DEFAULT)) {
+ bk_widget_menu_itembut(&w, &wr);
+ }
+ float tx = row.xmin + bk_pad();
+ if (icons) {
+ const float cx = tx + bk_icon_size() * 0.5f - 0.1f * uu;
+ if (it->checked >= 0) {
+ menu_check_icon(cx, ry + rh * 0.5f, it->checked > 0);
+ }
+ else if (it->icon) {
+ bk_icon(it->icon, cx, ry + rh * 0.5f, NULL, it->enabled ? 1.0f : 0.5f, 0);
+ }
+ tx += bk_icon_size() + 0.2f * uu;
+ }
+ bk_clip_push(row.xmin, row.ymin, bk_rw(&row), rh);
+ BKRect lr = bk_rect(row.xmin, ry, bk_rw(&row), rh);
+ bk_text(tx, bk_text_baseline(&lr), it->text, -1, w.text, false);
+ if (it->shortcut) {
+ uchar sc[4];
+ memcpy(sc, w.text, 4);
+ sc[3] = (uchar)(sc[3] * 0.55f);
+ const float sw = bk_text_width(it->shortcut, -1, false);
+ bk_text(row.xmax - bk_pad() - sw - (it->nsub ? uu : 0), bk_text_baseline(&lr), it->shortcut,
+ -1, sc, false);
+ }
+ bk_clip_pop();
+ if (it->nsub) {
+ uchar ac[4];
+ memcpy(ac, w.text, 4);
+ ac[3] = (uchar)(ac[3] * 0.8f);
+ bk_icon(bk_icons_lookup("RIGHTARROW"), row.xmax - 0.5f * uu, ry + rh * 0.5f, ac, 1.0f,
+ 0.6f * uu);
+ }
+ }
+}
+
+static void menu_free(BKNode *n)
+{
+ MenuData *m = MENU(n);
+ bk_menuspec_free(m->all, m->nall);
+ bk_menuspec_free(m->filtered, m->nfiltered);
+ free(m->title);
+ free(m->current);
+ free(m);
+}
+
+void bk_menu_on_close(BKNode *menu)
+{
+ (void)menu;
+}
+
+const BKClass bk_cls_menu = {.name = "menu",
+ .flags = CLS_INTERACTIVE | CLS_POPUP,
+ .free_ext = menu_free,
+ .measure = menu_measure,
+ .draw = menu_draw,
+ .press = menu_press,
+ .release = menu_release,
+ .move = menu_move,
+ .key = menu_key};
+
+BKNode *bk_menu_new(const BKMenuSpec *items, int n, const char *title, const char *current)
+{
+ BKNode *menu = bk_node_new_cls(&bk_cls_menu);
+ MenuData *m = (MenuData *)calloc(1, sizeof(MenuData));
+ place_init(&m->place);
+ m->all = bk_menuspec_copy(items, n);
+ m->nall = n;
+ m->title = title ? bk_strdup(title) : NULL;
+ m->current = current ? bk_strdup(current) : NULL;
+ m->from_row = -1;
+ menu->ext = m;
+ menu->hot = -1;
+ if (current) {
+ for (int i = 0; i < n; i++) {
+ if (!is_sep(&items[i]) && strcmp(items[i].text, current) == 0) {
+ menu->hot = i;
+ }
+ }
+ }
+ return menu;
+}
+
+void BK_open_menu(BKContext *ctx, BKNode *owner, const BKMenuSpec *items, int n, const char *title,
+ int at_x, int at_y)
+{
+ BKNode *menu = bk_menu_new(items, n, title, NULL);
+ if (at_x > PLACE_NONE && at_y > PLACE_NONE && (at_x || at_y)) {
+ MENU(menu)->place.at_x = at_x;
+ MENU(menu)->place.at_y = at_y;
+ }
+ bk_open_popup(ctx, menu, owner ? owner : ctx->root, NULL);
+}
+
+int BK_menu_row_count(BKNode *menu)
+{
+ int count = 0;
+ if (menu->cls == &bk_cls_menu || menu->cls == &bk_cls_pie) {
+ menu_items(menu, &count);
+ }
+ return count;
+}
+
+void BK_menu_row_rect(BKNode *menu, int i, int r[4])
+{
+ if (menu->cls == &bk_cls_pie) {
+ BKRect rr = pie_item_rect_pub(menu, i);
+ r[0] = rr.xmin;
+ r[1] = rr.ymin;
+ r[2] = bk_rw(&rr);
+ r[3] = bk_rh(&rr);
+ return;
+ }
+ int ry, rh;
+ menu_row_geom(menu, i, &ry, &rh);
+ r[0] = menu->x + menu_pad();
+ r[1] = ry;
+ r[2] = menu->w - 2 * menu_pad();
+ r[3] = rh;
+}
+
+const char *BK_menu_row_text(BKNode *menu, int i)
+{
+ int count = 0;
+ BKMenuSpec *items = menu_items(menu, &count);
+ return (i >= 0 && i < count) ? items[i].text : "";
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Pie menu (Blender order: W, E, S, N, NW, NE, SW, SE)
+ * \{ */
+
+static const float g_pie_dirs[8][2] = {{-1, 0}, {1, 0}, {0, 1},
+ {0, -1}, {-0.71f, -0.71f}, {0.71f, -0.71f},
+ {-0.71f, 0.71f}, {0.71f, 0.71f}};
+
+typedef struct PieData {
+ MenuData menu; /* items in menu.all */
+ float cx, cy;
+ int at_x, at_y;
+} PieData;
+
+#define PIE(n) ((PieData *)(n)->ext)
+
+static float pie_radius(void)
+{
+ return 4.2f * u();
+}
+
+static BKRect pie_item_rect(BKNode *n, int i)
+{
+ PieData *pd = PIE(n);
+ const BKMenuSpec *it = &pd->menu.all[i];
+ const float uu = (float)u();
+ float w = bk_text_width(it->text, -1, false) + 2 * bk_pad() +
+ (it->icon ? bk_icon_size() + 0.3f * uu : 0);
+ w = BK_MAX(w, 3 * uu);
+ const float px = pd->cx + g_pie_dirs[i][0] * pie_radius();
+ const float py = pd->cy + g_pie_dirs[i][1] * pie_radius() * 0.8f;
+ float x;
+ if (g_pie_dirs[i][0] < -0.1f) {
+ x = px - w;
+ }
+ else if (g_pie_dirs[i][0] > 0.1f) {
+ x = px;
+ }
+ else {
+ x = px - w * 0.5f;
+ }
+ return bk_rect((int)x, (int)(py - uu * 0.5f), (int)w, (int)uu);
+}
+
+static BKRect pie_item_rect_pub(BKNode *n, int i)
+{
+ return pie_item_rect(n, i);
+}
+
+static int pie_dir_hot(BKNode *n, int x, int y)
+{
+ PieData *pd = PIE(n);
+ const int count = BK_MIN(8, pd->menu.nall);
+ for (int i = 0; i < count; i++) {
+ BKRect r = pie_item_rect(n, i);
+ if (x >= r.xmin && x < r.xmax && y >= r.ymin && y < r.ymax) {
+ return i;
+ }
+ }
+ const float dx = x - pd->cx, dy = y - pd->cy;
+ if (hypotf(dx, dy) < 0.8f * u()) {
+ return -1;
+ }
+ const float a = atan2f(dy, dx);
+ int best = -1;
+ float best_d = 9.0f;
+ for (int i = 0; i < count; i++) {
+ const float da = a - atan2f(g_pie_dirs[i][1], g_pie_dirs[i][0]);
+ const float d = fabsf(atan2f(sinf(da), cosf(da)));
+ if (d < best_d) {
+ best = i;
+ best_d = d;
+ }
+ }
+ return best;
+}
+
+static void pie_arrange(BKNode *n)
+{
+ PieData *pd = PIE(n);
+ const float r = pie_radius(), uu = (float)u();
+ const float mx = r + 6 * uu, my = r * 0.8f + uu;
+ const float ax = pd->at_x > PLACE_NONE ? pd->at_x : n->w * 0.5f;
+ const float ay = pd->at_y > PLACE_NONE ? pd->at_y : n->h * 0.5f;
+ pd->cx = BK_MAX(mx, BK_MIN(n->w - mx, ax));
+ pd->cy = BK_MAX(my, BK_MIN(n->h - my, ay));
+}
+
+static BKNode *pie_hit(BKNode *n, int x, int y)
+{
+ return n; /* modal: owns the whole window while open */
+}
+
+static void pie_pick(BKNode *n, int i)
+{
+ PieData *pd = PIE(n);
+ BKContext *ctx = bk_ctx(n);
+ if (!ctx) {
+ return;
+ }
+ if (i < 0 || i >= BK_MIN(8, pd->menu.nall) || !pd->menu.all[i].enabled) {
+ BK_close_popups(ctx);
+ return;
+ }
+ void (*fn)(void *) = pd->menu.all[i].fn;
+ void *data = pd->menu.all[i].data, *ref = pd->menu.all[i].ref;
+ bk_retain(ref);
+ BK_close_popups(ctx);
+ if (fn) {
+ fn(data);
+ }
+ else if (ref && ctx->host.emit) {
+ ctx->host.emit(ctx->host.data, NULL, BK_EV_CALL, ref, 0, 0);
+ }
+ bk_release(ref);
+}
+
+static int pie_move(BKNode *n, BKEvent *e)
+{
+ const int hot = pie_dir_hot(n, e->x, e->y);
+ if (hot != n->hot) {
+ n->hot = hot;
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int pie_press(BKNode *n, BKEvent *e)
+{
+ pie_pick(n, pie_dir_hot(n, e->x, e->y));
+ return 1;
+}
+
+static int pie_key(BKNode *n, BKEvent *e)
+{
+ if (e->text && e->text[0] >= '1' && e->text[0] <= '8' && !e->text[1]) {
+ pie_pick(n, e->text[0] - '1');
+ return 1;
+ }
+ if (bk_keysym_is(e->keysym, "Return") || bk_keysym_is(e->keysym, "KP_Enter")) {
+ pie_pick(n, n->hot);
+ return 1;
+ }
+ return 0;
+}
+
+static void pie_draw(BKNode *n)
+{
+ PieData *pd = PIE(n);
+ const float uu = (float)u();
+ float c[4];
+ /* center disc with a direction indicator (draw_pie_center) */
+ bk_rgba_alpha(bk_theme.pie_menu.inner, 0.85f, c);
+ bk_circle(pd->cx, pd->cy, 0.9f * uu, c);
+ bk_rgba(bk_theme.menu_back.outline, c);
+ bk_ring(pd->cx, pd->cy, 0.9f * uu, c, 1.0f);
+ if (n->hot >= 0) {
+ const float a = atan2f(g_pie_dirs[n->hot][1], g_pie_dirs[n->hot][0]);
+ float ic[4];
+ bk_rgba(bk_theme.pie_menu.item, ic);
+ for (int t = -4; t < 4; t++) {
+ bk_line(pd->cx + 0.9f * uu * cosf(a + t / 10.0f), pd->cy + 0.9f * uu * sinf(a + t / 10.0f),
+ pd->cx + 0.9f * uu * cosf(a + (t + 1) / 10.0f),
+ pd->cy + 0.9f * uu * sinf(a + (t + 1) / 10.0f), ic, BK_MAX(2.0f, 0.15f * uu));
+ }
+ }
+ if (pd->menu.title) {
+ const float tw = bk_text_width(pd->menu.title, -1, false) + 2 * bk_pad();
+ BKRect tr = bk_rect((int)(pd->cx - tw * 0.5f), (int)(pd->cy - pie_radius() * 0.8f - 2.2f * uu),
+ (int)tw, (int)uu);
+ bk_widget_menu_back(&tr, CNR_ALL);
+ bk_text_in(&tr, pd->menu.title, bk_theme.menu_back.text, BK_ALIGN_CENTER, false);
+ }
+ for (int i = 0; i < BK_MIN(8, pd->menu.nall); i++) {
+ BKRect r = pie_item_rect(n, i);
+ const BKMenuSpec *it = &pd->menu.all[i];
+ int st = (i == n->hot ? ST_HOVER : 0) | (it->enabled ? 0 : ST_DISABLED);
+ BKWCol w = bk_theme.pie_menu;
+ /* widget_state_pie_menu_item */
+ if (st & ST_HOVER) {
+ memcpy(w.text, w.text_sel, 3);
+ memcpy(w.inner, w.item, 4);
+ }
+ bk_shadow(&r, bk_widget_radius(&w));
+ BKRect wr = r;
+ bk_widget_but(&w, &wr, 0, CNR_ALL);
+ bk_text_icon(&r, it->text, it->icon, w.text, BK_ALIGN_CENTER, it->enabled);
+ }
+}
+
+static void pie_free(BKNode *n)
+{
+ PieData *pd = PIE(n);
+ bk_menuspec_free(pd->menu.all, pd->menu.nall);
+ free(pd->menu.title);
+ free(pd);
+}
+
+const BKClass bk_cls_pie = {.name = "pie",
+ .flags = CLS_INTERACTIVE | CLS_POPUP,
+ .free_ext = pie_free,
+ .arrange = pie_arrange,
+ .draw = pie_draw,
+ .hit = pie_hit,
+ .press = pie_press,
+ .move = pie_move,
+ .key = pie_key};
+
+void BK_open_pie(BKContext *ctx, const BKMenuSpec *items, int n, const char *title)
+{
+ BKNode *pie = bk_node_new_cls(&bk_cls_pie);
+ PieData *pd = (PieData *)calloc(1, sizeof(PieData));
+ place_init(&pd->menu.place);
+ pd->menu.all = bk_menuspec_copy(items, BK_MIN(n, 8));
+ pd->menu.nall = BK_MIN(n, 8);
+ pd->menu.title = title ? bk_strdup(title) : NULL;
+ pd->at_x = ctx->pointer_x;
+ pd->at_y = ctx->pointer_y;
+ pie->ext = pd;
+ pie->hot = -1;
+ bk_open_popup(ctx, pie, ctx->root, NULL);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Popover panel (holds the Popover's body while open)
+ * \{ */
+
+typedef struct PopoverData {
+ BKPopupPlace place;
+} PopoverData;
+
+static int popover_pad(void)
+{
+ return 2 * bk_iround(0.2f * u());
+}
+
+static void popover_panel_measure(BKNode *n, int *rw, int *rh)
+{
+ int bw = 0, bh = 0;
+ if (n->nkids) {
+ bk_natural(n->kids[0], &bw, &bh);
+ }
+ const int p = popover_pad();
+ *rw = BK_MAX(bw, 10 * u()) + 2 * p;
+ *rh = bh + 2 * p;
+}
+
+static void popover_panel_arrange(BKNode *n)
+{
+ const int p = popover_pad();
+ if (n->nkids) {
+ bk_arrange(n->kids[0], n->x + p, n->y + p, n->w - 2 * p, n->h - 2 * p);
+ }
+}
+
+static BKNode *popover_panel_hit(BKNode *n, int x, int y)
+{
+ BKNode *f = n->nkids ? bk_hit(n->kids[0], x, y) : NULL;
+ return f ? f : n;
+}
+
+static void popover_panel_draw(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ bk_widget_menu_back(&r, CNR_ALL);
+}
+
+static void popover_panel_free(BKNode *n)
+{
+ free(n->ext);
+}
+
+const BKClass bk_cls_popover_panel = {.name = "popover_panel",
+ .flags = CLS_INTERACTIVE | CLS_POPUP,
+ .free_ext = popover_panel_free,
+ .measure = popover_panel_measure,
+ .arrange = popover_panel_arrange,
+ .draw = popover_panel_draw,
+ .hit = popover_panel_hit};
+
+BKNode *bk_popover_panel_new(BKNode *owner, BKNode *body)
+{
+ BKNode *p = bk_node_new_cls(&bk_cls_popover_panel);
+ PopoverData *d = (PopoverData *)calloc(1, sizeof(PopoverData));
+ place_init(&d->place);
+ p->ext = d;
+ /* borrow the body (it stays owned by the popover button) */
+ p->kids = (BKNode **)malloc(sizeof(BKNode *));
+ p->kids[0] = body;
+ p->nkids = 1;
+ p->capkids = 1;
+ body->parent = p;
+ return p;
+}
+
+/** \} */
diff --git a/kit/intern/kit_textarea.c b/kit/intern/kit_textarea.c
new file mode 100644
index 0000000..3956218
--- /dev/null
+++ b/kit/intern/kit_textarea.c
@@ -0,0 +1,612 @@
+/* Multi-line text area (Tk Text, Qt QTextEdit/QPlainTextEdit).
+ *
+ * UTF-8 buffer with caret/selection, colored spans (tags), vertical
+ * scrolling; editing keys follow the single-line field (Blender's word
+ * jumps via BLI_str_cursor_step_utf8). Drawn on Blender's text-field
+ * widget (wcol_text).
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "kit_intern.h"
+
+typedef enum { STRCUR_JUMP_NONE, STRCUR_JUMP_DELIM, STRCUR_JUMP_ALL } eStrCursorJumpType;
+typedef enum { STRCUR_DIR_PREV, STRCUR_DIR_NEXT } eStrCursorJumpDirection;
+void BLI_str_cursor_step_utf8(const char *str, int str_maxlen, int *pos,
+ eStrCursorJumpDirection direction, eStrCursorJumpType jump,
+ bool use_init_step);
+void BLI_str_cursor_step_bounds_utf8(const char *str, int str_maxlen, int pos, int *r_start,
+ int *r_end);
+
+typedef BKTextSpan Span;
+
+typedef struct TAData {
+ char *text;
+ int len, cap;
+ int caret, anchor; /* anchor < 0: no selection */
+ float want_x; /* column memory for Up/Down */
+ int scroll; /* first visible line */
+ int *lines; /* line start offsets */
+ int nlines, caplines;
+ Span *spans;
+ int nspans;
+} TAData;
+
+#define TA(n) ((TAData *)(n)->ext)
+
+static int line_h(void)
+{
+ return bk_iround(0.8f * bk_unit());
+}
+
+static void ta_reindex(TAData *t)
+{
+ t->nlines = 0;
+ for (int i = 0; i <= t->len; i++) {
+ if (i == 0 || t->text[i - 1] == '\n') {
+ if (t->nlines == t->caplines) {
+ t->caplines = t->caplines ? t->caplines * 2 : 64;
+ t->lines = (int *)realloc(t->lines, sizeof(int) * (size_t)t->caplines);
+ }
+ t->lines[t->nlines++] = i;
+ }
+ }
+}
+
+static int line_end(const TAData *t, int line)
+{
+ return line + 1 < t->nlines ? t->lines[line + 1] - 1 : t->len;
+}
+
+static int line_of(const TAData *t, int off)
+{
+ int lo = 0, hi = t->nlines - 1;
+ while (lo < hi) {
+ const int mid = (lo + hi + 1) / 2;
+ if (t->lines[mid] <= off) {
+ lo = mid;
+ }
+ else {
+ hi = mid - 1;
+ }
+ }
+ return lo;
+}
+
+static void ta_init(BKNode *n)
+{
+ TAData *t = (TAData *)calloc(1, sizeof(TAData));
+ t->cap = 64;
+ t->text = (char *)calloc(1, (size_t)t->cap);
+ t->anchor = -1;
+ ta_reindex(t);
+ n->ext = t;
+ n->rows = 8;
+}
+
+static void ta_free(BKNode *n)
+{
+ TAData *t = TA(n);
+ free(t->text);
+ free(t->lines);
+ free(t->spans);
+ free(t);
+}
+
+static void ta_changed(BKNode *n)
+{
+ ta_reindex(TA(n));
+ bk_invalidate(n);
+ bk_emit(n, BK_EV_CHANGE, NULL, TA(n)->caret, 0);
+}
+
+static void ta_insert_raw(TAData *t, int off, const char *s)
+{
+ const int n = (int)strlen(s);
+ if (t->len + n + 1 > t->cap) {
+ t->cap = t->len + n + 64;
+ t->text = (char *)realloc(t->text, (size_t)t->cap);
+ }
+ off = BK_CLAMP(off, 0, t->len);
+ memmove(t->text + off + n, t->text + off, (size_t)(t->len - off + 1));
+ memcpy(t->text + off, s, (size_t)n);
+ t->len += n;
+ /* keep spans attached to their text */
+ for (int i = 0; i < t->nspans; i++) {
+ if (t->spans[i].start >= off) {
+ t->spans[i].start += n;
+ }
+ if (t->spans[i].end > off) {
+ t->spans[i].end += n;
+ }
+ }
+}
+
+static void ta_delete_raw(TAData *t, int a, int b)
+{
+ a = BK_CLAMP(a, 0, t->len);
+ b = BK_CLAMP(b, a, t->len);
+ memmove(t->text + a, t->text + b, (size_t)(t->len - b + 1));
+ t->len -= b - a;
+ for (int i = 0; i < t->nspans; i++) {
+ Span *s = &t->spans[i];
+ s->start = s->start >= b ? s->start - (b - a) : BK_MIN(s->start, a);
+ s->end = s->end >= b ? s->end - (b - a) : BK_MIN(s->end, a);
+ }
+}
+
+void BK_textarea_insert(BKNode *n, int off, const char *text)
+{
+ TAData *t = TA(n);
+ ta_insert_raw(t, off, text ? text : "");
+ if (t->caret >= off) {
+ t->caret += (int)strlen(text ? text : "");
+ }
+ t->anchor = -1;
+ ta_reindex(t);
+ bk_invalidate(n);
+}
+
+void BK_textarea_delete(BKNode *n, int a, int b)
+{
+ TAData *t = TA(n);
+ ta_delete_raw(t, a, b);
+ if (t->caret > a) {
+ t->caret = BK_MAX(a, t->caret - (b - a));
+ }
+ t->anchor = -1;
+ ta_reindex(t);
+ bk_invalidate(n);
+}
+
+int BK_textarea_caret(BKNode *n)
+{
+ return TA(n)->caret;
+}
+
+void BK_textarea_set_caret(BKNode *n, int off)
+{
+ TA(n)->caret = BK_CLAMP(off, 0, TA(n)->len);
+ TA(n)->anchor = -1;
+ bk_invalidate(n);
+}
+
+int BK_textarea_selection(BKNode *n, int *a, int *b)
+{
+ TAData *t = TA(n);
+ if (t->anchor < 0 || t->anchor == t->caret) {
+ return 0;
+ }
+ *a = BK_MIN(t->anchor, t->caret);
+ *b = BK_MAX(t->anchor, t->caret);
+ return 1;
+}
+
+void BK_textarea_set_selection(BKNode *n, int a, int b)
+{
+ TAData *t = TA(n);
+ t->anchor = BK_CLAMP(a, 0, t->len);
+ t->caret = BK_CLAMP(b, 0, t->len);
+ bk_invalidate(n);
+}
+
+void BK_textarea_set_spans(BKNode *n, const BKTextSpan *spans, int count)
+{
+ TAData *t = TA(n);
+ free(t->spans);
+ t->spans = (Span *)calloc((size_t)BK_MAX(1, count), sizeof(Span));
+ memcpy(t->spans, spans, sizeof(Span) * (size_t)count);
+ t->nspans = count;
+ bk_invalidate(n);
+}
+
+static int visible_lines(const BKNode *n)
+{
+ return BK_MAX(1, (n->h - bk_pad()) / line_h());
+}
+
+static void ta_view(BKNode *n, int axis, int *first, int *vis, int *total)
+{
+ if (axis == 0) { /* lines */
+ *first = TA(n)->scroll;
+ *vis = visible_lines(n);
+ *total = TA(n)->nlines;
+ }
+}
+
+static void ta_set_view(BKNode *n, int axis, int first)
+{
+ if (axis == 0) {
+ TA(n)->scroll = first;
+ }
+}
+
+void BK_textarea_see(BKNode *n, int off)
+{
+ TAData *t = TA(n);
+ const int line = line_of(t, BK_CLAMP(off, 0, t->len)), vis = visible_lines(n);
+ if (line < t->scroll) {
+ t->scroll = line;
+ }
+ else if (line >= t->scroll + vis) {
+ t->scroll = line - vis + 1;
+ }
+ bk_invalidate(n);
+}
+
+/* Set/get the whole text through the generic "value" property. */
+int bk_textarea_set_text(BKNode *n, const char *s)
+{
+ TAData *t = TA(n);
+ ta_delete_raw(t, 0, t->len);
+ t->nspans = 0;
+ ta_insert_raw(t, 0, s ? s : "");
+ t->caret = BK_MIN(t->caret, t->len);
+ t->anchor = -1;
+ ta_reindex(t);
+ bk_invalidate(n);
+ return 1;
+}
+
+const char *bk_textarea_text(BKNode *n)
+{
+ return TA(n)->text;
+}
+
+/* -- input -- */
+
+static int col_at(const TAData *t, int line, float px)
+{
+ const int a = t->lines[line], b = line_end(t, line);
+ float prev = 0.0f;
+ int i = a;
+ while (i < b) {
+ int nx = i;
+ BLI_str_cursor_step_utf8(t->text, t->len, &nx, STRCUR_DIR_NEXT, STRCUR_JUMP_NONE, true);
+ const float w = bk_text_width(t->text + a, nx - a, false);
+ if (px < (prev + w) * 0.5f) {
+ return i;
+ }
+ prev = w;
+ i = nx;
+ }
+ return b;
+}
+
+static int offset_at(BKNode *n, int x, int y)
+{
+ TAData *t = TA(n);
+ const int line = BK_CLAMP((y - n->y - bk_pad() / 2) / line_h() + t->scroll, 0, t->nlines - 1);
+ return col_at(t, line, (float)(x - n->x - bk_pad()));
+}
+
+int BK_textarea_index_at(BKNode *n, int x, int y)
+{
+ return offset_at(n, x, y);
+}
+
+static float caret_x(const TAData *t, int off)
+{
+ const int line = line_of(t, off);
+ return bk_text_width(t->text + t->lines[line], off - t->lines[line], false);
+}
+
+static void move(TAData *t, int to, bool extend)
+{
+ if (extend) {
+ if (t->anchor < 0) {
+ t->anchor = t->caret;
+ }
+ }
+ else {
+ t->anchor = -1;
+ }
+ t->caret = BK_CLAMP(to, 0, t->len);
+}
+
+static bool delete_selection(BKNode *n)
+{
+ int a, b;
+ if (!BK_textarea_selection(n, &a, &b)) {
+ return false;
+ }
+ bk_undo_record(n, 1);
+ ta_delete_raw(TA(n), a, b);
+ TA(n)->caret = a;
+ TA(n)->anchor = -1;
+ return true;
+}
+
+static int ta_press(BKNode *n, BKEvent *e)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (ctx && ctx->focus != n) {
+ if (ctx->focus && ctx->focus->cls->finish_edit) {
+ ctx->focus->cls->finish_edit(ctx->focus, true);
+ }
+ ctx->focus = n;
+ }
+ move(TA(n), offset_at(n, e->x, e->y), EV_SHIFT(e));
+ TA(n)->want_x = caret_x(TA(n), TA(n)->caret);
+ bk_invalidate(n);
+ return 1;
+}
+
+static int ta_dbl(BKNode *n, BKEvent *e)
+{
+ TAData *t = TA(n);
+ int a, b;
+ BLI_str_cursor_step_bounds_utf8(t->text, t->len, offset_at(n, e->x, e->y), &a, &b);
+ t->anchor = a;
+ t->caret = b;
+ bk_invalidate(n);
+ return 1;
+}
+
+static int ta_drag(BKNode *n, BKEvent *e)
+{
+ TAData *t = TA(n);
+ if (t->anchor < 0) {
+ t->anchor = t->caret;
+ }
+ t->caret = offset_at(n, e->x, e->y);
+ BK_textarea_see(n, t->caret);
+ return 1;
+}
+
+static int ta_wheel(BKNode *n, BKEvent *e)
+{
+ TAData *t = TA(n);
+ const int ns = BK_CLAMP(t->scroll - 3 * e->delta, 0, BK_MAX(0, t->nlines - visible_lines(n)));
+ if (ns != t->scroll) {
+ t->scroll = ns;
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int step(TAData *t, int pos, bool next, bool word)
+{
+ BLI_str_cursor_step_utf8(t->text, t->len, &pos, next ? STRCUR_DIR_NEXT : STRCUR_DIR_PREV,
+ word ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE, true);
+ return pos;
+}
+
+static int ta_key(BKNode *n, BKEvent *e)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (!ctx || ctx->focus != n || !NODE_ENABLED(n)) {
+ return 0;
+ }
+ TAData *t = TA(n);
+ const char *ks = e->keysym;
+ const bool ctrl = EV_CTRL(e), shift = EV_SHIFT(e);
+ int a, b;
+ const bool sel = BK_textarea_selection(n, &a, &b);
+ bool edited = false, keep_x = false;
+ if (bk_keysym_is(ks, "Escape")) {
+ ctx->focus = NULL;
+ t->anchor = -1;
+ bk_invalidate(n);
+ return 1;
+ }
+ if (ctrl && bk_keysym_is(ks, "a")) {
+ t->anchor = 0;
+ t->caret = t->len;
+ }
+ else if (ctrl && (bk_keysym_is(ks, "c") || bk_keysym_is(ks, "x"))) {
+ if (sel) {
+ char *s = (char *)malloc((size_t)(b - a + 1));
+ memcpy(s, t->text + a, (size_t)(b - a));
+ s[b - a] = 0;
+ bk_clipboard_set(ctx, s);
+ free(s);
+ if (bk_keysym_is(ks, "x")) {
+ edited = delete_selection(n);
+ }
+ }
+ }
+ else if (ctrl && bk_keysym_is(ks, "v")) {
+ char *clip = bk_clipboard_get(ctx);
+ if (clip) {
+ bk_undo_record(n, 1);
+ delete_selection(n);
+ ta_insert_raw(t, t->caret, clip);
+ t->caret += (int)strlen(clip);
+ free(clip);
+ edited = true;
+ }
+ }
+ else if (bk_keysym_is(ks, "Left") || bk_keysym_is(ks, "Right")) {
+ const bool right = bk_keysym_is(ks, "Right");
+ if (sel && !shift) {
+ move(t, right ? b : a, false);
+ }
+ else {
+ move(t, step(t, t->caret, right, ctrl), shift);
+ }
+ }
+ else if (bk_keysym_is(ks, "Up") || bk_keysym_is(ks, "Down") || bk_keysym_is(ks, "Prior") ||
+ bk_keysym_is(ks, "Next"))
+ {
+ const int line = line_of(t, t->caret);
+ int d = bk_keysym_is(ks, "Up") ? -1 : (bk_keysym_is(ks, "Down") ? 1 : 0);
+ if (!d) {
+ d = (bk_keysym_is(ks, "Prior") ? -1 : 1) * visible_lines(n);
+ }
+ const int target = BK_CLAMP(line + d, 0, t->nlines - 1);
+ move(t, col_at(t, target, t->want_x), shift);
+ keep_x = true;
+ }
+ else if (bk_keysym_is(ks, "Home")) {
+ move(t, ctrl ? 0 : t->lines[line_of(t, t->caret)], shift);
+ }
+ else if (bk_keysym_is(ks, "End")) {
+ move(t, ctrl ? t->len : line_end(t, line_of(t, t->caret)), shift);
+ }
+ else if (bk_keysym_is(ks, "BackSpace")) {
+ if (!(edited = delete_selection(n)) && t->caret > 0) {
+ bk_undo_record(n, 1);
+ const int start = step(t, t->caret, false, ctrl);
+ ta_delete_raw(t, start, t->caret);
+ t->caret = start;
+ edited = true;
+ }
+ }
+ else if (bk_keysym_is(ks, "Delete")) {
+ if (!(edited = delete_selection(n)) && t->caret < t->len) {
+ bk_undo_record(n, 1);
+ ta_delete_raw(t, t->caret, step(t, t->caret, true, ctrl));
+ edited = true;
+ }
+ }
+ else if (bk_keysym_is(ks, "Return") || bk_keysym_is(ks, "KP_Enter") ||
+ bk_keysym_is(ks, "Tab") || (e->text && (unsigned char)e->text[0] >= 0x20 && !ctrl))
+ {
+ const char *ins = bk_keysym_is(ks, "Tab") ? " " :
+ (bk_keysym_is(ks, "Return") || bk_keysym_is(ks, "KP_Enter")) ? "\n" :
+ e->text;
+ bk_undo_record(n, 1);
+ delete_selection(n);
+ ta_insert_raw(t, t->caret, ins);
+ t->caret += (int)strlen(ins);
+ t->anchor = -1;
+ edited = true;
+ }
+ else {
+ return 0;
+ }
+ if (!keep_x) {
+ ta_reindex(t);
+ t->want_x = caret_x(t, t->caret);
+ }
+ if (edited) {
+ ta_changed(n);
+ }
+ BK_textarea_see(n, t->caret);
+ return 1;
+}
+
+static int ta_cursor(BKNode *n, int x, int y)
+{
+ return BK_CURSOR_TEXT;
+}
+
+static void ta_finish(BKNode *n, bool confirm)
+{
+ TA(n)->anchor = -1;
+ bk_invalidate(n);
+}
+
+static void ta_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = 12 * bk_unit();
+ *rh = n->rows * line_h() + bk_pad();
+}
+
+static void draw_line_spans(TAData *t, int a, int b, float x, const BKRect *line,
+ const uchar def[4])
+{
+ for (int i = 0; i < t->nspans; i++) { /* backgrounds first */
+ const Span *s = &t->spans[i];
+ const int s0 = BK_MAX(s->start, a), s1 = BK_MIN(s->end, b);
+ if (s->has_bg && s1 > s0) {
+ const float sx = x + bk_text_width(t->text + a, s0 - a, false);
+ bk_fill_f(sx, (float)line->ymin, bk_text_width(t->text + s0, s1 - s0, false),
+ (float)bk_rh(line), s->bg);
+ }
+ }
+ const float base = bk_text_baseline(line);
+ /* split [a, b) at span boundaries; later spans win */
+ int pos = a;
+ while (pos < b) {
+ int next = b;
+ const float *col = NULL;
+ for (int i = 0; i < t->nspans; i++) {
+ const Span *s = &t->spans[i];
+ if (s->start <= pos && s->end > pos) {
+ if (s->has_fg) {
+ col = s->fg;
+ }
+ next = BK_MIN(next, s->end);
+ }
+ else if (s->start > pos) {
+ next = BK_MIN(next, s->start);
+ }
+ }
+ const float sx = x + bk_text_width(t->text + a, pos - a, false);
+ if (col) {
+ bk_text_f(sx, base, t->text + pos, next - pos, col, false);
+ }
+ else {
+ bk_text(sx, base, t->text + pos, next - pos, def, false);
+ }
+ pos = next;
+ }
+}
+
+static void ta_draw(BKNode *n)
+{
+ TAData *t = TA(n);
+ BKContext *ctx = bk_ctx(n);
+ const bool focused = ctx && ctx->focus == n;
+ BKRect r = bk_node_rect(n);
+ int st = NODE_ENABLED(n) ? (bk_hovered(n) ? ST_HOVER : 0) : ST_DISABLED;
+ if (focused) {
+ st = ST_SELECT;
+ }
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.textfield, st);
+ bk_widget_textbut(&w, &r, st, n->corners);
+ const int p = bk_pad(), lh = line_h();
+ bk_clip_push(n->x + 2, n->y + 2, n->w - 4, n->h - 4);
+ t->scroll = BK_CLAMP(t->scroll, 0, BK_MAX(0, t->nlines - 1));
+ int a = -1, b = -1;
+ BK_textarea_selection(n, &a, &b);
+ const float x0 = (float)(n->x + p);
+ for (int line = t->scroll; line < t->nlines; line++) {
+ const int y = n->y + p / 2 + (line - t->scroll) * lh;
+ if (y > n->y + n->h) {
+ break;
+ }
+ const int la = t->lines[line], lb = line_end(t, line);
+ if (a >= 0 && a < lb + 1 && b > la) { /* selection on this line */
+ const int s0 = BK_MAX(a, la), s1 = BK_MIN(b, lb);
+ const float sx = x0 + bk_text_width(t->text + la, s0 - la, false);
+ float sw = bk_text_width(t->text + s0, s1 - s0, false);
+ if (b > lb) {
+ sw += bk_font_size() * 0.4f; /* the newline */
+ }
+ bk_fill(sx, (float)y, sw, (float)lh, bk_theme.selection);
+ }
+ const BKRect lr = bk_rect(n->x, y, n->w, lh);
+ draw_line_spans(t, la, lb, x0, &lr, w.text);
+ if (focused && t->caret >= la && t->caret <= lb) {
+ const float cx = x0 + bk_text_width(t->text + la, t->caret - la, false);
+ bk_fill(floorf(cx), (float)y + 1, BK_MAX(1.0f, floorf(0.1f * bk_unit() + 0.5f)),
+ (float)lh - 2, bk_theme.cursor);
+ }
+ }
+ bk_clip_pop();
+}
+
+const BKClass bk_cls_textarea = {.name = "textarea",
+ .flags = CLS_INTERACTIVE,
+ .cursor = BK_CURSOR_TEXT,
+ .init = ta_init,
+ .free_ext = ta_free,
+ .measure = ta_measure,
+ .draw = ta_draw,
+ .press = ta_press,
+ .dbl = ta_dbl,
+ .drag = ta_drag,
+ .wheel = ta_wheel,
+ .key = ta_key,
+ .cursor_at = ta_cursor,
+ .finish_edit = ta_finish,
+ .view = ta_view,
+ .set_view = ta_set_view};
diff --git a/kit/intern/kit_views.c b/kit/intern/kit_views.c
new file mode 100644
index 0000000..04fc3d0
--- /dev/null
+++ b/kit/intern/kit_views.c
@@ -0,0 +1,1288 @@
+/* Data views: UI list, tree view (outliner) and grid view (preview tiles).
+ *
+ * List and tree share one row-view core (rows, scrolling, hover, selection,
+ * keyboard navigation, rename, scrollbar); each only describes its rows.
+ * Rows draw with Blender's widget_list_itembut.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "kit_intern.h"
+
+static int u(void)
+{
+ return bk_unit();
+}
+
+/* -------------------------------------------------------------------- */
+/** \name Row view core
+ * \{ */
+
+typedef struct RowOps {
+ int (*count)(BKNode *n);
+ const char *(*text)(BKNode *n, int row);
+ int (*selected)(BKNode *n);
+ void (*select)(BKNode *n, int row);
+ void (*rename)(BKNode *n, int row, const char *text);
+ int (*press_row)(BKNode *n, int row, BKEvent *e); /* 1 = consumed (arrows, toggles) */
+ void (*draw_row)(BKNode *n, int row, const BKRect *r, const uchar color[4]);
+ /* multi-selection (selmode != 0) */
+ bool (*marked)(BKNode *n, int row);
+ void (*mark)(BKNode *n, int row, bool on);
+ void (*clear_marks)(BKNode *n);
+} RowOps;
+
+static const RowOps *row_ops(const BKNode *n);
+
+static int rv_pad(void)
+{
+ return bk_iround(0.15f * u());
+}
+
+static int rv_header_h(const BKNode *n)
+{
+ return n->shortcuts.n ? u() : 0; /* column headers ("headers" property) */
+}
+
+static int rv_top(const BKNode *n)
+{
+ return rv_pad() + rv_header_h(n);
+}
+
+static int rv_visible(const BKNode *n)
+{
+ return BK_MAX(1, (n->h - rv_pad() - rv_top(n)) / u());
+}
+
+static int rv_max_scroll(BKNode *n)
+{
+ return BK_MAX(0, row_ops(n)->count(n) - rv_visible(n));
+}
+
+static int rv_row_at(BKNode *n, int y)
+{
+ if (y < n->y + rv_top(n)) {
+ return -1;
+ }
+ const int i = (y - n->y - rv_top(n)) / u() + n->scroll;
+ return (i >= 0 && i < row_ops(n)->count(n)) ? i : -1;
+}
+
+static int rv_row_y(const BKNode *n, int row)
+{
+ return n->y + rv_top(n) + (row - n->scroll) * u();
+}
+
+static int rv_bar_w(BKNode *n)
+{
+ if (n->flags & NF_NOSCROLLBAR) {
+ return 0;
+ }
+ return row_ops(n)->count(n) > rv_visible(n) ? bk_iround(0.3f * u()) : 0;
+}
+
+static void rv_view(BKNode *n, int axis, int *first, int *vis, int *total)
+{
+ if (axis == 0) { /* rows */
+ *first = n->scroll;
+ *vis = rv_visible(n);
+ *total = row_ops(n)->count(n);
+ }
+}
+
+static void rv_set_view(BKNode *n, int axis, int first)
+{
+ if (axis == 0) {
+ n->scroll = first;
+ }
+}
+
+static void rv_scroll_into_view(BKNode *n)
+{
+ const int i = row_ops(n)->selected(n), vis = rv_visible(n);
+ if (i < 0) {
+ return;
+ }
+ if (i < n->scroll) {
+ n->scroll = i;
+ }
+ else if (i >= n->scroll + vis) {
+ n->scroll = i - vis + 1;
+ }
+ bk_invalidate(n);
+}
+
+static void rv_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = 8 * u();
+ *rh = n->rows * u() + 2 * rv_pad() + rv_header_h(n);
+}
+
+/* Column x positions for multi-column views: column 0 gets the larger share. */
+static void rv_columns(const BKNode *n, int ncols, int x0, int w, int *xs)
+{
+ if (ncols <= 1) {
+ xs[0] = x0;
+ xs[1] = x0 + w;
+ return;
+ }
+ const int first = ncols == 2 ? w / 2 : (int)(w * 0.4f);
+ xs[0] = x0;
+ xs[1] = x0 + first;
+ for (int k = 2; k <= ncols; k++) {
+ xs[k] = xs[1] + (w - first) * (k - 1) / (ncols - 1);
+ }
+}
+
+static void rv_draw_headers(BKNode *n, int x0, int w)
+{
+ const int hh = rv_header_h(n);
+ if (!hh) {
+ return;
+ }
+ int xs[17];
+ const int ncols = BK_MIN(16, n->shortcuts.n);
+ rv_columns(n, ncols, x0, w, xs);
+ float line[4];
+ bk_rgba_alpha(bk_theme.text, 0.12f, line);
+ const int y = n->y + rv_pad();
+ bk_fill_f(x0, y + hh - 1, w, 1, line);
+ uchar tc[4];
+ memcpy(tc, bk_theme.text, 4);
+ tc[3] = 170;
+ for (int k = 0; k < ncols; k++) {
+ BKRect r = bk_rect(xs[k], y, xs[k + 1] - xs[k], hh);
+ bk_text_in(&r, n->shortcuts.v[k], tc, BK_ALIGN_LEFT, false);
+ if (k) {
+ bk_fill_f(xs[k], y + 3, 1, hh - 6, line);
+ }
+ }
+}
+
+static int rv_move(BKNode *n, BKEvent *e)
+{
+ const int hot = rv_row_at(n, e->y);
+ if (hot != n->hot) {
+ n->hot = hot;
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int rv_leave(BKNode *n)
+{
+ n->hot = -1;
+ return 1;
+}
+
+static bool rv_selected_row(BKNode *n, int row, int sel)
+{
+ return n->selmode ? row_ops(n)->marked(n, row) : row == sel;
+}
+
+/* Tk's selectmode: browse/single (0), multiple (1: click toggles), extended
+ * (2: click selects one, Ctrl toggles, Shift extends from the active row). */
+static void rv_click_select(BKNode *n, int row, BKEvent *e)
+{
+ const RowOps *ops = row_ops(n);
+ if (!n->selmode) {
+ ops->select(n, row);
+ return;
+ }
+ const int active = ops->selected(n);
+ if (n->selmode == 3) { /* single, shown with marks (can be cleared) */
+ ops->clear_marks(n);
+ ops->mark(n, row, true);
+ }
+ else if (n->selmode == 1 || EV_CTRL(e)) {
+ ops->mark(n, row, !ops->marked(n, row));
+ }
+ else if (EV_SHIFT(e) && active >= 0) {
+ ops->clear_marks(n);
+ for (int r = BK_MIN(active, row); r <= BK_MAX(active, row); r++) {
+ ops->mark(n, r, true);
+ }
+ }
+ else {
+ ops->clear_marks(n);
+ ops->mark(n, row, true);
+ }
+ if (!EV_SHIFT(e)) {
+ ops->select(n, row); /* the active row (Shift keeps the anchor) */
+ }
+ bk_invalidate(n);
+ bk_emit(n, BK_EV_CHANGE, NULL, row, 0);
+}
+
+static int rv_press(BKNode *n, BKEvent *e)
+{
+ if (n->edit) {
+ return 1;
+ }
+ if (rv_header_h(n) && e->y < n->y + rv_top(n)) { /* column heading: Tk's heading command */
+ int xs[17];
+ const int ncols = BK_MIN(16, n->shortcuts.n);
+ rv_columns(n, ncols, n->x + rv_pad(), n->w - 2 * rv_pad() - rv_bar_w(n), xs);
+ for (int k = 0; k < ncols; k++) {
+ if (e->x >= xs[k] && e->x < xs[k + 1]) {
+ bk_emit(n, BK_EV_CLICK, NULL, k, 0);
+ break;
+ }
+ }
+ return 1;
+ }
+ const RowOps *ops = row_ops(n);
+ const int i = rv_row_at(n, e->y);
+ if (i >= 0 && !(ops->press_row && ops->press_row(n, i, e))) {
+ rv_click_select(n, i, e);
+ }
+ return 1;
+}
+
+static void rv_begin_rename(BKNode *n, int row)
+{
+ n->rename_row = row;
+ bk_begin_edit(n, row_ops(n)->text(n, row), true);
+}
+
+static int rv_dbl(BKNode *n, BKEvent *e)
+{
+ const RowOps *ops = row_ops(n);
+ const int i = rv_row_at(n, e->y);
+ if (i < 0 || (ops->press_row && ops->press_row(n, i, e))) {
+ return 1;
+ }
+ ops->select(n, i);
+ rv_begin_rename(n, i);
+ return 1;
+}
+
+static void rv_step(BKNode *n, int dir)
+{
+ const RowOps *ops = row_ops(n);
+ const int count = ops->count(n);
+ if (!count) {
+ return;
+ }
+ const int i = ops->selected(n);
+ ops->select(n, BK_CLAMP((i >= 0 ? i : 0) - dir, 0, count - 1));
+ if (n->selmode >= 2) { /* extended / single: the keyboard moves the selection */
+ ops->clear_marks(n);
+ ops->mark(n, ops->selected(n), true);
+ bk_emit(n, BK_EV_CHANGE, NULL, ops->selected(n), 0);
+ }
+ rv_scroll_into_view(n);
+}
+
+static int rv_wheel(BKNode *n, BKEvent *e)
+{
+ if (EV_CTRL(e)) {
+ rv_step(n, e->delta > 0 ? 1 : -1);
+ return 1;
+ }
+ const int ns = BK_CLAMP(n->scroll - e->delta, 0, rv_max_scroll(n));
+ if (ns != n->scroll) {
+ n->scroll = ns;
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int rv_key(BKNode *n, BKEvent *e)
+{
+ if (n->edit) {
+ return bk_edit_key(n, e);
+ }
+ const RowOps *ops = row_ops(n);
+ if (bk_keysym_is(e->keysym, "Up") || bk_keysym_is(e->keysym, "Down")) {
+ rv_step(n, bk_keysym_is(e->keysym, "Up") ? 1 : -1);
+ return 1;
+ }
+ if ((bk_keysym_is(e->keysym, "Home") || bk_keysym_is(e->keysym, "End")) && ops->count(n)) {
+ ops->select(n, bk_keysym_is(e->keysym, "Home") ? 0 : ops->count(n) - 1);
+ rv_scroll_into_view(n);
+ return 1;
+ }
+ if (bk_keysym_is(e->keysym, "F2") && ops->selected(n) >= 0) {
+ rv_begin_rename(n, ops->selected(n));
+ return 1;
+ }
+ return bk_value_key(n, e);
+}
+
+static void rv_finish(BKNode *n, bool confirm)
+{
+ const RowOps *ops = row_ops(n);
+ const int i = n->rename_row;
+ if (confirm && n->edit && n->edit->text[0] && i >= 0 && i < ops->count(n)) {
+ ops->rename(n, i, n->edit->text);
+ bk_emit(n, BK_EV_RENAME, NULL, i, 0);
+ }
+}
+
+static void rv_draw(BKNode *n)
+{
+ const RowOps *ops = row_ops(n);
+ BKRect r = bk_node_rect(n);
+ BKWCol box = bk_theme.box;
+ if (!NODE_ENABLED(n)) {
+ box.inner[3] /= 2;
+ }
+ BKRect br = r;
+ bk_widget_box(&box, &br, n->corners, NULL);
+ const int p = rv_pad(), rh = u(), sb = rv_bar_w(n), count = ops->count(n);
+ n->scroll = BK_CLAMP(n->scroll, 0, rv_max_scroll(n));
+ const int sel = ops->selected(n);
+ bk_clip_push(n->x + 1, n->y + 1, n->w - 2, n->h - 2);
+ rv_draw_headers(n, n->x + p, n->w - 2 * p - sb);
+ for (int i = n->scroll; i < count; i++) {
+ const int y = rv_row_y(n, i);
+ if (y >= n->y + n->h) {
+ break;
+ }
+ BKRect row = bk_rect(n->x + p, y, n->w - 2 * p - sb, rh);
+ int st = (rv_selected_row(n, i, sel) ? ST_SELECT : 0) |
+ (i == n->hot && bk_hovered(n) ? ST_HOVER : 0);
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.list_item, st & ST_SELECT);
+ BKRect wr = row;
+ bk_widget_list_itembut(&w, &wr, st);
+ if (n->edit && i == n->rename_row) {
+ bk_te_draw(n->edit, &row, bk_theme.list_item.text);
+ }
+ else {
+ uchar tc[4];
+ memcpy(tc, (st & ST_SELECT) ? bk_theme.list_item.text_sel : bk_theme.list_item.text, 4);
+ if (!NODE_ENABLED(n)) {
+ tc[3] /= 2;
+ }
+ ops->draw_row(n, i, &row, tc);
+ }
+ }
+ bk_clip_pop();
+ if (sb) { /* thin Blender scrollbar */
+ const int top = rv_top(n);
+ const int track_h = n->h - p - top, vis = rv_visible(n);
+ const float th = BK_MAX(u() * 0.6f, (float)track_h * vis / count);
+ const float ty = n->y + top + (track_h - th) * n->scroll / (float)BK_MAX(1, count - vis);
+ float c[4];
+ bk_rgba(bk_theme.scroll.item, c);
+ bk_roundbox(n->x + n->w - sb - p * 0.5f, ty, sb * 0.6f, th, sb * 0.3f, CNR_ALL, c);
+ }
+}
+
+static int rv_cursor(BKNode *n, int x, int y)
+{
+ return n->edit ? BK_CURSOR_TEXT : BK_CURSOR_DEFAULT;
+}
+
+#define ROWVIEW_CLASS_COMMON \
+ .flags = CLS_INTERACTIVE | CLS_VALUE, .measure = rv_measure, .draw = rv_draw, \
+ .press = rv_press, .dbl = rv_dbl, .move = rv_move, .leave = rv_leave, .key = rv_key, \
+ .wheel = rv_wheel, .finish_edit = rv_finish, .cursor_at = rv_cursor, .step = rv_step, \
+ .view = rv_view, .set_view = rv_set_view
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name ListView
+ * \{ */
+
+static int list_count(BKNode *n)
+{
+ return n->items.n;
+}
+static const char *list_text(BKNode *n, int row)
+{
+ return (row >= 0 && row < n->items.n) ? n->items.v[row] : "";
+}
+static int list_selected(BKNode *n)
+{
+ return n->items.n ? (int)n->value : -1;
+}
+static void list_select(BKNode *n, int row)
+{
+ bk_set_value(n, row);
+}
+static void list_rename(BKNode *n, int row, const char *text)
+{
+ free(n->items.v[row]);
+ n->items.v[row] = bk_strdup(text);
+}
+static void list_draw_row(BKNode *n, int row, const BKRect *r, const uchar color[4])
+{
+ const int icon = (n->item_icons && row < n->item_icons_s.n) ? n->item_icons[row] : 0;
+ bk_text_icon(r, n->items.v[row], icon, color, BK_ALIGN_LEFT, NODE_ENABLED(n));
+}
+
+static bool list_marked(BKNode *n, int row)
+{
+ return row >= 0 && row < n->nmarks && n->marks[row];
+}
+
+static void list_mark(BKNode *n, int row, bool on)
+{
+ if (row < 0) {
+ return;
+ }
+ if (row >= n->nmarks) {
+ const int count = BK_MAX(row + 1, n->items.n);
+ n->marks = (unsigned char *)realloc(n->marks, (size_t)count);
+ memset(n->marks + n->nmarks, 0, (size_t)(count - n->nmarks));
+ n->nmarks = count;
+ }
+ n->marks[row] = on;
+ bk_invalidate(n);
+}
+
+static void list_clear_marks(BKNode *n)
+{
+ if (n->marks) {
+ memset(n->marks, 0, (size_t)n->nmarks);
+ }
+ bk_invalidate(n);
+}
+
+static int list_get_num(BKNode *n, const char *key, double *r_v)
+{
+ if (strncmp(key, "mark", 4) == 0 && key[4] >= '0' && key[4] <= '9') { /* "mark12" */
+ *r_v = list_marked(n, atoi(key + 4));
+ return 1;
+ }
+ return 0;
+}
+
+static int list_set_num(BKNode *n, const char *key, double v)
+{
+ if (strncmp(key, "mark", 4) == 0 && key[4] >= '0' && key[4] <= '9') {
+ list_mark(n, atoi(key + 4), v != 0);
+ return 1;
+ }
+ if (strcmp(key, "clearmarks") == 0) {
+ list_clear_marks(n);
+ return 1;
+ }
+ return 0;
+}
+
+static const RowOps g_list_ops = {list_count, list_text, list_selected,
+ list_select, list_rename, NULL,
+ list_draw_row, list_marked, list_mark,
+ list_clear_marks};
+
+static int list_to_text(BKNode *n, char *buf, int size)
+{
+ snprintf(buf, (size_t)size, "%s", list_text(n, (int)n->value));
+ return 1;
+}
+
+static void list_init(BKNode *n)
+{
+ n->flags |= NF_HAS_MIN | NF_INTEGER;
+ n->vmin = 0;
+}
+
+const BKClass bk_cls_list = {.name = "list",
+ ROWVIEW_CLASS_COMMON,
+ .init = list_init,
+ .to_text = list_to_text,
+ .set_num = list_set_num,
+ .get_num = list_get_num};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name TreeView
+ * \{ */
+
+struct BKTreeItem {
+ BKStrs values; /* extra columns */
+ char *label;
+ int icon;
+ bool expanded;
+ bool marked; /* multi-selection */
+ unsigned toggles; /* bit per toggle column */
+ BKTreeItem *parent;
+ BKTreeItem **kids;
+ int nkids, cap;
+ void *ref;
+};
+
+typedef struct TreeData {
+ BKTreeItem **roots;
+ int nroots;
+ BKTreeItem *selected;
+ int columns[8]; /* toggle columns: icon pairs (off, on) */
+ int ncolumns;
+ /* flattened rows, rebuilt on demand */
+ BKTreeItem **rows;
+ int *depth;
+ int nrows, caprows;
+ bool flat; /* no item has children: rows line up with the headers (a table) */
+ int toggle_col, toggle_value; /* drag along a toggle column */
+} TreeData;
+
+#define TREE(n) ((TreeData *)(n)->ext)
+
+BKTreeItem *BK_tree_item_new(const char *label, int icon)
+{
+ BKTreeItem *it = (BKTreeItem *)calloc(1, sizeof(BKTreeItem));
+ it->label = bk_strdup(label ? label : "");
+ it->icon = icon;
+ it->expanded = true;
+ return it;
+}
+
+void BK_tree_item_free(BKTreeItem *it)
+{
+ if (!it) {
+ return;
+ }
+ for (int i = 0; i < it->nkids; i++) {
+ it->kids[i]->parent = NULL;
+ if (it->kids[i]->ref) {
+ bk_release(it->kids[i]->ref);
+ }
+ else {
+ BK_tree_item_free(it->kids[i]);
+ }
+ }
+ free(it->kids);
+ free(it->label);
+ bk_strs_free(&it->values);
+ free(it);
+}
+
+void BK_tree_item_set_values(BKTreeItem *it, const char *const *values, int n)
+{
+ bk_strs_set(&it->values, values, n);
+}
+
+void BK_tree_item_set_ref(BKTreeItem *it, void *ref)
+{
+ it->ref = ref;
+}
+void *BK_tree_item_ref(const BKTreeItem *it)
+{
+ return it->ref;
+}
+
+void BK_tree_item_clear(BKTreeItem *parent)
+{
+ for (int i = 0; i < parent->nkids; i++) {
+ BKTreeItem *kid = parent->kids[i];
+ kid->parent = NULL;
+ if (kid->ref) {
+ bk_release(kid->ref);
+ }
+ }
+ parent->nkids = 0;
+}
+
+void BK_tree_item_add(BKTreeItem *parent, BKTreeItem *child)
+{
+ if (parent->nkids == parent->cap) {
+ parent->cap = parent->cap ? parent->cap * 2 : 4;
+ parent->kids = (BKTreeItem **)realloc(parent->kids, sizeof(BKTreeItem *) * (size_t)parent->cap);
+ }
+ parent->kids[parent->nkids++] = child;
+ child->parent = parent;
+ bk_retain(child->ref);
+}
+
+void BK_tree_item_set(BKTreeItem *it, const char *key, double v)
+{
+ if (strcmp(key, "expanded") == 0) {
+ it->expanded = v != 0;
+ }
+ else if (strcmp(key, "marked") == 0) {
+ it->marked = v != 0;
+ }
+ else if (strcmp(key, "icon") == 0) {
+ it->icon = (int)v;
+ }
+ else if (strncmp(key, "toggle", 6) == 0) {
+ const int bit = atoi(key + 6);
+ if (v != 0) {
+ it->toggles |= 1u << bit;
+ }
+ else {
+ it->toggles &= ~(1u << bit);
+ }
+ }
+}
+
+double BK_tree_item_get(const BKTreeItem *it, const char *key)
+{
+ if (strcmp(key, "expanded") == 0) {
+ return it->expanded;
+ }
+ if (strcmp(key, "marked") == 0) {
+ return it->marked;
+ }
+ if (strcmp(key, "icon") == 0) {
+ return it->icon;
+ }
+ if (strncmp(key, "toggle", 6) == 0) {
+ return (it->toggles >> atoi(key + 6)) & 1u;
+ }
+ return 0;
+}
+
+void BK_tree_item_set_label(BKTreeItem *it, const char *label)
+{
+ bk_set_text(&it->label, label);
+}
+const char *BK_tree_item_label(const BKTreeItem *it)
+{
+ return it->label;
+}
+int BK_tree_item_child_count(const BKTreeItem *it)
+{
+ return it->nkids;
+}
+BKTreeItem *BK_tree_item_child(const BKTreeItem *it, int i)
+{
+ return (i >= 0 && i < it->nkids) ? it->kids[i] : NULL;
+}
+
+static void tree_add_rows(TreeData *t, BKTreeItem *it, int depth)
+{
+ if (t->nrows == t->caprows) {
+ t->caprows = t->caprows ? t->caprows * 2 : 32;
+ t->rows = (BKTreeItem **)realloc(t->rows, sizeof(BKTreeItem *) * (size_t)t->caprows);
+ t->depth = (int *)realloc(t->depth, sizeof(int) * (size_t)t->caprows);
+ }
+ t->rows[t->nrows] = it;
+ t->depth[t->nrows] = depth;
+ t->nrows++;
+ if (it->expanded) {
+ for (int i = 0; i < it->nkids; i++) {
+ tree_add_rows(t, it->kids[i], depth + 1);
+ }
+ }
+}
+
+static void tree_flatten(BKNode *n)
+{
+ TreeData *t = TREE(n);
+ t->nrows = 0;
+ t->flat = true;
+ for (int i = 0; i < t->nroots; i++) {
+ tree_add_rows(t, t->roots[i], 0);
+ t->flat = t->flat && t->roots[i]->nkids == 0;
+ }
+}
+
+static void tree_init(BKNode *n)
+{
+ n->ext = calloc(1, sizeof(TreeData));
+ n->rows = 8;
+}
+
+static void tree_free(BKNode *n)
+{
+ TreeData *t = TREE(n);
+ for (int i = 0; i < t->nroots; i++) {
+ if (t->roots[i]->ref) {
+ bk_release(t->roots[i]->ref);
+ }
+ else {
+ BK_tree_item_free(t->roots[i]);
+ }
+ }
+ free(t->roots);
+ free(t->rows);
+ free(t->depth);
+ free(t);
+}
+
+void BK_tree_set_roots(BKNode *n, BKTreeItem *const *roots, int count)
+{
+ TreeData *t = TREE(n);
+ for (int i = 0; i < count; i++) {
+ bk_retain(roots[i]->ref);
+ }
+ for (int i = 0; i < t->nroots; i++) {
+ if (t->roots[i]->ref) {
+ bk_release(t->roots[i]->ref);
+ }
+ }
+ free(t->roots);
+ t->roots = (BKTreeItem **)malloc(sizeof(BKTreeItem *) * (size_t)BK_MAX(1, count));
+ memcpy(t->roots, roots, sizeof(BKTreeItem *) * (size_t)count);
+ t->nroots = count;
+ t->selected = NULL;
+ tree_flatten(n);
+ bk_invalidate(n);
+}
+
+static int tree_count(BKNode *n)
+{
+ tree_flatten(n);
+ return TREE(n)->nrows;
+}
+
+static const char *tree_text(BKNode *n, int row)
+{
+ tree_flatten(n);
+ return (row >= 0 && row < TREE(n)->nrows) ? TREE(n)->rows[row]->label : "";
+}
+
+static int tree_selected(BKNode *n)
+{
+ TreeData *t = TREE(n);
+ tree_flatten(n);
+ for (int i = 0; i < t->nrows; i++) {
+ if (t->rows[i] == t->selected) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+static void tree_select(BKNode *n, int row)
+{
+ TreeData *t = TREE(n);
+ tree_flatten(n);
+ if (row >= 0 && row < t->nrows && t->rows[row] != t->selected) {
+ t->selected = t->rows[row];
+ bk_invalidate(n);
+ bk_emit(n, BK_EV_CHANGE, t->selected->ref, row, 0);
+ }
+}
+
+static void tree_rename(BKNode *n, int row, const char *text)
+{
+ bk_set_text(&TREE(n)->rows[row]->label, text);
+}
+
+static int tree_indent(void)
+{
+ return bk_iround(0.9f * u());
+}
+
+static int tree_col_x(BKNode *n, int k)
+{
+ TreeData *t = TREE(n);
+ const int right = n->x + n->w - rv_pad() - rv_bar_w(n);
+ return right - (t->ncolumns - k) * u();
+}
+
+static void tree_set_expanded(BKTreeItem *it, bool expanded, bool recursive)
+{
+ it->expanded = expanded;
+ if (recursive) {
+ for (int i = 0; i < it->nkids; i++) {
+ tree_set_expanded(it->kids[i], expanded, true);
+ }
+ }
+}
+
+static void tree_set_toggle(BKNode *n, BKTreeItem *it, int col, int value)
+{
+ const unsigned bit = 1u << col;
+ if (((it->toggles & bit) != 0) != (value != 0)) {
+ it->toggles = value ? (it->toggles | bit) : (it->toggles & ~bit);
+ bk_invalidate(n);
+ bk_emit(n, BK_EV_TOGGLE, it->ref, col, value);
+ }
+}
+
+/* User expand/collapse: tell the host (Tk's <<TreeviewOpen>> / <<TreeviewClose>>). */
+static void tree_open(BKNode *n, BKTreeItem *it, bool expanded, bool recursive)
+{
+ const bool was = it->expanded;
+ tree_set_expanded(it, expanded, recursive);
+ if (was != expanded) {
+ bk_emit(n, BK_EV_TOGGLE, it->ref, -1, expanded);
+ }
+}
+
+static int tree_press_row(BKNode *n, int row, BKEvent *e)
+{
+ TreeData *t = TREE(n);
+ BKTreeItem *it = t->rows[row];
+ const int ind = tree_indent();
+ const int ax = n->x + rv_pad() + t->depth[row] * ind;
+ if (it->nkids && e->x >= ax && e->x < ax + ind) {
+ tree_open(n, it, !it->expanded, EV_SHIFT(e)); /* Shift: recursively */
+ bk_invalidate(n);
+ return 1;
+ }
+ for (int k = 0; k < t->ncolumns; k++) {
+ const int cx = tree_col_x(n, k);
+ if (e->x >= cx && e->x < cx + u()) {
+ const int value = !((it->toggles >> k) & 1u);
+ tree_set_toggle(n, it, k, value);
+ t->toggle_col = k + 1;
+ t->toggle_value = value;
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static void tree_draw_row(BKNode *n, int row, const BKRect *r, const uchar color[4])
+{
+ TreeData *t = TREE(n);
+ BKTreeItem *it = t->rows[row];
+ const int depth = t->depth[row], ind = tree_indent();
+ float line[4];
+ bk_rgba_alpha(bk_theme.text, 0.08f, line);
+ for (int d = 0; d < depth; d++) { /* faint hierarchy lines */
+ bk_fill_f(r->xmin + d * ind + ind * 0.5f, r->ymin, 1, bk_rh(r), line);
+ }
+ const int ax = r->xmin + depth * ind;
+ if (it->nkids) {
+ float c[4];
+ bk_rgba_alpha(color, 0.75f, c);
+ bk_tria(ax + ind * 0.5f, r->ymin + bk_rh(r) * 0.5f, it->expanded ? 'v' : 'h', c,
+ 0.15f * u());
+ }
+ const int right = t->ncolumns ? tree_col_x(n, 0) : r->xmax;
+ int xs[17];
+ const int ncols = BK_MIN(16, BK_MAX(n->shortcuts.n, it->values.n + 1));
+ rv_columns(n, ncols, r->xmin, right - r->xmin, xs);
+ BKRect lr = {t->flat ? r->xmin : ax + ind - bk_pad() / 2, r->ymin, xs[1], r->ymax};
+ bk_text_icon(&lr, it->label, it->icon, color, BK_ALIGN_LEFT, NODE_ENABLED(n));
+ for (int k = 1; k < ncols && k - 1 < it->values.n; k++) {
+ BKRect cr = bk_rect(xs[k], r->ymin, xs[k + 1] - xs[k], bk_rh(r));
+ bk_text_in(&cr, it->values.v[k - 1], color, BK_ALIGN_LEFT, false);
+ }
+ for (int k = 0; k < t->ncolumns; k++) {
+ const int on = (it->toggles >> k) & 1u;
+ const int icon = t->columns[k * 2 + on];
+ uchar ic[4];
+ memcpy(ic, bk_theme.text, 4);
+ ic[3] = (uchar)(on ? 115 : 217);
+ bk_icon(icon, tree_col_x(n, k) + u() * 0.5f, r->ymin + bk_rh(r) * 0.5f, ic, 1.0f, 0);
+ }
+}
+
+static bool tree_marked(BKNode *n, int row)
+{
+ tree_flatten(n);
+ return row >= 0 && row < TREE(n)->nrows && TREE(n)->rows[row]->marked;
+}
+
+static void tree_mark(BKNode *n, int row, bool on)
+{
+ tree_flatten(n);
+ if (row >= 0 && row < TREE(n)->nrows) {
+ TREE(n)->rows[row]->marked = on;
+ bk_invalidate(n);
+ }
+}
+
+static void tree_unmark(BKTreeItem *it)
+{
+ it->marked = false;
+ for (int i = 0; i < it->nkids; i++) {
+ tree_unmark(it->kids[i]);
+ }
+}
+
+static void tree_clear_marks(BKNode *n)
+{
+ for (int i = 0; i < TREE(n)->nroots; i++) {
+ tree_unmark(TREE(n)->roots[i]);
+ }
+ bk_invalidate(n);
+}
+
+static const RowOps g_tree_ops = {tree_count, tree_text, tree_selected, tree_select,
+ tree_rename, tree_press_row, tree_draw_row, tree_marked,
+ tree_mark, tree_clear_marks};
+
+static int tree_drag(BKNode *n, BKEvent *e)
+{
+ TreeData *t = TREE(n);
+ if (t->toggle_col) { /* drag down a toggle column (outliner) */
+ const int row = rv_row_at(n, e->y);
+ if (row >= 0) {
+ tree_set_toggle(n, t->rows[row], t->toggle_col - 1, t->toggle_value);
+ }
+ return 1;
+ }
+ return 0;
+}
+
+static int tree_release(BKNode *n, BKEvent *e)
+{
+ TREE(n)->toggle_col = 0;
+ return 1;
+}
+
+static int tree_key(BKNode *n, BKEvent *e)
+{
+ TreeData *t = TREE(n);
+ if (!n->edit && t->selected &&
+ (bk_keysym_is(e->keysym, "Left") || bk_keysym_is(e->keysym, "Right")))
+ {
+ BKTreeItem *it = t->selected;
+ if (bk_keysym_is(e->keysym, "Right") && it->nkids) {
+ tree_open(n, it, true, EV_SHIFT(e));
+ }
+ else if (bk_keysym_is(e->keysym, "Left")) {
+ if (it->expanded && it->nkids) {
+ tree_open(n, it, false, EV_SHIFT(e));
+ }
+ else if (it->parent) {
+ t->selected = it->parent;
+ bk_emit(n, BK_EV_CHANGE, it->parent->ref, tree_selected(n), 0);
+ rv_scroll_into_view(n);
+ }
+ }
+ bk_invalidate(n);
+ return 1;
+ }
+ return rv_key(n, e);
+}
+
+static void tree_expand_all(void *data)
+{
+ BKNode *n = (BKNode *)data;
+ if (TREE(n)->selected) {
+ tree_open(n, TREE(n)->selected, true, true);
+ bk_invalidate(n);
+ }
+}
+
+static void tree_collapse_all(void *data)
+{
+ BKNode *n = (BKNode *)data;
+ if (TREE(n)->selected) {
+ tree_open(n, TREE(n)->selected, false, true);
+ bk_invalidate(n);
+ }
+}
+
+static void tree_rename_selected(void *data)
+{
+ BKNode *n = (BKNode *)data;
+ const int row = tree_selected(n);
+ if (row >= 0) {
+ rv_begin_rename(n, row);
+ }
+}
+
+static int tree_context(BKNode *n, BKMenuSpec *items, int max)
+{
+ if (!TREE(n)->selected || max < 4) {
+ return 0;
+ }
+ memset(items, 0, sizeof(BKMenuSpec) * 4);
+ items[0] = (BKMenuSpec){"Expand All", 0, NULL, -1, 1};
+ items[0].fn = tree_expand_all;
+ items[1] = (BKMenuSpec){"Collapse All", 0, NULL, -1, 1};
+ items[1].fn = tree_collapse_all;
+ items[2] = (BKMenuSpec){"-", 0, NULL, -1, 1};
+ items[3] = (BKMenuSpec){"Rename", 0, "F2", -1, 1};
+ items[3].fn = tree_rename_selected;
+ for (int i = 0; i < 4; i++) {
+ items[i].data = n;
+ }
+ return 4;
+}
+
+static int tree_to_text(BKNode *n, char *buf, int size)
+{
+ snprintf(buf, (size_t)size, "%s", TREE(n)->selected ? TREE(n)->selected->label : "");
+ return 1;
+}
+
+static void tree_reset(BKNode *n, bool zero)
+{
+}
+
+const BKClass bk_cls_tree = {.name = "tree",
+ ROWVIEW_CLASS_COMMON,
+ .init = tree_init,
+ .free_ext = tree_free,
+ .drag = tree_drag,
+ .release = tree_release,
+ .key = tree_key,
+ .context_items = tree_context,
+ .to_text = tree_to_text,
+ .reset = tree_reset};
+
+BKTreeItem *BK_tree_selected(BKNode *n)
+{
+ return TREE(n)->selected;
+}
+
+void BK_tree_select(BKNode *n, BKTreeItem *it)
+{
+ TREE(n)->selected = it;
+ bk_invalidate(n);
+}
+
+int BK_tree_row_count(BKNode *n)
+{
+ return tree_count(n);
+}
+
+BKTreeItem *BK_tree_row(BKNode *n, int row)
+{
+ tree_flatten(n);
+ return (row >= 0 && row < TREE(n)->nrows) ? TREE(n)->rows[row] : NULL;
+}
+
+void BK_tree_row_rect(BKNode *n, int row, int r[4])
+{
+ r[0] = n->x + rv_pad();
+ r[1] = rv_row_y(n, row);
+ r[2] = n->w - 2 * rv_pad() - rv_bar_w(n);
+ r[3] = u();
+}
+
+/* Toggle columns are configured through the "icons" strings property:
+ * pairs of (off, on) icon names, e.g. HIDE_OFF, HIDE_ON. */
+int bk_tree_columns_from_icons(BKNode *n)
+{
+ TreeData *t = TREE(n);
+ t->ncolumns = BK_MIN(4, n->item_icons_s.n / 2);
+ for (int i = 0; i < t->ncolumns * 2; i++) {
+ t->columns[i] = n->item_icons[i];
+ }
+ return t->ncolumns;
+}
+
+/** \} */
+
+static const RowOps *row_ops(const BKNode *n)
+{
+ return n->cls == &bk_cls_tree ? &g_tree_ops : &g_list_ops;
+}
+
+/* -------------------------------------------------------------------- */
+/** \name GridView (preview tiles)
+ * \{ */
+
+typedef struct GridData {
+ float (*colors)[4]; /* per tile preview color (alpha 0 = icon) */
+ int ncolors;
+} GridData;
+
+static int tile_px(const BKNode *n)
+{
+ return bk_iround((n->tile > 0 ? n->tile : 4.0f) * u());
+}
+
+static int grid_cols(const BKNode *n)
+{
+ return BK_MAX(1, (n->w - bk_pad()) / (tile_px(n) + bk_pad()));
+}
+
+static BKRect grid_tile(const BKNode *n, int i)
+{
+ const int t = tile_px(n), p = bk_pad(), cols = grid_cols(n);
+ const float gap = (n->w - cols * t) / (float)(cols + 1);
+ const int r = i / cols, c = i % cols;
+ return bk_rect(bk_iround(n->x + gap + c * (t + gap)), n->y + p + (r - n->scroll) * (t + p), t,
+ t);
+}
+
+static int grid_index_at(const BKNode *n, int x, int y)
+{
+ for (int i = 0; i < n->items.n; i++) {
+ BKRect r = grid_tile(n, i);
+ if (x >= r.xmin && x < r.xmax && y >= r.ymin && y < r.ymax) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+static int grid_visible_rows(const BKNode *n)
+{
+ return BK_MAX(1, n->h / (tile_px(n) + bk_pad()));
+}
+
+static int grid_row_count(const BKNode *n)
+{
+ return (n->items.n + grid_cols(n) - 1) / grid_cols(n);
+}
+
+static void gridview_init(BKNode *n)
+{
+ n->ext = calloc(1, sizeof(GridData));
+ n->tile = 4.0f;
+ n->height_units = 2.0f; /* rows */
+ n->flags |= NF_HAS_MIN | NF_INTEGER;
+}
+
+static void gridview_free(BKNode *n)
+{
+ GridData *g = (GridData *)n->ext;
+ free(g->colors);
+ free(g);
+}
+
+void BK_gridview_set_colors(BKNode *n, const float (*colors)[4], int count)
+{
+ GridData *g = (GridData *)n->ext;
+ free(g->colors);
+ g->colors = (float(*)[4])calloc((size_t)BK_MAX(1, count), sizeof(float[4]));
+ memcpy(g->colors, colors, sizeof(float[4]) * (size_t)count);
+ g->ncolors = count;
+ bk_invalidate(n);
+}
+
+static void gridview_measure(BKNode *n, int *rw, int *rh)
+{
+ const int t = tile_px(n), p = bk_pad();
+ *rw = t * 2 + 3 * p;
+ *rh = (int)(n->height_units * (t + p) + p);
+}
+
+static int gridview_move(BKNode *n, BKEvent *e)
+{
+ const int hot = grid_index_at(n, e->x, e->y);
+ if (hot != n->hot) {
+ n->hot = hot;
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int gridview_press(BKNode *n, BKEvent *e)
+{
+ const int i = grid_index_at(n, e->x, e->y);
+ if (i >= 0) {
+ bk_set_value(n, i);
+ }
+ return 1;
+}
+
+static void gridview_activate(BKNode *n)
+{
+ bk_emit(n, BK_EV_ACTIVATE, NULL, n->value, 0);
+}
+
+static int gridview_dbl(BKNode *n, BKEvent *e)
+{
+ const int i = grid_index_at(n, e->x, e->y);
+ if (i >= 0) {
+ bk_set_value(n, i);
+ gridview_activate(n);
+ }
+ return 1;
+}
+
+static int gridview_wheel(BKNode *n, BKEvent *e)
+{
+ if (EV_CTRL(e)) {
+ bk_set_value(n, BK_CLAMP((int)n->value - (e->delta > 0 ? 1 : -1), 0, n->items.n - 1));
+ return 1;
+ }
+ const int ns = BK_CLAMP(n->scroll - e->delta, 0, BK_MAX(0, grid_row_count(n) - grid_visible_rows(n)));
+ if (ns != n->scroll) {
+ n->scroll = ns;
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int gridview_key(BKNode *n, BKEvent *e)
+{
+ int move = 0;
+ if (bk_keysym_is(e->keysym, "Left")) {
+ move = -1;
+ }
+ else if (bk_keysym_is(e->keysym, "Right")) {
+ move = 1;
+ }
+ else if (bk_keysym_is(e->keysym, "Up")) {
+ move = -grid_cols(n);
+ }
+ else if (bk_keysym_is(e->keysym, "Down")) {
+ move = grid_cols(n);
+ }
+ if (move && n->items.n) {
+ bk_set_value(n, BK_CLAMP((int)n->value + move, 0, n->items.n - 1));
+ const int r = (int)n->value / grid_cols(n), vis = grid_visible_rows(n);
+ n->scroll = BK_MIN(BK_MAX(n->scroll, r - vis + 1), r);
+ return 1;
+ }
+ return bk_value_key(n, e);
+}
+
+static void gridview_draw(BKNode *n)
+{
+ GridData *g = (GridData *)n->ext;
+ BKRect r = bk_node_rect(n);
+ BKWCol box = bk_theme.box;
+ bk_widget_box(&box, &r, n->corners, NULL);
+ bk_clip_push(n->x + 1, n->y + 1, n->w - 2, n->h - 2);
+ const float uu = (float)u();
+ for (int i = 0; i < n->items.n; i++) {
+ BKRect t = grid_tile(n, i);
+ if (t.ymax < n->y || t.ymin > n->y + n->h) {
+ continue;
+ }
+ const bool sel = i == (int)n->value, hot = i == n->hot && bk_hovered(n);
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.list_item, sel ? ST_SELECT : 0);
+ if (!sel) {
+ /* preview tiles keep a subtle background (BUT_ICON_PREVIEW) */
+ memcpy(w.inner, bk_theme.text, 3);
+ w.inner[3] = hot ? 28 : 11;
+ }
+ BKRect tr = t;
+ bk_widget_list_itembut(&w, &tr, 0);
+ const float pad = 0.35f * uu;
+ const float pw = bk_rw(&t) - 2 * pad, ph = bk_rh(&t) - 2 * pad - uu;
+ if (i < g->ncolors && g->colors[i][3] > 0) {
+ bk_roundbox(t.xmin + pad, t.ymin + pad, pw, ph, 0.2f * uu, CNR_ALL, g->colors[i]);
+ }
+ else {
+ const int icon = (n->item_icons && i < n->item_icons_s.n) ? n->item_icons[i] : 0;
+ bk_icon(icon, t.xmin + bk_rw(&t) * 0.5f, t.ymin + pad + ph * 0.5f, NULL, 1.0f,
+ BK_MIN(pw, ph) * 0.6f);
+ }
+ BKRect lr = bk_rect(t.xmin, t.ymax - (int)(1.15f * uu), bk_rw(&t), (int)uu);
+ bk_text_in(&lr, n->items.v[i], sel ? bk_theme.list_item.text_sel : bk_theme.list_item.text,
+ BK_ALIGN_CENTER, false);
+ }
+ bk_clip_pop();
+}
+
+static int gridview_to_text(BKNode *n, char *buf, int size)
+{
+ snprintf(buf, (size_t)size, "%s",
+ ((int)n->value >= 0 && (int)n->value < n->items.n) ? n->items.v[(int)n->value] : "");
+ return 1;
+}
+
+static void gridview_step(BKNode *n, int dir)
+{
+ bk_set_value(n, BK_CLAMP((int)n->value - dir, 0, BK_MAX(0, n->items.n - 1)));
+}
+
+const BKClass bk_cls_gridview = {.name = "gridview",
+ .flags = CLS_INTERACTIVE | CLS_VALUE,
+ .init = gridview_init,
+ .free_ext = gridview_free,
+ .measure = gridview_measure,
+ .draw = gridview_draw,
+ .press = gridview_press,
+ .dbl = gridview_dbl,
+ .move = gridview_move,
+ .leave = rv_leave,
+ .key = gridview_key,
+ .wheel = gridview_wheel,
+ .to_text = gridview_to_text,
+ .step = gridview_step,
+ .activate = gridview_activate};
+
+/** \} */
diff --git a/kit/intern/kit_widgets.c b/kit/intern/kit_widgets.c
new file mode 100644
index 0000000..01c4e9c
--- /dev/null
+++ b/kit/intern/kit_widgets.c
@@ -0,0 +1,2844 @@
+/* Layouts and leaf widgets.
+ *
+ * Layout follows Blender's uiLayout: columns/rows with buttonspace gaps,
+ * aligned blocks share edges (corners squared, no gaps, emboss only on the
+ * last), property splits, boxes and panels (header + body, sub-panels).
+ * Widgets draw with the ported interface_widgets.cc functions and follow
+ * interface_handlers.cc behavior: number drag/click/type, toggles with
+ * drag-toggle, text editing, enum menus.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <ctype.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "kit_intern.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Shared helpers
+ * \{ */
+
+static int u(void)
+{
+ return bk_unit();
+}
+
+/* Blender's uiStyle: buttonspacex/y, boxspace, panel margins. */
+static int space_y(void)
+{
+ return BK_MAX(1, bk_iround(2.0f * bk_scale_fac));
+}
+static int space_x(void)
+{
+ return bk_iround(0.2f * u());
+}
+
+static int state_of(const BKNode *n)
+{
+ int st = 0;
+ if (!NODE_ENABLED(n)) {
+ st |= ST_DISABLED;
+ }
+ else if (bk_hovered(n)) {
+ st |= ST_HOVER;
+ }
+ if (!(n->flags & NF_EMBOSS)) {
+ st |= ST_NO_EMBOSS;
+ }
+ if (n->flags & NF_SELECTED) {
+ st = (st & ~ST_HOVER) | ST_SELECT; /* part of a multi-drag */
+ }
+ /* aligned column: only the bottom button draws the emboss */
+ if (n->parent && (n->parent->flags & NF_ALIGN) && !(n->corners & (CNR_BL | CNR_BR)) &&
+ (n->parent->cls == &bk_cls_column))
+ {
+ st |= ST_ALIGN_DOWN;
+ }
+ return st;
+}
+
+static void format_number(const BKNode *n, double v, char *buf, int size)
+{
+ if (n->flags & NF_INTEGER) {
+ snprintf(buf, (size_t)size, "%d", (int)floor(v + 0.5));
+ }
+ else {
+ snprintf(buf, (size_t)size, "%.*f", n->precision, v);
+ }
+}
+
+static void number_text(const BKNode *n, char *buf, int size)
+{
+ format_number(n, n->value, buf, size);
+ if (n->suffix) {
+ strncat(buf, n->suffix, (size_t)(size - (int)strlen(buf) - 1));
+ }
+}
+
+static const char *item_text(const BKNode *n, int i)
+{
+ return (i >= 0 && i < n->items.n) ? n->items.v[i] : "";
+}
+
+static int item_icon(const BKNode *n, int i)
+{
+ return (n->item_icons && i >= 0 && i < n->item_icons_s.n) ? n->item_icons[i] : 0;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Column / Row / Grid / Box
+ * \{ */
+
+static int stack_gap(const BKNode *n, bool row)
+{
+ if (n->flags & NF_ALIGN) {
+ return 0;
+ }
+ if (n->spacing >= 0) {
+ return n->spacing;
+ }
+ return row ? space_x() : space_y();
+}
+
+static int join_corners(const BKNode *n, int i, int count, int first, int last)
+{
+ if (!(n->flags & NF_ALIGN) || count == 1) {
+ return n->corners;
+ }
+ int c = 0;
+ if (i == 0) {
+ c |= first;
+ }
+ if (i == count - 1) {
+ c |= last;
+ }
+ return c & n->corners;
+}
+
+static void column_measure(BKNode *n, int *rw, int *rh)
+{
+ const int gap = stack_gap(n, false), p = n->padding;
+ int w = 0, h = 0, count = 0;
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!NODE_VISIBLE(c)) {
+ continue;
+ }
+ int cw, ch;
+ bk_natural(c, &cw, &ch);
+ w = BK_MAX(w, cw);
+ h += ch + (count ? gap : 0);
+ count++;
+ }
+ *rw = w + 2 * p;
+ *rh = h + 2 * p;
+}
+
+static void column_arrange(BKNode *n)
+{
+ const int gap = stack_gap(n, false), p = n->padding;
+ int count = 0;
+ for (int i = 0; i < n->nkids; i++) {
+ count += NODE_VISIBLE(n->kids[i]);
+ }
+ int y = n->y + p, k = 0;
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!NODE_VISIBLE(c)) {
+ continue;
+ }
+ c->corners = join_corners(n, k, count, CNR_TL | CNR_TR, CNR_BL | CNR_BR);
+ int cw, ch;
+ bk_natural(c, &cw, &ch);
+ bk_arrange(c, n->x + p, y, n->w - 2 * p, ch);
+ y += ch + gap;
+ k++;
+ }
+}
+
+static int vector_key(BKNode *n, BKEvent *e)
+{
+ /* Ctrl+Alt+C / Ctrl+Alt+V over a vector copies/pastes all components. */
+ if (!(n->flags & NF_VECTOR) || !(EV_CTRL(e) && EV_ALT(e))) {
+ return 0;
+ }
+ BKContext *ctx = bk_ctx(n);
+ if (bk_keysym_is(e->keysym, "c")) {
+ char buf[512] = "[", num[64];
+ for (int i = 0; i < n->nkids; i++) {
+ format_number(n->kids[i], n->kids[i]->value, num, sizeof(num));
+ strcat(buf, num);
+ strcat(buf, i + 1 < n->nkids ? ", " : "]");
+ }
+ bk_clipboard_set(ctx, buf);
+ return 1;
+ }
+ if (bk_keysym_is(e->keysym, "v")) {
+ char *s = bk_clipboard_get(ctx);
+ if (!s) {
+ return 1;
+ }
+ double vals[16];
+ int count = 0;
+ char *tok = s;
+ while (*tok && count < 16) {
+ while (*tok && (*tok == '[' || *tok == '(' || *tok == ' ' || *tok == ',')) {
+ tok++;
+ }
+ if (!*tok || *tok == ']' || *tok == ')') {
+ break;
+ }
+ char *end;
+ vals[count] = strtod(tok, &end);
+ if (end == tok) {
+ count = -1;
+ break;
+ }
+ count++;
+ tok = end;
+ }
+ if (count == n->nkids) {
+ for (int i = 0; i < count; i++) {
+ bk_set_value(n->kids[i], vals[i]);
+ }
+ }
+ free(s);
+ return 1;
+ }
+ return 0;
+}
+
+const BKClass bk_cls_column = {
+ .name = "column", .measure = column_measure, .arrange = column_arrange, .key = vector_key};
+
+static void row_measure(BKNode *n, int *rw, int *rh)
+{
+ const int gap = stack_gap(n, true), p = n->padding;
+ int w = 0, h = 0, count = 0;
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!NODE_VISIBLE(c)) {
+ continue;
+ }
+ int cw, ch;
+ bk_natural(c, &cw, &ch);
+ w += cw + (count ? gap : 0);
+ h = BK_MAX(h, ch);
+ count++;
+ }
+ *rw = w + 2 * p;
+ *rh = h + 2 * p;
+}
+
+static void row_arrange(BKNode *n)
+{
+ const int gap = stack_gap(n, true), p = n->padding;
+ int count = 0, fixed = 0;
+ float total = 0.0f;
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!NODE_VISIBLE(c)) {
+ continue;
+ }
+ count++;
+ if (c->weight <= 0.0f) { /* weight 0: natural width (icon buttons) */
+ int cw, ch;
+ bk_natural(c, &cw, &ch);
+ fixed += cw;
+ }
+ else {
+ total += c->weight;
+ }
+ }
+ if (!count) {
+ return;
+ }
+ const float avail = BK_MAX(0.0f, (float)(n->w - 2 * p - gap * (count - 1) - fixed));
+ if (total <= 0.0f) {
+ total = 1.0f;
+ }
+ float x = (float)(n->x + p);
+ int k = 0;
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!NODE_VISIBLE(c)) {
+ continue;
+ }
+ c->corners = join_corners(n, k, count, CNR_TL | CNR_BL, CNR_TR | CNR_BR);
+ float cw;
+ if (c->weight <= 0.0f) {
+ int nw, nh;
+ bk_natural(c, &nw, &nh);
+ cw = (float)nw;
+ }
+ else {
+ cw = avail * c->weight / total;
+ }
+ const int x0 = bk_iround(x), x1 = bk_iround(x + cw);
+ bk_arrange(c, x0, n->y + p, x1 - x0, n->h - 2 * p);
+ x += cw + gap;
+ k++;
+ }
+}
+
+const BKClass bk_cls_row = {.name = "row", .measure = row_measure, .arrange = row_arrange};
+
+static void grid_measure(BKNode *n, int *rw, int *rh)
+{
+ const int cols = BK_MAX(1, n->columns), gap = (n->flags & NF_ALIGN) ? 0 : space_x();
+ int cw = 0, h = 0, rowh = 0, k = 0, rows = 0;
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!NODE_VISIBLE(c)) {
+ continue;
+ }
+ int w, hh;
+ bk_natural(c, &w, &hh);
+ cw = BK_MAX(cw, w);
+ rowh = BK_MAX(rowh, hh);
+ if (++k % cols == 0) {
+ h += rowh;
+ rowh = 0;
+ rows++;
+ }
+ }
+ if (k % cols) {
+ h += rowh;
+ rows++;
+ }
+ *rw = cw * cols + gap * (cols - 1);
+ *rh = h + space_y() * BK_MAX(0, rows - 1);
+}
+
+static void grid_arrange(BKNode *n)
+{
+ const int cols = BK_MAX(1, n->columns), gap = (n->flags & NF_ALIGN) ? 0 : space_x();
+ const float cw = (n->w - gap * (cols - 1)) / (float)cols;
+ int y = n->y, k = 0, rowh = 0;
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (!NODE_VISIBLE(c)) {
+ continue;
+ }
+ int w, h;
+ bk_natural(c, &w, &h);
+ const int col = k % cols;
+ const int x0 = bk_iround(n->x + col * (cw + gap)), x1 = bk_iround(n->x + col * (cw + gap) + cw);
+ bk_arrange(c, x0, y, x1 - x0, h);
+ rowh = BK_MAX(rowh, h);
+ if (col == cols - 1) {
+ y += rowh + space_y();
+ rowh = 0;
+ }
+ k++;
+ }
+}
+
+static void grid_init(BKNode *n)
+{
+ n->columns = 2;
+}
+
+const BKClass bk_cls_grid = {
+ .name = "grid", .init = grid_init, .measure = grid_measure, .arrange = grid_arrange};
+
+static void box_init(BKNode *n)
+{
+ n->padding = bk_iround(0.3f * u());
+}
+
+static void box_draw(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ BKWCol w = bk_theme.box;
+ bk_widget_box(&w, &r, n->corners, NULL);
+}
+
+const BKClass bk_cls_box = {.name = "box",
+ .init = box_init,
+ .measure = column_measure,
+ .arrange = column_arrange,
+ .draw = box_draw};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Panel (header + collapsible body, sub-panels, drag-collapse, reorder)
+ * \{ */
+
+#define PANEL_BODY(n) ((BKNode *)(n)->ext)
+
+static void panel_init(BKNode *n)
+{
+ BKNode *body = bk_node_new_cls(&bk_cls_column);
+ body->padding = bk_iround(0.4f * u());
+ n->ext = body;
+ BK_node_add(n, body, -1);
+ n->value = 1; /* open */
+}
+
+static bool panel_is_sub(const BKNode *n)
+{
+ const BKNode *p = n->parent;
+ return p && p->parent && p->parent->cls == &bk_cls_panel && PANEL_BODY(p->parent) == p;
+}
+
+static int panel_header_h(const BKNode *n)
+{
+ /* PNL_HEADER = UI_UNIT_Y * 1.25 */
+ return bk_iround((panel_is_sub(n) ? 1.1f : 1.25f) * u());
+}
+
+static int panel_grip_w(const BKNode *n)
+{
+ return panel_is_sub(n) ? 0 : u();
+}
+
+static void panel_measure(BKNode *n, int *rw, int *rh)
+{
+ int bw = 0, bh = 0;
+ bk_natural(PANEL_BODY(n), &bw, &bh);
+ int hw = (int)bk_text_width(n->text, -1, false) + 3 * u();
+ for (int i = 0; i < n->nkids; i++) {
+ if (n->kids[i] != PANEL_BODY(n)) {
+ int w, h;
+ bk_natural(n->kids[i], &w, &h);
+ hw += w;
+ }
+ }
+ *rw = BK_MAX(bw, hw);
+ float open = (n->flags & NF_COLLAPSED) ? 0.0f : 1.0f;
+ if (bk_anim_running(n)) {
+ const float t = n->anim; /* smoothstep, like Blender's panel animation */
+ open = t * t * (3.0f - 2.0f * t);
+ }
+ *rh = panel_header_h(n) + (int)(bh * open + 0.5f);
+}
+
+static float panel_title_x(BKNode *n)
+{
+ float x = n->x + 1.1f * u();
+ for (int i = 0; i < n->nkids; i++) {
+ if (n->kids[i] != PANEL_BODY(n)) {
+ int w, h;
+ bk_natural(n->kids[i], &w, &h);
+ x += w + 0.2f * u();
+ }
+ }
+ return x;
+}
+
+static void panel_arrange(BKNode *n)
+{
+ const int hh = panel_header_h(n);
+ float hx = n->x + 1.1f * u();
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (c == PANEL_BODY(n)) {
+ continue;
+ }
+ int w, h;
+ bk_natural(c, &w, &h);
+ bk_arrange(c, (int)hx, n->y + (hh - u()) / 2, w, u());
+ hx += w + 0.2f * u();
+ }
+ BKNode *body = PANEL_BODY(n);
+ if ((n->flags & NF_COLLAPSED) && !bk_anim_running(n)) {
+ body->flags &= ~NF_VISIBLE;
+ }
+ else {
+ body->flags |= NF_VISIBLE;
+ }
+ int bw, bh;
+ bk_natural(body, &bw, &bh);
+ bk_arrange(body, n->x, n->y + hh, n->w, bh); /* clipped while animating */
+ n->value = !(n->flags & NF_COLLAPSED);
+}
+
+static BKNode *panel_hit(BKNode *n, int x, int y)
+{
+ if (y < n->y + panel_header_h(n)) {
+ for (int i = n->nkids - 1; i >= 0; i--) {
+ if (n->kids[i] != PANEL_BODY(n)) {
+ BKNode *f = bk_hit(n->kids[i], x, y);
+ if (f) {
+ return f;
+ }
+ }
+ }
+ return n;
+ }
+ return bk_hit(PANEL_BODY(n), x, y);
+}
+
+static bool panel_on_grip(const BKNode *n, int x, int y)
+{
+ return panel_grip_w(n) && x >= n->x + n->w - panel_grip_w(n) && y < n->y + panel_header_h(n);
+}
+
+static int panel_cursor_at(BKNode *n, int x, int y)
+{
+ return panel_on_grip(n, x, y) ? BK_CURSOR_MOVE : BK_CURSOR_DEFAULT;
+}
+
+static void panel_set_open(BKNode *n, bool open)
+{
+ if (open == !(n->flags & NF_COLLAPSED)) {
+ return;
+ }
+ if (!bk_anim_running(n)) {
+ n->anim = open ? 0.0f : 1.0f; /* animate from the current state */
+ }
+ if (open) {
+ n->flags &= ~NF_COLLAPSED;
+ }
+ else {
+ n->flags |= NF_COLLAPSED;
+ }
+ n->value = open;
+ bk_anim_start(n);
+ bk_relayout(n);
+ bk_emit(n, BK_EV_CHANGE, NULL, open, 0);
+}
+
+static int panel_press(BKNode *n, BKEvent *e)
+{
+ n->dragmode = panel_on_grip(n, e->x, e->y) ? 1 : 0;
+ if (n->dragmode) {
+ return 1;
+ }
+ if (EV_CTRL(e) && n->parent) { /* Ctrl+click: collapse all others */
+ for (int i = 0; i < n->parent->nkids; i++) {
+ BKNode *s = n->parent->kids[i];
+ if (s->cls == &bk_cls_panel) {
+ panel_set_open(s, s == n);
+ }
+ }
+ return 1;
+ }
+ panel_set_open(n, n->flags & NF_COLLAPSED);
+ bk_start_drag_toggle(bk_ctx(n), DRAG_GROUP_PANEL, (int)n->value);
+ return 1;
+}
+
+static int panel_drag(BKNode *n, BKEvent *e)
+{
+ BKNode *p = n->parent;
+ if (n->dragmode != 1 || !p) {
+ return 0;
+ }
+ /* reorder among sibling panels by pointer position */
+ int self = -1, last_panel = -1, before = -1;
+ for (int i = 0; i < p->nkids; i++) {
+ BKNode *s = p->kids[i];
+ if (s == n) {
+ self = i;
+ continue;
+ }
+ if (s->cls != &bk_cls_panel) {
+ continue;
+ }
+ last_panel = i;
+ if (before < 0 && e->y < s->y + s->h / 2) {
+ before = i;
+ }
+ }
+ if (self < 0 || last_panel < 0) {
+ return 0;
+ }
+ int target = before >= 0 ? before : last_panel + 1;
+ if (target > self) {
+ target--;
+ }
+ if (target == self) {
+ return 0;
+ }
+ memmove(p->kids + self, p->kids + self + 1, sizeof(BKNode *) * (size_t)(p->nkids - self - 1));
+ memmove(p->kids + target + 1, p->kids + target,
+ sizeof(BKNode *) * (size_t)(p->nkids - 1 - target));
+ p->kids[target] = n;
+ bk_relayout(n);
+ return 1;
+}
+
+static int panel_release(BKNode *n, BKEvent *e)
+{
+ n->dragmode = 0;
+ return 1;
+}
+
+static int panel_key(BKNode *n, BKEvent *e)
+{
+ if (bk_keysym_is(e->keysym, "Return") || bk_keysym_is(e->keysym, "KP_Enter") ||
+ bk_keysym_is(e->keysym, "space") || (bk_keysym_is(e->keysym, "a") && !EV_CTRL(e)))
+ {
+ panel_set_open(n, n->flags & NF_COLLAPSED); /* Blender: A over a header toggles it */
+ return 1;
+ }
+ return 0;
+}
+
+static void panel_draw(BKNode *n)
+{
+ const int hh = panel_header_h(n);
+ const float uu = (float)u();
+ float c[4];
+ if (panel_is_sub(n)) {
+ float line[4];
+ bk_rgba(bk_theme.panel_outline, line);
+ line[3] = BK_MAX(line[3], 0.15f);
+ bk_fill_f(n->x, n->y, n->w, 1, line);
+ if (!(n->flags & NF_COLLAPSED)) {
+ bk_fill(n->x, n->y + hh, n->w, n->h - hh, bk_theme.panel_sub_back);
+ }
+ if (bk_hovered(n)) {
+ const float hl[4] = {1, 1, 1, 0.04f};
+ bk_fill_f(n->x, n->y + 1, n->w, hh - 1, hl);
+ }
+ }
+ else {
+ const float rad = bk_theme.panel_roundness * 0.5f * uu;
+ bk_rgba(bk_theme.panel_back, c);
+ bk_roundbox(n->x, n->y, n->w, n->h, rad, CNR_ALL, c);
+ bk_rgba(bk_theme.panel_header, c);
+ if (bk_hovered(n)) {
+ for (int k = 0; k < 3; k++) {
+ c[k] = BK_MIN(1.0f, c[k] + 0.03f);
+ }
+ }
+ bk_roundbox(n->x, n->y, n->w, hh, rad, (n->flags & NF_COLLAPSED) ? CNR_ALL : (CNR_TL | CNR_TR),
+ c);
+ bk_rgba(bk_theme.panel_outline, c);
+ BuiWidgetBase wb = {{(float)n->x, (float)n->y, (float)n->w, (float)n->h}, rad, rad - 1, CNR_ALL};
+ memcpy(wb.outline, c, sizeof(c));
+ wb.pixelsize = 1.0f;
+ BUI_raster_widget_base(bk_draw.r, &wb);
+ const uchar grip[4] = {255, 255, 255, 64};
+ bk_icon(bk_icons_lookup("GRIP"), n->x + n->w - panel_grip_w(n) * 0.5f, n->y + hh * 0.5f,
+ grip, 1.0f, 0.6f * uu);
+ }
+ bk_rgba_alpha(bk_theme.text, 0.8f, c);
+ bk_tria(n->x + 0.6f * uu, n->y + hh * 0.5f, (n->flags & NF_COLLAPSED) ? 'h' : 'v', c, 0);
+ float tx = panel_title_x(n);
+ if (n->icon) {
+ bk_icon(n->icon, tx + bk_icon_size() * 0.5f, n->y + hh * 0.5f, NULL, 1.0f, 0);
+ tx += bk_icon_size() + 0.25f * uu;
+ }
+ BKRect tr = {(int)tx - bk_pad(), n->y, n->x + n->w - panel_grip_w(n), n->y + hh};
+ bk_text_in(&tr, n->text, bk_theme.text, BK_ALIGN_LEFT, false);
+}
+
+static void panel_draw_tree(BKNode *n)
+{
+ if (!NODE_VISIBLE(n)) {
+ return;
+ }
+ BKRect r = bk_rect(n->x - 3, n->y - 3, n->w + 6, n->h + 6);
+ if (!bk_clip_visible(&r)) {
+ return;
+ }
+ panel_draw(n);
+ bk_clip_push(n->x, n->y, n->w, n->h); /* the body slides under the panel edge */
+ for (int i = 0; i < n->nkids; i++) {
+ bk_draw_tree(n->kids[i]);
+ }
+ bk_clip_pop();
+}
+
+const BKClass bk_cls_panel = {.name = "panel",
+ .draw_tree = panel_draw_tree,
+ .flags = CLS_INTERACTIVE,
+ .drag_group = DRAG_GROUP_PANEL,
+ .init = panel_init,
+ .measure = panel_measure,
+ .arrange = panel_arrange,
+ .draw = panel_draw,
+ .hit = panel_hit,
+ .press = panel_press,
+ .drag = panel_drag,
+ .release = panel_release,
+ .key = panel_key,
+ .cursor_at = panel_cursor_at};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Tabs (top) and SideTabs (properties editor navigation bar)
+ * \{ */
+
+static BKNode *current_page(const BKNode *n)
+{
+ return (n->current >= 0 && n->current < n->nkids) ? n->kids[n->current] : NULL;
+}
+
+static void tabs_select(BKNode *n, int i)
+{
+ if (i >= 0 && i < n->nkids && i != n->current) {
+ n->current = i;
+ bk_relayout(n);
+ bk_emit(n, BK_EV_CHANGE, NULL, i, 0);
+ }
+}
+
+static int tab_h(void)
+{
+ return bk_iround(1.25f * u());
+}
+
+static void tab_geom(BKNode *n, int i, int *x, int *w)
+{
+ int xx = n->x;
+ for (int k = 0; k < n->items.n; k++) {
+ const int tw = (int)bk_text_width(n->items.v[k], -1, false) + 2 * u();
+ if (k == i) {
+ *x = xx;
+ *w = tw;
+ return;
+ }
+ xx += tw + 2;
+ }
+ *x = xx;
+ *w = 0;
+}
+
+static void tabs_measure(BKNode *n, int *rw, int *rh)
+{
+ int pw = 0, ph = 0, tabs_w = 0;
+ for (int i = 0; i < n->nkids; i++) { /* the largest page: switching tabs keeps the size */
+ int w, h;
+ bk_natural(n->kids[i], &w, &h);
+ pw = BK_MAX(pw, w);
+ ph = BK_MAX(ph, h);
+ }
+ for (int k = 0; k < n->items.n; k++) {
+ tabs_w += (int)bk_text_width(n->items.v[k], -1, false) + 2 * u() + 2;
+ }
+ *rw = BK_MAX(tabs_w, pw);
+ *rh = tab_h() + ph;
+}
+
+static void tabs_arrange(BKNode *n)
+{
+ const int th = tab_h();
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (i == n->current) {
+ c->flags |= NF_VISIBLE;
+ bk_arrange(c, n->x, n->y + th, n->w, BK_MAX(0, n->h - th));
+ }
+ else {
+ c->flags &= ~NF_VISIBLE;
+ }
+ }
+}
+
+static int tabs_tab_at(BKNode *n, int x, int y)
+{
+ if (y >= n->y + tab_h()) {
+ return -1;
+ }
+ for (int i = 0; i < n->items.n; i++) {
+ int tx, tw;
+ tab_geom(n, i, &tx, &tw);
+ if (x >= tx && x < tx + tw) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+static BKNode *tabs_hit(BKNode *n, int x, int y)
+{
+ if (y < n->y + tab_h()) {
+ return n;
+ }
+ BKNode *page = current_page(n);
+ return page ? bk_hit(page, x, y) : NULL;
+}
+
+static int tabs_press(BKNode *n, BKEvent *e)
+{
+ tabs_select(n, tabs_tab_at(n, e->x, e->y));
+ return 1;
+}
+
+static int tabs_move(BKNode *n, BKEvent *e)
+{
+ const int hot = tabs_tab_at(n, e->x, e->y);
+ if (hot != n->hot) {
+ n->hot = hot;
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int tabs_leave(BKNode *n)
+{
+ n->hot = -1;
+ return 1;
+}
+
+static int tabs_wheel(BKNode *n, BKEvent *e)
+{
+ if (EV_CTRL(e)) {
+ tabs_select(n, n->current - (e->delta > 0 ? 1 : -1));
+ return 1;
+ }
+ return 0;
+}
+
+static void tabs_draw(BKNode *n)
+{
+ const int th = tab_h();
+ const float rad = bk_widget_radius(&bk_theme.tab);
+ float c[4];
+ for (int i = 0; i < n->items.n; i++) {
+ int tx, tw;
+ tab_geom(n, i, &tx, &tw);
+ const bool active = i == n->current;
+ if (active) {
+ bk_rgba(bk_theme.panel_back, c);
+ }
+ else {
+ BKWCol w = bk_theme.tab;
+ if (i == n->hot) {
+ bk_widget_active_color(&w);
+ }
+ bk_rgba(w.inner, c);
+ }
+ bk_roundbox(tx, n->y + 2, tw, th - 2 + (active ? 2 : 0), rad, CNR_TL | CNR_TR, c);
+ BKRect tr = bk_rect(tx, n->y + 2, tw, th - 2);
+ bk_text_in(&tr, n->items.v[i], active ? bk_theme.tab.text_sel : bk_theme.tab.text,
+ BK_ALIGN_CENTER, false);
+ }
+ bk_rgba(bk_theme.panel_back, c);
+ bk_roundbox(n->x, n->y + th, n->w, n->h - th, rad, CNR_ALL & ~CNR_TL, c);
+}
+
+const BKClass bk_cls_tabs = {.name = "tabs",
+ .flags = CLS_INTERACTIVE,
+ .measure = tabs_measure,
+ .arrange = tabs_arrange,
+ .draw = tabs_draw,
+ .hit = tabs_hit,
+ .press = tabs_press,
+ .move = tabs_move,
+ .leave = tabs_leave,
+ .wheel = tabs_wheel};
+
+static int side_bar_w(void)
+{
+ return bk_iround(1.6f * u());
+}
+static int side_tab_h(void)
+{
+ return bk_iround(1.4f * u());
+}
+
+static void sidetabs_measure(BKNode *n, int *rw, int *rh)
+{
+ BKNode *page = current_page(n);
+ int pw = 0, ph = 0;
+ if (page) {
+ bk_natural(page, &pw, &ph);
+ }
+ *rw = side_bar_w() + pw;
+ *rh = BK_MAX(ph, n->nkids * side_tab_h() + bk_pad());
+}
+
+static void sidetabs_arrange(BKNode *n)
+{
+ const int bw = side_bar_w();
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ if (i == n->current) {
+ c->flags |= NF_VISIBLE;
+ bk_arrange(c, n->x + bw, n->y, n->w - bw, n->h);
+ }
+ else {
+ c->flags &= ~NF_VISIBLE;
+ }
+ }
+}
+
+static int sidetabs_tab_at(BKNode *n, int x, int y)
+{
+ if (x >= n->x + side_bar_w()) {
+ return -1;
+ }
+ const int i = (y - n->y - bk_pad()) / side_tab_h();
+ return (y >= n->y + bk_pad() && i >= 0 && i < n->nkids) ? i : -1;
+}
+
+static BKNode *sidetabs_hit(BKNode *n, int x, int y)
+{
+ if (x < n->x + side_bar_w()) {
+ return n;
+ }
+ BKNode *page = current_page(n);
+ return page ? bk_hit(page, x, y) : NULL;
+}
+
+static int sidetabs_press(BKNode *n, BKEvent *e)
+{
+ tabs_select(n, sidetabs_tab_at(n, e->x, e->y));
+ return 1;
+}
+
+static int sidetabs_move(BKNode *n, BKEvent *e)
+{
+ const int hot = sidetabs_tab_at(n, e->x, e->y);
+ if (hot != n->hot) {
+ n->hot = hot;
+ /* the tooltip shows the hovered tab's name */
+ bk_set_text(&n->desc, hot >= 0 ? item_text(n, hot) : "");
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int sidetabs_wheel(BKNode *n, BKEvent *e)
+{
+ if (EV_CTRL(e) || e->x < n->x + side_bar_w()) {
+ tabs_select(n, n->current - (e->delta > 0 ? 1 : -1));
+ return 1;
+ }
+ return 0;
+}
+
+static void sidetabs_draw(BKNode *n)
+{
+ const int bw = side_bar_w(), th = side_tab_h(), p = bk_pad();
+ const float rad = bk_widget_radius(&bk_theme.tab);
+ float c[4];
+ bk_fill(n->x, n->y, bw, n->h, bk_theme.tabs_bg);
+ for (int i = 0; i < n->nkids; i++) {
+ const int ty = n->y + p + i * th;
+ const bool active = i == n->current, hot = i == n->hot;
+ if (active) {
+ bk_rgba(bk_theme.region_bg, c);
+ bk_roundbox(n->x + 3, ty + 1, bw - 3, th - 2, rad, CNR_TL | CNR_BL, c);
+ }
+ else if (hot) {
+ const float hl[4] = {1, 1, 1, 0.08f};
+ bk_roundbox(n->x + 3, ty + 1, bw - 6, th - 2, rad, CNR_ALL, hl);
+ }
+ bk_icon(item_icon(n, i), n->x + bw * 0.5f + 1, ty + th * 0.5f, NULL,
+ (active || hot) ? 1.0f : 0.55f, 0);
+ }
+}
+
+const BKClass bk_cls_sidetabs = {.name = "sidetabs",
+ .flags = CLS_INTERACTIVE,
+ .measure = sidetabs_measure,
+ .arrange = sidetabs_arrange,
+ .draw = sidetabs_draw,
+ .hit = sidetabs_hit,
+ .press = sidetabs_press,
+ .move = sidetabs_move,
+ .leave = tabs_leave,
+ .wheel = sidetabs_wheel};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name ScrollView
+ * \{ */
+
+static int scroll_bar_w(void)
+{
+ return bk_iround(0.35f * u());
+}
+
+static int scroll_content_h(BKNode *n)
+{
+ if (!n->nkids) {
+ return 0;
+ }
+ int w, h;
+ bk_natural(n->kids[0], &w, &h);
+ return h;
+}
+
+static int scroll_max(BKNode *n)
+{
+ return BK_MAX(0, scroll_content_h(n) - n->h);
+}
+
+static void scroll_measure(BKNode *n, int *rw, int *rh)
+{
+ int cw = 0, ch = 0;
+ if (n->nkids) {
+ bk_natural(n->kids[0], &cw, &ch);
+ }
+ *rw = cw + scroll_bar_w();
+ *rh = n->height_units > 0 ? (int)(n->height_units * u()) : n->rows * u();
+}
+
+static void scroll_arrange(BKNode *n)
+{
+ n->scroll = BK_CLAMP(n->scroll, 0, scroll_max(n));
+ if (n->nkids) {
+ bk_arrange(n->kids[0], n->x, n->y - n->scroll, n->w - scroll_bar_w(),
+ BK_MAX(n->h, scroll_content_h(n)));
+ }
+}
+
+static BKNode *scroll_hit(BKNode *n, int x, int y)
+{
+ if (x >= n->x + n->w - scroll_bar_w()) {
+ return n;
+ }
+ return n->nkids ? bk_hit(n->kids[0], x, y) : NULL;
+}
+
+static void scroll_thumb(BKNode *n, float *ty, float *th)
+{
+ const int ch = BK_MAX(1, scroll_content_h(n)), ms = scroll_max(n);
+ *th = BK_MAX((float)u(), n->h * BK_MIN(1.0f, (float)n->h / ch));
+ *ty = n->y + (n->h - *th) * (ms ? (float)n->scroll / ms : 0.0f);
+}
+
+static void scroll_set(BKNode *n, int v)
+{
+ v = BK_CLAMP(v, 0, scroll_max(n));
+ if (v != n->scroll) {
+ n->scroll = v;
+ bk_relayout(n);
+ }
+}
+
+static int scroll_press(BKNode *n, BKEvent *e)
+{
+ float ty, th;
+ scroll_thumb(n, &ty, &th);
+ if (!(e->y >= ty && e->y < ty + th)) { /* click the track: jump */
+ const float frac = (e->y - n->y - th * 0.5f) / BK_MAX(1.0f, n->h - th);
+ scroll_set(n, (int)(BK_CLAMP(frac, 0.0f, 1.0f) * scroll_max(n)));
+ }
+ n->drag_start = n->scroll;
+ return 1;
+}
+
+static int scroll_drag(BKNode *n, BKEvent *e)
+{
+ float ty, th;
+ scroll_thumb(n, &ty, &th);
+ const float span = BK_MAX(1.0f, n->h - th);
+ scroll_set(n, (int)(n->drag_start + e->dy * scroll_max(n) / span));
+ return 1;
+}
+
+static int scroll_wheel(BKNode *n, BKEvent *e)
+{
+ if (EV_CTRL(e)) {
+ return 0;
+ }
+ const int old = n->scroll;
+ scroll_set(n, n->scroll - e->delta * u() * 2);
+ return n->scroll != old;
+}
+
+static void scroll_draw_tree(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ if (!bk_clip_visible(&r)) {
+ return;
+ }
+ bk_clip_push(n->x, n->y, n->w, n->h);
+ if (n->nkids) {
+ bk_draw_tree(n->kids[0]);
+ }
+ bk_clip_pop();
+ if (scroll_max(n) > 0) {
+ float ty, th;
+ scroll_thumb(n, &ty, &th);
+ const int bw = scroll_bar_w();
+ BKWCol w = bk_theme.scroll;
+ BKRect track = bk_rect(n->x + n->w - bw * 3 / 4, n->y, bw / 2, n->h);
+ BKRect slider = bk_rect(track.xmin, (int)ty + 1, bw / 2, (int)th - 2);
+ if (bk_hovered(n)) {
+ bk_widget_active_color(&w);
+ }
+ bk_widget_scroll(&w, &track, &slider, bk_pressed(n));
+ }
+}
+
+const BKClass bk_cls_scroll = {.name = "scroll",
+ .flags = CLS_INTERACTIVE,
+ .measure = scroll_measure,
+ .arrange = scroll_arrange,
+ .draw_tree = scroll_draw_tree,
+ .hit = scroll_hit,
+ .press = scroll_press,
+ .drag = scroll_drag,
+ .wheel = scroll_wheel};
+
+/* -------------------------------------------------------------------- */
+/** \name Scrollbar
+ *
+ * A stand-alone Blender scroller (View2D style, drawn by bk_widget_scroll)
+ * for Tk's Scrollbar: it shows the [first, last] fractions it is given and
+ * asks its client to move with BK_EV_SCROLL (moveto / units), never
+ * scrolling anything itself (Tk's scrollbar protocol).
+ * \{ */
+
+static bool sb_vertical(const BKNode *n)
+{
+ return (n->flags & NF_VERTICAL) != 0;
+}
+
+static void sb_measure(BKNode *n, int *rw, int *rh)
+{
+ const int thick = BK_MAX(8, bk_iround(0.5f * u()));
+ *rw = sb_vertical(n) ? thick : 2 * u();
+ *rh = sb_vertical(n) ? 2 * u() : thick;
+}
+
+/* Track and thumb rects; returns the track length along the axis. */
+static int sb_rects(const BKNode *n, BKRect *track, BKRect *thumb)
+{
+ const bool v = sb_vertical(n);
+ const int thick = v ? n->w : n->h, inset = BK_MAX(1, thick / 5);
+ *track = v ? bk_rect(n->x + inset, n->y + 1, n->w - 2 * inset, n->h - 2) :
+ bk_rect(n->x + 1, n->y + inset, n->w - 2, n->h - 2 * inset);
+ const int len = v ? bk_rh(track) : bk_rw(track);
+ const int min_thumb = BK_MIN(len, bk_iround(0.6f * u()));
+ int a = (int)(n->value * len), b = (int)(n->factor * len);
+ if (b - a < min_thumb) { /* keep a grabbable thumb, centered on the view */
+ const int mid = (a + b) / 2;
+ a = BK_CLAMP(mid - min_thumb / 2, 0, len - min_thumb);
+ b = a + min_thumb;
+ }
+ *thumb = v ? bk_rect(track->xmin, track->ymin + a, bk_rw(track), b - a) :
+ bk_rect(track->xmin + a, track->ymin, b - a, bk_rh(track));
+ return BK_MAX(1, len);
+}
+
+static void sb_moveto(BKNode *n, double first)
+{
+ const double span = n->factor - n->value;
+ bk_emit(n, BK_EV_SCROLL, NULL, 0, BK_CLAMP(first, 0.0, 1.0 - span));
+}
+
+static int sb_press(BKNode *n, BKEvent *e)
+{
+ BKRect track, thumb;
+ const int len = sb_rects(n, &track, &thumb);
+ const int pos = sb_vertical(n) ? e->y : e->x;
+ const int t0 = sb_vertical(n) ? thumb.ymin : thumb.xmin;
+ const int t1 = sb_vertical(n) ? thumb.ymax : thumb.xmax;
+ n->drag_start = n->value;
+ if (pos < t0 || pos >= t1) { /* Blender: the thumb jumps under the pointer */
+ const int base = sb_vertical(n) ? track.ymin : track.xmin;
+ const double span = n->factor - n->value;
+ n->drag_start = BK_CLAMP((double)(pos - base) / len - span * 0.5, 0.0, 1.0 - span);
+ sb_moveto(n, n->drag_start);
+ }
+ return 1;
+}
+
+static int sb_drag(BKNode *n, BKEvent *e)
+{
+ BKRect track, thumb;
+ const int len = sb_rects(n, &track, &thumb);
+ sb_moveto(n, n->drag_start + (double)(sb_vertical(n) ? e->dy : e->dx) / len);
+ return 1;
+}
+
+static int sb_wheel(BKNode *n, BKEvent *e)
+{
+ bk_emit(n, BK_EV_SCROLL, NULL, 1, -e->delta);
+ return 1;
+}
+
+static void sb_draw(BKNode *n)
+{
+ BKRect track, thumb;
+ sb_rects(n, &track, &thumb);
+ BKWCol w = bk_theme.scroll;
+ if (bk_hovered(n) || bk_pressed(n)) {
+ bk_widget_active_color(&w);
+ }
+ const bool full = n->value <= 0.0 && n->factor >= 1.0;
+ BKRect none = bk_rect(0, 0, 0, 0);
+ bk_widget_scroll(&w, &track, full ? &none : &thumb, bk_pressed(n));
+}
+
+static int sb_set_num(BKNode *n, const char *key, double v)
+{
+ if (strcmp(key, "first") == 0 || strcmp(key, "last") == 0) {
+ double *dst = key[0] == 'f' ? &n->value : &n->factor;
+ v = BK_CLAMP(v, 0.0, 1.0);
+ if (*dst != v) {
+ *dst = v;
+ bk_invalidate(n);
+ }
+ return 1;
+ }
+ return 0;
+}
+
+static int sb_get_num(BKNode *n, const char *key, double *r_v)
+{
+ if (strcmp(key, "first") == 0 || strcmp(key, "last") == 0) {
+ *r_v = key[0] == 'f' ? n->value : n->factor;
+ return 1;
+ }
+ return 0;
+}
+
+static void sb_init(BKNode *n)
+{
+ n->flags |= NF_VERTICAL; /* Tk's default orient */
+ n->value = 0.0;
+ n->factor = 1.0;
+}
+
+const BKClass bk_cls_scrollbar = {.name = "scrollbar",
+ .flags = CLS_INTERACTIVE,
+ .init = sb_init,
+ .measure = sb_measure,
+ .draw = sb_draw,
+ .press = sb_press,
+ .drag = sb_drag,
+ .wheel = sb_wheel,
+ .set_num = sb_set_num,
+ .get_num = sb_get_num};
+
+/** \} */
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Label, Separator, Progress
+ * \{ */
+
+static void label_measure(BKNode *n, int *rw, int *rh)
+{
+ const BKImage *img = (const BKImage *)n->image;
+ if (img && !(n->text && n->text[0])) {
+ *rw = img->w;
+ *rh = img->h;
+ return;
+ }
+ const char *s = n->text ? n->text : "";
+ int lines = 1, widest = 0;
+ for (const char *line = s;; lines++) { /* widest line of a multi-line label */
+ const char *end = strchr(line, '\n');
+ const int len = end ? (int)(end - line) : (int)strlen(line);
+ char buf[512];
+ memcpy(buf, line, (size_t)BK_MIN(len, 511));
+ buf[BK_MIN(len, 511)] = 0;
+ widest = BK_MAX(widest, (int)bk_content_width(buf, n->icon, n->flags & NF_BOLD));
+ if (!end) {
+ break;
+ }
+ line = end + 1;
+ }
+ *rw = widest + 2 * bk_pad();
+ *rh = lines > 1 ? BK_MAX(u(), (int)(lines * bk_line_height()) + bk_pad()) : u();
+}
+
+static void label_draw(BKNode *n)
+{
+ uchar c[4];
+ memcpy(c, n->has_color_text ? n->color_text : bk_theme.text, 4);
+ if (!NODE_ENABLED(n)) {
+ c[3] /= 2;
+ }
+ BKRect r = bk_node_rect(n);
+ const BKImage *img = (const BKImage *)n->image;
+ if (img) { /* Tk Label(image=) / QLabel.setPixmap */
+ bk_image_draw(img, r.xmin + (bk_rw(&r) - img->w) / 2, r.ymin + (bk_rh(&r) - img->h) / 2,
+ img->w, img->h, NODE_ENABLED(n) ? 1.0f : 0.5f);
+ if (!(n->text && n->text[0])) {
+ return;
+ }
+ }
+ if (n->icon) {
+ bk_text_icon(&r, n->text, n->icon, c, n->align, NODE_ENABLED(n));
+ }
+ else {
+ bk_text_in(&r, n->text, c, n->align, n->flags & NF_BOLD);
+ }
+}
+
+const BKClass bk_cls_label = {.name = "label", .measure = label_measure, .draw = label_draw};
+
+static void separator_init(BKNode *n)
+{
+ n->factor = 0.5;
+}
+
+static void separator_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = 0;
+ *rh = BK_MAX(1, (int)(n->factor * u()));
+}
+
+static void separator_draw(BKNode *n)
+{
+ if (n->flags & NF_LINE) {
+ float c[4];
+ bk_rgba_alpha(bk_theme.text, 0.15f, c);
+ bk_fill_f(n->x, n->y + n->h / 2, n->w, 1, c);
+ }
+}
+
+const BKClass bk_cls_separator = {.name = "separator",
+ .init = separator_init,
+ .measure = separator_measure,
+ .draw = separator_draw};
+
+static void progress_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = 6 * u();
+ *rh = u();
+}
+
+static void progress_draw(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.progress, NODE_ENABLED(n) ? 0 : ST_DISABLED);
+ bk_widget_progress(&w, &r, n->corners, (float)n->factor);
+ if (n->text) {
+ bk_text_in(&r, n->text, w.text, BK_ALIGN_CENTER, false);
+ }
+}
+
+const BKClass bk_cls_progress = {
+ .name = "progress", .measure = progress_measure, .draw = progress_draw};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Button (operator), Toggle, Checkbox, Decorator
+ * \{ */
+
+static void button_measure(BKNode *n, int *rw, int *rh)
+{
+ const BKImage *img = (const BKImage *)n->image;
+ if (img) { /* Tk Button(image=): the image replaces the text */
+ *rw = img->w + bk_pad();
+ *rh = BK_MAX(u(), img->h + bk_pad() / 2);
+ return;
+ }
+ const char *s = n->cls == &bk_cls_button ? n->text : n->label;
+ if (!s || !s[0]) {
+ *rw = u();
+ }
+ else {
+ *rw = BK_MAX((int)bk_content_width(s, n->icon, false) + 2 * u(), 3 * u());
+ }
+ *rh = u();
+}
+
+static int button_press(BKNode *n, BKEvent *e)
+{
+ bk_invalidate(n); /* pressed look */
+ return 1;
+}
+
+static void button_click(BKNode *n)
+{
+ if (NODE_ENABLED(n)) {
+ if (n->on_click) {
+ n->on_click(n, n->on_click_data);
+ }
+ bk_emit(n, BK_EV_CLICK, NULL, 0, 0);
+ }
+}
+
+static int button_release(BKNode *n, BKEvent *e)
+{
+ if (e->inside) {
+ button_click(n);
+ }
+ return 1;
+}
+
+static int button_key(BKNode *n, BKEvent *e)
+{
+ if (bk_keysym_is(e->keysym, "Return") || bk_keysym_is(e->keysym, "KP_Enter")) {
+ button_click(n);
+ return 1;
+ }
+ return 0;
+}
+
+static void draw_flat_or_embossed(BKNode *n, BKWCol *w, BKRect *r, int st)
+{
+ if (n->flags & NF_EMBOSS) {
+ bk_widget_but(w, r, st, n->corners);
+ }
+ else if (st & (ST_HOVER | ST_SELECT)) {
+ /* Blender's emboss=False hover: a faint rounded highlight */
+ float c[4];
+ bk_rgba_alpha(bk_theme.text, (st & ST_SELECT) ? 0.12f : 0.08f, c);
+ bk_roundbox(r->xmin, r->ymin, bk_rw(r), bk_rh(r), bk_widget_radius(w), n->corners, c);
+ }
+}
+
+static void button_draw(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ int st = state_of(n);
+ if (bk_pressed(n)) {
+ st = (st & ~ST_HOVER) | ST_SELECT;
+ }
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.regular, st);
+ draw_flat_or_embossed(n, &w, &r, st);
+ const BKImage *img = (const BKImage *)n->image;
+ if (img) {
+ bk_image_draw(img, r.xmin + (bk_rw(&r) - img->w) / 2, r.ymin + (bk_rh(&r) - img->h) / 2,
+ img->w, img->h, NODE_ENABLED(n) ? 1.0f : 0.5f);
+ return;
+ }
+ bk_text_icon(&r, n->text, n->icon, (n->flags & NF_EMBOSS) ? w.text : bk_theme.text,
+ BK_ALIGN_CENTER, NODE_ENABLED(n));
+}
+
+const BKClass bk_cls_button = {.name = "button",
+ .flags = CLS_INTERACTIVE,
+ .measure = button_measure,
+ .draw = button_draw,
+ .press = button_press,
+ .release = button_release,
+ .key = button_key};
+
+/* -- booleans -- */
+
+static int bool_to_text(BKNode *n, char *buf, int size)
+{
+ snprintf(buf, (size_t)size, "%s", n->value ? "True" : "False");
+ return 1;
+}
+
+static int bool_from_text(BKNode *n, const char *s)
+{
+ if (bk_keysym_is(s, "1") || bk_keysym_is(s, "true") || bk_keysym_is(s, "yes") ||
+ bk_keysym_is(s, "on"))
+ {
+ bk_set_value(n, 1);
+ return 1;
+ }
+ if (bk_keysym_is(s, "0") || bk_keysym_is(s, "false") || bk_keysym_is(s, "no") ||
+ bk_keysym_is(s, "off"))
+ {
+ bk_set_value(n, 0);
+ return 1;
+ }
+ return 0;
+}
+
+static void bool_toggle(BKNode *n)
+{
+ bk_set_value(n, n->value ? 0 : 1);
+}
+
+static void bool_step(BKNode *n, int dir)
+{
+ bool_toggle(n);
+}
+
+static void bool_reset(BKNode *n, bool zero)
+{
+ bk_set_value(n, zero ? 0 : n->defval);
+}
+
+static int bool_press(BKNode *n, BKEvent *e)
+{
+ bool_toggle(n);
+ bk_start_drag_toggle(bk_ctx(n), DRAG_GROUP_TOGGLE, n->value != 0);
+ return 1;
+}
+
+static void checkbox_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = u() + (int)bk_text_width(n->label, -1, false) + bk_pad();
+ *rh = u();
+}
+
+static void checkbox_draw(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ int st = state_of(n);
+ if (n->value) {
+ st |= ST_SELECT;
+ }
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.option, st);
+ bk_widget_optionbut(&w, &r, st);
+ uchar tc[4];
+ memcpy(tc, bk_theme.option.text, 4);
+ if (!NODE_ENABLED(n)) {
+ tc[3] /= 2;
+ }
+ r.xmin -= bk_pad() / 2; /* a small gap after the box, like Blender */
+ bk_text_in(&r, n->label, tc, BK_ALIGN_LEFT, false);
+}
+
+#define BOOL_CLASS_COMMON \
+ .flags = CLS_INTERACTIVE | CLS_VALUE, .drag_group = DRAG_GROUP_TOGGLE, .press = bool_press, \
+ .to_text = bool_to_text, .from_text = bool_from_text, .step = bool_step, \
+ .reset = bool_reset, .activate = bool_toggle
+
+const BKClass bk_cls_checkbox = {.name = "checkbox",
+ BOOL_CLASS_COMMON,
+ .measure = checkbox_measure,
+ .draw = checkbox_draw};
+
+static void toggle_draw(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ int st = state_of(n);
+ const bool on = n->value != 0;
+ if (on && (n->flags & NF_EMBOSS)) {
+ st |= ST_SELECT;
+ }
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.toggle, st);
+ draw_flat_or_embossed(n, &w, &r, st);
+ const int icon = (on && n->icon_on) ? n->icon_on : n->icon;
+ uchar tc[4];
+ memcpy(tc, (n->flags & NF_EMBOSS) ? w.text : bk_theme.text, 4);
+ const bool dim = !(n->flags & NF_EMBOSS) && !on && !n->icon_on;
+ if (dim) {
+ tc[3] = (uchar)(tc[3] * 0.45f); /* flat toggles dim when off */
+ }
+ if (icon && (!n->label || !n->label[0])) {
+ bk_icon(icon, r.xmin + bk_rw(&r) * 0.5f, r.ymin + bk_rh(&r) * 0.5f, dim ? tc : NULL,
+ NODE_ENABLED(n) ? 1.0f : 0.5f, 0);
+ }
+ else {
+ bk_text_icon(&r, n->label, icon, tc, BK_ALIGN_CENTER, NODE_ENABLED(n));
+ }
+}
+
+const BKClass bk_cls_toggle = {
+ .name = "toggle", BOOL_CLASS_COMMON, .measure = button_measure, .draw = toggle_draw};
+
+static void decorator_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = *rh = u();
+}
+
+static void decorator_draw(BKNode *n)
+{
+ /* Blender's property decorator: a dot, or a keyframe diamond when keyed */
+ const char *name = n->value ? "DECORATE_KEYFRAME" : "DECORATE";
+ uchar c[4];
+ memcpy(c, bk_theme.text, 4);
+ c[3] = (uchar)(255 * (bk_hovered(n) ? 0.6f : 0.4f));
+ bk_icon(bk_icons_lookup(name), n->x + n->w * 0.5f, n->y + n->h * 0.5f, n->value ? NULL : c,
+ NODE_ENABLED(n) ? 1.0f : 0.5f, 0);
+}
+
+static int decorator_context(BKNode *n, BKMenuSpec *items, int max)
+{
+ return 0;
+}
+
+const BKClass bk_cls_decorator = {.name = "decorator",
+ BOOL_CLASS_COMMON,
+ .measure = decorator_measure,
+ .draw = decorator_draw,
+ .context_items = decorator_context};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Numbers: NumberField and NumberSlider
+ * \{ */
+
+static int number_to_text(BKNode *n, char *buf, int size)
+{
+ format_number(n, n->value, buf, size);
+ return 1;
+}
+
+static int number_from_text(BKNode *n, const char *s)
+{
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "%s", s);
+ if (n->suffix && n->suffix[0]) {
+ const size_t ls = strlen(tmp), lf = strlen(n->suffix);
+ if (ls >= lf && strcmp(tmp + ls - lf, n->suffix) == 0) {
+ tmp[ls - lf] = 0;
+ }
+ }
+ double v;
+ if (!BK_eval_number(tmp, &v)) {
+ return 0;
+ }
+ bk_set_value(n, v);
+ return 1;
+}
+
+static void number_step(BKNode *n, int dir)
+{
+ bk_set_value(n, n->value + dir * n->step);
+}
+
+static void number_reset(BKNode *n, bool zero)
+{
+ bk_set_value(n, zero ? 0.0 : n->defval);
+}
+
+static void number_negate(BKNode *n)
+{
+ bk_set_value(n, -n->value);
+}
+
+static void number_begin_text(BKNode *n)
+{
+ char buf[128];
+ format_number(n, n->value, buf, sizeof(buf));
+ bk_begin_edit(n, buf, true);
+}
+
+static void number_finish(BKNode *n, bool confirm)
+{
+ if (confirm && n->edit) {
+ number_from_text(n, n->edit->text);
+ }
+}
+
+static int number_cursor_at(BKNode *n, int x, int y)
+{
+ return n->edit ? BK_CURSOR_TEXT : BK_CURSOR_EW;
+}
+
+static double snap(const BKNode *n, double v, bool ctrl)
+{
+ if (!ctrl) {
+ return v;
+ }
+ /* Ctrl: snap to coarse increments (sliders: to the step) */
+ const double inc = (n->flags & NF_INTEGER) || n->cls == &bk_cls_slider ? n->step :
+ n->step * 10.0;
+ return inc > 0 ? floor(v / inc + 0.5) * inc : v;
+}
+
+static double scrub_delta(BKNode *n, BKEvent *e)
+{
+ const double precise = EV_SHIFT(e) ? 0.1 : 1.0;
+ if (n->cls == &bk_cls_slider) {
+ return e->dx / (double)BK_MAX(1, n->w) * (n->vmax - n->vmin) * precise;
+ }
+ return e->dx / (0.5 * u()) * n->step * precise;
+}
+
+static int number_press(BKNode *n, BKEvent *e)
+{
+ if (n->edit) {
+ bk_te_click(n->edit, (float)(e->lx - bk_pad()), EV_SHIFT(e));
+ bk_invalidate(n);
+ return 1;
+ }
+ n->drag_start = n->value;
+ n->dragmode = 0;
+ for (int i = 0; i < n->nlinked; i++) {
+ n->linked_start[i] = n->linked[i]->value;
+ }
+ return 1;
+}
+
+static bool is_number(const BKNode *n)
+{
+ return n->cls == &bk_cls_number || n->cls == &bk_cls_slider;
+}
+
+/* Blender's multi-value drag: press a number field, drag vertically over
+ * other number fields to collect them, then drag horizontally to change
+ * them all by the same amount. */
+static int multi_drag(BKNode *n, BKEvent *e)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (!ctx) {
+ return 0;
+ }
+ const int threshold = BK_MAX(3, (int)(0.5f * u()));
+ if (n->dragmode == 2) { /* collecting */
+ BKNode *under = bk_hit_at(ctx, n->x + n->w / 2, e->y);
+ if (under && under != n && is_number(under) && NODE_ENABLED(under) &&
+ !(under->flags & NF_SELECTED) && ctx->nmulti < BK_MAX_MULTI)
+ {
+ under->flags |= NF_SELECTED;
+ ctx->multi_start[ctx->nmulti] = under->value;
+ ctx->multi[ctx->nmulti++] = under;
+ bk_invalidate(under);
+ }
+ if (abs(e->x - ctx->multi_x0) > threshold && ctx->nmulti > 1) {
+ n->dragmode = 3; /* now edit them all */
+ ctx->multi_x0 = e->x;
+ }
+ return 1;
+ }
+ /* editing: each field moves by its own scrub amount for the same motion */
+ BKEvent me = *e;
+ me.dx = e->x - ctx->multi_x0;
+ for (int i = 0; i < ctx->nmulti; i++) {
+ BKNode *m = ctx->multi[i];
+ bk_set_value(m, snap(m, ctx->multi_start[i] + scrub_delta(m, &me), EV_CTRL(e)));
+ }
+ return 1;
+}
+
+static int number_dbl(BKNode *n, BKEvent *e)
+{
+ if (n->edit) {
+ bk_te_select_word(n->edit, bk_te_index_at(n->edit, (float)(e->lx - bk_pad())));
+ bk_invalidate(n);
+ return 1;
+ }
+ return number_press(n, e);
+}
+
+static int number_drag(BKNode *n, BKEvent *e)
+{
+ if (n->edit) {
+ bk_te_drag(n->edit, (float)(e->lx - bk_pad()));
+ bk_invalidate(n);
+ return 1;
+ }
+ if (n->dragmode == 0) { /* first motion decides: vertical = multi-drag */
+ BKContext *ctx = bk_ctx(n);
+ if (ctx && abs(e->dy) > abs(e->dx)) {
+ n->dragmode = 2;
+ n->flags |= NF_SELECTED;
+ ctx->nmulti = 1;
+ ctx->multi[0] = n;
+ ctx->multi_start[0] = n->drag_start;
+ ctx->multi_x0 = e->x;
+ bk_invalidate(n);
+ return 1;
+ }
+ n->dragmode = 1;
+ }
+ if (n->dragmode >= 2) {
+ return multi_drag(n, e);
+ }
+ bk_set_value(n, snap(n, n->drag_start + scrub_delta(n, e), EV_CTRL(e)));
+ if (EV_ALT(e)) { /* Blender: Alt edits all linked fields by the same amount */
+ const double delta = n->value - n->drag_start;
+ for (int i = 0; i < n->nlinked; i++) {
+ bk_set_value(n->linked[i], n->linked_start[i] + delta);
+ }
+ }
+ return 1;
+}
+
+static int arrow_w(const BKNode *n)
+{
+ return BK_MIN(n->w / 3, (int)(n->h * 0.7f)); /* handle_width */
+}
+
+static int number_release(BKNode *n, BKEvent *e)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (ctx && n->dragmode >= 2) {
+ for (int i = 0; i < ctx->nmulti; i++) {
+ ctx->multi[i]->flags &= ~NF_SELECTED;
+ bk_invalidate(ctx->multi[i]);
+ }
+ ctx->nmulti = 0;
+ }
+ n->dragmode = 0;
+ if (n->edit || e->dragged || !e->inside) {
+ return 1;
+ }
+ if (n->cls == &bk_cls_number) {
+ const int aw = arrow_w(n);
+ if (e->lx < aw) {
+ number_step(n, -1);
+ return 1;
+ }
+ if (e->lx >= n->w - aw) {
+ number_step(n, 1);
+ return 1;
+ }
+ }
+ number_begin_text(n);
+ return 1;
+}
+
+static int number_key(BKNode *n, BKEvent *e)
+{
+ if (n->edit) {
+ return bk_edit_key(n, e);
+ }
+ return bk_value_key(n, e);
+}
+
+static int number_move(BKNode *n, BKEvent *e)
+{
+ if (n->cls != &bk_cls_number) {
+ return 0;
+ }
+ const int aw = arrow_w(n);
+ const int zone = e->lx < aw ? 1 : (e->lx >= n->w - aw ? 2 : 0);
+ if (zone != n->hot) {
+ n->hot = zone;
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int number_leave(BKNode *n)
+{
+ n->hot = -1;
+ return 1;
+}
+
+static void number_measure(BKNode *n, int *rw, int *rh)
+{
+ char val[128];
+ number_text(n, val, sizeof(val));
+ float tw = bk_text_width(val, -1, false);
+ if (n->label && n->label[0]) {
+ tw += bk_text_width(n->label, -1, false) + bk_text_width(": ", 2, false);
+ }
+ *rw = BK_MAX((int)tw + 2 * u(), 5 * u());
+ *rh = u();
+}
+
+static void number_texts(BKNode *n, const BKRect *r, const uchar color[4])
+{
+ char val[128];
+ number_text(n, val, sizeof(val));
+ BKRect tr = *r; /* narrowed by the widget (arrow zones), plus the text margin */
+ if (n->label && n->label[0]) {
+ const float vw = bk_text_width(val, -1, false);
+ BKRect lr = tr;
+ lr.xmax = (int)(tr.xmax - vw - bk_pad());
+ bk_text_in(&lr, n->label, color, BK_ALIGN_LEFT, false);
+ bk_text_in(&tr, val, color, BK_ALIGN_RIGHT, false);
+ }
+ else {
+ bk_text_in(&tr, val, color, BK_ALIGN_CENTER, false);
+ }
+}
+
+static void draw_editing(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.textfield, ST_SELECT | ST_TEXT_INPUT);
+ bk_widget_textbut(&w, &r, ST_SELECT, n->corners);
+ bk_te_draw(n->edit, &r, w.text);
+}
+
+static void number_draw(BKNode *n)
+{
+ if (n->edit) {
+ draw_editing(n);
+ return;
+ }
+ BKRect r = bk_node_rect(n);
+ int st = state_of(n);
+ if (st & ST_HOVER) {
+ st |= n->hot == 1 ? ST_HOVER_LEFT : (n->hot == 2 ? ST_HOVER_RIGHT : 0);
+ }
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.num, st);
+ bk_widget_numbut(&w, &r, st, n->corners);
+ number_texts(n, &r, w.text);
+}
+
+#define NUMBER_CLASS_COMMON \
+ .flags = CLS_INTERACTIVE | CLS_VALUE, .cursor = BK_CURSOR_EW, \
+ .drag_cursor = BK_CURSOR_NONE, .measure = number_measure, .press = number_press, \
+ .dbl = number_dbl, .drag = number_drag, .release = number_release, .key = number_key, \
+ .move = number_move, .leave = number_leave, .cursor_at = number_cursor_at, \
+ .finish_edit = number_finish, .to_text = number_to_text, .from_text = number_from_text, \
+ .step = number_step, .reset = number_reset, .negate = number_negate, \
+ .activate = number_begin_text
+
+static void number_init(BKNode *n)
+{
+ n->vmin = -1e30;
+ n->vmax = 1e30;
+}
+
+const BKClass bk_cls_number = {
+ .name = "number", NUMBER_CLASS_COMMON, .init = number_init, .draw = number_draw};
+
+static void slider_init(BKNode *n)
+{
+ n->vmin = 0.0;
+ n->vmax = 1.0;
+ n->flags |= NF_HAS_MIN | NF_HAS_MAX;
+}
+
+static void slider_draw(BKNode *n)
+{
+ if (n->edit) {
+ draw_editing(n);
+ return;
+ }
+ BKRect r = bk_node_rect(n);
+ const int st = state_of(n);
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.numslider, st);
+ const double span = (n->vmax - n->vmin) != 0 ? (n->vmax - n->vmin) : 1.0;
+ bk_widget_numslider(&w, &r, st, n->corners, (float)((n->value - n->vmin) / span));
+ number_texts(n, &r, w.text);
+}
+
+const BKClass bk_cls_slider = {
+ .name = "slider", NUMBER_CLASS_COMMON, .init = slider_init, .draw = slider_draw};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Text fields: TextField, SearchField, HotkeyField
+ * \{ */
+
+static int text_inset(const BKNode *n)
+{
+ return n->icon ? bk_icon_size() + (int)(0.3f * u()) : 0;
+}
+
+static int text_to_text(BKNode *n, char *buf, int size)
+{
+ snprintf(buf, (size_t)size, "%s", n->text ? n->text : "");
+ return 1;
+}
+
+static int text_from_text(BKNode *n, const char *s)
+{
+ if (!bk_streq(n->text, s)) {
+ bk_undo_record(n, 1);
+ bk_set_text(&n->text, s);
+ bk_changed(n);
+ }
+ return 1;
+}
+
+static void text_reset(BKNode *n, bool zero)
+{
+ text_from_text(n, "");
+}
+
+static void text_activate(BKNode *n)
+{
+ bk_begin_edit(n, n->text ? n->text : "", true);
+}
+
+static void text_finish(BKNode *n, bool confirm)
+{
+ if (confirm && n->edit) {
+ text_from_text(n, n->edit->text);
+ }
+}
+
+static float text_x(BKNode *n, BKEvent *e)
+{
+ return (float)(e->lx - bk_pad() - text_inset(n));
+}
+
+static int text_press(BKNode *n, BKEvent *e)
+{
+ if (!n->edit) {
+ bk_begin_edit(n, n->text ? n->text : "", false);
+ }
+ bk_te_click(n->edit, text_x(n, e), EV_SHIFT(e));
+ bk_invalidate(n);
+ return 1;
+}
+
+static int text_dbl(BKNode *n, BKEvent *e)
+{
+ if (!n->edit) {
+ return text_press(n, e);
+ }
+ bk_te_select_word(n->edit, bk_te_index_at(n->edit, text_x(n, e)));
+ bk_invalidate(n);
+ return 1;
+}
+
+static int text_drag(BKNode *n, BKEvent *e)
+{
+ if (n->edit) {
+ bk_te_drag(n->edit, text_x(n, e));
+ bk_invalidate(n);
+ }
+ return 1;
+}
+
+static int text_key(BKNode *n, BKEvent *e)
+{
+ if (!n->edit) {
+ return bk_value_key(n, e);
+ }
+ BKTextEdit *te = n->edit;
+ char *before = bk_strdup(te->text);
+ BKContext *ctx = bk_ctx(n);
+ const int res = bk_te_key(te, ctx, e->text, e->keysym, e->mods);
+ if ((n->flags & NF_LIVE) && res == TE_CHANGED && strcmp(before, te->text) != 0) {
+ text_from_text(n, te->text);
+ }
+ free(before);
+ if (res == TE_NEXT || res == TE_PREV) {
+ if (ctx) {
+ ctx->focus = NULL;
+ text_finish(n, true);
+ bk_te_free(n->edit);
+ n->edit = NULL;
+ bk_edit_next(n, res == TE_NEXT ? 1 : -1);
+ }
+ bk_invalidate(n);
+ return 1;
+ }
+ if (res == TE_CONFIRM && (n->flags & NF_EVENTS)) {
+ bk_emit(n, BK_EV_SUBMIT, NULL, 0, 0);
+ }
+ if (res == TE_CONFIRM || res == TE_CANCEL) {
+ /* end the edit and release focus */
+ if (ctx) {
+ ctx->focus = NULL;
+ if (res == TE_CONFIRM) {
+ text_finish(n, true);
+ }
+ else if (n->flags & NF_LIVE) {
+ /* live fields already applied the text */
+ }
+ bk_te_free(n->edit);
+ n->edit = NULL;
+ }
+ }
+ bk_invalidate(n);
+ return 1;
+}
+
+static int text_cursor_at(BKNode *n, int x, int y)
+{
+ return BK_CURSOR_TEXT;
+}
+
+static void text_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = 7 * u();
+ *rh = u();
+}
+
+static void text_draw(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ const int inset = text_inset(n);
+ const bool editing = n->edit != NULL;
+ int st = state_of(n);
+ if (editing) {
+ st = ST_SELECT | ST_TEXT_INPUT;
+ }
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.textfield, st);
+ bk_widget_textbut(&w, &r, st, n->corners);
+ if (n->icon) {
+ uchar ic[4];
+ memcpy(ic, w.text, 4);
+ ic[3] = (uchar)(ic[3] * 0.7f);
+ bk_icon(n->icon, r.xmin + 0.2f * u() + bk_icon_size() * 0.5f, r.ymin + bk_rh(&r) * 0.5f, ic,
+ 1.0f, 0);
+ }
+ BKRect tr = r;
+ tr.xmin += inset;
+ if (editing) {
+ bk_te_draw(n->edit, &tr, w.text);
+ return;
+ }
+ char buf[512];
+ const char *shown = n->text ? n->text : "";
+ uchar tc[4];
+ memcpy(tc, w.text, 4);
+ if (!shown[0]) {
+ shown = n->placeholder ? n->placeholder : "";
+ tc[3] = (uchar)(tc[3] * 0.45f);
+ }
+ char masked[256];
+ if (n->mask[0] && n->text && n->text[0]) {
+ bk_mask_text(n->text, (int)strlen(n->text), n->mask, masked, sizeof(masked));
+ shown = masked;
+ }
+ if (n->label && n->label[0]) {
+ snprintf(buf, sizeof(buf), "%s: %s", n->label, shown);
+ shown = buf;
+ }
+ bk_text_in(&tr, shown, tc, BK_ALIGN_LEFT, false);
+}
+
+#define TEXT_CLASS_COMMON \
+ .flags = CLS_INTERACTIVE | CLS_VALUE, .cursor = BK_CURSOR_TEXT, .measure = text_measure, \
+ .draw = text_draw, .press = text_press, .dbl = text_dbl, .drag = text_drag, \
+ .key = text_key, .cursor_at = text_cursor_at, .finish_edit = text_finish, \
+ .to_text = text_to_text, .from_text = text_from_text, .reset = text_reset, \
+ .activate = text_activate
+
+const BKClass bk_cls_text = {.name = "text", TEXT_CLASS_COMMON};
+
+static void search_init(BKNode *n)
+{
+ n->icon = bk_icons_lookup("SEARCH");
+ n->flags |= NF_LIVE;
+ bk_set_text(&n->placeholder, "Search");
+}
+
+const BKClass bk_cls_search = {.name = "search", TEXT_CLASS_COMMON, .init = search_init};
+
+/* Blender-style key text, e.g. "Ctrl Shift A". */
+static void key_label(BKEvent *e, char *buf, int size)
+{
+ static const struct {
+ const char *ks, *name;
+ } names[] = {{"space", "Spacebar"}, {"Return", "Return"}, {"Escape", "Esc"},
+ {"BackSpace", "Backspace"}, {"Delete", "Delete"}, {"Tab", "Tab"},
+ {"Prior", "Page Up"}, {"Next", "Page Down"}};
+ buf[0] = 0;
+ if (EV_CTRL(e)) {
+ strcat(buf, "Ctrl ");
+ }
+ if (EV_ALT(e)) {
+ strcat(buf, "Alt ");
+ }
+ if (EV_SHIFT(e)) {
+ strcat(buf, "Shift ");
+ }
+ for (size_t i = 0; i < sizeof(names) / sizeof(names[0]); i++) {
+ if (bk_keysym_is(e->keysym, names[i].ks)) {
+ strncat(buf, names[i].name, (size_t)(size - (int)strlen(buf) - 1));
+ return;
+ }
+ }
+ char k[32];
+ snprintf(k, sizeof(k), "%s", e->keysym);
+ if (strlen(k) == 1) {
+ k[0] = (char)toupper((uchar)k[0]);
+ }
+ for (char *c = k; *c; c++) {
+ if (*c == '_') {
+ *c = ' ';
+ }
+ }
+ strncat(buf, k, (size_t)(size - (int)strlen(buf) - 1));
+}
+
+static bool is_modifier(const char *ks)
+{
+ static const char *mods[] = {"Shift_L", "Shift_R", "Control_L", "Control_R", "Alt_L",
+ "Alt_R", "Meta_L", "Meta_R", "Super_L", "Super_R",
+ "Caps_Lock", "Win_L", "Win_R"};
+ for (size_t i = 0; i < sizeof(mods) / sizeof(mods[0]); i++) {
+ if (bk_keysym_is(ks, mods[i])) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static void hotkey_activate(BKNode *n)
+{
+ BKContext *ctx = bk_ctx(n);
+ n->dragmode = 99; /* capturing */
+ if (ctx) {
+ if (ctx->focus && ctx->focus != n && ctx->focus->cls->finish_edit) {
+ ctx->focus->cls->finish_edit(ctx->focus, true);
+ }
+ ctx->focus = n;
+ }
+ bk_invalidate(n);
+}
+
+static int hotkey_press(BKNode *n, BKEvent *e)
+{
+ if (n->dragmode != 99) {
+ hotkey_activate(n);
+ }
+ return 1;
+}
+
+static void hotkey_finish(BKNode *n, bool confirm)
+{
+ n->dragmode = 0;
+ bk_invalidate(n);
+}
+
+static int hotkey_key(BKNode *n, BKEvent *e)
+{
+ if (n->dragmode != 99) {
+ return bk_value_key(n, e);
+ }
+ BKContext *ctx = bk_ctx(n);
+ if (bk_keysym_is(e->keysym, "Escape")) {
+ if (ctx) {
+ ctx->focus = NULL;
+ }
+ hotkey_finish(n, false);
+ }
+ else if (!is_modifier(e->keysym)) {
+ char buf[96];
+ key_label(e, buf, sizeof(buf));
+ if (ctx) {
+ ctx->focus = NULL;
+ }
+ hotkey_finish(n, true);
+ text_from_text(n, buf);
+ }
+ return 1;
+}
+
+static void hotkey_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = 6 * u();
+ *rh = u();
+}
+
+static void hotkey_draw(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ const bool cap = n->dragmode == 99;
+ int st = state_of(n) | (cap ? ST_SELECT : 0);
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.regular, st);
+ bk_widget_but(&w, &r, st, n->corners);
+ char buf[256];
+ const char *v = cap ? "Press a key" : ((n->text && n->text[0]) ? n->text : "None");
+ if (n->label && n->label[0]) {
+ snprintf(buf, sizeof(buf), "%s: %s", n->label, v);
+ v = buf;
+ }
+ bk_text_in(&r, v, w.text, BK_ALIGN_CENTER, false);
+}
+
+const BKClass bk_cls_hotkey = {.name = "hotkey",
+ .flags = CLS_INTERACTIVE | CLS_VALUE,
+ .measure = hotkey_measure,
+ .draw = hotkey_draw,
+ .press = hotkey_press,
+ .key = hotkey_key,
+ .finish_edit = hotkey_finish,
+ .to_text = text_to_text,
+ .from_text = text_from_text,
+ .reset = text_reset,
+ .activate = hotkey_activate};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Choices: Dropdown (enum menu) and EnumRow (expanded enum)
+ * \{ */
+
+static int choice_to_text(BKNode *n, char *buf, int size)
+{
+ snprintf(buf, (size_t)size, "%s", item_text(n, (int)n->value));
+ return 1;
+}
+
+static int choice_from_text(BKNode *n, const char *s)
+{
+ for (int i = 0; i < n->items.n; i++) {
+ if (strcmp(n->items.v[i], s) == 0) {
+ bk_set_value(n, i);
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static void choice_step(BKNode *n, int dir)
+{
+ if (n->items.n) {
+ bk_set_value(n, BK_CLAMP((int)n->value - dir, 0, n->items.n - 1)); /* wheel up = previous */
+ }
+}
+
+static void choice_reset(BKNode *n, bool zero)
+{
+ bk_set_value(n, n->defval);
+}
+
+static void choice_init(BKNode *n)
+{
+ n->flags |= NF_HAS_MIN | NF_INTEGER;
+ n->vmin = 0;
+}
+
+static void dropdown_pick(void *data)
+{
+ /* data encodes node + index */
+}
+
+static void dropdown_activate(BKNode *n)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (!ctx || !n->items.n) {
+ return;
+ }
+ BKMenuSpec *items = (BKMenuSpec *)calloc((size_t)n->items.n, sizeof(BKMenuSpec));
+ for (int i = 0; i < n->items.n; i++) {
+ items[i].text = n->items.v[i];
+ items[i].icon = item_icon(n, i);
+ items[i].checked = -1;
+ items[i].enabled = 1;
+ items[i].fn = NULL;
+ items[i].data = (void *)(intptr_t)i; /* picked index (handled by the menu) */
+ }
+ BKNode *menu = bk_menu_new(items, n->items.n, n->label && n->label[0] ? n->label : NULL,
+ item_text(n, (int)n->value));
+ free(items);
+ bk_open_popup(ctx, menu, n, NULL);
+ (void)dropdown_pick;
+}
+
+static int dropdown_press(BKNode *n, BKEvent *e)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (bk_owns_popup(ctx, n)) {
+ BK_close_popups(ctx);
+ }
+ else {
+ dropdown_activate(n);
+ }
+ return 1;
+}
+
+static void dropdown_measure(BKNode *n, int *rw, int *rh)
+{
+ if (n->flags & NF_ICON_ONLY) {
+ *rw = (int)(1.6f * u());
+ *rh = u();
+ return;
+ }
+ float widest = 0;
+ for (int i = 0; i < n->items.n; i++) {
+ widest = BK_MAX(widest, bk_content_width(n->items.v[i], item_icon(n, i), false));
+ }
+ const float lw = (n->label && n->label[0]) ? bk_text_width(n->label, -1, false) +
+ bk_text_width(": ", 2, false) :
+ 0;
+ *rw = (int)(widest + lw + 2.5f * u());
+ *rh = u();
+}
+
+static void dropdown_draw(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ int st = state_of(n);
+ if (bk_owns_popup(bk_ctx(n), n)) {
+ st |= ST_SELECT;
+ }
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.menu, st);
+ bk_widget_menubut(&w, &r, st, n->corners);
+ const int i = (int)n->value;
+ if (n->flags & NF_ICON_ONLY) {
+ bk_icon(item_icon(n, i), n->x + 0.6f * u(), n->y + n->h * 0.5f, NULL,
+ NODE_ENABLED(n) ? 1.0f : 0.5f, 0);
+ return;
+ }
+ char buf[256];
+ const char *s = item_text(n, i);
+ if (n->label && n->label[0]) {
+ snprintf(buf, sizeof(buf), "%s: %s", n->label, s);
+ s = buf;
+ }
+ bk_text_icon(&r, s, item_icon(n, i), w.text, BK_ALIGN_LEFT, NODE_ENABLED(n));
+}
+
+const BKClass bk_cls_dropdown = {.name = "dropdown",
+ .flags = CLS_INTERACTIVE | CLS_VALUE,
+ .init = choice_init,
+ .measure = dropdown_measure,
+ .draw = dropdown_draw,
+ .press = dropdown_press,
+ .to_text = choice_to_text,
+ .from_text = choice_from_text,
+ .step = choice_step,
+ .reset = choice_reset,
+ .activate = dropdown_activate};
+
+static int enum_label_w(const BKNode *n)
+{
+ return (n->label && n->label[0] && !(n->flags & NF_VERTICAL)) ?
+ (int)bk_text_width(n->label, -1, false) + 2 * bk_pad() :
+ 0;
+}
+
+static int enum_label_h(const BKNode *n)
+{
+ return (n->label && n->label[0] && (n->flags & NF_VERTICAL)) ? u() : 0;
+}
+
+static int enum_seg_w(const BKNode *n, int i)
+{
+ if (n->flags & NF_ICON_ONLY) {
+ return u();
+ }
+ return (int)bk_content_width(n->items.v[i], item_icon(n, i), false) + 2 * bk_pad();
+}
+
+static void enum_measure(BKNode *n, int *rw, int *rh)
+{
+ if (n->flags & NF_VERTICAL) {
+ int widest = n->label ? (int)bk_text_width(n->label, -1, false) : 0;
+ for (int i = 0; i < n->items.n; i++) {
+ widest = BK_MAX(widest, enum_seg_w(n, i));
+ }
+ *rw = widest;
+ *rh = enum_label_h(n) + n->items.n * u();
+ return;
+ }
+ int w = enum_label_w(n);
+ for (int i = 0; i < n->items.n; i++) {
+ w += enum_seg_w(n, i);
+ }
+ *rw = w;
+ *rh = u();
+}
+
+static BKRect enum_segment(const BKNode *n, int i)
+{
+ if (n->flags & NF_VERTICAL) {
+ return bk_rect(n->x, n->y + enum_label_h(n) + i * u(), n->w, u());
+ }
+ const int x0 = n->x + enum_label_w(n);
+ const float sw = (n->x + n->w - x0) / (float)BK_MAX(1, n->items.n);
+ const int a = bk_iround(x0 + i * sw), b = bk_iround(x0 + (i + 1) * sw);
+ return bk_rect(a, n->y, b - a, n->h);
+}
+
+static int enum_seg_at(const BKNode *n, int x, int y)
+{
+ for (int i = 0; i < n->items.n; i++) {
+ BKRect s = enum_segment(n, i);
+ if (x >= s.xmin && x < s.xmax && y >= s.ymin && y < s.ymax) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+static int enum_move(BKNode *n, BKEvent *e)
+{
+ const int hot = enum_seg_at(n, e->x, e->y);
+ if (hot != n->hot) {
+ n->hot = hot;
+ bk_invalidate(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int enum_press(BKNode *n, BKEvent *e)
+{
+ const int i = enum_seg_at(n, e->x, e->y);
+ if (i >= 0) {
+ bk_set_value(n, i);
+ }
+ return 1;
+}
+
+static void enum_activate(BKNode *n)
+{
+ choice_step(n, -1);
+}
+
+static void enum_draw(BKNode *n)
+{
+ if (n->label && n->label[0]) {
+ BKRect lr = (n->flags & NF_VERTICAL) ? bk_rect(n->x, n->y, n->w, u()) :
+ bk_rect(n->x, n->y, enum_label_w(n), n->h);
+ uchar c[4];
+ memcpy(c, bk_theme.text, 4);
+ if (!NODE_ENABLED(n)) {
+ c[3] /= 2;
+ }
+ bk_text_in(&lr, n->label, c, BK_ALIGN_LEFT, false);
+ }
+ const bool vertical = n->flags & NF_VERTICAL;
+ const int first_c = vertical ? (CNR_TL | CNR_TR) : (n->corners & (CNR_TL | CNR_BL));
+ const int last_c = vertical ? (CNR_BL | CNR_BR) : (n->corners & (CNR_TR | CNR_BR));
+ const int last = n->items.n - 1;
+ for (int i = 0; i < n->items.n; i++) {
+ BKRect s = enum_segment(n, i);
+ const int corners = (i == 0 ? first_c : 0) | (i == last ? last_c : 0);
+ int st = NODE_ENABLED(n) ? 0 : ST_DISABLED;
+ if ((int)n->value == i) {
+ st |= ST_SELECT;
+ }
+ else if (bk_hovered(n) && i == n->hot) {
+ st |= ST_HOVER;
+ }
+ if (vertical && i != last) {
+ st |= ST_ALIGN_DOWN;
+ }
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.radio, st);
+ bk_widget_but(&w, &s, st, corners); /* widget_radiobut */
+ bk_text_icon(&s, (n->flags & NF_ICON_ONLY) ? "" : n->items.v[i], item_icon(n, i), w.text,
+ vertical ? BK_ALIGN_LEFT : BK_ALIGN_CENTER, NODE_ENABLED(n));
+ }
+}
+
+const BKClass bk_cls_enum = {.name = "enum",
+ .flags = CLS_INTERACTIVE | CLS_VALUE,
+ .init = choice_init,
+ .measure = enum_measure,
+ .draw = enum_draw,
+ .press = enum_press,
+ .move = enum_move,
+ .leave = number_leave,
+ .to_text = choice_to_text,
+ .from_text = choice_from_text,
+ .step = choice_step,
+ .reset = choice_reset,
+ .activate = enum_activate};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name ColorSwatch
+ * \{ */
+
+static int swatch_to_text(BKNode *n, char *buf, int size)
+{
+ snprintf(buf, (size_t)size, "#%02x%02x%02x%02x", bk_iround(n->color[0] * 255),
+ bk_iround(n->color[1] * 255), bk_iround(n->color[2] * 255),
+ bk_iround(n->color[3] * 255));
+ return 1;
+}
+
+int bk_parse_hex(const char *s, float out[4], const float alpha)
+{
+ while (*s == ' ' || *s == '#') {
+ s++;
+ }
+ const size_t len = strlen(s);
+ if (len != 6 && len != 8) {
+ return 0;
+ }
+ unsigned v[4] = {0, 0, 0, (unsigned)bk_iround(alpha * 255)};
+ for (size_t i = 0; i < len / 2; i++) {
+ char h[3] = {s[2 * i], s[2 * i + 1], 0};
+ char *end;
+ v[i] = (unsigned)strtoul(h, &end, 16);
+ if (*end) {
+ return 0;
+ }
+ }
+ for (int k = 0; k < 4; k++) {
+ out[k] = v[k] / 255.0f;
+ }
+ return 1;
+}
+
+static int swatch_from_text(BKNode *n, const char *s)
+{
+ float c[4];
+ if (!bk_parse_hex(s, c, n->color[3])) {
+ return 0;
+ }
+ BK_set_color(n, "set_value", c);
+ return 1;
+}
+
+static void swatch_reset(BKNode *n, bool zero)
+{
+ const float black[4] = {0, 0, 0, 1};
+ BK_set_color(n, "set_value", black);
+}
+
+static void swatch_activate(BKNode *n)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (ctx) {
+ bk_open_popup(ctx, bk_picker_new(n), n, NULL);
+ }
+}
+
+static int swatch_press(BKNode *n, BKEvent *e)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (bk_owns_popup(ctx, n)) {
+ BK_close_popups(ctx);
+ }
+ else {
+ swatch_activate(n);
+ }
+ return 1;
+}
+
+static void swatch_init(BKNode *n)
+{
+ n->color[0] = n->color[1] = n->color[2] = n->color[3] = 1.0f;
+ n->flags |= NF_ALPHA;
+}
+
+static void swatch_measure(BKNode *n, int *rw, int *rh)
+{
+ const int lw = (n->label && n->label[0]) ? (int)bk_text_width(n->label, -1, false) + 2 * bk_pad() :
+ 0;
+ *rw = lw + 3 * u();
+ *rh = u();
+}
+
+static void swatch_draw(BKNode *n)
+{
+ int lw = 0;
+ if (n->label && n->label[0]) {
+ lw = (int)bk_text_width(n->label, -1, false) + 2 * bk_pad();
+ BKRect lr = bk_rect(n->x, n->y, lw, n->h);
+ bk_text_in(&lr, n->label, bk_theme.text, BK_ALIGN_LEFT, false);
+ }
+ BKRect r = bk_rect(n->x + lw, n->y, n->w - lw, n->h);
+ const int st = state_of(n);
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.regular, st);
+ /* Blender: opaque color on the left half, color with alpha on the right */
+ const float opaque[4] = {n->color[0], n->color[1], n->color[2], 1.0f};
+ bk_widget_swatch(&w, &r, st, n->corners, opaque);
+ if (n->color[3] < 1.0f) {
+ bk_clip_push(r.xmin + bk_rw(&r) / 2, r.ymin - 2, bk_rw(&r), bk_rh(&r) + 4);
+ bk_widget_swatch(&w, &r, st, n->corners, n->color);
+ bk_clip_pop();
+ }
+}
+
+const BKClass bk_cls_swatch = {.name = "swatch",
+ .flags = CLS_INTERACTIVE | CLS_VALUE,
+ .init = swatch_init,
+ .measure = swatch_measure,
+ .draw = swatch_draw,
+ .press = swatch_press,
+ .to_text = swatch_to_text,
+ .from_text = swatch_from_text,
+ .reset = swatch_reset,
+ .activate = swatch_activate};
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Popover button, MenuButton, MenuBar
+ * \{ */
+
+static void popover_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = BK_MAX((int)bk_content_width(n->text, n->icon, false) + 2 * u(), 2 * u());
+ *rh = u();
+}
+
+BKNode *bk_popover_panel_new(BKNode *owner, BKNode *body);
+
+static int popover_press(BKNode *n, BKEvent *e)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (!ctx) {
+ return 0;
+ }
+ if (bk_owns_popup(ctx, n)) {
+ BK_close_popups(ctx);
+ }
+ else if (n->nkids) {
+ bk_open_popup(ctx, bk_popover_panel_new(n, n->kids[0]), n, NULL);
+ }
+ return 1;
+}
+
+static BKNode *popover_hit(BKNode *n, int x, int y)
+{
+ return n; /* the body lives in the popup while open */
+}
+
+static void popover_draw_tree(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ if (!NODE_VISIBLE(n) || !bk_clip_visible(&r)) {
+ return;
+ }
+ int st = state_of(n);
+ if (bk_owns_popup(bk_ctx(n), n)) {
+ st |= ST_SELECT;
+ }
+ BKWCol w;
+ bk_widget_state(&w, &bk_theme.menu, st);
+ bk_widget_menubut(&w, &r, st, n->corners);
+ bk_text_icon(&r, n->text, n->icon, w.text, BK_ALIGN_LEFT, NODE_ENABLED(n));
+}
+
+static void popover_init(BKNode *n)
+{
+ BKNode *body = bk_node_new_cls(&bk_cls_column);
+ body->spacing = bk_iround(0.2f * u());
+ BK_node_add(n, body, -1);
+}
+
+const BKClass bk_cls_popover = {.name = "popover",
+ .flags = CLS_INTERACTIVE,
+ .init = popover_init,
+ .measure = popover_measure,
+ .draw_tree = popover_draw_tree,
+ .hit = popover_hit,
+ .press = popover_press};
+
+typedef struct MenuButtonData {
+ BKMenuSpec *items;
+ int n;
+} MenuButtonData;
+
+void bk_menuspec_free(BKMenuSpec *items, int n);
+BKMenuSpec *bk_menuspec_copy(const BKMenuSpec *items, int n);
+
+void BK_menubutton_set_items(BKNode *n, const BKMenuSpec *items, int count)
+{
+ MenuButtonData *d = (MenuButtonData *)n->ext;
+ if (!d) {
+ d = (MenuButtonData *)calloc(1, sizeof(MenuButtonData));
+ n->ext = d;
+ }
+ bk_menuspec_free(d->items, d->n);
+ d->items = bk_menuspec_copy(items, count);
+ d->n = count;
+}
+
+static void menubutton_free(BKNode *n)
+{
+ MenuButtonData *d = (MenuButtonData *)n->ext;
+ if (d) {
+ bk_menuspec_free(d->items, d->n);
+ free(d);
+ }
+}
+
+static void menubutton_open(BKNode *n)
+{
+ BKContext *ctx = bk_ctx(n);
+ MenuButtonData *d = (MenuButtonData *)n->ext;
+ if (ctx && d) {
+ bk_open_popup(ctx, bk_menu_new(d->items, d->n, NULL, NULL), n, NULL);
+ }
+}
+
+static int menubutton_press(BKNode *n, BKEvent *e)
+{
+ BKContext *ctx = bk_ctx(n);
+ if (bk_owns_popup(ctx, n)) {
+ BK_close_popups(ctx);
+ }
+ else {
+ menubutton_open(n);
+ }
+ return 1;
+}
+
+static int menubutton_move(BKNode *n, BKEvent *e)
+{
+ /* Blender: while a menu of this bar is open, hovering switches menus. */
+ BKContext *ctx = bk_ctx(n);
+ if (!ctx || !ctx->npopups || bk_owns_popup(ctx, n)) {
+ return 0;
+ }
+ BKNode *owner = ctx->popups[0]->parent;
+ if (owner && owner->cls == &bk_cls_menubutton && owner->parent == n->parent) {
+ menubutton_open(n);
+ return 1;
+ }
+ return 0;
+}
+
+static int menubutton_key(BKNode *n, BKEvent *e)
+{
+ if (bk_keysym_is(e->keysym, "Return") || bk_keysym_is(e->keysym, "space")) {
+ menubutton_open(n);
+ return 1;
+ }
+ return 0;
+}
+
+static void menubutton_measure(BKNode *n, int *rw, int *rh)
+{
+ *rw = (int)(bk_content_width(n->text, n->icon, false) + 2 * bk_pad() + 0.4f * u());
+ *rh = u();
+}
+
+static void menubutton_draw(BKNode *n)
+{
+ BKRect r = bk_node_rect(n);
+ const bool open = bk_owns_popup(bk_ctx(n), n);
+ int st = (open || bk_hovered(n)) ? ST_HOVER : 0;
+ BKWCol w = bk_theme.pulldown;
+ bk_widget_pulldownbut(&w, &r, st, CNR_ALL);
+ bk_text_icon(&r, n->text, n->icon, open || (st & ST_HOVER) ? w.text_sel : w.text,
+ BK_ALIGN_CENTER, NODE_ENABLED(n));
+}
+
+const BKClass bk_cls_menubutton = {.name = "menubutton",
+ .flags = CLS_INTERACTIVE,
+ .free_ext = menubutton_free,
+ .measure = menubutton_measure,
+ .draw = menubutton_draw,
+ .press = menubutton_press,
+ .move = menubutton_move,
+ .key = menubutton_key};
+
+static void menubar_measure(BKNode *n, int *rw, int *rh)
+{
+ const int p = bk_iround(0.2f * u());
+ int w = 0;
+ for (int i = 0; i < n->nkids; i++) {
+ int cw, ch;
+ bk_natural(n->kids[i], &cw, &ch);
+ w += cw;
+ }
+ *rw = w + 2 * p;
+ *rh = u() + 2 * p;
+}
+
+static void menubar_arrange(BKNode *n)
+{
+ /* menu buttons on the left, other components (weight 0) on the right */
+ const int p = bk_iround(0.2f * u());
+ int xl = n->x + p, xr = n->x + n->w - p;
+ for (int i = 0; i < n->nkids; i++) {
+ BKNode *c = n->kids[i];
+ int cw, ch;
+ bk_natural(c, &cw, &ch);
+ if (c->cls == &bk_cls_menubutton) {
+ bk_arrange(c, xl, n->y + p, cw, u());
+ xl += cw;
+ }
+ }
+ for (int i = n->nkids - 1; i >= 0; i--) {
+ BKNode *c = n->kids[i];
+ if (c->cls == &bk_cls_menubutton) {
+ continue;
+ }
+ int cw, ch;
+ bk_natural(c, &cw, &ch);
+ xr -= cw;
+ bk_arrange(c, xr, n->y + p, cw, u());
+ xr -= bk_iround(0.2f * u());
+ }
+}
+
+static void menubar_draw(BKNode *n)
+{
+ bk_fill(n->x, n->y, n->w, n->h, bk_theme.header_bg);
+}
+
+const BKClass bk_cls_menubar = {.name = "menubar",
+ .measure = menubar_measure,
+ .arrange = menubar_arrange,
+ .draw = menubar_draw};
+
+/** \} */
diff --git a/kit/intern/kit_window.c b/kit/intern/kit_window.c
new file mode 100644
index 0000000..8ccc070
--- /dev/null
+++ b/kit/intern/kit_window.c
@@ -0,0 +1,868 @@
+/* Native window host (Win32).
+ *
+ * A plain HWND that owns a BuiRaster and drives a BKContext: mouse and
+ * keyboard messages go straight to BK_* input, redraw requests coalesce into
+ * one posted render message, and the damaged tiles are blitted with
+ * BUI_raster_present_native. Nothing on the input -> render -> present path
+ * leaves C. Animations run vsync-paced (DwmFlush).
+ *
+ * Other platforms: BK_window_supported() returns 0 (hosts use Tk/Qt).
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "kit_intern.h"
+
+#ifdef _WIN32
+
+# ifndef UNICODE
+# define UNICODE
+# endif
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+# include <windowsx.h>
+
+# define WM_BK_RENDER (WM_APP + 1)
+# define ID_TIP 1
+# define ID_ANIM 2
+# define ID_USER_BASE 1000
+
+struct BKWindow {
+ HWND hwnd;
+ BKContext *ctx;
+ BKHost prev; /* the host's own callbacks (emit) */
+ BuiRaster *raster;
+ BKWindowCallbacks cb;
+ int render_pending, frames, cursor, tip_id, next_timer, tracking, full;
+ float scale;
+ int min_w, min_h, max_w, max_h; /* client size limits (logical px; 0 = none) */
+ int fixed_w, fixed_h; /* axes the user may not resize (Tk's resizable) */
+ int user_sizing; /* inside a user move/resize loop */
+ DWORD style; /* framed style restored by "override" 0 */
+};
+
+static int g_open = 0;
+
+/* Wake BK_window_run's GetMessage without WM_QUIT: a quit message would also
+ * end any other loop on this thread (e.g. a Tk mainloop in the same app). */
+static void wake_loop(void)
+{
+ PostThreadMessageW(GetCurrentThreadId(), WM_NULL, 0, 0);
+}
+static int g_quit = 0;
+static int (*g_stop)(void) = NULL;
+static const wchar_t *k_class = L"BUIKitWindow";
+
+int BK_window_supported(void)
+{
+ return 1;
+}
+
+static void dpi_awareness(void)
+{
+ static int done = 0;
+ if (done) {
+ return;
+ }
+ done = 1;
+ HMODULE user32 = GetModuleHandleW(L"user32.dll");
+ typedef BOOL(WINAPI * SetCtx)(HANDLE);
+ SetCtx set_ctx = user32 ? (SetCtx)(void *)GetProcAddress(user32,
+ "SetProcessDpiAwarenessContext") :
+ NULL;
+ if (!set_ctx || !set_ctx((HANDLE)-4 /* PER_MONITOR_AWARE_V2 */)) {
+ SetProcessDPIAware();
+ }
+}
+
+static float window_dpi_scale(HWND hwnd)
+{
+ const char *env = getenv("BUI_UI_SCALE");
+ if (env && atof(env) > 0) {
+ return (float)atof(env);
+ }
+ HMODULE user32 = GetModuleHandleW(L"user32.dll");
+ typedef UINT(WINAPI * GetDpi)(HWND);
+ GetDpi get = user32 ? (GetDpi)(void *)GetProcAddress(user32, "GetDpiForWindow") : NULL;
+ const UINT dpi = (get && hwnd) ? get(hwnd) : 96;
+ return BK_MAX(1.0f, dpi / 96.0f);
+}
+
+static wchar_t *utf8_to_wide(const char *s)
+{
+ const int n = MultiByteToWideChar(CP_UTF8, 0, s ? s : "", -1, NULL, 0);
+ wchar_t *w = (wchar_t *)malloc(sizeof(wchar_t) * (size_t)n);
+ MultiByteToWideChar(CP_UTF8, 0, s ? s : "", -1, w, n);
+ return w;
+}
+
+static char *wide_to_utf8(const wchar_t *w, int len)
+{
+ const int n = WideCharToMultiByte(CP_UTF8, 0, w, len, NULL, 0, NULL, NULL);
+ char *s = (char *)malloc((size_t)n + 1);
+ WideCharToMultiByte(CP_UTF8, 0, w, len, s, n, NULL, NULL);
+ s[n] = 0;
+ return s;
+}
+
+/* -- host services -- */
+
+static void host_request(void *data)
+{
+ BKWindow *win = (BKWindow *)data;
+ if (win->hwnd && !win->render_pending) {
+ win->render_pending = 1;
+ PostMessageW(win->hwnd, WM_BK_RENDER, 0, 0);
+ }
+}
+
+static HCURSOR cursor_handle(int c)
+{
+ LPCWSTR id = IDC_ARROW;
+ switch (c) {
+ case BK_CURSOR_EW:
+ id = IDC_SIZEWE;
+ break;
+ case BK_CURSOR_NS:
+ id = IDC_SIZENS;
+ break;
+ case BK_CURSOR_TEXT:
+ id = IDC_IBEAM;
+ break;
+ case BK_CURSOR_CROSSHAIR:
+ id = IDC_CROSS;
+ break;
+ case BK_CURSOR_HAND:
+ id = IDC_HAND;
+ break;
+ case BK_CURSOR_MOVE:
+ id = IDC_SIZEALL;
+ break;
+ case BK_CURSOR_NONE:
+ return NULL;
+ }
+ return LoadCursorW(NULL, id);
+}
+
+static void host_set_cursor(void *data, int cursor)
+{
+ BKWindow *win = (BKWindow *)data;
+ win->cursor = cursor;
+ SetCursor(cursor_handle(cursor));
+}
+
+static void host_warp(void *data, int x, int y)
+{
+ BKWindow *win = (BKWindow *)data;
+ POINT p = {x, y};
+ ClientToScreen(win->hwnd, &p);
+ SetCursorPos(p.x, p.y);
+}
+
+static char *host_clipboard_get(void *data)
+{
+ BKWindow *win = (BKWindow *)data;
+ char *out = NULL;
+ if (!OpenClipboard(win->hwnd)) {
+ return NULL;
+ }
+ HANDLE h = GetClipboardData(CF_UNICODETEXT);
+ if (h) {
+ const wchar_t *w = (const wchar_t *)GlobalLock(h);
+ if (w) {
+ out = wide_to_utf8(w, -1);
+ GlobalUnlock(h);
+ }
+ }
+ CloseClipboard();
+ return out;
+}
+
+static void host_clipboard_set(void *data, const char *text)
+{
+ BKWindow *win = (BKWindow *)data;
+ wchar_t *w = utf8_to_wide(text);
+ const size_t bytes = (wcslen(w) + 1) * sizeof(wchar_t);
+ if (OpenClipboard(win->hwnd)) {
+ EmptyClipboard();
+ HGLOBAL h = GlobalAlloc(GMEM_MOVEABLE, bytes);
+ if (h) {
+ memcpy(GlobalLock(h), w, bytes);
+ GlobalUnlock(h);
+ SetClipboardData(CF_UNICODETEXT, h);
+ }
+ CloseClipboard();
+ }
+ free(w);
+}
+
+static void host_schedule(void *data, int ms, int timer)
+{
+ BKWindow *win = (BKWindow *)data;
+ win->tip_id = timer;
+ SetTimer(win->hwnd, ID_TIP, (UINT)ms, NULL);
+}
+
+static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, double b)
+{
+ BKWindow *win = (BKWindow *)data;
+ if (win->prev.emit) {
+ win->prev.emit(win->prev.data, node, kind, ref, a, b);
+ }
+}
+
+/* -- rendering -- */
+
+typedef HRESULT(WINAPI *DwmFlushFn)(void);
+
+static void vsync(void)
+{
+ static DwmFlushFn flush = NULL;
+ static int loaded = 0;
+ if (!loaded) {
+ loaded = 1;
+ HMODULE dwm = LoadLibraryW(L"dwmapi.dll");
+ flush = dwm ? (DwmFlushFn)(void *)GetProcAddress(dwm, "DwmFlush") : NULL;
+ }
+ if (flush) {
+ flush();
+ }
+ else {
+ Sleep(8);
+ }
+}
+
+static void do_render(BKWindow *win)
+{
+ RECT rc;
+ GetClientRect(win->hwnd, &rc);
+ const int w = BK_MAX(1, rc.right - rc.left), h = BK_MAX(1, rc.bottom - rc.top);
+ const int resized = BUI_raster_width(win->raster) != w || BUI_raster_height(win->raster) != h;
+ const int regions = BK_render(win->ctx, win->raster, w, h, win->full);
+ win->full = 0;
+ if (regions || resized) {
+ BUI_raster_present_native(win->raster, win->hwnd, resized);
+ win->frames++;
+ }
+ if (BK_animating(win->ctx)) {
+ vsync(); /* pace animation frames to the display */
+ host_request(win);
+ }
+}
+
+/* -- input mapping -- */
+
+static int mods_now(WPARAM wp, int mouse)
+{
+ int m = 0;
+ if (GetKeyState(VK_SHIFT) < 0) {
+ m |= BK_SHIFT;
+ }
+ if (GetKeyState(VK_CONTROL) < 0) {
+ m |= BK_CTRL;
+ }
+ if (GetKeyState(VK_MENU) < 0) {
+ m |= BK_ALT;
+ }
+ if (mouse && (wp & MK_LBUTTON)) {
+ m |= BK_BUTTON1;
+ }
+ return m;
+}
+
+static const char *vk_keysym(WPARAM vk, char *buf)
+{
+ switch (vk) {
+ case VK_LEFT: return "Left";
+ case VK_RIGHT: return "Right";
+ case VK_UP: return "Up";
+ case VK_DOWN: return "Down";
+ case VK_HOME: return "Home";
+ case VK_END: return "End";
+ case VK_PRIOR: return "Prior";
+ case VK_NEXT: return "Next";
+ case VK_RETURN: return "Return";
+ case VK_ESCAPE: return "Escape";
+ case VK_BACK: return "BackSpace";
+ case VK_DELETE: return "Delete";
+ case VK_TAB: return "Tab";
+ case VK_INSERT: return "Insert";
+ case VK_SHIFT: return "Shift_L";
+ case VK_CONTROL: return "Control_L";
+ case VK_MENU: return "Alt_L";
+ case VK_SUBTRACT: return "KP_Subtract";
+ case VK_OEM_MINUS: return "minus";
+ case VK_SPACE: return "space";
+ }
+ if (vk >= VK_F1 && vk <= VK_F24) {
+ snprintf(buf, 8, "F%d", (int)(vk - VK_F1 + 1));
+ return buf;
+ }
+ if ((vk >= 'A' && vk <= 'Z') || (vk >= '0' && vk <= '9')) {
+ buf[0] = (char)((vk >= 'A' && vk <= 'Z') ? vk - 'A' + 'a' : vk);
+ buf[1] = 0;
+ return buf;
+ }
+ return NULL;
+}
+
+static LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
+{
+ BKWindow *win = (BKWindow *)GetWindowLongPtrW(hwnd, GWLP_USERDATA);
+ if (!win) {
+ return DefWindowProcW(hwnd, msg, wp, lp);
+ }
+ BKContext *ctx = win->ctx;
+ switch (msg) {
+ case WM_BK_RENDER:
+ win->render_pending = 0;
+ do_render(win);
+ return 0;
+ case WM_PAINT: {
+ PAINTSTRUCT ps;
+ BeginPaint(hwnd, &ps);
+ EndPaint(hwnd, &ps);
+ win->full = 1;
+ do_render(win);
+ BUI_raster_present_native(win->raster, hwnd, 1);
+ return 0;
+ }
+ case WM_ERASEBKGND:
+ return 1;
+ case WM_SIZE:
+ host_request(win);
+ return 0;
+ case WM_DPICHANGED: {
+ win->scale = HIWORD(wp) / 96.0f;
+ if (!getenv("BUI_UI_SCALE")) {
+ BK_set_scale(win->scale);
+ }
+ const RECT *r = (const RECT *)lp;
+ SetWindowPos(hwnd, NULL, r->left, r->top, r->right - r->left, r->bottom - r->top,
+ SWP_NOZORDER | SWP_NOACTIVATE);
+ BK_node_relayout(ctx->root);
+ host_request(win);
+ return 0;
+ }
+ case WM_SETCURSOR:
+ if (LOWORD(lp) == HTCLIENT) {
+ SetCursor(cursor_handle(win->cursor));
+ return TRUE;
+ }
+ break;
+ case WM_MOUSEMOVE:
+ if (!win->tracking) {
+ TRACKMOUSEEVENT t = {sizeof(t), TME_LEAVE, hwnd, 0};
+ TrackMouseEvent(&t);
+ win->tracking = 1;
+ }
+ BK_motion(ctx, GET_X_LPARAM(lp), GET_Y_LPARAM(lp), mods_now(wp, 1));
+ return 0;
+ case WM_MOUSELEAVE:
+ win->tracking = 0;
+ if (GetCapture() != hwnd) {
+ BK_motion(ctx, -100000, -100000, 0);
+ }
+ return 0;
+ case WM_LBUTTONDOWN:
+ SetCapture(hwnd);
+ SetFocus(hwnd);
+ BK_press(ctx, GET_X_LPARAM(lp), GET_Y_LPARAM(lp), mods_now(wp, 1));
+ return 0;
+ case WM_LBUTTONUP:
+ ReleaseCapture();
+ BK_release(ctx, GET_X_LPARAM(lp), GET_Y_LPARAM(lp), mods_now(wp, 1));
+ return 0;
+ case WM_RBUTTONDOWN:
+ BK_context_menu(ctx, GET_X_LPARAM(lp), GET_Y_LPARAM(lp), mods_now(wp, 1));
+ return 0;
+ case WM_RBUTTONUP:
+ case WM_MBUTTONDOWN:
+ case WM_MBUTTONUP:
+ BK_button(ctx, GET_X_LPARAM(lp), GET_Y_LPARAM(lp), msg == WM_RBUTTONUP ? 3 : 2,
+ msg != WM_MBUTTONDOWN, mods_now(wp, 1));
+ return 0;
+ case WM_KEYUP:
+ case WM_SYSKEYUP: {
+ char buf[8];
+ const char *ks = vk_keysym(wp, buf);
+ if (ks) {
+ BK_key_release(ctx, ks, mods_now(0, 0));
+ }
+ break;
+ }
+ case WM_ENTERSIZEMOVE:
+ case WM_EXITSIZEMOVE:
+ win->user_sizing = msg == WM_ENTERSIZEMOVE;
+ break;
+ case WM_GETMINMAXINFO: {
+ MINMAXINFO *mm = (MINMAXINFO *)lp;
+ if (win->user_sizing && (win->fixed_w || win->fixed_h)) { /* only the user is limited */
+ RECT wr;
+ GetWindowRect(hwnd, &wr);
+ if (win->fixed_w) {
+ mm->ptMinTrackSize.x = mm->ptMaxTrackSize.x = wr.right - wr.left;
+ }
+ if (win->fixed_h) {
+ mm->ptMinTrackSize.y = mm->ptMaxTrackSize.y = wr.bottom - wr.top;
+ }
+ return 0;
+ }
+ const DWORD style = (DWORD)GetWindowLongPtrW(hwnd, GWL_STYLE);
+ if (win->min_w || win->min_h) {
+ RECT r = {0, 0, (LONG)(win->min_w * win->scale), (LONG)(win->min_h * win->scale)};
+ AdjustWindowRect(&r, style, FALSE);
+ mm->ptMinTrackSize.x = win->min_w ? r.right - r.left : mm->ptMinTrackSize.x;
+ mm->ptMinTrackSize.y = win->min_h ? r.bottom - r.top : mm->ptMinTrackSize.y;
+ }
+ if (win->max_w || win->max_h) {
+ RECT r = {0, 0, (LONG)(win->max_w * win->scale), (LONG)(win->max_h * win->scale)};
+ AdjustWindowRect(&r, style, FALSE);
+ mm->ptMaxTrackSize.x = win->max_w ? r.right - r.left : mm->ptMaxTrackSize.x;
+ mm->ptMaxTrackSize.y = win->max_h ? r.bottom - r.top : mm->ptMaxTrackSize.y;
+ }
+ return 0;
+ }
+ case WM_MOUSEWHEEL: {
+ POINT p = {GET_X_LPARAM(lp), GET_Y_LPARAM(lp)};
+ ScreenToClient(hwnd, &p);
+ BK_wheel(ctx, p.x, p.y, GET_WHEEL_DELTA_WPARAM(wp) > 0 ? 1 : -1, mods_now(0, 0));
+ return 0;
+ }
+ case WM_KEYDOWN:
+ case WM_SYSKEYDOWN: {
+ char buf[8];
+ const int mods = mods_now(0, 0);
+ const char *ks = vk_keysym(wp, buf);
+ const int is_char_key = ks && ((wp >= 'A' && wp <= 'Z') || (wp >= '0' && wp <= '9') ||
+ wp == VK_SPACE || wp == VK_OEM_MINUS);
+ /* printable keys arrive as WM_CHAR unless Ctrl/Alt are held */
+ if (ks && (!is_char_key || (mods & (BK_CTRL | BK_ALT)))) {
+ if (BK_key(ctx, "", ks, mods)) {
+ return 0;
+ }
+ }
+ if (msg == WM_SYSKEYDOWN) {
+ break; /* Alt+F4 and the system menu */
+ }
+ return 0;
+ }
+ case WM_CHAR: {
+ static wchar_t high = 0;
+ wchar_t wc[3] = {(wchar_t)wp, 0, 0};
+ if (wp >= 0xD800 && wp <= 0xDBFF) {
+ high = (wchar_t)wp;
+ return 0;
+ }
+ if (wp >= 0xDC00 && wp <= 0xDFFF && high) {
+ wc[0] = high;
+ wc[1] = (wchar_t)wp;
+ high = 0;
+ }
+ if (wc[0] < 32 || wc[0] == 127 || (GetKeyState(VK_CONTROL) < 0 && GetKeyState(VK_MENU) >= 0)) {
+ return 0; /* control characters: handled as keys */
+ }
+ char *text = wide_to_utf8(wc, -1);
+ const char *keysym = (text[0] == ' ' && !text[1]) ? "space" :
+ (text[0] == '-' && !text[1]) ? "minus" :
+ text;
+ BK_key(ctx, text, keysym, mods_now(0, 0));
+ free(text);
+ return 0;
+ }
+ case WM_TIMER:
+ if (wp == ID_TIP) {
+ KillTimer(hwnd, ID_TIP);
+ BK_timer(ctx, win->tip_id);
+ }
+ else if (wp >= ID_USER_BASE) {
+ KillTimer(hwnd, wp);
+ if (win->cb.on_timer) {
+ win->cb.on_timer(win->cb.data, win, (int)(wp - ID_USER_BASE));
+ }
+ }
+ return 0;
+ case WM_CLOSE:
+ if (win->cb.on_close && !win->cb.on_close(win->cb.data, win)) {
+ return 0;
+ }
+ DestroyWindow(hwnd);
+ return 0;
+ case WM_DESTROY:
+ win->hwnd = NULL;
+ if (--g_open <= 0) {
+ wake_loop();
+ }
+ return 0;
+ }
+ return DefWindowProcW(hwnd, msg, wp, lp);
+}
+
+BKWindow *BK_window_new(BKContext *ctx, const char *title, int width, int height)
+{
+ dpi_awareness();
+ static int registered = 0;
+ HINSTANCE inst = GetModuleHandleW(NULL);
+ if (!registered) {
+ WNDCLASSEXW wc = {sizeof(wc)};
+ wc.lpfnWndProc = wndproc;
+ wc.hInstance = inst;
+ wc.hCursor = NULL; /* WM_SETCURSOR */
+ wc.lpszClassName = k_class;
+ wc.hIcon = LoadIconW(NULL, (LPCWSTR)IDI_APPLICATION);
+ if (!RegisterClassExW(&wc)) {
+ return NULL;
+ }
+ registered = 1;
+ }
+ BKWindow *win = (BKWindow *)calloc(1, sizeof(BKWindow));
+ win->ctx = ctx;
+ win->prev = ctx->host;
+ win->raster = BUI_raster_create(1, 1);
+ win->next_timer = 1;
+ win->scale = window_dpi_scale(NULL);
+ {
+ /* system DPI until the window exists */
+ HDC dc = GetDC(NULL);
+ const int dpi = GetDeviceCaps(dc, LOGPIXELSX);
+ ReleaseDC(NULL, dc);
+ if (!getenv("BUI_UI_SCALE")) {
+ win->scale = BK_MAX(1.0f, dpi / 96.0f);
+ }
+ }
+ BK_set_scale(win->scale);
+ RECT r = {0, 0, (LONG)(width * win->scale), (LONG)(height * win->scale)};
+ AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, FALSE);
+ wchar_t *wt = utf8_to_wide(title);
+ win->hwnd = CreateWindowExW(0, k_class, wt, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
+ CW_USEDEFAULT, CW_USEDEFAULT, r.right - r.left, r.bottom - r.top,
+ NULL, NULL, inst, NULL);
+ free(wt);
+ if (!win->hwnd) {
+ BUI_raster_free(win->raster);
+ free(win);
+ return NULL;
+ }
+ SetWindowLongPtrW(win->hwnd, GWLP_USERDATA, (LONG_PTR)win);
+ g_open++;
+ BKHost host = {win, host_request, host_set_cursor, host_warp,
+ host_clipboard_get, host_clipboard_set, host_schedule, host_emit};
+ BK_context_set_host(ctx, &host);
+ return win;
+}
+
+void BK_window_free(BKWindow *win)
+{
+ if (!win) {
+ return;
+ }
+ if (win->hwnd) {
+ SetWindowLongPtrW(win->hwnd, GWLP_USERDATA, 0);
+ DestroyWindow(win->hwnd);
+ if (--g_open <= 0) {
+ wake_loop();
+ }
+ }
+ if (win->ctx) {
+ BK_context_set_host(win->ctx, &win->prev);
+ }
+ BUI_raster_free(win->raster);
+ free(win);
+}
+
+void BK_window_set_callbacks(BKWindow *win, const BKWindowCallbacks *cb)
+{
+ win->cb = *cb;
+}
+
+void BK_window_show(BKWindow *win)
+{
+ if (win->hwnd) {
+ ShowWindow(win->hwnd, SW_SHOW);
+ UpdateWindow(win->hwnd);
+ }
+}
+
+void BK_window_close(BKWindow *win)
+{
+ if (win->hwnd) {
+ DestroyWindow(win->hwnd);
+ }
+}
+
+int BK_window_is_open(BKWindow *win)
+{
+ return win && win->hwnd != NULL;
+}
+
+void BK_window_set_title(BKWindow *win, const char *title)
+{
+ if (win->hwnd) {
+ wchar_t *w = utf8_to_wide(title);
+ SetWindowTextW(win->hwnd, w);
+ free(w);
+ }
+}
+
+void BK_window_set_size(BKWindow *win, int width, int height)
+{
+ if (!win->hwnd) {
+ return;
+ }
+ RECT r = {0, 0, (LONG)(width * win->scale), (LONG)(height * win->scale)};
+ AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, FALSE);
+ SetWindowPos(win->hwnd, NULL, 0, 0, r.right - r.left, r.bottom - r.top,
+ SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
+}
+
+void BK_window_get_size(BKWindow *win, int *w, int *h)
+{
+ RECT rc = {0, 0, 0, 0};
+ if (win->hwnd) {
+ GetClientRect(win->hwnd, &rc);
+ }
+ *w = rc.right;
+ *h = rc.bottom;
+}
+
+BuiRaster *BK_window_raster(BKWindow *win)
+{
+ return win->raster;
+}
+
+int BK_window_frames(BKWindow *win)
+{
+ return win->frames;
+}
+
+void BK_window_render_now(BKWindow *win)
+{
+ if (win->hwnd) {
+ win->render_pending = 0;
+ do_render(win);
+ }
+}
+
+int BK_window_timer(BKWindow *win, int ms)
+{
+ const int id = win->next_timer++;
+ if (win->hwnd) {
+ SetTimer(win->hwnd, ID_USER_BASE + (UINT_PTR)id, (UINT)BK_MAX(0, ms), NULL);
+ }
+ return id;
+}
+
+void BK_window_cancel_timer(BKWindow *win, int id)
+{
+ if (win->hwnd) {
+ KillTimer(win->hwnd, ID_USER_BASE + (UINT_PTR)id);
+ }
+}
+
+void *BK_window_handle(BKWindow *win)
+{
+ return win->hwnd;
+}
+
+static void set_style(HWND hwnd, DWORD style)
+{
+ SetWindowLongPtrW(hwnd, GWL_STYLE, (LONG_PTR)(style | (GetWindowLongPtrW(hwnd, GWL_STYLE) &
+ WS_VISIBLE)));
+ SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
+}
+
+void BK_window_wm(BKWindow *win, const char *key, double a, double b)
+{
+ HWND h = win->hwnd;
+ if (!h) {
+ return;
+ }
+ if (!strcmp(key, "pos")) {
+ SetWindowPos(h, NULL, (int)a, (int)b, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
+ }
+ else if (!strcmp(key, "minsize") || !strcmp(key, "maxsize")) {
+ int *w = key[1] == 'i' ? &win->min_w : &win->max_w, *hh = key[1] == 'i' ? &win->min_h :
+ &win->max_h;
+ *w = (int)a;
+ *hh = (int)b;
+ }
+ else if (!strcmp(key, "resizable")) {
+ DWORD style = (DWORD)GetWindowLongPtrW(h, GWL_STYLE) & ~WS_VISIBLE;
+ if (style & WS_CAPTION) {
+ style = (a || b) ? (style | WS_THICKFRAME | WS_MAXIMIZEBOX) :
+ (style & ~(WS_THICKFRAME | WS_MAXIMIZEBOX));
+ set_style(h, style);
+ }
+ win->fixed_w = a == 0.0;
+ win->fixed_h = b == 0.0;
+ }
+ else if (!strcmp(key, "topmost")) {
+ SetWindowPos(h, a ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
+ }
+ else if (!strcmp(key, "alpha")) {
+ const LONG_PTR ex = GetWindowLongPtrW(h, GWL_EXSTYLE);
+ SetWindowLongPtrW(h, GWL_EXSTYLE, ex | WS_EX_LAYERED);
+ SetLayeredWindowAttributes(h, 0, (BYTE)(BK_CLAMP(a, 0.0, 1.0) * 255.0 + 0.5), LWA_ALPHA);
+ }
+ else if (!strcmp(key, "override")) {
+ if (!win->style) {
+ win->style = (DWORD)GetWindowLongPtrW(h, GWL_STYLE) & ~WS_VISIBLE;
+ }
+ set_style(h, a ? WS_POPUP | WS_CLIPCHILDREN : win->style);
+ }
+ else if (!strcmp(key, "state")) {
+ static const int show[4] = {SW_RESTORE, SW_MINIMIZE, SW_HIDE, SW_MAXIMIZE};
+ ShowWindow(h, show[BK_CLAMP((int)a, 0, 3)]);
+ }
+ else if (!strcmp(key, "lift") || !strcmp(key, "lower")) {
+ SetWindowPos(h, key[1] == 'i' ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
+ }
+ else if (!strcmp(key, "disabled")) { /* modal dialogs disable their parent */
+ EnableWindow(h, a == 0.0);
+ }
+ else if (!strcmp(key, "focus")) {
+ SetForegroundWindow(h);
+ SetFocus(h);
+ }
+}
+
+int BK_window_wm_get(BKWindow *win, const char *key, double *r_a, double *r_b)
+{
+ *r_a = *r_b = 0.0;
+ if (!strcmp(key, "screen")) {
+ *r_a = GetSystemMetrics(SM_CXSCREEN);
+ *r_b = GetSystemMetrics(SM_CYSCREEN);
+ return 1;
+ }
+ if (!strcmp(key, "pointer")) {
+ POINT p;
+ GetCursorPos(&p);
+ *r_a = p.x;
+ *r_b = p.y;
+ return 1;
+ }
+ if (!strcmp(key, "scale")) {
+ *r_a = win ? win->scale : 1.0;
+ return 1;
+ }
+ if (!win || !win->hwnd) {
+ return 0;
+ }
+ if (!strcmp(key, "pos")) { /* client origin on screen */
+ POINT p = {0, 0};
+ ClientToScreen(win->hwnd, &p);
+ *r_a = p.x;
+ *r_b = p.y;
+ return 1;
+ }
+ if (!strcmp(key, "state")) {
+ *r_a = IsIconic(win->hwnd) ? 1 : !IsWindowVisible(win->hwnd) ? 2 : IsZoomed(win->hwnd) ? 3 :
+ 0;
+ return 1;
+ }
+ return 0;
+}
+
+void BK_window_set_stop_check(int (*stop)(void))
+{
+ g_stop = stop;
+}
+
+void BK_window_quit(void)
+{
+ g_quit = 1;
+ wake_loop();
+}
+
+void BK_window_run(void)
+{
+ g_quit = 0;
+ MSG msg;
+ while (g_open > 0 && !g_quit && GetMessageW(&msg, NULL, 0, 0) > 0) {
+ TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ if (g_stop && g_stop()) {
+ break;
+ }
+ }
+}
+
+int BK_window_pump(void)
+{
+ MSG msg;
+ while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
+ if (msg.message == WM_QUIT) {
+ break;
+ }
+ TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ if (g_stop && g_stop()) {
+ break;
+ }
+ }
+ return g_open;
+}
+
+#else /* !_WIN32 */
+
+int BK_window_supported(void)
+{
+ return 0;
+}
+BKWindow *BK_window_new(BKContext *ctx, const char *title, int width, int height)
+{
+ return NULL;
+}
+void BK_window_free(BKWindow *win) {}
+void BK_window_set_callbacks(BKWindow *win, const BKWindowCallbacks *cb) {}
+void BK_window_show(BKWindow *win) {}
+void BK_window_close(BKWindow *win) {}
+int BK_window_is_open(BKWindow *win)
+{
+ return 0;
+}
+void BK_window_set_title(BKWindow *win, const char *title) {}
+void BK_window_set_size(BKWindow *win, int width, int height) {}
+void BK_window_get_size(BKWindow *win, int *w, int *h)
+{
+ *w = *h = 0;
+}
+BuiRaster *BK_window_raster(BKWindow *win)
+{
+ return NULL;
+}
+int BK_window_frames(BKWindow *win)
+{
+ return 0;
+}
+void BK_window_render_now(BKWindow *win) {}
+int BK_window_timer(BKWindow *win, int ms)
+{
+ return 0;
+}
+void BK_window_cancel_timer(BKWindow *win, int id) {}
+void *BK_window_handle(BKWindow *win)
+{
+ return NULL;
+}
+void BK_window_wm(BKWindow *win, const char *key, double a, double b) {}
+int BK_window_wm_get(BKWindow *win, const char *key, double *r_a, double *r_b)
+{
+ *r_a = *r_b = 0.0;
+ return 0;
+}
+void BK_window_run(void) {}
+int BK_window_pump(void)
+{
+ return 0;
+}
+void BK_window_quit(void) {}
+void BK_window_set_stop_check(int (*stop)(void)) {}
+
+#endif
diff --git a/tools/__pycache__/kit_icons_src.cpython-314.pyc b/tools/__pycache__/kit_icons_src.cpython-314.pyc
new file mode 100644
index 0000000..a2243ad
Binary files /dev/null and b/tools/__pycache__/kit_icons_src.cpython-314.pyc differ
diff --git a/tools/extract_api.py b/tools/extract_api.py
new file mode 100644
index 0000000..490a7e1
--- /dev/null
+++ b/tools/extract_api.py
@@ -0,0 +1,93 @@
+"""Extract public API surfaces from the reference checkouts.
+
+- tkinter: AST-parse Lib/tkinter/__init__.py (+ ttk.py) for class methods.
+- Qt: regex the public method declarations out of the widget headers.
+
+Output: reference/API_NOTES.md — the target surface for the syntax layers.
+"""
+import ast
+import io
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+REF = ROOT / "reference"
+OUT = []
+
+# ---------------------------------------------------------------- tkinter
+def tk_classes(path):
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ for node in tree.body:
+ if isinstance(node, ast.ClassDef):
+ methods = []
+ for item in node.body:
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ if not item.name.startswith("_"):
+ methods.append(item.name)
+ yield node.name, methods
+
+
+TK_FILES = {
+ "tkinter/__init__.py": ["Misc", "Widget", "Tk", "Pack", "Place", "Grid",
+ "Frame", "Label", "Button", "Checkbutton",
+ "Radiobutton", "Entry", "Listbox", "Canvas",
+ "Scale", "Scrollbar", "Text", "Toplevel"],
+ "tkinter/ttk.py": ["Combobox", "Progressbar", "Scale", "Spinbox",
+ "Notebook", "Separator", "Sizegrip", "Treeview"],
+}
+
+OUT.append("## tkinter (from CPython %s)\n" % "reference/cpython")
+tk_total = set()
+for rel, wanted in TK_FILES.items():
+ p = REF / "cpython" / "Lib" / rel
+ if not p.exists():
+ continue
+ for cls, methods in tk_classes(p):
+ if cls in wanted:
+ OUT.append("### tkinter.%s (%d public methods)\n%s\n" %
+ (cls, len(methods), ", ".join(sorted(methods))))
+ tk_total.update(methods)
+OUT.append("**tkinter surface: %d unique public methods across mirrored classes**\n" % len(tk_total))
+
+# -------------------------------------------------------------------- Qt
+QT_HEADERS = {
+ "QApplication": "src/gui/kernel/qapplication.h",
+ "QWidget": "src/widgets/kernel/qwidget.h",
+ "QFrame": "src/widgets/widgets/qframe.h",
+ "QLabel": "src/widgets/widgets/qlabel.h",
+ "QPushButton": "src/widgets/widgets/qpushbutton.h",
+ "QCheckBox": "src/widgets/widgets/qcheckbox.h",
+ "QRadioButton": "src/widgets/widgets/qradiobutton.h",
+ "QLineEdit": "src/widgets/widgets/qlineedit.h",
+ "QComboBox": "src/widgets/widgets/qcombobox.h",
+ "QSlider": "src/widgets/widgets/qslider.h",
+ "QSpinBox": "src/widgets/widgets/qspinbox.h",
+ "QProgressBar": "src/widgets/widgets/qprogressbar.h",
+ "QGroupBox": "src/widgets/widgets/qgroupbox.h",
+}
+
+OUT.append("## Qt widgets (from qtbase headers)\n")
+qt_total = set()
+for cls, rel in QT_HEADERS.items():
+ p = REF / "qtbase" / rel
+ if not p.exists():
+ OUT.append("### %s — header missing (%s)\n" % (cls, rel))
+ continue
+ text = p.read_text(encoding="utf-8", errors="ignore")
+ names = set()
+ # public methods: "type name(" inside the header, filtered to identifiers
+ for m in re.finditer(r"^\s*(?:virtual\s+|static\s+)?[A-Za-z_][\w:<>,\s*&]*\s+\*?([a-zA-Z_]\w*)\s*\(",
+ text, re.M):
+ name = m.group(1)
+ if name in ("if", "for", "while", "switch", "return", "sizeof", "Q_DECL_DEPRECATED"):
+ continue
+ names.add(name)
+ # signals/slots emit via macros; keep the list as-is
+ OUT.append("### %s (%d candidate public methods)\n%s\n" %
+ (cls, len(names), ", ".join(sorted(names))))
+ qt_total.update(names)
+OUT.append("**Qt surface: %d unique candidate public methods across mirrored classes**\n" % len(qt_total))
+
+out_path = REF / "API_NOTES.md"
+io.open(out_path, "w", encoding="utf-8", newline="\n").write("\n".join(OUT))
+print("wrote", out_path, "— tkinter:", len(tk_total), "methods; qt:", len(qt_total), "methods")
diff --git a/tools/gen_kit_icons.py b/tools/gen_kit_icons.py
new file mode 100644
index 0000000..9251eb5
--- /dev/null
+++ b/tools/gen_kit_icons.py
@@ -0,0 +1,117 @@
+"""Generate kit/intern/kit_icons_data.c from tools/kit_icons_src.py.
+
+The icon shapes are written once, in Python (readable, easy to tweak); this
+records every drawing call each icon makes in a normalized 1x1 box and emits
+compact C tables the kit draws at any size.
+
+ py tools/gen_kit_icons.py
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+import importlib.util
+import os
+import sys
+import types
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(HERE)
+OUT = os.path.join(ROOT, "kit", "intern", "kit_icons_data.c")
+
+OP_LINE, OP_POLY, OP_DISC, OP_RING, OP_RECT, OP_FRAME, OP_BOX = range(7)
+REC = []
+
+
+def _rec(op, color, args, pts=()):
+ REC.append((op, tuple(color), tuple(args), tuple(pts)))
+
+
+fake = types.ModuleType("buipy")
+fake.draw_line = lambda x0, y0, x1, y1, c, w=1.0: _rec(OP_LINE, c, (x0, y0, x1, y1, w))
+fake.draw_polygon = lambda pts, c: _rec(OP_POLY, c, (), pts)
+fake.draw_circle = lambda cx, cy, r, c, filled=True, seg=48: _rec(OP_DISC, c, (cx, cy, r))
+fake.draw_ellipse = lambda cx, cy, rx, ry, c, filled=True, lw=1.0: _rec(
+ OP_RING, c, (cx, cy, rx, ry, lw))
+fake.draw_rect = lambda x, y, w, h, c: _rec(OP_RECT, c, (x, y, w, h))
+fake.draw_widget = lambda x, y, w, h, r, inner, outline, emboss, bottom, corners, lw: _rec(
+ OP_FRAME, outline, (x, y, w, h, r, lw))
+fake.draw_roundrect = lambda x, y, w, h, r, c: _rec(OP_BOX, c, (x, y, w, h, r))
+sys.modules["buipy"] = fake
+
+theme = types.ModuleType("bui.theme")
+theme.TEXT = (1.0, 1.0, 1.0, 1.0)
+theme.with_alpha = lambda c, a: (c[0], c[1], c[2], c[3] * a)
+bui = types.ModuleType("bui")
+bui.theme = theme
+sys.modules["bui"] = bui
+sys.modules["bui.theme"] = theme
+
+spec = importlib.util.spec_from_file_location("kit_icons_src", os.path.join(HERE, "kit_icons_src.py"))
+src = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(src)
+
+PEN_A, PEN_B = (1.0, 0.0, 0.0, 1.0), (0.0, 1.0, 0.0, 1.0)
+
+
+def record(fn, pen):
+ REC.clear()
+ fn(src._Pen(0.0, 0.0, 1.0, pen))
+ return list(REC)
+
+
+def color_mode(ca, cb):
+ """0 = pen color, 1 = pen color * alpha k, 2 = explicit rgba."""
+ if ca[:3] == PEN_A[:3] and cb[:3] == PEN_B[:3]:
+ return (0, 1.0) if abs(ca[3] - 1.0) < 1e-6 else (1, ca[3])
+ return (2, 1.0)
+
+
+def main():
+ names = sorted(src._ICONS)
+ fns = {}
+ for n in names: # aliases share one shape list
+ fns.setdefault(src._ICONS[n], []).append(n)
+ ops, pts, table, shape_of = [], [], [], {}
+ for fn, aliases in fns.items():
+ ra, rb = record(fn, PEN_A), record(fn, PEN_B)
+ first = len(ops)
+ for (op, ca, args, p), (_, cb, _, _) in zip(ra, rb):
+ mode, k = color_mode(ca, cb)
+ a = list(args) + [0.0] * (6 - len(args))
+ ops.append((op, mode, k, ca if mode == 2 else (0, 0, 0, 0), a, len(pts), len(p)))
+ pts.extend(p)
+ for n in aliases:
+ shape_of[n] = (first, len(ops) - first)
+ for n in names:
+ first, count = shape_of[n]
+ tint = src.TINT.get(n)
+ table.append((n, first, count, tint))
+
+ f = lambda v: "%.4ff" % v # noqa: E731
+ out = ["/* Generated by tools/gen_kit_icons.py from tools/kit_icons_src.py — do not edit.",
+ " * SPDX-License-Identifier: GPL-2.0-or-later */",
+ '#include "kit_icons_data.h"', "",
+ "const BKIconOp bk_icon_ops[] = {"]
+ for op, mode, k, c, a, po, pn in ops:
+ out.append(" {%d, %d, %s, {%s}, {%s}, %d, %d}," % (
+ op, mode, f(k), ", ".join(f(x) for x in c), ", ".join(f(x) for x in a), po, pn))
+ out.append("};")
+ out.append("const float bk_icon_pts[][2] = {")
+ for x, y in pts or [(0.0, 0.0)]:
+ out.append(" {%s, %s}," % (f(x), f(y)))
+ out.append("};")
+ out.append("const BKIconDef bk_icon_defs[] = {")
+ out.append(' {"", 0, 0, 0, {0, 0, 0, 0}},') # id 0 = no icon
+ for n, first, count, tint in table:
+ tc = tint or (0, 0, 0, 0)
+ out.append(' {"%s", %d, %d, %d, {%s}},' % (n, first, count, 1 if tint else 0,
+ ", ".join(f(x) for x in tc)))
+ out.append("};")
+ out.append("const int bk_icon_def_count = %d;" % (len(table) + 1))
+ with open(OUT, "w", encoding="utf-8", newline="\n") as fh:
+ fh.write("\n".join(out) + "\n")
+ print("wrote %s: %d icons, %d ops, %d points" % (OUT, len(table), len(ops), len(pts)))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/kit_icons_src.py b/tools/kit_icons_src.py
new file mode 100644
index 0000000..04483e9
--- /dev/null
+++ b/tools/kit_icons_src.py
@@ -0,0 +1,613 @@
+"""Vector icons named after Blender's (``ADD``, ``HIDE_OFF``, ``MODIFIER`` ...).
+
+Blender ships its icons as a bitmap sheet; these are resolution-independent
+vector re-drawings so they stay crisp at any UI scale. Each icon is drawn
+into a square ``(x, y, s)`` box in normalized 0..1 coordinates.
+
+ icons.draw("HIDE_OFF", x, y, size) # default tint
+ icons.draw("ADD", x, y, size, color) # explicit color
+ icons.names() # every available icon
+
+SPDX-License-Identifier: GPL-2.0-or-later
+"""
+
+from __future__ import annotations
+
+import math
+
+import buipy
+
+from bui import theme as T
+
+_ICONS = {}
+
+# Blender colors some icons (properties-editor tabs, data types).
+_ORANGE = (0.93, 0.58, 0.25, 1.0)
+_BLUE = (0.40, 0.62, 0.96, 1.0)
+_GREEN = (0.45, 0.78, 0.40, 1.0)
+_RED = (0.90, 0.36, 0.36, 1.0)
+_PURPLE = (0.70, 0.52, 0.95, 1.0)
+_YELLOW = (0.95, 0.80, 0.30, 1.0)
+TINT = {
+ "OBJECT_DATA": _ORANGE, "MESH_CUBE": _ORANGE, "MODIFIER": _BLUE,
+ "CONSTRAINT": _BLUE, "PHYSICS": _BLUE, "PARTICLES": _BLUE,
+ "MATERIAL": _RED, "WORLD": _RED, "TEXTURE": _RED, "LIGHT": _GREEN,
+ "CAMERA_DATA": _GREEN, "MESH_DATA": _GREEN, "SCENE_DATA": _PURPLE,
+ "ERROR": _YELLOW, "DECORATE_KEYFRAME": _YELLOW, "DECORATE_ANIMATE": _YELLOW,
+}
+
+
+def names():
+ return sorted(_ICONS)
+
+
+def exists(name) -> bool:
+ return name in _ICONS
+
+
+def draw(name, x, y, s, color=None) -> None:
+ """Draw icon ``name`` in the square at (x, y) of side ``s``."""
+ fn = _ICONS.get(name)
+ if fn is None:
+ return
+ if color is None:
+ color = TINT.get(name, T.with_alpha(T.TEXT, 0.9))
+ fn(_Pen(x, y, s, color))
+
+
+def _icon(*names_):
+ def reg(fn):
+ for n in names_:
+ _ICONS[n] = fn
+ return fn
+ return reg
+
+
+class _Pen:
+ """Normalized drawing in an icon box."""
+
+ __slots__ = ("x", "y", "s", "c", "lw")
+
+ def __init__(self, x, y, s, color):
+ self.x, self.y, self.s, self.c = x, y, s, color
+ self.lw = max(1.0, s * 0.085)
+
+ def p(self, u, v):
+ return (self.x + u * self.s, self.y + v * self.s)
+
+ def line(self, *pts, w=1.0, color=None):
+ pts = [self.p(u, v) for u, v in pts]
+ for (x0, y0), (x1, y1) in zip(pts, pts[1:]):
+ buipy.draw_line(x0, y0, x1, y1, color or self.c, self.lw * w)
+
+ def poly(self, *pts, color=None):
+ buipy.draw_polygon([self.p(u, v) for u, v in pts], color or self.c)
+
+ def disc(self, u, v, r, color=None):
+ cx, cy = self.p(u, v)
+ buipy.draw_circle(cx, cy, r * self.s, color or self.c)
+
+ def ring(self, u, v, r, w=1.0, ry=None, color=None):
+ cx, cy = self.p(u, v)
+ buipy.draw_ellipse(cx, cy, r * self.s, (ry if ry is not None else r) * self.s,
+ color or self.c, 0, self.lw * w)
+
+ def rect(self, u, v, w, h, color=None):
+ x, y = self.p(u, v)
+ buipy.draw_rect(x, y, w * self.s, h * self.s, color or self.c)
+
+ def frame(self, u, v, w, h, r=0.08, color=None):
+ x, y = self.p(u, v)
+ buipy.draw_widget(x, y, w * self.s, h * self.s, r * self.s, None,
+ color or self.c, None, None, 15, self.lw)
+
+ def box(self, u, v, w, h, r=0.08, color=None):
+ x, y = self.p(u, v)
+ buipy.draw_roundrect(x, y, w * self.s, h * self.s, r * self.s, color or self.c)
+
+ def arc(self, u, v, r, a0, a1, w=1.0, n=14):
+ """Arc in degrees (0 = right, 90 = up)."""
+ pts = []
+ for i in range(n + 1):
+ a = math.radians(a0 + (a1 - a0) * i / n)
+ pts.append((u + r * math.cos(a), v - r * math.sin(a)))
+ self.line(*pts, w=w)
+
+ def dim(self, k):
+ r, g, b, a = self.c
+ return (r, g, b, a * k)
+
+
+# -- symbols --------------------------------------------------------------------
+
+
+@_icon("ADD", "PLUS")
+def _add(p):
+ p.line((0.5, 0.18), (0.5, 0.82), w=1.2)
+ p.line((0.18, 0.5), (0.82, 0.5), w=1.2)
+
+
+@_icon("REMOVE", "MINUS")
+def _remove(p):
+ p.line((0.18, 0.5), (0.82, 0.5), w=1.2)
+
+
+@_icon("X", "CANCEL", "PANEL_CLOSE")
+def _x(p):
+ p.line((0.24, 0.24), (0.76, 0.76), w=1.2)
+ p.line((0.76, 0.24), (0.24, 0.76), w=1.2)
+
+
+@_icon("CHECKMARK")
+def _check(p):
+ p.line((0.2, 0.52), (0.42, 0.74), (0.82, 0.28), w=1.3)
+
+
+@_icon("SEARCH", "VIEWZOOM")
+def _search(p):
+ p.ring(0.43, 0.43, 0.24)
+ p.line((0.6, 0.6), (0.84, 0.84), w=1.5)
+
+
+@_icon("ZOOM_IN")
+def _zoom_in(p):
+ _search(p)
+ p.line((0.43, 0.32), (0.43, 0.54))
+ p.line((0.32, 0.43), (0.54, 0.43))
+
+
+@_icon("ZOOM_OUT")
+def _zoom_out(p):
+ _search(p)
+ p.line((0.32, 0.43), (0.54, 0.43))
+
+
+@_icon("TRIA_DOWN")
+def _tri_down(p):
+ p.poly((0.22, 0.36), (0.78, 0.36), (0.5, 0.7))
+
+
+@_icon("TRIA_UP")
+def _tri_up(p):
+ p.poly((0.22, 0.64), (0.78, 0.64), (0.5, 0.3))
+
+
+@_icon("TRIA_RIGHT")
+def _tri_right(p):
+ p.poly((0.36, 0.22), (0.36, 0.78), (0.7, 0.5))
+
+
+@_icon("TRIA_LEFT")
+def _tri_left(p):
+ p.poly((0.64, 0.22), (0.64, 0.78), (0.3, 0.5))
+
+
+@_icon("DOWNARROW_HLT")
+def _chev_down(p):
+ p.line((0.25, 0.4), (0.5, 0.64), (0.75, 0.4), w=1.1)
+
+
+@_icon("RIGHTARROW")
+def _chev_right(p):
+ p.line((0.4, 0.25), (0.64, 0.5), (0.4, 0.75), w=1.1)
+
+
+@_icon("INFO")
+def _info(p):
+ p.ring(0.5, 0.5, 0.36)
+ p.disc(0.5, 0.32, 0.055)
+ p.line((0.5, 0.44), (0.5, 0.7), w=1.2)
+
+
+@_icon("ERROR")
+def _error(p):
+ p.poly((0.5, 0.1), (0.92, 0.86), (0.08, 0.86))
+ k = (0.1, 0.1, 0.1, 1.0)
+ p.line((0.5, 0.36), (0.5, 0.62), w=1.3, color=k)
+ p.disc(0.5, 0.74, 0.05, color=k)
+
+
+@_icon("QUESTION")
+def _question(p):
+ p.ring(0.5, 0.5, 0.36)
+ p.arc(0.5, 0.42, 0.11, 160, -60)
+ p.line((0.55, 0.51), (0.5, 0.56), (0.5, 0.62))
+ p.disc(0.5, 0.72, 0.045)
+
+
+@_icon("DOT", "DECORATE", "LAYER_USED")
+def _dot(p):
+ p.disc(0.5, 0.5, 0.09)
+
+
+@_icon("DECORATE_KEYFRAME", "KEYFRAME_HLT")
+def _key_filled(p):
+ p.poly((0.5, 0.2), (0.8, 0.5), (0.5, 0.8), (0.2, 0.5))
+
+
+@_icon("DECORATE_ANIMATE", "KEYFRAME")
+def _key_open(p):
+ p.line((0.5, 0.2), (0.8, 0.5), (0.5, 0.8), (0.2, 0.5), (0.5, 0.2))
+
+
+@_icon("GRIP", "OPTIONS")
+def _grip(p):
+ for u in (0.36, 0.64):
+ for v in (0.25, 0.5, 0.75):
+ p.disc(u, v, 0.06)
+
+
+@_icon("COLLAPSEMENU", "MENU_PANEL")
+def _hamburger(p):
+ for v in (0.3, 0.5, 0.7):
+ p.line((0.2, v), (0.8, v), w=1.1)
+
+
+# -- visibility / state ---------------------------------------------------------------
+
+
+@_icon("HIDE_OFF", "RESTRICT_VIEW_OFF")
+def _eye(p):
+ p.arc(0.5, 0.86, 0.5, 135, 45, w=1.1)
+ p.arc(0.5, 0.14, 0.5, -135, -45, w=1.1)
+ p.disc(0.5, 0.5, 0.14)
+
+
+@_icon("HIDE_ON", "RESTRICT_VIEW_ON")
+def _eye_closed(p):
+ p.arc(0.5, 0.14, 0.5, -140, -40, w=1.1)
+ for u, v, du, dv in ((0.5, 0.64, 0.0, 0.14), (0.3, 0.6, -0.07, 0.12),
+ (0.7, 0.6, 0.07, 0.12)):
+ p.line((u, v), (u + du, v + dv))
+
+
+@_icon("RESTRICT_SELECT_OFF")
+def _pointer(p):
+ p.poly((0.28, 0.12), (0.28, 0.82), (0.45, 0.66), (0.58, 0.9), (0.68, 0.85),
+ (0.56, 0.62), (0.78, 0.6))
+
+
+@_icon("RESTRICT_SELECT_ON")
+def _pointer_off(p):
+ p.c = p.dim(0.35)
+ _pointer(p)
+
+
+@_icon("RESTRICT_RENDER_OFF", "RENDER_STILL", "CAMERA_DATA", "SCENE")
+def _camera(p):
+ p.box(0.12, 0.34, 0.56, 0.42, 0.08)
+ p.poly((0.68, 0.5), (0.9, 0.36), (0.9, 0.76), (0.68, 0.62))
+ p.ring(0.32, 0.24, 0.1)
+ p.ring(0.52, 0.24, 0.1)
+
+
+@_icon("RESTRICT_RENDER_ON")
+def _camera_off(p):
+ p.c = p.dim(0.35)
+ _camera(p)
+
+
+@_icon("LOCKED")
+def _locked(p):
+ p.box(0.22, 0.46, 0.56, 0.42, 0.08)
+ p.arc(0.5, 0.46, 0.18, 0, 180)
+
+
+@_icon("UNLOCKED")
+def _unlocked(p):
+ p.box(0.22, 0.46, 0.56, 0.42, 0.08)
+ p.arc(0.68, 0.38, 0.16, 0, 180)
+
+
+@_icon("PINNED")
+def _pinned(p):
+ p.line((0.5, 0.56), (0.5, 0.9), w=1.1)
+ p.box(0.3, 0.12, 0.4, 0.3, 0.06)
+ p.rect(0.2, 0.44, 0.6, 0.12)
+
+
+@_icon("UNPINNED")
+def _unpinned(p):
+ p.line((0.44, 0.56), (0.18, 0.86), w=1.1)
+ p.poly((0.5, 0.1), (0.9, 0.5), (0.6, 0.6), (0.4, 0.4))
+
+
+@_icon("FAKE_USER_OFF")
+def _shield_off(p):
+ p.line((0.5, 0.12), (0.82, 0.24), (0.78, 0.6), (0.5, 0.88), (0.22, 0.6),
+ (0.18, 0.24), (0.5, 0.12))
+
+
+@_icon("FAKE_USER_ON")
+def _shield_on(p):
+ p.poly((0.5, 0.12), (0.82, 0.24), (0.78, 0.6), (0.5, 0.88), (0.22, 0.6), (0.18, 0.24))
+
+
+@_icon("LINKED")
+def _linked(p):
+ p.ring(0.36, 0.5, 0.18, ry=0.12)
+ p.ring(0.64, 0.5, 0.18, ry=0.12)
+
+
+@_icon("UNLINKED")
+def _unlinked(p):
+ p.ring(0.28, 0.5, 0.16, ry=0.11)
+ p.ring(0.72, 0.5, 0.16, ry=0.11)
+
+
+# -- files / edit --------------------------------------------------------------------------
+
+
+@_icon("FILE_FOLDER", "FILEBROWSER", "FOLDER_REDIRECT")
+def _folder(p):
+ p.poly((0.1, 0.24), (0.4, 0.24), (0.48, 0.34), (0.9, 0.34), (0.9, 0.82), (0.1, 0.82))
+
+
+@_icon("FILE", "FILE_BLANK", "NEW")
+def _file(p):
+ p.line((0.24, 0.1), (0.6, 0.1), (0.78, 0.28), (0.78, 0.9), (0.24, 0.9), (0.24, 0.1))
+ p.line((0.6, 0.1), (0.6, 0.28), (0.78, 0.28))
+
+
+@_icon("DUPLICATE", "COPYDOWN")
+def _duplicate(p):
+ p.frame(0.14, 0.14, 0.5, 0.5, 0.06)
+ p.box(0.38, 0.38, 0.5, 0.5, 0.06)
+
+
+@_icon("PASTEDOWN")
+def _paste(p):
+ p.frame(0.18, 0.18, 0.64, 0.7, 0.06)
+ p.box(0.34, 0.1, 0.32, 0.16, 0.04)
+
+
+@_icon("TRASH")
+def _trash(p):
+ p.line((0.16, 0.24), (0.84, 0.24), w=1.2)
+ p.line((0.38, 0.24), (0.42, 0.12), (0.58, 0.12), (0.62, 0.24))
+ p.line((0.24, 0.3), (0.3, 0.88), (0.7, 0.88), (0.76, 0.3))
+ p.line((0.5, 0.38), (0.5, 0.78))
+
+
+@_icon("EYEDROPPER")
+def _eyedropper(p):
+ p.line((0.16, 0.84), (0.56, 0.44), w=1.4)
+ p.poly((0.5, 0.36), (0.72, 0.14), (0.86, 0.28), (0.64, 0.5))
+ p.line((0.44, 0.32), (0.68, 0.56), w=1.2)
+
+
+@_icon("EXPORT")
+def _export(p):
+ p.line((0.2, 0.55), (0.2, 0.86), (0.8, 0.86), (0.8, 0.55))
+ p.line((0.5, 0.66), (0.5, 0.14), w=1.2)
+ p.line((0.32, 0.32), (0.5, 0.14), (0.68, 0.32), w=1.2)
+
+
+@_icon("IMPORT")
+def _import(p):
+ p.line((0.2, 0.55), (0.2, 0.86), (0.8, 0.86), (0.8, 0.55))
+ p.line((0.5, 0.12), (0.5, 0.66), w=1.2)
+ p.line((0.32, 0.48), (0.5, 0.66), (0.68, 0.48), w=1.2)
+
+
+@_icon("LOOP_BACK", "UNDO")
+def _undo(p):
+ p.arc(0.54, 0.54, 0.28, 150, -110, w=1.1)
+ p.poly((0.12, 0.3), (0.36, 0.24), (0.26, 0.48))
+
+
+@_icon("LOOP_FORWARDS", "REDO")
+def _redo(p):
+ p.arc(0.46, 0.54, 0.28, 30, 290, w=1.1)
+ p.poly((0.88, 0.3), (0.64, 0.24), (0.74, 0.48))
+
+
+@_icon("SORTALPHA")
+def _sort(p):
+ for i, w in enumerate((0.3, 0.45, 0.6)):
+ p.line((0.2, 0.3 + i * 0.2), (0.2 + w, 0.3 + i * 0.2), w=1.1)
+
+
+@_icon("FILTER")
+def _filter(p):
+ p.poly((0.12, 0.18), (0.88, 0.18), (0.58, 0.52), (0.58, 0.84), (0.42, 0.76), (0.42, 0.52))
+
+
+@_icon("HOME")
+def _home(p):
+ p.poly((0.5, 0.12), (0.88, 0.48), (0.12, 0.48))
+ p.rect(0.24, 0.48, 0.52, 0.38)
+
+
+@_icon("FULLSCREEN_ENTER")
+def _fullscreen(p):
+ for (u, v), (du, dv) in (((0.16, 0.16), (1, 1)), ((0.84, 0.16), (-1, 1)),
+ ((0.16, 0.84), (1, -1)), ((0.84, 0.84), (-1, -1))):
+ p.line((u, v + 0.24 * dv), (u, v), (u + 0.24 * du, v), w=1.1)
+
+
+# -- playback ------------------------------------------------------------------------------
+
+
+@_icon("PLAY")
+def _play(p):
+ p.poly((0.3, 0.16), (0.3, 0.84), (0.82, 0.5))
+
+
+@_icon("PAUSE")
+def _pause(p):
+ p.rect(0.26, 0.18, 0.16, 0.64)
+ p.rect(0.58, 0.18, 0.16, 0.64)
+
+
+@_icon("REW")
+def _rew(p):
+ p.rect(0.16, 0.2, 0.1, 0.6)
+ p.poly((0.82, 0.2), (0.82, 0.8), (0.3, 0.5))
+
+
+@_icon("FF")
+def _ff(p):
+ p.rect(0.74, 0.2, 0.1, 0.6)
+ p.poly((0.18, 0.2), (0.18, 0.8), (0.7, 0.5))
+
+
+@_icon("REC")
+def _rec(p):
+ p.disc(0.5, 0.5, 0.3, color=(0.9, 0.25, 0.25, 1.0))
+
+
+# -- data / editors ------------------------------------------------------------------------
+
+
+@_icon("PREFERENCES", "SETTINGS", "TOOL_SETTINGS")
+def _gear(p):
+ for i in range(8):
+ a = math.radians(i * 45)
+ p.line((0.5 + 0.22 * math.cos(a), 0.5 + 0.22 * math.sin(a)),
+ (0.5 + 0.4 * math.cos(a), 0.5 + 0.4 * math.sin(a)), w=1.8)
+ p.ring(0.5, 0.5, 0.24, w=1.6)
+
+
+@_icon("MODIFIER", "PROPERTIES")
+def _wrench(p):
+ p.line((0.22, 0.8), (0.58, 0.44), w=2.0)
+ p.ring(0.66, 0.34, 0.16, w=1.6)
+
+
+@_icon("OBJECT_DATA", "OBJECT_DATAMODE")
+def _object(p):
+ p.poly((0.5, 0.12), (0.86, 0.32), (0.86, 0.7), (0.5, 0.9), (0.14, 0.7), (0.14, 0.32))
+ k = (0.0, 0.0, 0.0, 0.45)
+ p.line((0.14, 0.32), (0.5, 0.52), (0.86, 0.32), color=k)
+ p.line((0.5, 0.52), (0.5, 0.9), color=k)
+
+
+@_icon("MESH_CUBE", "CUBE", "MESH_DATA", "EDITMODE_HLT")
+def _cube(p):
+ p.line((0.5, 0.12), (0.86, 0.32), (0.86, 0.7), (0.5, 0.9), (0.14, 0.7), (0.14, 0.32),
+ (0.5, 0.12))
+ p.line((0.14, 0.32), (0.5, 0.52), (0.86, 0.32))
+ p.line((0.5, 0.52), (0.5, 0.9))
+
+
+@_icon("LIGHT", "LIGHT_DATA", "OUTLINER_OB_LIGHT")
+def _light(p):
+ p.disc(0.5, 0.42, 0.22)
+ p.rect(0.4, 0.66, 0.2, 0.18)
+
+
+@_icon("MATERIAL", "SHADING_RENDERED", "NODE_MATERIAL")
+def _material(p):
+ p.disc(0.5, 0.5, 0.36)
+ p.disc(0.4, 0.4, 0.1, color=(1.0, 1.0, 1.0, 0.7))
+
+
+@_icon("WORLD", "WORLD_DATA")
+def _world(p):
+ p.ring(0.5, 0.5, 0.36)
+ p.ring(0.5, 0.5, 0.16, ry=0.36)
+ p.line((0.14, 0.5), (0.86, 0.5))
+
+
+@_icon("TEXTURE", "IMAGE_DATA", "IMAGE")
+def _texture(p):
+ for i in range(3):
+ for j in range(3):
+ if (i + j) % 2 == 0:
+ p.rect(0.16 + i * 0.23, 0.16 + j * 0.23, 0.23, 0.23)
+ p.frame(0.16, 0.16, 0.69, 0.69, 0.04)
+
+
+@_icon("SCENE_DATA")
+def _scene(p):
+ p.disc(0.3, 0.66, 0.14)
+ p.poly((0.5, 0.18), (0.82, 0.82), (0.5, 0.82))
+ p.rect(0.12, 0.84, 0.76, 0.06)
+
+
+@_icon("COLLECTION", "OUTLINER_COLLECTION", "GROUP")
+def _collection(p):
+ p.frame(0.16, 0.24, 0.68, 0.56, 0.1)
+ p.line((0.16, 0.42), (0.84, 0.42))
+
+
+@_icon("OUTLINER")
+def _outliner(p):
+ for i, d in enumerate((0, 0.14, 0.14, 0)):
+ v = 0.22 + i * 0.19
+ p.rect(0.16 + d, v - 0.05, 0.1, 0.1)
+ p.line((0.32 + d, v), (0.84, v))
+
+
+@_icon("CONSTRAINT")
+def _constraint(p):
+ p.ring(0.32, 0.5, 0.18, ry=0.12)
+ p.ring(0.68, 0.5, 0.18, ry=0.12)
+ p.line((0.4, 0.5), (0.6, 0.5), w=1.3)
+
+
+@_icon("PHYSICS")
+def _physics(p):
+ p.ring(0.5, 0.5, 0.38, ry=0.14)
+ p.disc(0.5, 0.5, 0.14)
+
+
+@_icon("PARTICLES")
+def _particles(p):
+ for u, v, r in ((0.3, 0.3, 0.1), (0.7, 0.36, 0.08), (0.42, 0.7, 0.12), (0.76, 0.74, 0.07)):
+ p.disc(u, v, r)
+
+
+@_icon("CURVE_DATA", "CURVE_BEZCURVE")
+def _curve(p):
+ pts = []
+ for i in range(13):
+ t = i / 12
+ pts.append((0.14 + 0.72 * t, 0.7 - 0.5 * math.sin(math.pi * t) * (1 - 0.3 * t)))
+ p.line(*pts, w=1.1)
+
+
+@_icon("NODE", "NODETREE")
+def _node(p):
+ p.box(0.1, 0.16, 0.34, 0.3, 0.06)
+ p.box(0.56, 0.54, 0.34, 0.3, 0.06)
+ p.line((0.44, 0.31), (0.5, 0.31), (0.5, 0.69), (0.56, 0.69))
+
+
+@_icon("BRUSH_DATA", "SCULPTMODE_HLT")
+def _brush(p):
+ p.line((0.8, 0.14), (0.42, 0.56), w=1.6)
+ p.poly((0.42, 0.5), (0.5, 0.6), (0.3, 0.86), (0.14, 0.86), (0.18, 0.7))
+
+
+@_icon("SNAP_ON")
+def _magnet(p):
+ p.arc(0.5, 0.48, 0.26, 180, 360, w=2.2)
+ p.line((0.24, 0.48), (0.24, 0.18), w=2.2)
+ p.line((0.76, 0.48), (0.76, 0.18), w=2.2)
+
+
+@_icon("PROP_ON")
+def _proportional(p):
+ p.ring(0.5, 0.5, 0.36)
+ p.ring(0.5, 0.5, 0.2)
+ p.disc(0.5, 0.5, 0.07)
+
+
+@_icon("VIEW_CAMERA")
+def _view_camera(p):
+ p.frame(0.14, 0.24, 0.72, 0.52, 0.06)
+ p.poly((0.4, 0.38), (0.4, 0.62), (0.62, 0.5))
+
+
+@_icon("TIME", "PREVIEW_RANGE")
+def _clock(p):
+ p.ring(0.5, 0.5, 0.36)
+ p.line((0.5, 0.28), (0.5, 0.5), (0.66, 0.6))
+
+
+@_icon("TEXT", "FONT_DATA")
+def _text(p):
+ p.line((0.2, 0.2), (0.8, 0.2), w=1.3)
+ p.line((0.5, 0.2), (0.5, 0.84), w=1.3)
diff --git a/types/dna/include/DNA_action_types.h b/types/dna/include/DNA_action_types.h
index e280571..211e043 100644
--- a/types/dna/include/DNA_action_types.h
+++ b/types/dna/include/DNA_action_types.h
@@ -1,4 +1,4 @@
-/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
*
* SPDX-License-Identifier: GPL-2.0-or-later */
@@ -20,6 +20,9 @@
#include "DNA_session_uid_types.h"
#include "DNA_userdef_types.h" /* ThemeWireColor */
#include "DNA_view2d_types.h"
+#ifdef __cplusplus
+# include "GPU_batch.hh"
+#endif
#include "BLI_enum_flags.hh"
@@ -34,10 +37,15 @@ struct FCurve;
struct GHash;
struct Object;
struct SpaceLink;
+#ifdef __cplusplus
namespace gpu {
-class VertBuf;
-class Batch;
+using VertBuf = ::GPUVertBuf;
+using Batch = ::GPUBatch;
} // namespace gpu
+#else
+struct GPUVertBuf;
+struct GPUBatch;
+#endif
/* Forward declarations so the actual declarations can happen top-down. */
struct ActionLayer;
@@ -1362,3 +1370,4 @@ static_assert(
#endif
} // namespace blender
+
diff --git a/types/dna/include/DNA_listBase.h b/types/dna/include/DNA_listBase.h
index 73c7b05..83ccf7d 100644
--- a/types/dna/include/DNA_listBase.h
+++ b/types/dna/include/DNA_listBase.h
@@ -2,9 +2,9 @@
*
* SPDX-License-Identifier: GPL-2.0-or-later */
-/** \file
+/** ile
* \ingroup DNA
- * \brief These structs are the foundation for all linked lists in the library system.
+ * rief These structs are the foundation for all linked lists in the library system.
*
* Doubly-linked lists start from a ListBase and contain elements beginning
* with Link.
@@ -12,44 +12,40 @@
#pragma once
-namespace blender {
-
-/** Generic - all structs which are put into linked lists begin with this. */
+/* The de-C++ified core (core/include/DNA_listBase.h, shared through the
+ * BUI_DNA_LISTBASE_SHARED guard) owns the global struct definitions. The
+ * blender-qualified names below alias onto them so DNA structs and the C
+ * listbase API share exactly one type. */
+#ifndef BUI_DNA_LISTBASE_SHARED
+#define BUI_DNA_LISTBASE_SHARED
+typedef struct Link Link;
+typedef struct LinkData LinkData;
+typedef struct ListBase ListBase;
struct Link {
struct Link *next, *prev;
};
-
-/** Simple subclass of Link. Use this when it is not worth defining a custom one. */
struct LinkData {
struct LinkData *next, *prev;
void *data;
};
-
-/**
- * The basic double linked-list structure.
- *
- * \warning Never change the size/definition of this struct! The #init_structDNA
- * function (from dna_genfile.cc) uses it to compute the #pointer_size.
- */
struct ListBase {
void *first, *last;
};
+#endif
+
+#include "BLI_listbase_iterator.hh"
-#ifdef __cplusplus
+namespace blender {
-template<typename T> struct ListBaseTIterator;
-template<typename T> struct ListBaseEnumerateWrapper;
-template<typename T> struct ListBaseMutableWrapper;
-template<typename T> struct ListBaseBackwardWrapper;
-template<typename T> struct ListBaseMutableBackwardWrapper;
+using Link = ::Link;
+using LinkData = ::LinkData;
+using ListBase = ::ListBase;
/**
* This is a thin wrapper around #ListBase to make it type-safe. It's designed to be used in DNA
* structs. It is written as untyped #ListBase in .blend files for compatibility.
*/
template<typename T> struct ListBaseT : public ListBase {
- /* TODO: Add const and non-const iterators. However this will require some refactoring
- * as some places rely on being able to get a mutable list element from a const list. */
ListBaseTIterator<T> begin() const
{
return ListBaseTIterator<T>{static_cast<T *>(this->first)};
@@ -110,8 +106,4 @@ template<typename T> struct ListBaseT : public ListBase {
}
};
-#endif
-
-/* 8 byte alignment! */
-
} // namespace blender
diff --git a/types/dna/include/DNA_vec_types.h b/types/dna/include/DNA_vec_types.h
index 0f872ba..6d73a6c 100644
--- a/types/dna/include/DNA_vec_types.h
+++ b/types/dna/include/DNA_vec_types.h
@@ -1,4 +1,4 @@
-/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
+/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
*
* SPDX-License-Identifier: GPL-2.0-or-later */
@@ -8,6 +8,77 @@
#pragma once
+/* BUI: rectangles and DualQuat are defined once inside namespace blender
+ * (upstream layout) and aliased into the global namespace so plain C-style
+ * `rctf` usage works in C++ TUs. Pure-C consumers get real global struct
+ * definitions instead. */
+#ifdef __cplusplus
+
+namespace blender {
+
+/** integer rectangle. */
+struct rcti {
+ int xmin, xmax;
+ int ymin, ymax;
+
+ bool operator==(const rcti &other) const
+ {
+ return xmin == other.xmin && xmax == other.xmax && ymin == other.ymin && ymax == other.ymax;
+ }
+ bool operator!=(const rcti &other) const
+ {
+ return !(*this == other);
+ }
+};
+
+/** float rectangle. */
+struct rctf {
+ float xmin, xmax;
+ float ymin, ymax;
+};
+
+/** dual quaternion. */
+struct DualQuat {
+ float quat[4] = {};
+ float trans[4] = {};
+
+ float scale[4][4] = {};
+ float scale_weight = 0;
+};
+
+} // namespace blender
+
+using rcti = blender::rcti;
+using rctf = blender::rctf;
+using DualQuat = blender::DualQuat;
+
+#else /* !__cplusplus */
+
+typedef struct rcti rcti;
+struct rcti {
+ int xmin, xmax;
+ int ymin, ymax;
+};
+
+typedef struct rctf rctf;
+struct rctf {
+ float xmin, xmax;
+ float ymin, ymax;
+};
+
+/** dual quaternion. */
+typedef struct DualQuat DualQuat;
+struct DualQuat {
+ float quat[4];
+ float trans[4];
+
+ float scale[4][4];
+ float scale_weight;
+};
+
+#endif /* !__cplusplus */
+
+#ifdef __cplusplus
namespace blender {
/* types */
@@ -29,9 +100,10 @@ struct vec2i {
/* not used at the moment */
/*
struct vec2d {
- double x, y;
+ double x, y, z, w;
};
*/
+
struct vec3i {
int x, y, z;
};
@@ -39,7 +111,7 @@ struct vec3i {
struct vec3f {
float x, y, z;
};
-/*
+
struct vec3d {
double x, y, z;
};
@@ -47,12 +119,19 @@ struct vec3d {
struct vec4i {
int x, y, z, w;
};
-*/
+
struct vec4f {
float x, y, z, w;
};
/**
+ * A vector of four doubles.
+ */
+struct vec4d {
+ double x, y, z, w;
+};
+
+/*
* This type generally shouldn't be used. It only exists for cases where a DNA type that
* corresponds to `blender:float4x4` is required. Note that `float4x4` is 16 byte aligned, but we
* can't enforce that this struct yet.
@@ -66,36 +145,5 @@ struct vec4d {
};
*/
-/** integer rectangle. */
-struct rcti {
- int xmin, xmax;
- int ymin, ymax;
-
-#ifdef __cplusplus
- bool operator==(const rcti &other) const
- {
- return xmin == other.xmin && xmax == other.xmax && ymin == other.ymin && ymax == other.ymax;
- }
- bool operator!=(const rcti &other) const
- {
- return !(*this == other);
- }
-#endif
-};
-
-/** float rectangle. */
-struct rctf {
- float xmin, xmax;
- float ymin, ymax;
-};
-
-/** dual quaternion. */
-struct DualQuat {
- float quat[4] = {};
- float trans[4] = {};
-
- float scale[4][4] = {};
- float scale_weight = 0;
-};
-
} // namespace blender
+#endif /* __cplusplus */
diff --git a/ui/CMakeLists.txt b/ui/CMakeLists.txt
index a2e8798..9a951d9 100644
--- a/ui/CMakeLists.txt
+++ b/ui/CMakeLists.txt
@@ -42,6 +42,12 @@ if(BUI_BUILD_UI)
${CMAKE_SOURCE_DIR}/gpu/include
)
target_link_libraries(bui_ui PUBLIC bui::core bui::types bui::gpu bui::compat)
+ # Upstream headers rely on transitive math includes that the de-namespaced
+ # core no longer provides implicitly.
+ target_compile_options(bui_ui PRIVATE
+ "-includeBLI_math_vector.h"
+ "-includeBLI_math_color.h"
+ )
else()
# Headers-only target: lets consumers resolve UI_* headers without compiling.
add_library(bui_ui INTERFACE)
diff --git a/ui/include/UI_interface_layout.hh b/ui/include/UI_interface_layout.hh
new file mode 100644
index 0000000..1c3f91e
--- /dev/null
+++ b/ui/include/UI_interface_layout.hh
@@ -0,0 +1,1027 @@
+/* SPDX-FileCopyrightText: 2025 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+#include <functional>
+#include <optional>
+
+#include "BLI_enum_flags.hh"
+#include "BLI_math_vector_types.hh"
+#include "BLI_string_ref.hh"
+#include "BLI_utility_mixins.hh"
+#include "BLI_vector.hh"
+
+#include "UI_interface_types.hh"
+
+namespace blender {
+
+struct bContext;
+struct bContextStore;
+struct EnumPropertyItem;
+struct IDProperty;
+struct uiList;
+struct uiStyle;
+struct MenuType;
+struct PanelType;
+struct Panel;
+struct PointerRNA;
+struct PropertyRNA;
+struct StructRNA;
+struct wmOperatorType;
+struct TextboxState;
+
+namespace wm {
+enum class OpCallContext : int8_t;
+}
+
+/* Layout
+ *
+ * More automated layout of buttons. Has three levels:
+ * - Layout: contains a number templates, within a bounded width or height.
+ * - Template: predefined layouts for buttons with a number of slots, each
+ * slot can contain multiple items.
+ * - Item: item to put in a template slot, being either an RNA property,
+ * operator, label or menu. Also regular buttons can be used when setting
+ * uiBlockCurLayout. */
+
+namespace ui {
+enum class ItemType : int8_t;
+enum class ItemInternalFlag : uint8_t;
+enum class EmbossType : uint8_t;
+enum class LayoutAlign : int8_t;
+enum class ButProgressType : int8_t;
+enum class LayoutDirection : int8_t;
+enum class AlertIcon : int8_t;
+
+struct ItemInternal;
+struct LayoutInternal;
+struct Layout;
+struct LayoutRoot;
+
+struct PanelLayout {
+ Layout *header;
+ Layout *body;
+};
+
+struct Item {
+
+ Item(ItemType type);
+ Item(const Item &) = default;
+ virtual ~Item() = default;
+
+ [[nodiscard]] bool fixed_size() const;
+ void fixed_size_set(bool fixed_size);
+
+ [[nodiscard]] ItemType type() const;
+
+ [[nodiscard]] int2 size() const;
+ [[nodiscard]] int2 offset() const;
+
+ protected:
+ ItemInternalFlag flag_ = {};
+ ItemType type_ = {};
+
+ friend struct ItemInternal;
+};
+
+enum eUI_Item_Flag : uint16_t;
+
+enum class LayoutSeparatorType : int8_t {
+ Auto,
+ Space,
+ Line,
+};
+
+enum class NodeAssetMenuOperatorType : int8_t {
+ Add,
+ Swap,
+};
+
+/**
+ * Panel popup draw direction.
+ */
+enum class PopupAttachDirection : int8_t {
+ Vertical = 0,
+ Horizontal = 1,
+};
+
+enum class EnumTabExpand {
+ Default = 0,
+ Row,
+};
+
+struct Layout : public Item, NonCopyable, NonMovable {
+ protected:
+ LayoutRoot *root_ = nullptr;
+ bContextStore *context_ = nullptr;
+ Layout *parent_ = nullptr;
+ std::string heading_;
+
+ Vector<Item *> items_;
+
+ /** Sub layout to add child items, if not the layout itself. */
+ Layout *child_items_layout_ = nullptr;
+
+ int x_ = 0, y_ = 0, w_ = 0, h_ = 0;
+
+ short space_ = 0;
+
+ float scale_[2] = {0.0f, 0.0f};
+ bool align_ = false;
+ bool active_ = false;
+ bool active_default_ = false;
+ bool activate_init_ = false;
+ bool enabled_ = false;
+ bool redalert_ = false;
+ /** For layouts inside grid-flow, they and their items shall never have a fixed maximal size. */
+ bool variable_size_ = false;
+ LayoutAlign alignment_ = {};
+ EmbossType emboss_ = {};
+ /** for fixed width or height to avoid UI size changes */
+ float units_[2] = {0.0f, 0.0f};
+ /** Is copied to uiButs created in this layout. */
+ float search_weight_ = 0.0f;
+
+ public:
+ Layout(ItemType type, LayoutRoot *root);
+
+ [[nodiscard]] bool active() const;
+ /**
+ * Sets the active state of the layout and its items.
+ * When false the layout and its buttons are grayed out, user can still interact with them but
+ * generally they will not have an active use.
+ */
+ void active_set(bool active);
+
+ [[nodiscard]] bool active_default() const;
+ /**
+ * When set to true the next operator button added in the layout will be highlighted as default
+ * action when pressing return, in popup dialogs this overrides default confirmation buttons.
+ */
+ void active_default_set(bool active_default);
+
+ [[nodiscard]] bool activate_init() const;
+ /**
+ * When set to true, the next button added in the layout will be activated on first display.
+ * Only for popups dialogs and only the first button in the popup with this flag will be
+ * activated.
+ */
+ void activate_init_set(bool activate_init);
+
+ [[nodiscard]] LayoutAlign alignment() const;
+ void alignment_set(LayoutAlign alignment);
+
+ [[nodiscard]] Block *block() const;
+
+ void context_copy(const bContextStore *context);
+
+ [[nodiscard]] const PointerRNA *context_ptr_get(const StringRef name,
+ const StructRNA *type) const;
+ void context_ptr_set(StringRef name, const PointerRNA *ptr);
+
+ [[nodiscard]] std::optional<StringRefNull> context_string_get(const StringRef name) const;
+ void context_string_set(StringRef name, StringRef value);
+
+ [[nodiscard]] std::optional<int64_t> context_int_get(const StringRef name) const;
+ void context_int_set(StringRef name, int64_t value);
+
+ /** Only for convenience. */
+ void context_set_from_but(const Button *but);
+
+ [[nodiscard]] bContextStore *context_store() const;
+
+ [[nodiscard]] bool enabled() const;
+ /**
+ * Sets the enabled state of the layout and its items.
+ * When false the layout and its buttons are grayed out, user can't interaction with them, only
+ * buttons tooltips are available on hovering.
+ */
+ void enabled_set(bool enabled);
+
+ [[nodiscard]] EmbossType emboss() const;
+ void emboss_set(EmbossType emboss);
+
+ [[nodiscard]] LayoutDirection local_direction() const;
+
+ [[nodiscard]] wm::OpCallContext operator_context() const;
+ /** Sets the default call context for new operator buttons added in any #root_ sub-layout. */
+ void operator_context_set(wm::OpCallContext opcontext);
+
+ [[nodiscard]] bool red_alert() const;
+ /**
+ * When set to true new items added in the layout are highlighted with the error state
+ * color #TH_REDALERT.
+ */
+ void red_alert_set(bool red_alert);
+
+ [[nodiscard]] Panel *root_panel() const;
+
+ [[nodiscard]] float scale_x() const;
+ void scale_x_set(float scale);
+
+ [[nodiscard]] float scale_y() const;
+ void scale_y_set(float scale);
+
+ [[nodiscard]] float search_weight() const;
+ void search_weight_set(float weight);
+
+ [[nodiscard]] float ui_units_x() const;
+ /** Sets a fixed width size for this layout. */
+ void ui_units_x_set(float width);
+
+ [[nodiscard]] float ui_units_y() const;
+ /** Sets a fixed height size for this layout. */
+ void ui_units_y_set(float height);
+
+ [[nodiscard]] bool use_property_split() const;
+ /**
+ * Sets when to split property's label into a separate button when adding new property buttons.
+ */
+ void use_property_split_set(bool value);
+
+ [[nodiscard]] bool use_property_decorate() const;
+ /**
+ * Sets when to add an extra button to insert keyframes next to new property buttons added in the
+ * layout.
+ */
+ void use_property_decorate_set(bool is_sep);
+
+ [[nodiscard]] int width() const;
+
+ /** Sub-layout items. */
+
+ Layout &absolute(bool align = false);
+
+ /**
+ * Add a new box sub-layout, items placed in this sub-layout are added vertically one under
+ * each other in a column and are surrounded by a box.
+ */
+ Layout &box();
+ /**
+ * Add a new column sub-layout, items placed in this sub-layout are added vertically one under
+ * each other in a column.
+ */
+ Layout &column(bool align);
+ /**
+ * Add a new column sub-layout, items placed in this sub-layout are added vertically one under
+ * each other in a column.
+ * \param heading: Heading label to set to the first child element added in the sub-layout
+ * through #Layout::prop. When property split is used, this heading label is set in the split
+ * label column when there is no label defined.
+ */
+ Layout &column(bool align, StringRef heading);
+
+ /**
+ * Add a new row sub-layout, items placed in this sub-layout are added horizontally next to each
+ * other in row.
+ */
+ Layout &row(bool align);
+ /**
+ * Add a new row sub-layout, items placed in this sub-layout are added horizontally next to each
+ * other in row.
+ * \param heading: Heading label to set to the first child element added in the sub-layout
+ * through #Layout::prop. When property split is used, this heading label is set in the split
+ * label column when there is no label defined.
+ */
+ Layout &row(bool align, StringRef heading);
+
+ /**
+ * Add a new column flow sub-layout, items placed in this sub-layout would be evenly distributed
+ * in columns.
+ * \param number: the number of columns in which items are distributed.
+ */
+ Layout &column_flow(int number, bool align);
+ /**
+ * Add a new grid flow sub-layout, items placed in this sub-layout would be distributed in a
+ * grid.
+ * \param row_major: When true items are distributed by rows, otherwise items are distributed by
+ * columns.
+ * \param columns_len: When positive is the fixed number of columns to show, when 0 its automatic
+ * defined, when negative its an automatic stepped number of columns/rows to show (e.g. when \a
+ * row_major is true -3 will automatically show (1,2,3,6,9,...) columns, or when \a row_major is
+ * false -3 will automatically show (3,6,9,...) rows).
+ * \param even_columns: All columns will have the same width.
+ * \param even_rows: All rows will have the same height.
+ */
+ Layout &grid_flow(
+ bool row_major, int columns_len, bool even_columns, bool even_rows, bool align);
+
+ /** Add a new list box sub-layout. */
+ Layout &list_box(uiList *ui_list, PointerRNA *actptr, PropertyRNA *actprop);
+
+ /**
+ * Add a pie menu layout, buttons are arranged around a center.
+ * Only one pie menu per layout root can be added, if it's already initialized it will be
+ * returned instead of adding a new one.
+ */
+ Layout &menu_pie();
+
+ /** Add a new overlap sub-layout. */
+ Layout &overlap();
+
+ /**
+ * Create a "layout panel" which is a panel that is defined as part of the `Layout`. This
+ * allows creating expandable sections which can also be nested.
+ *
+ * The open-state of the panel is defined by an RNA property which is passed in as a pointer +
+ * property name pair. This gives the caller flexibility to decide who should own the open-state.
+ *
+ * \param C: The context is necessary because sometimes the panel may be forced to be open by the
+ * context even of the open-property is `false`. This can happen with e.g. property search.
+ * \param layout: The `Layout` that should contain the sub-panel.
+ * Only layouts that span the full width of the region are supported for now.
+ * \param open_prop_owner: Data that contains the open-property.
+ * \param open_prop_name: Name of the open-property in `open_prop_owner`.
+ *
+ * \return A #PanelLayout containing layouts for both the header row and the panel body. If the
+ * panel is closed and should not be drawn, the body layout will be NULL.
+ */
+ PanelLayout panel_prop(const bContext *C,
+ PointerRNA *open_prop_owner,
+ StringRefNull open_prop_name);
+ /**
+ * Variant of #panel_prop that automatically creates the header row with the
+ * given label and only returns the body layout.
+ *
+ * \param label: Text that's shown in the panel header. It should already be translated.
+ *
+ * \return NULL if the panel is closed and should not be drawn, otherwise the layout where the
+ * sub-panel should be inserted into.
+ */
+ Layout *panel_prop(const bContext *C,
+ PointerRNA *open_prop_owner,
+ StringRefNull open_prop_name,
+ StringRef label);
+ PanelLayout panel_prop_with_bool_header(const bContext *C,
+ PointerRNA *open_prop_owner,
+ StringRefNull open_prop_name,
+ PointerRNA *bool_prop_owner,
+ StringRefNull bool_prop_name,
+ std::optional<StringRef> label);
+ /**
+ * Variant of #panel_prop that automatically stores the open-close-state in the root
+ * panel. When a dynamic number of panels is required, it's recommended to use #panel_prop
+ * instead of passing in generated id names.
+ *
+ * \param idname: String that identifies the open-close-state in the root panel.
+ */
+ PanelLayout panel(const bContext *C, StringRef idname, bool default_closed);
+
+ /**
+ * Variant of #panel that automatically creates the header row with the given label and
+ * only returns the body layout.
+ *
+ * \param label: Text that's shown in the panel header. It should already be translated.
+ *
+ * \return NULL if the panel is closed and should not be drawn, otherwise the layout where the
+ * sub-panel should be inserted into.
+ */
+ Layout *panel(const bContext *C, StringRef idname, bool default_closed, StringRef label);
+
+ /**
+ * Add a new split sub-layout, items placed in this sub-layout are added horizontally next to
+ * each other in row, but width is split between the first item and remaining items.
+ * \param percentage: Width percent to split.
+ */
+ Layout &split(float percentage, bool align);
+
+ /** Items. */
+
+ /**
+ * Insert a decorator item for a button with the same property as \a prop.
+ * To force inserting a blank dummy element, nullptr can be passed for \a or and \a prop.
+ */
+ void decorator(PointerRNA *ptr, PropertyRNA *prop, int index);
+ /**
+ * Insert a decorator item for a button with the same property as \a prop.
+ * To force inserting a blank dummy element, nullptr can be passed for \a ptr or `std::nullopt`
+ * for \a propname.
+ */
+ void decorator(PointerRNA *ptr, std::optional<StringRefNull> propname, int index);
+
+ /** Adds a label item that will display text and/or icon in the layout. */
+ void label(StringRef name, int icon);
+
+ /**
+ * Adds link item, displays a url that can be clicked in the layout.
+ */
+ void link(StringRef url, StringRef name, int icon);
+
+ /**
+ * Adds a menu item, which is a button that when active will display a menu.
+ * If menu fails to poll with `WM_menutype_poll` it will not be added into the layout.
+ */
+ void menu(MenuType *mt, std::optional<StringRef> name, int icon);
+ /**
+ * Adds a menu item, which is a button that when active will display a menu.
+ * If menu fails to poll with `WM_menutype_poll` it will not be added into the layout.
+ */
+ void menu(StringRef menuname, std::optional<StringRef> name, int icon);
+
+ /** Adds the menu content into this layout. */
+ void menu_contents(StringRef menuname);
+
+ /**
+ * Adds a menu item, which is a button that when active will display a menu.
+ * \param name: Label to show in the menu button.
+ * \param func: Function that generates the menu layout.
+ * \param arg: Pointer to data used as last argument in \a func.
+ */
+ void menu_fn(StringRefNull name, int icon, MenuCreateFunc func, void *arg);
+ /**
+ * Adds a menu item, which is a button that when active will display a menu.
+ * \param name: Label to show in the menu button.
+ * \param func: Function that generates the menu layout.
+ * \param argN: Pointer to data used as last argument in \a func, it will be
+ * freed with the menu button.
+ */
+ void menu_fn_argN_free(StringRefNull name, int icon, MenuCreateFunc func, void *argN);
+ /**
+ * Adds a operator item, places a button in the layout to call the operator.
+ * \param ot: Operator to add.
+ * \param name: Text to show in the layout.
+ * \param context: Operator call context for #WM_operator_name_call.
+ * \returns Operator pointer to write properties.
+ */
+ PointerRNA op(wmOperatorType *ot,
+ std::optional<StringRef> name,
+ int icon,
+ wm::OpCallContext context,
+ eUI_Item_Flag flag);
+
+ /**
+ * Adds a operator item, places a button in the layout to call the operator.
+ * \param ot: Operator to add.
+ * \param name: Text to show in the layout.
+ * \returns Operator pointer to write properties.
+ */
+ PointerRNA op(wmOperatorType *ot, std::optional<StringRef> name, int icon);
+
+ /**
+ * Adds a operator item, places a button in the layout to call the operator.
+ * \param opname: Operator id name.
+ * \param name: Text to show in the layout.
+ * \returns Operator pointer to write properties, might be #PointerRNA_NULL if operator does not
+ * exists.
+ */
+ PointerRNA op(StringRefNull opname, std::optional<StringRef> name, int icon);
+
+ /**
+ * Adds a operator item, places a button in the layout to call the operator.
+ * \param opname: Operator id name.
+ * \param name: Text to show in the layout.
+ * \param context: Operator call context for #WM_operator_name_call.
+ * \returns Operator pointer to write properties, might be #PointerRNA_NULL if operator does not
+ * exists.
+ */
+ PointerRNA op(StringRefNull opname,
+ std::optional<StringRef> name,
+ int icon,
+ wm::OpCallContext context,
+ eUI_Item_Flag flag);
+ /**
+ * Expands and sets each enum property value as an operator button.
+ * \param propname: Name of the operator's enum property.
+ * \param properties: Extra operator properties values to set.
+ * \param active: an optional item to highlight.
+ */
+ void op_enum(StringRefNull opname,
+ StringRefNull propname,
+ IDProperty *properties,
+ wm::OpCallContext context,
+ eUI_Item_Flag flag,
+ const int active = -1);
+
+ /**
+ * Expands and sets each enum property value as an operator button.
+ * \param propname: Name of the operator's enum property.
+ */
+ void op_enum(StringRefNull opname, StringRefNull propname);
+ /**
+ * Expands and sets each enum property value as an operator button.
+ * \param prop: Operator's enum property.
+ * \param properties: Extra operator properties values to set.
+ * \param item_array: Precalculated item array, could be a subset of the enum property values.
+ * \param active: an optional item to highlight.
+ */
+ void op_enum_items(wmOperatorType *ot,
+ const PointerRNA &ptr,
+ PropertyRNA *prop,
+ IDProperty *properties,
+ wm::OpCallContext context,
+ eUI_Item_Flag flag,
+ const EnumPropertyItem *item_array,
+ int totitem,
+ int active = -1);
+
+ /**
+ * Adds a #op_enum menu.
+ * \returns Operator pointer to write extra properties to set when menu buttons are
+ * displayed, might be #PointerRNA_NULL if operator does not exist.
+ */
+ PointerRNA op_menu_enum(const bContext *C,
+ wmOperatorType *ot,
+ StringRefNull propname,
+ std::optional<StringRefNull> name,
+ int icon);
+ /**
+ * Adds a #op_enum menu.
+ * \returns Operator pointer to write extra properties to set when menu buttons are
+ * displayed, might be #PointerRNA_NULL if operator does not exist.
+ */
+ PointerRNA op_menu_enum(const bContext *C,
+ StringRefNull opname,
+ StringRefNull propname,
+ StringRefNull name,
+ int icon);
+ /**
+ * Adds a operator item, places a button in the layout to call the operator, if the button is
+ * held down, a menu will be displayed instead.
+ * \param ot: Operator to add.
+ * \param name: Text to show in the layout.
+ * \param context: Operator call context for #WM_operator_name_call.
+ * \param menu_id: menu to show on held down.
+ * \returns Operator pointer to write properties, might be #PointerRNA_NULL if operator does not
+ * exists.
+ */
+ PointerRNA op_menu_hold(wmOperatorType *ot,
+ std::optional<StringRef> name,
+ int icon,
+ wm::OpCallContext context,
+ eUI_Item_Flag flag,
+ const char *menu_id);
+
+ void progress_indicator(const char *text, float factor, ButProgressType progress_type);
+
+ /**
+ * Adds a RNA property item, and exposes it into the layout.
+ * \param ptr: RNA pointer to the struct owner of \a prop.
+ * \param prop: The property in \a ptr to add.
+ * \param index: When \a prop is a array property, indicates what entry to expose through the
+ * layout, #RNA_NO_INDEX (-1) means all.
+ */
+ void prop(PointerRNA *ptr,
+ PropertyRNA *prop,
+ int index,
+ int value,
+ eUI_Item_Flag flag,
+ std::optional<StringRef> name_opt,
+ int icon,
+ std::optional<StringRef> placeholder = std::nullopt);
+ /** Adds a RNA property item, and exposes it into the layout. */
+ void prop(PointerRNA *ptr,
+ StringRefNull propname,
+ eUI_Item_Flag flag,
+ std::optional<StringRef> name,
+ int icon);
+
+ void popover(const bContext *C, PanelType *pt, std::optional<StringRef> name_opt, int icon);
+ void popover(const bContext *C,
+ StringRef panel_type,
+ std::optional<StringRef> name_opt,
+ int icon,
+ PopupAttachDirection direction = PopupAttachDirection::Vertical);
+ void popover_group(
+ bContext *C, int space_id, int region_id, const char *context, const char *category);
+
+ /**
+ * Add a enum property value item. This button acts like a radio button that are used to chose
+ * a single enum value from a set of the enum property value items.
+ */
+ void prop_enum(
+ PointerRNA *ptr, PropertyRNA *prop, int value, std::optional<StringRefNull> name, int icon);
+ /**
+ * Add a enum property value item. This button acts like a radio button that are used to chose
+ * a single enum value from a set of the enum property value items.
+ */
+ void prop_enum(PointerRNA *ptr,
+ PropertyRNA *prop,
+ const char *value,
+ std::optional<StringRefNull> name,
+ int icon);
+ /**
+ * Add a enum property value item. This button acts like a radio button that are used to chose
+ * a single enum value from a set of the enum property value items.
+ */
+ void prop_enum(PointerRNA *ptr,
+ StringRefNull propname,
+ const char *value,
+ std::optional<StringRefNull> name,
+ int icon);
+
+ /** Add a enum property item, and exposes its value throw a radio button menu. */
+ void prop_menu_enum(PointerRNA *ptr,
+ PropertyRNA *prop,
+ std::optional<StringRefNull> name,
+ int icon);
+
+ /** Expands enum property value items as tabs buttons. */
+ void prop_tabs_enum(bContext *C,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ PointerRNA *ptr_highlight,
+ PropertyRNA *prop_highlight,
+ bool icon_only,
+ EnumTabExpand expand_as = EnumTabExpand::Default);
+
+ /** Expands enum property value items as radio buttons. */
+ void props_enum(PointerRNA *ptr, StringRefNull propname);
+
+ /**
+ * Adds a RNA enum/pointer/string/ property item, and exposes it into the layout. Button input
+ * would suggest values from the search property collection.
+ * \param searchprop: Collection property in \a searchptr from where to take input values.
+ * \param results_are_suggestions: Allow inputs that not match any suggested value.
+ * \param item_searchpropname: The name of the string property in the collection items to use for
+ * searching (if unset, code will use RNA_struc.
+ */
+ void prop_search(PointerRNA *ptr,
+ PropertyRNA *prop,
+ PointerRNA *searchptr,
+ PropertyRNA *searchprop,
+ PropertyRNA *item_searchpropname,
+ std::optional<StringRefNull> name,
+ int icon,
+ bool results_are_suggestions);
+ /**
+ * Adds a RNA enum/pointer/string/ property item, and exposes it into the layout. Button input
+ * would suggest values from the search property collection, input must match a suggested value.
+ * \param searchprop: Collection property in \a searchptr from where to take input values.
+ */
+ void prop_search(PointerRNA *ptr,
+ StringRefNull propname,
+ PointerRNA *searchptr,
+ StringRefNull searchpropname,
+ std::optional<StringRefNull> name,
+ int icon);
+
+ /**
+ * Adds a string property item as textbox, this will let multi-line text editing, textbox state
+ * will be persistent at runtime.
+ */
+ void textbox(const bContext *C, PointerRNA *ptr, StringRefNull propname);
+ /**
+ * Adds a string property item as textbox, this will let multi-line text editing.
+ * \param textbox_state: custom allocation for persistent textbox state.
+ */
+ void textbox_with_state(PointerRNA *ptr, StringRefNull propname, TextboxState *textbox_state);
+
+ /**
+ * Adds a RNA property item, and sets a custom popover to expose its value.
+ */
+ void prop_with_popover(PointerRNA *ptr,
+ PropertyRNA *prop,
+ int index,
+ int value,
+ eUI_Item_Flag flag,
+ std::optional<StringRefNull> name,
+ int icon,
+ const char *panel_type);
+
+ /**
+ * Adds a RNA property item, and sets a custom menu to expose its value.
+ */
+ void prop_with_menu(PointerRNA *ptr,
+ blender::StringRefNull propname,
+ eUI_Item_Flag flag,
+ std::optional<blender::StringRefNull> name,
+ int icon,
+ const char *menu_type);
+ /**
+ * Adds a RNA property item, and sets a custom menu to expose its value.
+ */
+ void prop_with_menu(PointerRNA *ptr,
+ PropertyRNA *prop,
+ int index,
+ int value,
+ eUI_Item_Flag flag,
+ std::optional<StringRefNull> name,
+ int icon,
+ const char *menu_type);
+
+ /** Simple button executing \a func on click. */
+ Button *button(StringRef name,
+ int icon,
+ std::function<void(bContext &)> func,
+ std::optional<StringRef> tooltip = std::nullopt);
+
+ /** Adds a separator item, that adds empty space between items. */
+ void separator(float factor = 1.0f, LayoutSeparatorType type = LayoutSeparatorType::Auto);
+
+ /** Adds a spacer item that inserts empty horizontal space between other items in the layout. */
+ void separator_spacer();
+
+ friend struct LayoutInternal;
+
+ [[nodiscard]] LayoutRoot *root() const;
+ [[nodiscard]] const bContextStore *context() const;
+ [[nodiscard]] Layout *parent() const;
+ [[nodiscard]] StringRef heading() const;
+ void heading_reset();
+ [[nodiscard]] Span<Item *> items() const;
+ [[nodiscard]] bool align() const;
+ [[nodiscard]] bool variable_size() const;
+ [[nodiscard]] EmbossType emboss_or_undefined() const;
+ [[nodiscard]] int2 size() const;
+ [[nodiscard]] int2 offset() const;
+
+ protected:
+ void estimate();
+ virtual void estimate_impl();
+ void resolve();
+ virtual void resolve_impl();
+};
+
+inline bool Layout::active() const
+{
+ return active_;
+}
+inline void Layout::active_set(bool active)
+{
+ active_ = active;
+}
+
+inline bool Layout::active_default() const
+{
+ return active_default_;
+}
+inline void Layout::active_default_set(bool active_default)
+{
+ active_default_ = active_default;
+}
+
+inline bool Layout::activate_init() const
+{
+ return activate_init_;
+}
+inline void Layout::activate_init_set(bool activate_init)
+{
+ activate_init_ = activate_init;
+}
+
+inline LayoutAlign Layout::alignment() const
+{
+ return alignment_;
+}
+
+inline void Layout::alignment_set(LayoutAlign alignment)
+{
+ alignment_ = alignment;
+}
+
+inline bContextStore *Layout::context_store() const
+{
+ return context_;
+}
+
+inline bool Layout::enabled() const
+{
+ return enabled_;
+}
+inline void Layout::enabled_set(bool enabled)
+{
+ enabled_ = enabled;
+}
+
+inline bool Layout::red_alert() const
+{
+ return redalert_;
+}
+inline void Layout::red_alert_set(bool red_alert)
+{
+ redalert_ = red_alert;
+}
+
+inline float Layout::search_weight() const
+{
+ return search_weight_;
+}
+inline void Layout::search_weight_set(float weight)
+{
+ search_weight_ = weight;
+}
+
+inline float Layout::scale_x() const
+{
+ return scale_[0];
+}
+inline void Layout::scale_x_set(float scale)
+{
+ scale_[0] = scale;
+}
+
+inline float Layout::scale_y() const
+{
+ return scale_[1];
+}
+inline void Layout::scale_y_set(float scale)
+{
+ scale_[1] = scale;
+}
+
+inline float Layout::ui_units_x() const
+{
+ return units_[0];
+}
+inline void Layout::ui_units_x_set(float width)
+{
+ units_[0] = width;
+}
+
+inline float Layout::ui_units_y() const
+{
+ return units_[1];
+}
+inline void Layout::ui_units_y_set(float height)
+{
+ units_[1] = height;
+}
+
+inline int Layout::width() const
+{
+ return this->w_;
+}
+
+enum class LayoutDirection : int8_t {
+ Horizontal = 0,
+ Vertical = 1,
+};
+
+enum class LayoutType : int8_t {
+ Panel = 0,
+ Header = 1,
+ Menu = 2,
+ Toolbar = 3,
+ PieMenu = 4,
+ VerticalBar = 5,
+};
+
+enum class LayoutAlign : int8_t {
+ Expand = 0,
+ Left = 1,
+ Center = 2,
+ Right = 3,
+};
+enum class ButProgressType : int8_t {
+ Bar = 0,
+ Ring = 1,
+};
+
+Layout &block_layout(Block *block,
+ LayoutDirection direction,
+ LayoutType type,
+ int x,
+ int y,
+ int size,
+ int em,
+ int padding,
+ const uiStyle *style);
+int2 block_layout_resolve(Block *block);
+
+void block_layout_set_current(Block *block, Layout *layout);
+bool block_layout_needs_resolving(const Block *block);
+/**
+ * Used for property search when the layout process needs to be cancelled in order to avoid
+ * computing the locations for buttons, but the layout items created while adding the buttons
+ * must still be freed.
+ */
+void block_layout_free(Block *block);
+
+enum eUI_Item_Flag : uint16_t {
+ /* ITEM_O_RETURN_PROPS = 1 << 0, */ /* UNUSED */
+ ITEM_R_EXPAND = 1 << 1,
+ ITEM_R_SLIDER = 1 << 2,
+ /**
+ * Use for booleans, causes the button to draw with an outline (emboss),
+ * instead of text with a checkbox.
+ * This is implied when toggle buttons have an icon
+ * unless #ITEM_R_ICON_NEVER flag is set.
+ */
+ ITEM_R_TOGGLE = 1 << 3,
+ /**
+ * Don't attempt to use an icon when the icon is set to #ICON_NONE.
+ *
+ * Use for booleans, causes the buttons to always show as a checkbox
+ * even when there is an icon (which would normally show the button as a toggle).
+ */
+ ITEM_R_ICON_NEVER = 1 << 4,
+ ITEM_R_ICON_ONLY = 1 << 5,
+ ITEM_R_EVENT = 1 << 6,
+ ITEM_R_FULL_EVENT = 1 << 7,
+ ITEM_R_NO_BG = 1 << 8,
+ ITEM_R_IMMEDIATE = 1 << 9,
+ ITEM_O_DEPRESS = 1 << 10,
+ ITEM_R_COMPACT = 1 << 11,
+ ITEM_R_CHECKBOX_INVERT = 1 << 12,
+ /** Don't add a real decorator item, just blank space. */
+ ITEM_R_FORCE_BLANK_DECORATE = 1 << 13,
+ /* Even create the property split layout if there's no name to show there. */
+ ITEM_R_SPLIT_EMPTY_NAME = 1 << 14,
+ /**
+ * Only for text buttons (for now): Force the button as active in a semi-modal state (capturing
+ * text input while leaving the remaining UI interactive).
+ */
+ ITEM_R_TEXT_BUT_FORCE_SEMI_MODAL_ACTIVE = 1 << 15,
+};
+ENUM_OPERATORS(eUI_Item_Flag)
+#define UI_ITEM_NONE ui::eUI_Item_Flag(0)
+
+/**
+ * Apply property search behavior, setting panel flags and deactivating buttons that don't match.
+ *
+ * \note Must not be run after #block_layout_resolve.
+ */
+bool block_apply_search_filter(Block *block, const char *search_filter);
+
+/**
+ * Set tooltip function for all buttons in the layout.
+ * func, arg and free_arg are passed on to button_func_tooltip_set, so their meaning is the same.
+ *
+ * \param func: The callback function that gets called to get tooltip content
+ * \param arg: An optional opaque pointer that gets passed to func
+ * \param free_arg: An optional callback for freeing arg (can be set to e.g. MEM_delete)
+ * \param copy_arg: An optional callback for duplicating arg in case button_func_tooltip_set
+ * is being called on multiple buttons (can be set to e.g. MEM_dupalloc). If set to NULL, arg will
+ * be passed as-is to all buttons.
+ */
+void uiLayoutSetTooltipFunc(
+ Layout *layout, ButtonToolTipFunc func, void *arg, CopyArgFunc copy_arg, FreeArgFunc free_arg);
+
+/**
+ * Same as above but should be used when building a fully custom tooltip instead of just
+ * generating a description.
+ */
+void uiLayoutSetTooltipCustomFunc(Layout *layout,
+ ButtonToolTipCustomFunc func,
+ void *arg,
+ CopyArgFunc copy_arg,
+ FreeArgFunc free_arg);
+
+void menutype_draw(bContext *C, MenuType *mt, Layout *layout);
+
+/**
+ * Used for popup panels only.
+ */
+void UI_paneltype_draw(bContext *C, PanelType *pt, Layout *layout);
+
+int uiLayoutListItemPaddingWidth();
+void uiLayoutListItemAddPadding(Layout *layout);
+
+/* Layout create functions. */
+
+bool uiLayoutEndsWithPanelHeader(const Layout &layout);
+
+struct PropertySplitWrapper {
+ Layout *label_column;
+ Layout *property_row;
+ /**
+ * Column for decorators. Note that this may be null, see #uiItemPropertySplitWrapperCreate().
+ */
+ Layout *decorate_column;
+};
+
+/**
+ * Normally, we handle the split layout in #Layout::prop(), but there are other cases where the
+ * logic is needed. Ideally, #Layout::prop() could just call this, but it currently has too many
+ * special needs.
+ *
+ * The returned #uiPropertySplitWrapper.decorator_column may be null when decorators are disabled
+ * (#uiLayoutGetPropDecorate() returns false).
+ */
+PropertySplitWrapper uiItemPropertySplitWrapperCreate(Layout *parent_layout);
+
+Button *uiItemL_ex(Layout *layout, StringRef name, int icon, bool highlight, bool redalert);
+/**
+ * Helper to add a label using a property split layout if needed. After calling this the
+ * active layout will be the one to place the labeled items in. An additional layout may be
+ * returned to place decorator buttons in.
+ *
+ * \return the layout to place decorators in, if #UI_ITEM_PROP_SEP is enabled. Otherwise null.
+ */
+Layout *uiItemL_respect_property_split(Layout *layout, StringRef text, int icon);
+/**
+ * Label icon for dragging.
+ */
+void uiItemLDrag(Layout *layout, PointerRNA *ptr, StringRef name, int icon);
+
+/* Only for testing, inspecting layouts. */
+/**
+ * Evaluate layout items as a Python dictionary.
+ */
+std::string layout_introspect(Layout *layout);
+
+/**
+ * Helpers to add a big icon and create a split layout for alert popups.
+ * Returns the layout to place further items into the alert box.
+ */
+Layout *uiItemsAlertBox(Block *block,
+ const uiStyle *style,
+ const int dialog_width,
+ const AlertIcon icon,
+ const int icon_size);
+Layout *uiItemsAlertBox(Block *block, const int size, const AlertIcon icon);
+
+} // namespace ui
+} // namespace blender
diff --git a/ui/include/UI_interface_types.hh b/ui/include/UI_interface_types.hh
new file mode 100644
index 0000000..8f67a47
--- /dev/null
+++ b/ui/include/UI_interface_types.hh
@@ -0,0 +1,62 @@
+/* SPDX-FileCopyrightText: 2025 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+#pragma once
+
+#include <string>
+
+#include "BLI_string_ref.hh"
+
+namespace blender {
+
+struct bContext;
+
+namespace ui {
+struct Block;
+struct Button;
+struct Layout;
+struct TooltipData;
+
+/* names */
+#define UI_MAX_DRAW_STR 550
+#define UI_MAX_NAME_STR 256
+#define UI_MAX_SHORTCUT_STR 64
+
+#define RNA_NO_INDEX -1
+
+/* Menu Callbacks */
+
+using MenuCreateFunc = void (*)(bContext *C, Layout *layout, void *arg1);
+using MenuHandleFunc = void (*)(bContext *C, void *arg, int event);
+
+/**
+ * Used for cycling menu values without opening the menu (Ctrl-Wheel).
+ * \param direction: forward or backwards [1 / -1].
+ * \param arg1: `Button.poin` (as with #MenuCreateFunc).
+ * \return true when the button was changed.
+ */
+using MenuStepFunc = bool (*)(bContext *C, int direction, void *arg1);
+
+using CopyArgFunc = void *(*)(const void *arg);
+using FreeArgFunc = void (*)(void *arg);
+
+/** Must return an allocated string. */
+using ButtonToolTipFunc = std::string (*)(bContext *C, void *argN, StringRef tip);
+
+/**
+ * \param data: The tooltip data to be filled.
+ * \param but: The exact button the tooltip is shown for. This is needed when the tooltip function
+ * is shared across multiple buttons but there still needs to be some customization per button.
+ * Mostly useful when using #uiLayoutSetTooltipCustomFunc.
+ */
+using ButtonToolTipCustomFunc = void (*)(bContext &C, TooltipData &data, Button *but, void *argN);
+
+} // namespace ui
+
+namespace ocio {
+class Display;
+} // namespace ocio
+using ColorManagedDisplay = ocio::Display;
+
+} // namespace blender
diff --git a/ui/intern/interface_draw.cc b/ui/intern/interface_draw.cc
index 564b878..527b408 100644
--- a/ui/intern/interface_draw.cc
+++ b/ui/intern/interface_draw.cc
@@ -1546,11 +1546,11 @@ void draw_but_UNITVEC(Button *but,
GPU_matrix_scale_1f(size);
gpu::Batch *sphere = GPU_batch_preset_sphere(2);
- SimpleLightingData simple_lighting_data;
+ gpu::SimpleLightingData simple_lighting_data;
copy_v4_fl4(simple_lighting_data.l_color, diffuse[0], diffuse[1], diffuse[2], 1.0f);
copy_v3_v3(simple_lighting_data.light, light);
gpu::UniformBuf *ubo = GPU_uniformbuf_create_ex(
- sizeof(SimpleLightingData), &simple_lighting_data, __func__);
+ sizeof(gpu::SimpleLightingData), &simple_lighting_data, __func__);
GPU_batch_program_set_builtin(sphere, GPU_SHADER_SIMPLE_LIGHTING);
GPU_batch_uniformbuf_bind(sphere, "simple_lighting_data", ubo);
diff --git a/ui/intern/interface_intern.hh b/ui/intern/interface_intern.hh
index 78eef9d..d77cc37 100644
--- a/ui/intern/interface_intern.hh
+++ b/ui/intern/interface_intern.hh
@@ -50,8 +50,8 @@ struct wmOperatorType;
struct wmTimer;
namespace gpu {
-class Batch;
-}
+using ::blender::gpu::Batch;
+} // namespace gpu
namespace ui {
diff --git a/ui/intern/interface_widgets.cc b/ui/intern/interface_widgets.cc
index 4a4da93..094ffcc 100644
--- a/ui/intern/interface_widgets.cc
+++ b/ui/intern/interface_widgets.cc
@@ -38,7 +38,7 @@
#include "UI_interface_icons.hh"
#include "UI_view2d.hh"
-#include "buttons/interface_textbox.hh"
+#include "interface_textbox.hh"
#include "interface_intern.hh"
#include "GPU_batch.hh"
diff --git a/ui/intern/view2d_intern.hh b/ui/intern/view2d_intern.hh
new file mode 100644
index 0000000..be8ccb7
--- /dev/null
+++ b/ui/intern/view2d_intern.hh
@@ -0,0 +1,50 @@
+/* SPDX-FileCopyrightText: 2023 Blender Authors
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later */
+
+/** \file
+ * \ingroup edinterface
+ *
+ * Share between view2d_*.cc files.
+ */
+
+#pragma once
+
+#include "DNA_vec_types.h"
+
+namespace blender {
+
+struct bContext;
+struct View2D;
+
+namespace ui {
+
+struct View2DScrollers {
+ /* focus bubbles */
+ int vert_min, vert_max; /* vertical scroll-bar */
+ int hor_min, hor_max; /* horizontal scroll-bar */
+
+ /** Exact size of slider backdrop. */
+ rcti hor, vert;
+};
+
+/**
+ * Calculate relevant scroller properties.
+ */
+void view2d_scrollers_calc(View2D *v2d, const rcti *mask_custom, View2DScrollers *r_scrollers);
+
+/**
+ * Change the size of the maximum viewable area (i.e. 'tot' rect).
+ */
+void view2d_totRect_set_resize(View2D *v2d, int width, int height, bool resize);
+
+bool view2d_edge_pan_poll(bContext *C);
+
+/**
+ * For paginated scrolling, get the page height to scroll. This may be a custom height
+ * (#View2D.page_size_y) but defaults to the #View2D.mask height.
+ */
+float view2d_page_size_y(const View2D &v2d);
+
+} // namespace ui
+} // namespace blender