# slikui > A sleek, header-only C++ UI library for graphics applications - retained-mode widget tree, declarative builder API, one narrow rendering contract. Python bindings included. slikui - a header-only C++20 UI library for graphics applications, with first-class Python bindings. Guides and per-widget reference. # Getting started # Getting started - C++ Header-only: include `slikui.hpp` (multi-header, `include/` on your include path) or `dist/slikui.hpp` (amalgamated single file - also attached to every GitHub Release). No linking, no code generation, C++20. ## A first window Minimal GLFW + OpenGL app - `examples/01_hello` is exactly this: ``` #include "slikui.hpp" // the library #include // GL 3.3 core renderer #include // window + event translation #include // find_system_font() int main() { slikui::glfw::GlfwWindow window(480, 320, "hello"); slikui::opengl::OpenglSink sink(window); slikui::Context ctx(sink); ctx.load_font_file(slikui::find_system_font()); window.attach(ctx); auto& root = ctx.set_root(); root.set_padding(16).set_gap(8); root.add("Hello, slikui!"); root.add("Save") .set_variant(slikui::Button::Variant::Primary); while (!window.should_close()) { window.poll_events(); // -> ctx.handle(event) ctx.tick(slikui::Time{}); // layout + animation ctx.render(); // -> DrawList -> GL } } ``` ## Responding to the user Widgets report what the user did through callbacks. Pass a function to the widget's `on_...` setter; it runs inside `window.poll_events()` (which calls `ctx.handle`) when the user acts: ``` auto& status = root.add("Not saved yet"); root.add("Save").on_click([&] { status.set_text("Saved"); }); root.add().set_range(0, 100).on_change([&](float v) { status.set_text("Volume " + std::to_string(int(v))); }); root.add() .set_items({"Small", "Medium", "Large"}) .on_select([&](size_t index) { status.set_text("Size " + std::to_string(index)); }); ``` The lambdas capture `status` by reference, which is fine: widgets live as long as the tree. Anything else a callback captures must outlive the widget too. [Callbacks](https://jamesgregson.github.io/slikui/guide/callbacks/index.md) lists every widget's callbacks, the arguments they receive, and when they fire. ## Headless - raw pixels The software backend needs no window or GPU: it antialiases into an owned or borrowed `uint32_t` framebuffer. `examples/02_raw_pixels` writes a PPM this way - this is also how the docs' component screenshots are produced. ``` #include slikui::software::Target target(480, 320); // raw pixels slikui::software::Sink sink(target); slikui::Context ctx(sink); ctx.set_frame_size({480, 320}); ctx.load_font_file(slikui::find_system_font()); // ... build the tree, tick, render ... // target.pixels() -> const uint32_t* ``` ## The include tree ``` include/slikui/ |-- core/ math (Vec2/Rect/Padding), Color, Event, Time, utf8 |-- layout/ Constraints, CrossMode, flex distribution |-- render/ DrawList (display list), IRenderSink |-- style/ Theme (palette + metrics), Anim (tween), easing |-- text/ Font (stb_truetype), glyph atlas, wrap/measure |-- widgets/ Widget base + the widget set (all.hpp = everything) |-- context.hpp Context: tree ownership, input, popups, frame loop `-- backends/ software/ | opengl/ | glfw/ (self-gating on __has_include) ``` Every public header compiles standalone (`tools/check_headers.sh` enforces it in CI). The GL/GLFW backends self-gate: without the system headers installed they compile to nothing. ## Next - [Callbacks](https://jamesgregson.github.io/slikui/guide/callbacks/index.md) - every widget's callbacks and what they receive - [Core concepts](https://jamesgregson.github.io/slikui/guide/core-concepts/index.md) - the frame loop in detail - [Widget index](https://jamesgregson.github.io/slikui/reference/index.md) - everything you can put on screen - [Building the demos](https://jamesgregson.github.io/slikui/development/index.md) - cmake targets, the gallery, the showcase - [Render backends](https://jamesgregson.github.io/slikui/guide/backends/index.md) - port to Vulkan/Metal/SDL # Getting started - Python Install the bindings - pip picks the wheel matching your OS, CPU and Python (3.10-3.14 on Linux x86_64/aarch64, macOS arm64, Windows x64); without a wheel, pip builds from the sdist (needs a C++20 compiler): ``` pip install slikui-python ``` Headless and testable by default: the software rasterizer renders into a `numpy` framebuffer - no window, no GPU, no event loop required. ## A first frame ``` import slikui ui = slikui.App(320, 200) # Target + Sink + Context + font root = ui.set_root(slikui.Column, padding=16, gap=8) root.add(slikui.Label, "Hello, slikui!", font_size=26) root.add(slikui.Button, "Save", variant=slikui.ButtonVariant.Primary) ui.tick(0.0, 1 / 60) # layout + animation frame = ui.render() # zero-copy (H, W) uint32 ndarray slikui.save_image(frame, "hello.png") ``` `App` is also a context manager; `close()` destroys the tree and releases the Python callbacks it holds so shutdown is leak-free: ``` with slikui.App(320, 200) as ui: ... ``` ## Responding to the user Widgets report what the user did through callbacks. Pass any callable to the widget's `on_...` setter, or as a keyword argument when you add it: ``` status = root.add(slikui.Label, "Not saved yet") root.add(slikui.Button, "Save", on_click=lambda: status.set_text("Saved")) root.add(slikui.Slider, range=(0, 100), on_change=lambda v: status.set_text(f"Volume {int(v)}")) # v: float root.add(slikui.Dropdown, items=["Small", "Medium", "Large"], on_select=lambda i: status.set_text(f"Size {i}")) # i: int ``` Callbacks run inside `ui.handle(event)`, when the event that triggers them is dispatched. [Callbacks](https://jamesgregson.github.io/slikui/guide/callbacks/index.md) lists every widget's callbacks, the arguments they receive, and when they fire. ## Driving it with events Build real `slikui.Event` values and push them through the real dispatch path - this is exactly how the simulated-input tests work: ``` ui.handle(slikui.mouse_press((60, 40))) # click through hit-testing ui.handle(slikui.text_input("h")) # into the focused TextField ui.handle(slikui.scroll(pos, (0, -1))) # wheel, "ctrl+shift" mods supported ``` ## Building from source The C++ side is header-only, nothing to link: ``` pip install -e . # editable, into your venv - from the repo root python -m pytest python/tests # widgets, events, custom widgets, renderer parity python -m slikui.examples.hello # shipped demos: writes hello.png in CWD python -m slikui.examples --list # the whole shipped suite ``` Interactive demos (optional deps): `pip install glfw PyOpenGL`, then `python python/examples/glfw_demo.py` - the software rasterizer blended over a GL scene - and `python python/examples/showcase.py` (every widget live; `--smoke out.png` runs it headless and its transcript is byte-identical to the C++ twin's). The shipped suite has a live mode too: add `--window` to any example and the same demo opens in a real GLFW window with mouse and keyboard wired through the real event dispatch path - nothing about the headless modes changes. ``` pip install "slikui-python[demo]" # glfw + PyOpenGL (quotes matter in zsh) python -m slikui.examples.hello --window python -m slikui.examples.gallery --window # scrolls; click around python -m slikui.examples.events --window # the probe logs your input live python -m slikui.examples.paint --window # scrub the meter, toggle, watch it run python -m slikui.examples.controls --window # knob, XY pad, joystick python -m slikui.examples.keyboard --window # focus tour and Snake python -m slikui.examples.window --window # a small live app ``` All eight, with screenshots: [Python examples](https://jamesgregson.github.io/slikui/guide/examples/index.md). The window host is a thin translation layer (GLFW callbacks -> `slikui` events -> premultiplied blit of the core's framebuffer); the demos stay importable without glfw or PyOpenGL, since the host is imported lazily. ## Next - [Callbacks](https://jamesgregson.github.io/slikui/guide/callbacks/index.md) - every widget's callbacks and what they receive - [Python examples](https://jamesgregson.github.io/slikui/guide/examples/index.md) - the shipped demo suite and its four modes (headless, smoke, docs capture, live window) - [Python bindings reference](https://jamesgregson.github.io/slikui/reference/python-bindings/index.md) - App, events, your own renderer, custom widgets - [Widget index](https://jamesgregson.github.io/slikui/reference/index.md) - everything you can put on screen - [Theming](https://jamesgregson.github.io/slikui/guide/theming/index.md) - presets and HiDPI scale # Guides # Render backends Everything slikui needs from a graphics API is one interface: ``` class IRenderSink { public: virtual ~IRenderSink() = default; virtual void upload(const TexUpload&) = 0; virtual void render(const DrawList&, Vec2 framebuffer_size) = 0; virtual void release(std::uint32_t id) {} // optional: texture is dead }; ``` Two backends ship out of the box and are the reference implementations: - **`slikui::software::Sink`** - antialiased CPU rasterizer over a raw `uint32_t` framebuffer (owned or borrowed). Works headless, on embedded targets, or blitted into any engine. `sink.set_scale()` renders logical coordinates at any pixel density. - **`slikui::opengl::OpenglSink`** - GL 3.3 core renderer using your **system OpenGL headers** (no vendored loader). Window/input layers are separate and optional: GLFW (`backends/glfw/`) and SDL3 (`backends/sdl/`), each split into input translation for a window you own and a ready-made window. All self-gate on `__has_include`, so they compile to nothing when the headers are absent. Anything else - Vulkan, Metal, SDL_Renderer, a raylib batch - implements the same two methods. A minimal sink is ~100-400 lines; the software sink is the smallest complete example, start there when porting. Every screenshot on this site is real `IRenderSink` output from the software backend - the two methods are the entire contract. ## Frame flow ``` ctx.render() |- upload() for dirty atlases (font atlas, images) |- build DrawList (root tree, popups, toasts, then dialogs) `- sink.render(list, framebuffer_size) ``` `render` should clear nothing by default - the list contains a background rect (`Context::render(clear=true)` paints `Theme::background` first). Presenting (swap buffers, blit) stays with the window layer, not the sink. ## Texture uploads ``` struct TexUpload { std::uint32_t id; // from Context::next_texture_id() int width, height; TexFormat format; // Alpha8 (glyph atlas) or Rgba8 (images) const std::uint8_t* pixels;// row-major, tightly packed }; ``` - `Alpha8`: one coverage byte per pixel. Store it as `R8` (GL) or expand to RGBA on upload; shaders multiply color by the red/alpha channel. - `Rgba8`: straight (non-premultiplied) alpha. - `upload` may be called repeatedly for the same id (atlas regrows) - treat it as create-or-replace. Texture ids are never reused for different content. - `release(id)` is called when the widget owning a texture (`Image`, `ImageView`, `CompareView`) is destroyed; free it then. It can arrive outside `render()` - e.g. from `Context::clear_tree()` at shutdown, with no GPU context current - so GPU sinks should queue the delete and perform it on the next `render()` (`OpenglSink` does). It is never called from `~Context`; a sink frees what it still holds when it is destroyed. - After a sink loses its textures (GPU context lost or recreated), call `Context::invalidate_textures()`: the next `render()` re-uploads the font atlas and every live widget texture. ## DrawList semantics The list is flat commands in paint order. Geometry is in framebuffer pixels, y-down. Clipping is *not* pre-applied - apply the clip stack: | Cmd | Meaning | Fields | | -------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------- | | `Rect` | filled rect; `radius > 0` rounds corners with antialiasing; `hollow` draws a `thickness`-wide border instead of fill | rect, radius, thickness, hollow, color | | `Line` | capsule from (x,y) to (x+w, y+h) with `thickness` | rect (endpoints), thickness, color | | `Glyph` | alpha quad tinted by `color`; `uv` is in atlas pixels | rect (dst), uv, tex_id, color | | `Image` | textured quad, straight alpha | rect (dst), uv, tex_id | | `ClipPush`/`ClipPop` | push/pop a clip rect; **intersect** with the current clip on push | rect (push only) | Guarantees you can rely on: - `ClipPush`/`ClipPop` are balanced (`DrawList::clip_balanced()`). - `uv` values for glyphs/images are in **texture pixels** - normalize by the texture's size from the last `upload` of that id. - Whitespace glyphs are never emitted (widgets skip them). ## Event translation (window layer) The window layer converts native events into `slikui::Event` and calls `Context::handle` - one vocabulary regardless of platform: | slikui event | GLFW source | builder (`slikui::glfw::`) | | --------------------------- | ------------------------------------------------------------------------------- | -------------------------- | | `MouseMove` | cursor-pos callback (`pos`, `delta`, held `mods`) | `cursor_pos_event` | | `MousePress`/`MouseRelease` | mouse-button callback (`button` via `map_button`, `pos`, `mods`) | `mouse_button_event` | | `Scroll` | scroll callback (`scroll`, held `mods`) | `scroll_event` | | `KeyPress`/`KeyRelease` | key callback (`key` via `map_key`, `mods`, `repeat`) | `key_event` | | `TextInput` | char callback (`codepoint`, Unicode scalar) | `char_event` | | `FocusLost` | window-focus callback (focus out) | `focus_event` | | `FrameResize` | framebuffer-size callback (`pos` = **pixel** size; Context converts to logical) | `framebuffer_size_event` | Mouse positions are **logical points** - GLFW's cursor coordinates (window space) pass through unchanged, matching the layout space Context works in. Only `FrameResize` carries framebuffer pixels. Buttons need mapping: GLFW numbers them LEFT=0, **RIGHT=1, MIDDLE=2**; slikui uses `MouseLeft=0`, **`MouseMiddle=1`, `MouseRight=2`**. `map_button` does it (extra buttons pass through). ### Using your own GLFW window `slikui/backends/glfw/glfw_input.hpp` works on any `GLFWwindow*` - it never creates a window or touches GL. Pick the level that fits your app: ``` #include // (a) You own the callbacks: forward what the UI should see. glfwSetMouseButtonCallback(win, [](GLFWwindow* w, int b, int a, int m) { if (ui_under_cursor(w)) ctx().handle(slikui::glfw::mouse_button_event(w, b, a, m)); else camera_button(w, b, a, m); }); // (b) GlfwInput installs slikui's callbacks, CHAINING to the ones you set // before it (yours run first) and restoring them in its destructor. It // does not use the window user pointer. slikui::glfw::GlfwInput input(win); // after your own glfwSet*Callback slikui::glfw::attach_services(ctx, win); // clipboard + cursor shapes while (!glfwWindowShouldClose(win)) { glfwPollEvents(); input.dispatch(ctx); // or route input.events() yourself ... } ``` `GlfwWindow` (`glfw_window.hpp`) is the ready-made option: it creates a GL 3.3 core window and owns a `GlfwInput` (`win.input()`). One `GlfwInput` per window; destroy it before the window (or call `release_window()`). Python has the same three levels in `slikui.glfw_input` (pyGLFW): `mouse_button_event(...)` and friends, `slikui.GlfwInput(win, app)` (chains, `close()` restores; no target = queue, `take()`), and `attach_services(ctx, win)`. ### SDL3 `slikui/backends/sdl/` mirrors the GLFW layers for SDL 3.2+. SDL delivers input through its event queue rather than callbacks, so there is nothing to install or chain - you hand slikui the events you poll: ``` #include slikui::sdl::SdlInput input(window); // filters by window id, starts text input slikui::sdl::attach_services(ctx); // clipboard + cursor shapes (global in SDL) SDL_Event ev; while (SDL_PollEvent(&ev)) { if (!input.process(ev)) my_app(ev); // quit, gamepads, other windows, ... } input.dispatch(ctx); // or route input.events() yourself ``` - `translate(const SDL_Event&, std::vector&)` is the stateless level (one SDL event can yield several: TEXT_INPUT is UTF-8, one `TextInput` per codepoint). - `SdlWindow` (`sdl_window.hpp`) creates a resizable HiDPI window with a GL 3.3 core context and owns an `SdlInput`; `dispatch(ctx)` pumps and translates, `on_event` gets what slikui doesn't use. - **Buttons** are 1-based in SDL (LEFT=1, MIDDLE=2, RIGHT=3); `map_button` converts. **Keys** map by keycode, so shortcuts follow the user's layout (AZERTY Ctrl+Z is the key labelled Z). GLFW maps by physical position, so the two differ on non-US layouts. - Python: `slikui.sdl_input` (PySDL3) - `translate(ev)`, `slikui.SdlInput(win, target)` with `process(ev)` / `take()`, `attach_services(ctx)`; `python/examples/sdl_demo.py`. PySDL3 downloads SDL binaries unless `SDL_DOWNLOAD_BINARIES=0 SDL_FIND_BINARIES=1 SDL_DISABLE_METADATA=1` (use a system SDL3). ### Sharing input with your scene Hosts that draw their own scene under the UI ask the Context where each event belongs, instead of hit-testing panels themselves: ``` using T = slikui::Event::Type; bool pointer = e.type == T::MouseMove || e.type == T::MousePress || e.type == T::MouseRelease || e.type == T::Scroll; bool to_ui = pointer ? ctx.wants_mouse(e.pos) : ctx.wants_keyboard(); ``` `wants_mouse(pos)` is true during a UI press or drag (so the release comes back to the UI), with a modal dialog open, or over any popup, dialog or widget that is not `mouse_transparent()`. Pure layout - `Column`, `Row`, `Spacer` - is transparent, so a full-window layout with a docked panel lets the pointer through everywhere except the panel. Custom layout-only widgets override `mouse_transparent()` to return true (Python too). `wants_keyboard()` is true when a widget has focus or a modal is open. `examples/06_sdl_opengl` and `python/examples/glfw_demo.py` route this way. ## A minimal new sink (sketch) ``` class MySink : public slikui::IRenderSink { void upload(const slikui::TexUpload& up) override { textures[up.id] = make_texture(up); // create-or-replace } void render(const slikui::DrawList& list, slikui::Vec2 fb) override { begin_frame(fb); for (const auto& cmd : list.commands()) { switch (cmd.type) { case slikui::DrawCmd::Type::ClipPush: push_clip(cmd.rect); break; case slikui::DrawCmd::Type::ClipPop: pop_clip(); break; default: draw(cmd); break; // rect/line/glyph/image } } end_frame(); } }; ``` ## GPU sinks: `GpuBatcher` `slikui/render/batcher.hpp` does the API-independent half of a GPU sink. `GpuBatcher::build(list, frame, scale)` turns a frame into two arrays: - **instances** - one `GpuInstance` (20 floats: rect, rgba, uv in texels, shape `{kind, radius, border, line half-thickness}`, line endpoints) per drawable command, in logical px. Commands entirely outside their clip, transparent fills and empty quads are culled. - **batches** - `{first, count, tex_id, scissor x/y/w/h}` runs sharing one scissor and one texture. Scissors are framebuffer px, bottom-left origin, ready for `glScissor`. Shapes never break a texture run, so a typical frame is a handful of batches. A sink uploads the instances once per frame and, per batch, sets the scissor, binds the texture and draws `count` instances of a 4-vertex triangle strip. The reference GLSL 330 shaders (`kGpuVertexShader`, `kGpuFragmentShader`) take the five vec4 attributes at locations 0-4 with divisor 1, and the uniforms `u_res`, `u_scale`, `u_tex`. Blend with `glBlendFuncSeparate(SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE_MINUS_SRC_ALPHA)` - the software sink's straight-alpha "over". The shaders reproduce the software rasterizer's coverage (SDF rounded rects/borders, capsule lines, bilinear Alpha8, nearest Rgba8): `tests/gl_parity.cpp` renders shapes and a full widget tree through `OpenglSink` offscreen and requires them to match the software sink to 2/255 per channel. Both sinks cover a glyph/image quad by **pixel center**: pixel (x, y) is drawn when (x + .5, y + .5) lies inside the quad and its index lies inside the clip (the glScissor rule) - a CPU sink should do the same, or fractional glyphs pick up a row of their atlas neighbour. ## Reference notes from the GL sink - `OpenglSink` is a thin layer over `GpuBatcher`: one streamed VBO (orphaned each frame), one instanced draw per batch. GL 3.3 has no base-instance draw, so it re-points the attributes at `first`. - `render()` sets viewport, program, VAO, texture unit 0, blending and scissor, disables depth/cull/stencil, and leaves them that way; it draws into the bound framebuffer. `shutdown()` frees everything (context current). - Textures: R8 for Alpha8 (`GL_LINEAR`), RGBA8 for Rgba8 (`GL_NEAREST`, as the software sink samples). `release()` defers `glDeleteTextures` to the next `render()`. ## Python: your own renderer `slikui.RenderSink` is a trampoline over C++ `IRenderSink`: subclass it, implement `upload(tex)` and `render(commands, fb_size)`, and slikui hands you every frame as a flat command list - point it at pygame, moderngl, PIL, anything. `slikui.CanvasSink` is a worked example: a pure-numpy rasterizer producing **pixel-identical** output to the C++ software backend (verified by test). Details: [Python bindings](https://jamesgregson.github.io/slikui/reference/python-bindings/index.md). # Callbacks Widgets tell your app what the user did through **callbacks**: functions you hand to a widget's `on_...` setter. A button calls `on_click` when it is clicked; a slider calls `on_change` with its new value; a list calls `on_select` with the row index. This page shows how to connect them, when they run, and what each one receives. ## Connecting a callback ``` auto& root = ctx.set_root(); root.set_padding(16).set_gap(8); auto& count = root.add("Clicked 0 times"); int clicks = 0; root.add("Click me").on_click([&] { ++clicks; count.set_text("Clicked " + std::to_string(clicks) + " times"); }); auto& volume = root.add("Volume 50"); root.add() .set_range(0, 100) .set_value(50) // setters don't run the callback .on_change([&](float v) { volume.set_text("Volume " + std::to_string(int(v))); }); root.add() .set_placeholder("Name, then Enter") .on_submit([&](std::string_view name) { count.set_text("Hello, " + std::string(name)); }); ``` ``` root = ui.set_root(slikui.Column, padding=16, gap=8) count = root.add(slikui.Label, "Clicked 0 times") state = {"clicks": 0} # app state the callbacks share def on_click(): state["clicks"] += 1 count.set_text(f"Clicked {state['clicks']} times") root.add(slikui.Button, "Click me", on_click=on_click) volume = root.add(slikui.Label, "Volume 50") root.add(slikui.Slider, range=(0, 100), value=50, on_change=lambda v: volume.set_text(f"Volume {int(v)}")) root.add(slikui.TextField, placeholder="Name, then Enter", on_submit=lambda name: count.set_text(f"Hello, {name}")) ``` The pattern is the same for every widget: - **`on_xxx(fn)`** stores `fn` and returns the widget, so it chains with the other setters. Each slot holds one callback; calling `on_xxx` again replaces it. - **Python:** pass any callable, either through the setter (`slider.on_change(fn)`) or as a keyword when building the widget (`root.add(slikui.Button, "OK", on_click=fn)`). - **Arguments:** the callback receives the new value, or the index of the row or item that was picked. The [table below](#every-callback) lists them. Python gets plain types: `float`, `bool`, `int` for indices, `str` for text, plus `slikui.Color` and `slikui.Vec2`. ## When callbacks run - **Inside `ctx.handle(event)`**, synchronously, on the UI thread, while the event that caused them is being dispatched. Nothing is queued. (A setter that fires its callback, and closing a menu or dialog from your own code, call them from that call instead.) - **After the widget has updated itself.** In `on_change`, `slider.value()` already returns the new value; in `on_select`, `list.selected()` is the new row. - **Only for changes the user makes**, unless you ask. Every setter for a value that a callback reports takes a last `fire_callback` argument, default `false`: `slider.set_value(0.5)` moves the slider silently, so updating a widget from your own state never loops back into your callback. Pass `true` to run the callback as if the user had made the change: `slider.set_value(0.5, true)`. Either way the callback only runs if the value actually changed. The last column of the table names each widget's setter. - **The tree may be changed from inside a callback.** You can add widgets, remove widgets (even the one whose callback is running), open or close dialogs and popups, and move focus. Removed widgets are destroyed when the current `handle()` returns, not mid-dispatch. - **Buttons fire on release:** a press and release on the same widget, Enter or Space. Dragging off the button before releasing cancels the click. ## Every callback "Setter" is the widget's own setter for the same value. It runs the callback only when given `fire_callback = true` and the value changes. | Widget | Callback | C++ signature | Python receives | Fires when | Setter | | ------------------------------------------ | ---------------------- | ----------------------------- | ----------------------------- | ------------------------------------------------- | ------------------------- | | `Button`, `IconButton` | `on_click` | `void()` | nothing | clicked, or Enter/Space when focused | - | | `Checkbox`, `Radio`, `Switch` | `on_change` | `void(bool checked)` | `bool` | toggled by click or Space (Switch: also Enter) | `set_checked` | | `Slider` | `on_change` | `void(float value)` | `float` | dragged, or keys | `set_value` | | `DragValue` | `on_change` | `void(float value)` | `float` | dragged, typed, or keys | `set_value` | | `Vec2Edit` / `Vec3Edit` / `Vec4Edit` | `on_change` | `void()` | nothing: read the bound array | any component changed | - | | `Vec2Pad` | `on_change` | `void(Vec2 value)` | `slikui.Vec2` | dragged, or arrow keys | `set_value` | | `ColorEdit` | `on_change` | `void(Color color)` | `slikui.Color` | edited in the picker | `set_color` | | `Segmented` | `on_select` | `void(size_t index)` | `int` | a segment picked | `set_selected` | | `Tabs` | `on_change` | `void(size_t index)` | `int` | a tab picked | `set_selected` | | `TextField`, `SearchBox` | `on_change` | `void(std::string_view text)` | `str` | every edit | `set_text` | | `TextField`, `SearchBox` | `on_submit` | `void(std::string_view text)` | `str` | Enter pressed | - | | `TextArea` | `on_change` | `void(std::string_view text)` | `str` | every edit | `set_text` | | `ListView` | `on_select` | `void(size_t index)` | `int` | a row clicked, or moved to with keys | `set_selected` | | `ListView` | `on_activate` | `void(size_t index)` | `int` | double-click, or Enter/Space | - | | `Dropdown` | `on_select` | `void(size_t index)` | `int` | an item chosen | `set_selected` | | `TreeView` | `on_select` | `void(size_t row)` | `int` | a row clicked, or moved to with keys | `set_selected` | | `TreeView` | `on_toggle` | `void(size_t row, bool open)` | `int, bool` | a row opened or closed by its arrow or Left/Right | `set_expanded(row, open)` | | `TreeView` | `on_activate` | `void(size_t row)` | `int` | double-click, or Enter/Space | - | | `Table` | `on_select` | `void(size_t row)` | `int` | a row clicked, or moved to with keys | `set_selected` | | `Table` | `on_activate` | `void(size_t row)` | `int` | double-click, or Enter/Space | - | | `Expander` | `on_toggle` | `void(bool open)` | `bool` | header clicked, or Space/Enter | `set_open` | | `Splitter` | `on_change` | `void(float fraction)` | `float` | divider dragged, or keys | `set_fraction` | | `Menu` | `on_open` / `on_close` | `void()` | nothing | about to open / after it closed (any reason) | - | | `Dialog` (and `MessageBox`, `FileBrowser`) | `on_close` | `void()` | nothing | closed by any means, once per close | - | | `FileBrowser` | `on_pick` | `void(std::string path)` | `str` | a file or folder chosen | - | Row indices for `TreeView` are positions in the list you passed to `set_rows`, whether or not the row is currently visible. ### Callbacks passed when adding items Some widgets take the callback together with the item it belongs to: | API | Callback | Runs when | | ----------------------------------------------------- | --------------------- | -------------------------------------------------------------- | | `Menu::add_item(label, fn, hint, enabled)` | `void()` | the item is chosen (then the menus close) | | `Menu::add_checkable(label, is_checked, toggle, ...)` | `bool()` and `void()` | `is_checked` is asked at paint time; `toggle` runs when chosen | | `Toolbar::add_button(icon, fn, tooltip)` | `void()` | the button is clicked | | `MessageBox::add_button(label, fn)` | `void()` | the button is clicked (then the box closes) | | `Context::add_shortcut(key, mods, fn)` | `void()` | the key chord is pressed anywhere (a modifier is required) | ### Hooks that customise rather than notify These are called by the widget or the Context when they need something from you, not in response to the user: | API | Signature | Purpose | | ------------------------------------------------------ | ------------------------------------- | ------------------------------------------------------------------ | | `DragValue::set_format(fn)` | `std::string(float)` | format the shown value | | `IconButton::set_icon_painter(fn)` | `void(DrawList&, Rect, Color)` | draw a custom icon | | `Context::set_clipboard_source` / `set_clipboard_sink` | `std::string()` / `void(std::string)` | connect the system clipboard (the window backends do this for you) | | `Context::set_cursor_host(fn)` | `void(Cursor)` | change the mouse cursor shape (likewise) | ## Captures and lifetime **C++.** A callback lives as long as its widget. Whatever its lambda captures must outlive the widget, or the callback will read freed memory. - Capturing other widgets by reference (`[&count]`) is safe while they stay in the tree. Widgets are owned by the tree, and `add()` returns a reference that stays valid until that widget is removed. - Capturing locals by reference (`[&clicks]`) is only safe if the locals outlive the UI, for example locals of `main` that also owns the event loop. Otherwise keep app state in an object that outlives the tree and capture a pointer or reference to it. - If a widget is removed, its callbacks go with it. Remove a widget before destroying what its callbacks capture. **Python.** Closures keep what they reference alive, so the usual Python rules apply. A callback that captures its own widget forms a reference cycle through the C++ tree; `App.close()`, or leaving `with slikui.App(...)`, breaks those cycles. ## Lower level: events Callbacks cover what the built-in widgets do. For a widget of your own, or to watch raw input, override `on_event` and handle `Click`, `KeyPress`, `MouseMove` and the other events directly. See [Input & events](https://jamesgregson.github.io/slikui/guide/input-events/index.md) for the event vocabulary and routing, and [Custom widgets](https://jamesgregson.github.io/slikui/guide/custom-widgets/index.md) for writing a widget. # Core concepts slikui is a **retained-mode widget tree** driven by a three-call frame loop. You build the tree once, keep it alive, and each frame the context routes input, relayouts, animates, and paints. There is no immediate-mode API, no per-frame widget construction, and no cached styled state to invalidate. ## The frame loop Every application drives a `slikui::Context` with the same three calls: ``` ctx.handle(event); // 1. input - hit-test, focus, popups ctx.tick({now, dt}); // 2. layout - attach -> measure -> arrange -> animation ctx.render(); // 3. paint - DrawList -> your sink ``` ``` while (running) { while (auto event = window.poll_event()) ctx.handle(event); ctx.tick(slikui::Time{now, dt}); ctx.render(); sink.present(); } ``` ``` ui = slikui.App(480, 320) # Target + Sink + Context + font # ... build the tree ... while running: ui.handle(slikui.mouse_press((60, 40))) # translated input events ui.tick(now, dt) ui.render() # -> (H, W) uint32 ndarray ``` The Python [`App`](https://jamesgregson.github.io/slikui/getting-started/python/index.md) shell wraps Target + Sink + Context (plus font loading) and returns the framebuffer as a zero-copy `numpy` array from `render()`. ## What each stage does **1. Input (`handle`).** Backend/window layers translate native events into one `slikui::Event` vocabulary (see [Input & events](https://jamesgregson.github.io/slikui/guide/input-events/index.md)). `Context::handle` hit-tests the deepest visible widget under the pointer, then dispatches the event *up the parent chain* until some widget consumes it. Key and text events go to the focused widget. Clicking outside a popup dismisses it - popups are destroyed at the end of `handle`, never during dispatch. **2. Tick (`tick(Time{now, dt})`).** First `attach_tree` hands every widget a `Context*` (fonts, theme) on first sight. Then the root is measured and arranged top-down: every widget implements ``` Size measure(const Constraints&); // intrinsic size under bounds void arrange(const Rect& abs); // assign own absolute frame + children ``` Frames are **absolute framebuffer coordinates**, which makes hit-testing, painting and clipping trivial. Finally each widget's `tick(Time)` runs - hover/press transitions and the `Anim` tween helper advance here. **3. Paint (`render`).** `paint_tree` walks the tree; widgets append commands to a flat `DrawList` through `PaintEnv` (draw list + theme + font). Containers may provide `clip_rect()` to clip their subtree; hit-testing honors the same clip, so content clipped out of view can't be clicked. The finished list goes to the [render sink](https://jamesgregson.github.io/slikui/guide/backends/index.md); popups paint after the root, then toasts, then dialogs on top. ## Layout in one paragraph Flexbox-flavoured: `Column`/`Row` stack children along their main axis with a `gap` and `padding`; cross-axis alignment is `Stretch`/`Start`/`Center`. Children whose `expands_main()` is true (e.g. `Spacer`) split leftover main-axis space. Layout is recomputed from scratch every tick, so window resizes reflow automatically - see [Layout](https://jamesgregson.github.io/slikui/guide/layout/index.md) and the full [architecture](https://jamesgregson.github.io/slikui/reference/architecture/index.md) notes. ## Ownership and lifetime - The tree is `std::unique_ptr`-owned: `ctx.set_root(...)` and `widget.add(...)` construct and own. You keep references, not owners. - Callbacks (`on_click`, `on_change`, ...) capture app state by reference/pointer - **keep captures valid** for the tree's lifetime, or remove the widget first. - `widget.remove(child)` / `clear_children()` destroy a subtree - immediately between frames, or at the end of the running `handle()`/`tick()` when called from a handler, so a widget may remove itself in its own callback. - Popup widgets are owned by the context until the end of the event that closes them. Menus are the exception: they are *borrowed* popups you build once and open many times. - In Python the bindings are non-owning wrappers over the C++ tree; `App.close()` (also run by `with App(...)`) destroys the tree and releases the Python callbacks it holds. A widget you pass to `push_popup`, `open_context_menu` or `open_dialog` is kept alive by the context while it is open, so a temporary is fine. A `Menu` given to `set_context_menu` is not: keep that Python object alive yourself, typically as an attribute of the widget it belongs to. ## Threading Single-threaded. One `Context` per thread; never touch a context from another thread. Drive everything from the main thread (or the thread that owns the window). In Python, `Context.tick`, `render` and `handle` (and the `App` methods that call them) release the GIL while the C++ work runs. Other Python threads, such as an audio callback or a worker, keep running during a frame. Your `paint` / `on_event` overrides, callbacks and a Python `RenderSink` still run with the GIL, on the UI thread. That also means the GIL no longer stops another thread from changing the widget tree mid-frame, so the single-thread rule matters more. A worker thread must not touch widgets. Send its results to the UI thread (a `queue.Queue` you drain each frame, say) and update widgets there. ## Where to go next - [Getting started - C++](https://jamesgregson.github.io/slikui/getting-started/cpp/index.md) or [Python](https://jamesgregson.github.io/slikui/getting-started/python/index.md) for a runnable first window. - [Layout](https://jamesgregson.github.io/slikui/guide/layout/index.md) for the container set. - [Input & events](https://jamesgregson.github.io/slikui/guide/input-events/index.md) for the event vocabulary, focus and shortcuts. - [Render backends](https://jamesgregson.github.io/slikui/guide/backends/index.md) to run on GL, raw pixels, or your own API. # Custom widgets Both languages can define new widgets against the same core contract. The C++ core lays out, paints, hit-tests and dispatches events to your class - in Python this works through a nanobind trampoline, and it is pixel-identical to the C++ path (there is a parity test against the C++ `Swatch`). ## The widget contract A widget implements whichever of these it needs: | Method | Role | | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `measure(const Constraints&)` | intrinsic size under bounds; return clamped `Size` | | `arrange(const Rect&)` | assign own absolute frame + children (default assigns `bounds`) | | `paint(const PaintEnv&)` | append draw commands to `env.list` (before the children) | | `paint_over(const PaintEnv&)` | draw on top of the children (decorations, overlays) | | `on_event(const Event&)` | return `true` to consume an event | | `tick(Time)` | animation / per-frame state | | `focusable()`, `expands_main()`, `stretch_cross()` | opt-in layout/focus behavior | | `tooltip_at(Vec2)` | tooltip text for the pointer position (per-part tips); default the `set_tooltip` text | | `clip_rect()` | container clipping for its subtree (painting and hit-testing) | | `child_clip_rect(const Widget&)` | C++ only: extra clip for one child's subtree (e.g. per pane) | | `scroll_into_view(const Rect&)` | C++ only: scrolling containers bring a keyboard-focused descendant into view | | `attached(Context&)` | called once when the widget joins a context | | `theme_changed()` | the context's theme changed (UI scale/zoom, preset, palette): drop cached text layouts or theme-derived colors | Layout runs in `Context::tick` (Python `app.tick()`), not in `render`: bounds are zero, and `context()` is null, until the first tick after a widget is added. What `on_event` receives - every mouse button, synthesized `Click`/`DoubleClick`, `MouseEnter`/`MouseLeave`, `FocusGained`/`FocusLost`, `KeyRelease` - and the mouse-capture drag idiom are in [Input & events](https://jamesgregson.github.io/slikui/guide/input-events/#routing-rules). Frames are absolute framebuffer coordinates; `paint_tree`, hit-testing and `tick_tree` all recurse through `children`, so a wrapper widget that only overrides `measure`/`arrange` keeps its subtree fully live. Painting emits into `env.list` (`rect`, `hollow_rect`, `line`, `circle`, `image`, `glyph`, clip stack) using `env.theme` colors - the same [DrawList commands](https://jamesgregson.github.io/slikui/guide/backends/#drawlist-semantics) every backend receives. `env.visible_rect` is the part of the window your drawing can show through: the frame, narrowed by every clip above the widget (a ScrollArea's viewport, a Splitter pane). It's in the same coordinates as `bounds`. Anything outside it is clipped away, so a long widget can skip it. For example, a list with fixed-height rows draws only rows `floor((visible.y - bounds.y) / row_h)` to `ceil((visible.bottom() - bounds.y) / row_h)`. `TreeView`, `ListView` and `Table` do this. ### Record once, replay every frame A widget whose drawing rarely changes (a chart, a score, a diagram) doesn't need to re-issue every command each frame. Record the drawing into your own `DrawList` at the origin, then append the recording to `env.list` with one call, moved to where the widget is. Appending copies commands in C++, so in Python it costs one call however long the recording is. Replaying 2,000 commands is about 40x faster than drawing them again. ``` void paint(const slikui::PaintEnv& env) const override { if (dirty_) { // contents changed cache_.clear(); draw_static(cache_); // at (0, 0) dirty_ = false; } env.list.append(cache_, {bounds.x, bounds.y}); } void theme_changed() override { dirty_ = true; } ``` ``` def paint(self, env): if self.cache is None: # contents changed -> set to None self.cache = slikui.DrawList() self.draw_static(self.cache) # at (0, 0) env.list.append(self.cache, slikui.Vec2(self.bounds.x, self.bounds.y)) def theme_changed(self): self.cache = None ``` - **Re-record in `theme_changed`.** A recording holds theme colors and, for text, glyph positions in the font atlas, which are only valid at the scale and font it was recorded with. - **Start from an array.** `DrawList.extend(array, offset)` appends from a `DRAWCMD_DTYPE` array, the format `as_array()` returns. Commands are checked first. - **Keep clips balanced.** Both calls reject a list whose `push_clip`/`pop_clip` don't match. ## Drawing text `env.text` draws a string at a point and `env.text_in` draws it inside a rect. With no options you get the theme's body font, size and text color; pass only what differs. Both return the rect the text occupies, so you can place what comes next. Sizes are logical px - theme scale is handled for you. ``` void paint(const slikui::PaintEnv& env) const override { using slikui::TextAlign, slikui::TextVAlign, slikui::TextOverflow; env.text({bounds.x, bounds.y}, "Hello"); env.text_in(bounds, "42%", {.size = 20, .bold = true, .align = TextAlign::Center, .valign = TextVAlign::Middle}); env.text_in(cell, name, {.overflow = TextOverflow::Ellipsis}); slikui::Rect r = env.text({x, y}, "42", {.size = 24, .bold = true}); env.text({r.right(), y}, "%", {.size = 14}); // follows the number } Size measure(const slikui::Constraints& c) override { return c.clamp(ctx->text_size("42%", {.size = 20, .bold = true})); } ``` ``` def paint(self, env): env.text(slikui.Vec2(self.bounds.x, self.bounds.y), "Hello") env.text_in(self.bounds, "42%", size=20, bold=True, align="center", valign="middle") env.text_in(cell, name, overflow="ellipsis") r = env.text(slikui.Vec2(x, y), "42", size=24, bold=True) env.text(slikui.Vec2(r.x + r.w, y), "%", size=14) def measure(self, constraints): return constraints.clamp(self.context.text_size("42%", size=20, bold=True)) ``` The options (`slikui::TextOpts`), all defaulting to the theme: | Option | Meaning | | --------------------------------------- | --------------------------------------------------------------------------------------------------- | | `font` | family or role: `"body"` (default), `"heading"`, `"mono"`, or a name passed to `add_font` | | `size` | logical px; 0 = `theme.base_font_px` | | `color` | alpha 0 / `None` = `theme.text` | | `bold`, `italic`, `underline`, `strike` | style; missing faces are synthesized | | `align` | `Left` / `Center` / `Right`: which part of the text sits on the point, or alignment inside the rect | | `valign` | `Top` / `Middle` / `Baseline` / `Bottom` | | `wrap` | wrap to the rect width (`text_in`) or `max_width` (`text`) | | `max_width` | `text` only: the available width for `wrap` and `overflow` | | `overflow` | `Visible`, `Clip` to the available width, or `Ellipsis` (single line) | In C++ the options are a struct, so designated initializers must follow the order of the table (`{.size = 20, .bold = true}`, not `{.bold = true, .size = 20}`); a reusable style is just a `static const slikui::TextOpts`. Python takes them as keyword arguments, and `align` / `valign` / `overflow` also accept lowercase names (`"center"`). `ctx->text_metrics(opts)` gives ascent, descent and line height for laying out lines yourself. `env.text` lays out on every call, and the context caches the result, so drawing the same strings every frame is cheap. For interactive text, keep a `TextBlock` instead: it is laid out once, drawn with `env.draw(block, pos)`, and answers `hit_test(point)`, `caret_rect(index)` and `selection_rects(start, end)` (byte offsets in C++, str indices in Python). ``` slikui::TextBlock block = ctx->text_layout(paragraph, /*wrap_width=*/240, {.font = "mono"}); size_t caret = block.hit_test(click_pos - top_left); ``` Worked versions of all of this - a tag sized by `text_size`, a stat card, ellipsis vs wrapping, and drag-to-select on a `TextBlock` - are in the `text` example (`python -m slikui.examples.text --window`) and its C++ twin `examples/07_text`; see [Python examples](https://jamesgregson.github.io/slikui/guide/examples/#text). ## C++ example Define the widget, implement `measure`/`paint`/`on_event`, add it like any other. `Meter` below is the C++ twin of the Python example further down - the capture tool renders the identical tree: same 10 px measure, same paint math, same click-to-scrub event. State is a private `float` in C++ and a plain attribute in Python; the trampoline forwards the protocol calls either way. ``` class Meter : public slikui::Widget { public: explicit Meter(float value = 0.f) : value_(value) {} Size measure(const Constraints& c) override { return c.clamp({0.f, 10.f}); } void paint(const slikui::PaintEnv& env) const override { env.list.rect(bounds, env.theme.surface_alt, bounds.h / 2); if (value_ > 0.f) env.list.rect({bounds.x, bounds.y, bounds.w * value_, bounds.h}, env.theme.accent, bounds.h / 2); } bool on_event(const slikui::Event& e) override { // Click to the left/right of the fill to move it. if (e.type == slikui::Event::Type::MousePress && bounds.contains(e.pos)) { value_ = std::clamp((e.pos.x - bounds.x) / bounds.w, 0.f, 1.f); return true; } return false; } private: float value_ = 0.f; }; auto& title = root.add("Custom widget"); title.set_font_size(26); root.add("Meter is a C++ class subclassing slikui::Widget") .set_color(ctx.theme().text_dim); root.add(0.4f); // stretch_cross() defaults to true root.add("Click the bar to scrub it") .set_color(ctx.theme().text_dim); ``` `examples/05_showcase` ships two production custom widgets: `Fill` (expands on the main axis and hands its whole area to a single child) and `LevelMeter` (LED bar with click/drag scrubbing, peak-hold and a warning gradient). ## Python example Subclass `slikui.Widget`, implement `measure` / `paint` / `on_event` (plus opt-in `tick`, `stretch_cross`, `expands_main`, `focusable`, `arrange`, `clip_rect`, `paint_over`, `attached`, `theme_changed`, `widget_type`). Widgets read `self.bounds`, `self.focused` and `self.context` (for `capture_mouse`/`release_mouse`/`set_focus`), and can call `self.request_focus()` and `self.set_cursor(...)`: ``` class Meter(slikui.Widget): """A horizontal bar that fills as `value` (0..1) approaches 1.""" def __init__(self, value=0.0): super().__init__() # required self.value = value def measure(self, constraints): return constraints.clamp(slikui.Size(0, 10)) def paint(self, env): env.list.rect(self.bounds, env.theme.surface_alt, self.bounds.h / 2) if self.value > 0: fill = slikui.Rect(self.bounds.x, self.bounds.y, self.bounds.w * self.value, self.bounds.h) env.list.rect(fill, env.theme.accent, self.bounds.h / 2) def on_event(self, event): # Click to the left/right of the fill to move it. if event.type == slikui.EventType.MousePress and self.bounds.contains(event.pos): v = (event.pos.x - self.bounds.x) / self.bounds.w self.value = max(0.0, min(v, 1.0)) return True return False ``` Add instances with `container.add_widget(obj)` or `container.add(Meter, 0.4)`; a custom root is `context.set_root_widget(...)`. Python state lives in ordinary instance attributes. ## Rules and gotchas - Python subclasses **must call `super().__init__()`**. - Besides `slikui.Widget`, you can subclass `Panel`, `Column` and `Row`: overrides dispatch, and `super()` calls reach the built-in behaviour (`super().paint(env)` draws the panel, `super().measure(c)` lays out the children). Other bound types (`Slider`, `Button`, ...) have no override seam - overriding `on_event`, `paint`, ... on them raises `TypeError` at class creation. To decorate one of those, wrap it: delegate `measure`/`arrange` to the child and draw in `paint_over` (`LimitSlider` in `slikui.examples.controls`). - Draw text with `env.text` / `env.text_in` (see [Drawing text](#drawing-text)); `Label` widgets beside a custom widget still work for captions. - Keep the wrappers `add()` returns (`self.slider = self.add(slikui.Slider)`) and capture them in callbacks freely. They are views of widgets the tree owns: valid until the tree drops the widget (`remove`, `App.close()`, or its container being destroyed). Using one after that raises `TypeError`. - Callbacks into Python must outlive the tree: `App.close()` (context manager exit, `atexit`) releases them; see [Python bindings](https://jamesgregson.github.io/slikui/reference/python-bindings/index.md). - The full worked example ships in the wheel: `slikui/examples/paint.py` (run `python -m slikui.examples.paint --docs-image custom_widget docs/images/custom_widget.png` to regenerate the image above; the demo page has Sparkline, RadialGauge, ClockFace and a layout-bounds wrapper beside the Meter). The interactive twin is `python/examples/showcase.py`. # Python examples The wheel ships a curated demo suite as `slikui.examples` - the usage reference that matches the slikui version you installed. Every example file runs on its own (copy it anywhere and run `python controls.py`), checks itself, and drives the real event dispatch path. Every widget quoted on these pages is self-contained: paste the block into your own file and it runs, imports included. ## Run them The examples ship in the wheel, so there is nothing to download: ``` pip install slikui-python # headless: renders to PNG pip install "slikui-python[demo]" # + glfw and PyOpenGL for live windows python -m slikui.examples.controls --window # open one live (any name below) python -m slikui.examples.controls # or headless: writes ./controls.png ``` The quotes around `"slikui-python[demo]"` matter in zsh, the macOS default shell. The suite itself: ``` python -m slikui.examples --list # what's shipped python -m slikui.examples --where # the directory: read the sources python -m slikui.examples --contract # what a custom widget receives, measured live python -m slikui.examples --smoke all # scripted self-check of every example ``` `slikui-examples` is the same launcher as a command. `help(slikui.examples)` prints the index and the custom-widget contract in one screen. ## The suite | # | Example | Shows | | --- | ---------- | ---------------------------------------------------------------------------------------------- | | 01 | `hello` | first frame, minimal tree, headless render | | 02 | `gallery` | widget survey - most built-in widgets in one tall page | | 03 | `events` | event anatomy: `EventProbe` narrates every event it receives | | 04 | `paint` | drawing cookbook: Meter, Sparkline, RadialGauge, ClockFace, BoundsDebug | | 05 | `controls` | Knob, XYPad, Joystick with full mouse + keyboard; LimitSlider decorates a built-in | | 06 | `keyboard` | focus traversal and rings, global shortcuts, Snake | | 07 | `renderer` | the render contract: two renderers, identical pixels, and your own | | 08 | `window` | a live app in a GLFW window (the same tour runs headless) | | 09 | `text` | Label styles, font families, custom widgets that draw, measure, wrap, truncate and select text | ## See them The frames below are the examples' own `--smoke` output - post-interaction frames captured by the same scripted pass CI runs: ## Every example has the same four modes ``` python -m slikui.examples.paint # headless render -> paint.png python -m slikui.examples.paint --png out.png python -m slikui.examples.paint --smoke # scripted interaction pass, self-checking python -m slikui.examples.paint --window # live GLFW window (needs the demo extra) ``` - **Default** - render one frame to `./NAME.png`; no display, no glfw. - **`--smoke`** - synthetic input (click, drag, scroll, keys) against a fixed clock; asserts and prints a transcript. This is what CI runs, so the examples double as the wheel's acceptance test. - **`--window`** - the same demo live: GLFW callbacks feed real events, the core renders into its framebuffer, and a thin premultiplied blit puts it on screen. Needs `pip install "slikui-python[demo]"`; the host is imported lazily, so the base wheel never pulls in glfw or PyOpenGL. ## EventProbe in depth `events` is the place to start if you're writing a custom widget: it shows what arrives and in what order - enter/leave, press/release/click, double-click, a captured drag, focus gained/lost, key down/up. It has its own section in [Input & events](https://jamesgregson.github.io/slikui/guide/input-events/#watching-events-the-shipped-eventprobe-demo). ## Custom widgets in depth `paint` is the worked drawing example - measure/arrange/paint, direct DrawList drawing, tick animation, hover via `MouseLeave`, and a debug overlay drawn with `paint_over`. See [Custom widgets](https://jamesgregson.github.io/slikui/guide/custom-widgets/index.md) for the guide and the screenshot-capture contract (`--docs-image`). ## Extended controls `controls` builds three controls the built-in set doesn't have. Every drag uses one idiom - capture the mouse on press, release on release, cancel on `FocusLost` - so drags survive the pointer leaving the widget: ``` import math import slikui T, K = slikui.EventType, slikui.Key LEFT = slikui.MouseButton.MouseLeft class Knob(slikui.Widget): """Rotary dial over [lo, hi]. ``on_change(value)`` fires on every edit.""" START, SWEEP, DRAG_PX = 135.0, 270.0, 150.0 # degrees; px per full range def __init__(self, lo=0.0, hi=1.0, value=0.5, step=0.05): super().__init__() self.lo, self.hi, self.step = lo, hi, step self.value = self.default = min(max(value, lo), hi) self.on_change = None self._drag = None # (start y, start value) while dragging self.set_cursor(slikui.Cursor.ResizeV) def set(self, v): v = min(max(v, self.lo), self.hi) if v != self.value: self.value = v if self.on_change: self.on_change(v) def measure(self, constraints): return constraints.clamp(slikui.Size(64, 64)) def stretch_cross(self): return False def focusable(self): return True def on_event(self, e): span = self.hi - self.lo if e.type == T.MousePress and e.button == LEFT: self._drag = (e.pos.y, self.value) self.context.capture_mouse(self) return True if e.type == T.MouseMove and self._drag: y0, v0 = self._drag fine = 0.1 if e.shift else 1.0 self.set(v0 + (y0 - e.pos.y) / self.DRAG_PX * span * fine) return True if e.type in (T.MouseRelease, T.FocusLost) and self._drag: self._drag = None self.context.release_mouse(self) return True if e.type == T.DoubleClick: self.set(self.default) return True if e.type == T.Scroll: self.set(self.value + e.scroll.y * self.step * span) return True if e.type == T.KeyPress and self.focused: step = self.step * span * (0.1 if e.ctrl else 1.0) moves = {K.Left: -step, K.Down: -step, K.Right: step, K.Up: step} if e.key in moves: self.set(self.value + moves[e.key]) elif e.key == K.Home: self.set(self.lo) elif e.key == K.End: self.set(self.hi) else: return False return True return False def _pt(self, cx, cy, r, t): a = math.radians(self.START + t * self.SWEEP) return slikui.Vec2(cx + r * math.cos(a), cy + r * math.sin(a)) def paint(self, env): b, th = self.bounds, env.theme cx, cy = b.x + b.w / 2, b.y + b.h / 2 r = min(b.w, b.h) / 2 - 5 t = (self.value - self.lo) / ((self.hi - self.lo) or 1.0) n = 36 for i in range(n): # track, then the value arc over it col = th.accent if (i + 1) / n <= t + 1e-6 else th.surface_alt env.list.line(self._pt(cx, cy, r, i / n), self._pt(cx, cy, r, (i + 1) / n), col, 4.0) env.list.circle(slikui.Vec2(cx, cy), r * 0.62, th.surface) env.list.line(slikui.Vec2(cx, cy), self._pt(cx, cy, r * 0.55, t), th.text, 2.5) if self.focused: # a round focus ring: hollow_rect with full radius env.list.hollow_rect(b.inflate(-1, -1), th.accent, 1.5, b.w / 2) ``` `Joystick` holds a key set from `KeyPress`/`KeyRelease`, so WASD pushes the stick only while held; the stick springs back in `tick`: ``` import math import slikui T, K = slikui.EventType, slikui.Key LEFT = slikui.MouseButton.MouseLeft class Joystick(slikui.Widget): """Stick vector in the unit disc (y up), springing back to centre.""" SPRING = 12.0 # 1/s - exponential return rate KEYS = {K.W: (0, 1), K.Up: (0, 1), K.S: (0, -1), K.Down: (0, -1), K.A: (-1, 0), K.Left: (-1, 0), K.D: (1, 0), K.Right: (1, 0)} def __init__(self): super().__init__() self.vx = self.vy = 0.0 self.frozen = False self._dragging = False self._held = set() # keys currently down - needs KeyRelease def measure(self, constraints): return constraints.clamp(slikui.Size(110, 110)) def stretch_cross(self): return False def focusable(self): return True def _aim(self, p): b = self.bounds r = b.w / 2 - 14 x, y = (p.x - b.center().x) / r, -(p.y - b.center().y) / r m = math.hypot(x, y) self.vx, self.vy = (x / m, y / m) if m > 1 else (x, y) def on_event(self, e): if e.type == T.MousePress and e.button == LEFT: self._dragging = True self._aim(e.pos) self.context.capture_mouse(self) return True if e.type == T.MouseMove and self._dragging: self._aim(e.pos) return True if e.type in (T.MouseRelease, T.FocusLost) and self._dragging: self._dragging = False self.context.release_mouse(self) if e.type == T.FocusLost: self._held.clear() if e.type == T.KeyPress and e.key in self.KEYS: self._held.add(e.key) return True if e.type == T.KeyRelease and e.key in self.KEYS: self._held.discard(e.key) return True if e.type == T.KeyPress and e.key == K.Space: self.frozen = not self.frozen return True return False def tick(self, t): if self._dragging or self.frozen: return if self._held: # keys push the stick to the rim x = sum(self.KEYS[k][0] for k in self._held) y = sum(self.KEYS[k][1] for k in self._held) m = math.hypot(x, y) or 1.0 self.vx, self.vy = x / m, y / m return k = math.exp(-self.SPRING * t.dt) # spring back self.vx, self.vy = self.vx * k, self.vy * k def paint(self, env): b, th = self.bounds, env.theme env.list.rect(b, th.surface_alt, b.w / 2) env.list.hollow_rect(b, th.accent if self.focused else th.border, 1, b.w / 2) r = b.w / 2 - 14 c = b.center() knob = slikui.Vec2(c.x + self.vx * r, c.y - self.vy * r) env.list.line(c, knob, th.border, 3) env.list.circle(knob, 12, th.warning if self.frozen else th.accent) class BallBox(slikui.Widget): """A ball steered by a Joystick: velocity follows the stick.""" def __init__(self, stick): super().__init__() self.stick = stick self.x, self.y, self.vx, self.vy = 0.5, 0.5, 0.0, 0.0 def measure(self, constraints): return constraints.clamp(slikui.Size(140, 110)) def tick(self, t): self.vx += self.stick.vx * 2.0 * t.dt self.vy -= self.stick.vy * 2.0 * t.dt self.vx *= 0.98 self.vy *= 0.98 self.x += self.vx * t.dt self.y += self.vy * t.dt for p, v in (("x", "vx"), ("y", "vy")): # bounce off the walls if not 0.0 <= getattr(self, p) <= 1.0: setattr(self, p, min(max(getattr(self, p), 0.0), 1.0)) setattr(self, v, -getattr(self, v)) def paint(self, env): b, th = self.bounds, env.theme env.list.rect(b, th.surface_alt, 6) env.list.circle(slikui.Vec2(b.x + 8 + self.x * (b.w - 16), b.y + 8 + self.y * (b.h - 16)), 8, th.accent) ``` `LimitSlider` decorates the built-in `Slider`, which Python can't subclass: it wraps one, delegates layout, and draws its marks in `paint_over`, after the Slider has painted: ``` import slikui class LimitSlider(slikui.Widget): """The built-in Slider with limit marks on its track. Python can't subclass bound widgets, so this wraps one: layout is delegated to the child, and the marks are drawn in ``paint_over`` - after the Slider has painted, so they sit on top of its track. The track geometry mirrors the Slider's paint (8 px inset, centred; no label row). """ INSET = 8.0 def __init__(self, lo, hi, value, limits): super().__init__() self.lo, self.hi, self.limits = lo, hi, limits self.slider = self.add(slikui.Slider, lo, hi, value=value) def measure(self, constraints): return self.slider.measure(constraints) def arrange(self, area): self.bounds = area self.slider.arrange(area) def paint_over(self, env): b, th = self.slider.bounds, env.theme x0, x1 = b.x + self.INSET, b.right() - self.INSET cy = b.y + b.h / 2 for v in self.limits: x = x0 + (v - self.lo) / (self.hi - self.lo) * (x1 - x0) env.list.line(slikui.Vec2(x, cy - 7), slikui.Vec2(x, cy + 7), th.warning, 2) ``` ## Keyboard `keyboard` covers focus traversal (each chip draws its own focus ring and reports `FocusGained`/`FocusLost`), a global `Ctrl`+`R` shortcut, and a whole game in one widget: ``` import random import slikui T, K = slikui.EventType, slikui.Key class Snake(slikui.Widget): """Grid snake. Steering is buffered per step so a quick Up+Left between two steps can't reverse the snake into itself.""" COLS, ROWS, CELL = 24, 14, 14 DIRS = {K.Up: (0, -1), K.W: (0, -1), K.Down: (0, 1), K.S: (0, 1), K.Left: (-1, 0), K.A: (-1, 0), K.Right: (1, 0), K.D: (1, 0)} def __init__(self, seed=7): super().__init__() self.rng = random.Random(seed) # deterministic food for scripted runs self.rate = 6.0 # steps per second self.on_score = None self.restart() def restart(self): y = self.ROWS // 2 self.body = [(5, y), (4, y), (3, y)] # head first self.dir = self.next_dir = (1, 0) self.score, self.paused, self.dead, self._acc = 0, False, False, 0.0 self.place_food() if self.on_score: self.on_score(self.score) def place_food(self): free = [(x, y) for x in range(self.COLS) for y in range(self.ROWS) if (x, y) not in self.body] self.food = self.rng.choice(free) def measure(self, constraints): return constraints.clamp(slikui.Size(self.COLS * self.CELL, self.ROWS * self.CELL)) def stretch_cross(self): return False def focusable(self): return True def draws_own_focus(self): return True # paint() shows focus; no built-in ring on top def on_event(self, e): if e.type == T.FocusLost: self.paused = True # never run unattended elif e.type == T.KeyPress and e.key in self.DIRS: d = self.DIRS[e.key] if d != (-self.dir[0], -self.dir[1]): # no reversing self.next_dir = d return True elif e.type == T.KeyPress and e.key == K.Space: self.paused = not self.paused return True elif e.type == T.KeyPress and e.key == K.R: self.restart() return True elif e.type == T.Scroll: self.rate = min(max(self.rate + e.scroll.y, 2.0), 20.0) return True return e.type == T.MousePress def step(self): self.dir = self.next_dir hx, hy = self.body[0] head = (hx + self.dir[0], hy + self.dir[1]) if (not (0 <= head[0] < self.COLS and 0 <= head[1] < self.ROWS) or head in self.body[:-1]): self.dead = True return self.body.insert(0, head) if head == self.food: self.score += 1 if self.on_score: self.on_score(self.score) self.place_food() else: self.body.pop() def tick(self, t): if self.paused or self.dead: return self._acc += t.dt while self._acc >= 1.0 / self.rate and not self.dead: self._acc -= 1.0 / self.rate self.step() def paint(self, env): b, th, c = self.bounds, env.theme, self.CELL env.list.rect(b, th.surface_alt, 4) def cell(x, y, color, inset=1.0, radius=3.0): env.list.rect(slikui.Rect(b.x + x * c + inset, b.y + y * c + inset, c - 2 * inset, c - 2 * inset), color, radius) env.list.circle(slikui.Vec2(b.x + (self.food[0] + 0.5) * c, b.y + (self.food[1] + 0.5) * c), c * 0.35, th.warning) for i, (x, y) in enumerate(self.body): cell(x, y, th.danger if self.dead else (th.accent if i == 0 else th.text_dim)) edge = th.accent if self.focused else th.border env.list.hollow_rect(b, edge, 2 if self.focused else 1, 4) ``` ## Text `text` draws all of its text from custom widgets (see [Drawing text](https://jamesgregson.github.io/slikui/guide/custom-widgets/#drawing-text)). `Tag` measures itself with `text_size` and centers its text with `env.text_in`: ``` import slikui class Tag(slikui.Widget): """A pill-shaped label sized to its text: ``measure`` asks the context how big the text is, ``paint`` centers it in the pill with ``env.text_in``. The same options go to both calls, so they agree.""" PAD_X, PAD_Y = 10, 4 def __init__(self, text, color=None): super().__init__() self.text = text self.color = color # None -> theme accent def opts(self): return dict(size=12, bold=True) def measure(self, constraints): s = self.context.text_size(self.text, **self.opts()) return constraints.clamp(slikui.Size(s.w + 2 * self.PAD_X, s.h + 2 * self.PAD_Y)) def stretch_cross(self): return False def paint(self, env): b = self.bounds env.list.rect(b, self.color or env.theme.accent, b.h / 2) env.text_in(b, self.text, align="center", valign="middle", color=slikui.Color(255, 255, 255), **self.opts()) ``` `SelectableText` keeps a `TextBlock`, re-laid only when its width changes, and uses it for drag-to-select: ``` import slikui class SelectableText(slikui.Widget): """Wrapped, drag-to-select text: a kept ``TextBlock`` answers which character is under the pointer (``hit_test``), where the caret goes (``caret_rect``) and what to highlight (``selection_rects``). Indices are ordinary ``str`` indices.""" def __init__(self, text, on_select=None): super().__init__() self.text = text self.on_select = on_select self.block = None self.anchor = self.caret = 0 self.dragging = False @property def selected(self): a, b = sorted((self.anchor, self.caret)) return self.text[a:b] def measure(self, constraints): w = constraints.max.x if constraints.max.x < 1e6 else 0 return constraints.clamp(self.context.text_size(self.text, wrap=True, max_width=w)) def arrange(self, area): self.bounds = area # Re-lay the block only when the width changes. if self.block is None or self.block_w != area.w: self.block = self.context.text_layout(self.text, area.w) self.block_w = area.w def _index(self, pos): return self.block.hit_test(slikui.Vec2(pos.x - self.bounds.x, pos.y - self.bounds.y)) def on_event(self, e): T = slikui.EventType if e.type == T.MousePress and e.button == slikui.MouseButton.MouseLeft: self.anchor = self.caret = self._index(e.pos) self.dragging = True self.context.capture_mouse(self) return True if e.type == T.MouseMove and self.dragging: self.caret = self._index(e.pos) return True if e.type == T.MouseRelease and self.dragging: self.dragging = False self.context.release_mouse(self) if self.on_select: self.on_select(self.selected) return True return False def paint(self, env): if self.block is None: return b, th = self.bounds, env.theme for r in self.block.selection_rects(self.anchor, self.caret): env.list.rect(slikui.Rect(b.x + r.x, b.y + r.y, r.w, r.h), th.accent.with_alpha(0.35)) env.draw(self.block, slikui.Vec2(b.x, b.y)) c = self.block.caret_rect(self.caret) env.list.rect(slikui.Rect(b.x + c.x, b.y + c.y, 1.5, c.h), th.accent) ``` The C++ twin is `examples/07_text` (`--smoke` runs the same checks headless). ## Your own renderer `renderer` proves the C++ and pure-Python renderers produce identical frames, then shows the seam a third-party renderer plugs into: ``` from collections import Counter import slikui class TraceSink(slikui.RenderSink): """The skeleton of a third-party renderer. ``upload`` gets each texture once (and again when it changes): ``up.id``, ``up.width``, ``up.height``, ``up.format`` (Alpha8 for the font atlas, Rgba8 for images) and ``up.pixels``. Create your GPU texture here, keyed by ``up.id``. ``render`` gets the whole frame, in paint order. Per command: * Rect - ``rect``, ``color``, ``radius``; ``hollow`` + ``thickness`` for outlines (a rounded-rect SDF quad on the GPU). * Line - from ``(rect.x, rect.y)`` to ``(rect.x + rect.w, rect.y + rect.h)``, ``thickness``, ``color`` (a capsule). * Glyph - textured quad: ``rect`` on screen, ``uv`` in *texel* units of texture ``tex_id`` (alpha8), tinted by ``color``. * Image - like Glyph, rgba texture, untinted. * ClipPush / ClipPop - a scissor stack: intersect ``rect`` with the top. Coordinates are logical points; multiply by your HiDPI scale. To draw over your own 3D scene, call ``ctx.render(False)`` so slikui skips its full-frame background rect. """ def __init__(self, width, height): super().__init__() self.inner = slikui.CanvasSink(width, height) # stand-in backend self.uploads = {} # tex id -> (w, h, format) self.counts = Counter() def upload(self, up): self.uploads[up.id] = (up.width, up.height, up.format) self.inner.upload(up) # -> glTexImage2D / pygame.Surface ... def render(self, cmds, framebuffer_size): self.counts = Counter(c.type.name for c in cmds) self.inner.render(cmds, framebuffer_size) # -> your draw loop ``` ## A live window `window` runs a small tour in a real window; its root widget sees every mouse move that bubbles up unconsumed: ``` import slikui class PointerRoot(slikui.Widget): """Root container that reports the pointer position: events bubble from the widget under the pointer up to the root unless a widget consumes them, so the root sees moves over anything that doesn't.""" def __init__(self): super().__init__() self.on_pointer = None def measure(self, constraints): return self.children[0].measure(constraints) def arrange(self, area): self.bounds = area self.children[0].arrange(area) def on_event(self, e): if e.type == slikui.EventType.MouseMove and self.on_pointer: self.on_pointer(e.pos.x, e.pos.y) return False ``` Any windowing toolkit works the same way: translate its input into `slikui.mouse_press` / `key_press` / `text_input` (and friends) events for `app.handle`, call `app.tick` then `app.render` each frame, and show the returned `(H, W)` uint32 array. # Input & events Backends translate native events into one `slikui::Event` vocabulary; `Context::handle` routes them. Your application code rarely constructs events by hand in C++ - the [window layer](https://jamesgregson.github.io/slikui/guide/backends/index.md) does it - but the vocabulary is the same on every platform and it is exactly what you translate (or synthesize in tests) yourself. To react to what the user does with the built-in widgets, you don't need events at all: use their callbacks (`on_click`, `on_change`, ...), see [Callbacks](https://jamesgregson.github.io/slikui/guide/callbacks/index.md). Events matter when you write your own widget or host. ## The event vocabulary Hosts send raw input: | Event | Carries | Notes | | ----------------------------- | --------------------------------- | ------------------------------------------------ | | `MouseMove` | `pos`, `delta`, `mods` | logical points, y-down | | `MousePress` / `MouseRelease` | `button`, `pos`, `mods`, `clicks` | any button; routed through hit-testing | | `Scroll` | `pos`, `scroll`, `mods` | wheel ticks | | `KeyPress` / `KeyRelease` | `key`, `mods`, `repeat` | focus-routed; `repeat` marks auto-repeat presses | | `TextInput` | `codepoint` | Unicode scalar, to the focused widget | | `FocusLost` | - | the app lost focus: cancels drags, closes popups | | `FrameResize` | `pos` = pixel size | converted to the logical frame | The Context synthesizes these for widgets (hosts never send them): | Event | When | Delivered to | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | | `Click` | press + release on the same widget, any button; `clicks` = 1, 2, 3... | the pressed widget, bubbling | | `DoubleClick` | after the `Click` whose `clicks == 2` | the pressed widget, bubbling | | `MouseEnter` / `MouseLeave` | the pointer entered / left the widget *and its descendants* | that widget only | | `FocusGained` / `FocusLost` | keyboard focus moved (or the app lost focus mid-drag) | that widget only | | `PopupClosed` | this popup or dialog left the screen (click outside, Escape, focus loss, menu action, `close_popups`, ...); sent after the closing event, skipped if it was reopened in the same pass | the popup's root widget only | `clicks` counts presses of the same button within `Event::kMultiClickTime` (0.4 s, Python `slikui.Event.MULTI_CLICK_TIME`) and `kMultiClickSlop` (4 px) of the previous one. Events carry no timestamps, so the timing is measured on the Context's tick clock: headless tests must advance ticks between clicks. ``` // You normally receive these from the window layer; synthesizing works // the same way (headless tests do exactly this): ctx.handle(slikui::Event::mouse_press({60, 40})); ctx.handle(slikui::Event::text_input('h')); ``` ``` ui.handle(slikui.mouse_press((60, 40))) # click through hit-testing ui.handle(slikui.text_input("h")) # into the focused TextField ui.handle(slikui.scroll(pos, (0, -1))) # wheel, "ctrl+shift" mods supported ``` Python event constructors (`slikui.mouse_press`, `text_input`, `scroll`, `key_press`, ...) build real `Event` values that drive the real dispatch path - the simulated-input tests use them. ## Routing rules 1. **Hit-testing** - the deepest visible widget containing the pointer wins. 1. **Bubble up** - the event dispatches up the parent chain until a widget consumes it (widgets return `true` from `on_event`). Enter/Leave, FocusGained/FocusLost and PopupClosed never bubble. 1. **Every button** - left, middle and right presses all reach widgets (built-ins act on the left button only). A right press on a widget with a context menu opens the menu instead; that press and its release are not delivered. 1. **Focus** - key/text events go to the focused widget; with nothing focused, key events go to the hovered widget. A left click focuses the nearest focusable ancestor of the hit; `Tab` / `Shift`+`Tab` cycle focusables in tree order; `Escape` clears focus. Tab, Escape and shortcut chords are consumed by the Context. A `KeyRelease` is delivered only for a press the tree received. The focused widget gets an accent focus ring after keyboard navigation (Tab, arrow keys, Home/End, PageUp/PageDown) and none after a click, like `:focus-visible` on the web (`Context::focus_visible`). Text widgets show focus with their accent border instead. Override `Widget::draws_own_focus`, `focus_rect` or `paint_focus_ring` to change it. Closing a popup that holds focus returns focus to the widget that was focused when it opened. While a popup is open and focus is not inside one, `KeyPress` and `TextInput` go to the topmost popup's root first (a `Menu` uses them to navigate); whatever it doesn't consume continues to the usual target. ### Widget keys | Widget | Keys (when focused) | | ------------------ | ------------------------------------------------------------------------------------ | | Button, IconButton | Enter / Space click | | Checkbox, Radio | Space toggles | | Switch, Expander | Space / Enter toggle | | Slider | arrows a step, PageUp/PageDown a tenth, Home/End the ends | | DragValue | arrows a step, Enter to type a value, Escape cancels | | Vec2Pad | arrows 1% (Shift 10%) | | Tabs, Segmented | Left/Right (wrapping), Home/End | | ListView, Table | Up/Down, Home/End, PageUp/PageDown; Enter/Space `on_activate` | | TreeView | as ListView; Right opens / enters, Left closes / goes to the parent | | Dropdown | Up/Down/Home/End step while closed; Space/Enter/Alt+Down open | | ColorEdit | Space/Enter open the picker | | Menu (open) | Up/Down, Home/End, letters, Enter/Space, Right/Left for submenus | | MenuBar | one Tab stop; Left/Right between titles, Down/Enter/Space/Up open; F10 from anywhere | | Splitter | arrows along the split 10 px (Shift 50 px), Home/End | | LogView | Up/Down, PageUp/PageDown, Home/End scroll back (hovered too) | | ScrollArea | Up/Down, PageUp/PageDown, Home/End that a widget inside left unconsumed | Escape closes the topmost popup, then the topmost dialog, then clears focus. F10 opens the menu bar (and closes open popups); focus returns where it was once the menus close. A focused text widget (`TextField`, `SearchBox`, `TextArea`, a `DragValue` being typed into) consumes the `KeyPress` of every key that types a character: letters, digits, punctuation, Space and keypad keys, unless `Ctrl`/`Cmd` is held. So typing never triggers a key handler further up the tree. The character itself arrives as `TextInput`. Ctrl/Cmd chords and keys like the F-keys still bubble. `is_text_key(key)` tells which keys count. 5. **Popups** - clicking outside a popup dismisses it. Popups are owned by the context and destroyed at the end of `handle`, never during dispatch. 6. **Mouse capture** - a widget calls `ctx->capture_mouse(this)` (Python: `self.context.capture_mouse(self)`) on press to receive every following move and the release, even outside its bounds, and `release_mouse` when done. If the app loses focus mid-drag, the capturing widget receives `FocusLost` - cancel the drag there. ## Watching events: the shipped EventProbe demo `slikui.examples.events` is a custom widget whose whole job is narrating every event it receives into a LogView - enter/leave, press/release/click, double-click, a captured drag that leaves the widget, scroll, the right-click context menu, focus gained/lost, focus-routed keys (press and release) and text. Its `--smoke` pass drives the whole vocabulary synthetically and asserts each event arrives, in order, exactly where the routing rules above say it should. The probe is also the reference drag idiom - capture on press, release on release, cancel on `FocusLost`: ``` import slikui INFO = slikui.LogView.Level.Info WARN = slikui.LogView.Level.Warning OK = slikui.LogView.Level.Success T = slikui.EventType LEFT = slikui.MouseButton.MouseLeft def mods_str(mask): """0x3 -> 'ctrl+shift' - the inverse of slikui.mods('ctrl+shift').""" names = [] for bit, name in ((slikui.Mod.ModShift, "shift"), (slikui.Mod.ModCtrl, "ctrl"), (slikui.Mod.ModAlt, "alt"), (slikui.Mod.ModSuper, "super")): if mask & int(bit): names.append(name) return "+".join(names) if names else "none" def describe(e): """One human line per event - the shape of the whole vocabulary.""" t = e.type if t == T.MouseMove: return (f"move pos ({e.pos.x:.0f}, {e.pos.y:.0f})" f" delta ({e.delta.x:+.1f}, {e.delta.y:+.1f})") if t in (T.MousePress, T.MouseRelease, T.Click, T.DoubleClick): return (f"{t.name.lower():<8} button {e.button} clicks {e.clicks}" f" mods {mods_str(e.mods)}") if t == T.Scroll: return f"scroll ({e.scroll.x:+.1f}, {e.scroll.y:+.1f})" if t in (T.KeyPress, T.KeyRelease): rep = " (repeat)" if e.repeat else "" return f"{'keydown' if t == T.KeyPress else 'keyup':<8} {e.key.name} mods {mods_str(e.mods)}{rep}" if t == T.TextInput: return f"text {chr(e.codepoint)!r} (focus-routed)" if t in (T.MouseEnter, T.MouseLeave): return f"{'enter' if t == T.MouseEnter else 'leave':<8} pos ({e.pos.x:.0f}, {e.pos.y:.0f})" return t.name # FocusGained / FocusLost class EventProbe(slikui.Widget): """Narrates every event it receives into a LogView via ``sink``. Also the reference drag idiom: capture the mouse on press, so moves and the release keep arriving after the pointer leaves the widget; release the capture on MouseRelease; cancel on FocusLost (the app lost focus mid-drag - the release may never come). """ def __init__(self): super().__init__() self.sink = None # callable(level, text) - usually a LogView self.seen = [] # (EventType, line) - full record, for tests self.last_pos = None # last pointer position seen, for painting self.hovered = False self.dragging = False self.log_moves = True def measure(self, constraints): return constraints.clamp(slikui.Size(220, 120)) def stretch_cross(self): return False def focusable(self): return True def on_event(self, e): if e.type != T.MouseMove or self.log_moves: self._say(e.type, INFO, describe(e)) if e.type in (T.MouseMove, T.MousePress, T.MouseRelease, T.Scroll): self.last_pos = (e.pos.x, e.pos.y) if e.type == T.MouseEnter: self.hovered = True elif e.type == T.MouseLeave: self.hovered = False elif e.type == T.MousePress and e.button == LEFT: self.dragging = True self.context.capture_mouse(self) # moves + release keep coming elif e.type == T.MouseRelease and e.button == LEFT and self.dragging: self.dragging = False self.context.release_mouse(self) elif e.type == T.FocusLost and self.dragging: self.dragging = False # app lost focus mid-drag self.context.release_mouse(self) self._say("note", WARN, "drag cancelled by FocusLost") elif e.type == T.DoubleClick: self._say("note", OK, "double-click (core DoubleClick event)") # Consume pointer input; keys/text only log (bubbling is harmless). return e.type in (T.MouseMove, T.MousePress, T.MouseRelease, T.Click, T.DoubleClick, T.Scroll) def _say(self, kind, level, text): self.seen.append((kind, text)) if self.sink: self.sink(level, text) def paint(self, env): b, th = self.bounds, env.theme env.list.rect(b, th.surface_alt, 6) edge = th.accent if (self.focused or self.hovered) else th.border env.list.hollow_rect(b, edge, 2 if self.focused else 1, 6) if self.dragging: env.list.hollow_rect(b.inflate(2, 2), th.accent, 2, 8) if self.last_pos is not None and self.hovered: env.list.circle(slikui.Vec2(*self.last_pos), 6.0 if self.dragging else 3.0, th.accent) ``` Run it: `python -m slikui.examples.events` (headless screenshot) or `--smoke` for the scripted pass. For a one-screen summary measured on your installed build, run `python -m slikui.examples --contract`. ## Menus, context menus and shortcuts `MenuBar`/`Menu` are built once and opened as borrowed popups; any widget can carry a right-click menu; global accelerators run before widget dispatch (a modifier is required, so typing never triggers one). Full details and code: [Menus & toolbars](https://jamesgregson.github.io/slikui/reference/widgets-menus/index.md). ``` viewport.set_context_menu(&view_menu); // right-click ctx.add_shortcut(slikui::Key::R, slikui::ModCtrl, render_fn); ``` ``` viewport.set_context_menu(view_menu) # right-click ctx.add_shortcut(slikui.Key.R, slikui.mods("ctrl"), render_fn) ``` `Key` names physical keys: letters, top-row digits (`Num0`-`Num9`), punctuation, and the numeric keypad (`Kp0`-`Kp9`, `KpDecimal`, `KpDivide`, `KpMultiply`, `KpSubtract`, `KpAdd`, `KpEqual`; keypad Enter arrives as `Enter`). Bind both `Equal` and `KpAdd` to serve either zoom key. ## Clipboard `TextField`/`TextArea` read and write the host clipboard through `ctx.set_clipboard_source` / `ctx.set_clipboard_sink`. The GLFW backend wires the system clipboard; without a host the Ctrl/Cmd+A/C/X/V shortcuts are silent no-ops. ## Tooltips Any widget carries a tooltip with `set_tooltip("...")`. It appears after a ~0.6 s hover delay and dismisses on mouse-away or click. Because setters return `Widget&` (no deducing-this before C++23), base-class setters like `set_tooltip` must come **last** in a chain. ``` auto& row = root.add(); row.set_gap(10); row.add("Save"); row.add("Delete all") .set_tooltip("Removes every item - this cannot be undone"); ``` ``` row = root.add(slikui.Row, gap=10) row.add(slikui.Button, "Save") row.add(slikui.Button, "Delete all", tooltip="Removes every item - this cannot be undone") ``` A tooltip that is showing follows changes. Calling `set_tooltip` with new text swaps it at once, and `""` closes it. **Different tips for different parts of a widget.** The context asks the hovered widget for its text at the pointer each tick, through `tooltip_at(pos)`. It defaults to the `set_tooltip` text. When the answer changes under a showing tooltip, the tooltip swaps without waiting for the delay again, so moving down a list reads row after row. The built-ins use this: - `TreeView`: a row's own `Row::tooltip`; otherwise its full label when the row shows it cut off with "...". - `ListView` and `Segmented`: the full text of an item or segment drawn cut off. - Otherwise each falls back to the widget's `set_tooltip` text. A custom widget can override `tooltip_at` (Python too): ``` class Halves(slikui.Widget): def tooltip_at(self, pos): return "left" if pos.x < self.bounds.x + self.bounds.w / 2 else "right" ``` ## Cursor shapes Widgets request cursor shapes with `set_cursor(slikui::Cursor::...)` - hosts map them to system cursors via `ctx.set_cursor_host` (`GlfwWindow::attach` does this; in Python `ctx.set_cursor_host(fn)`). # Layout Layout is immediate-mode in spirit but retained in the tree. `Column` and `Row` are the workhorses; `Panel`, `Spacer` and `Divider` shape them; `Expander`, `Accordion` and `Splitter` handle collapsible and split regions. ## Row, Column, Spacer, Divider Both containers stack children with `set_gap` and `set_padding`, distribute extra main-axis space to children that expand, and align cross-axis with `set_cross` (`CrossMode::Stretch`, `Start`, `Center`). `Spacer` soaks up remaining space - use it to push siblings to the far edge. Any widget can do the same with `set_expand()` (Python: `expand=True`) - a `ScrollArea` or `Splitter` filling the rest of a window's column instead of keeping its size hint. `Divider` draws a rule. ``` auto& panel = root.add(); panel.set_padding(14).set_gap(10); panel.set_radius(10); panel.add("Panel - a bordered container"); auto& top = panel.add(); top.add("left"); top.add(); // pushes "right" to the far edge top.add("right"); panel.add(); auto& bot = panel.add(); bot.set_gap(16); bot.add("Snap", true); bot.add("Grid", false); ``` ``` panel = root.add(slikui.Panel, padding=14, gap=10, radius=10) panel.add(slikui.Label, "Panel - a bordered container") top = panel.add(slikui.Row) top.add(slikui.Label, "left") top.add(slikui.Spacer) # pushes "right" to the far edge top.add(slikui.Label, "right") panel.add(slikui.Divider) bot = panel.add(slikui.Row, gap=16) bot.add(slikui.Checkbox, "Snap", True) bot.add(slikui.Checkbox, "Grid", False) ``` ## Panel `Panel` is a bordered, rounded container - a `Container` that paints a surface. `set_background`, `set_border`, `set_radius` style it; everything else matches `Column`. ## Expander and Accordion `Expander` shows/hides its subtree behind a titled header (`set_title`, `set_open`, `on_toggle(void(bool))`). Closed children get zero frames and skip hit-testing - collapsing is genuinely free. `Accordion` stacks `Expander` sections. `add_section(title, open = false)` returns the section's `Expander` (itself a `Container`) - fill it with rows, sliders, whatever the group needs. By default the accordion is **exclusive**: opening one section closes the others. `set_exclusive(false)` lets every section stand open. ``` auto& acc = root.add(); acc.set_gap(6); auto& shape = acc.add_section("Shape", /*open=*/true); shape.set_gap(8); shape.add().set_items({"Cube", "Sphere", "Torus"}) .set_selected(0); auto& material = acc.add_section("Material"); material.set_gap(8); material.add(0.f, 1.f); // roughness material.add(0.f, 1.f); // metallic ``` ``` acc = root.add(slikui.Accordion, gap=6) shape = acc.add_section("Shape", True) shape.set_gap(8) shape.add(slikui.Dropdown, items=["Cube", "Sphere", "Torus"], selected=0) material = acc.add_section("Material") material.set_gap(8) material.add(slikui.Slider, 0, 1) # roughness material.add(slikui.Slider, 0, 1) # metallic ``` ## Splitter `Splitter` divides two children with a draggable divider: `set_fraction` (0-1), `on_change(void(float))`. Construct with `true` for a horizontal divider / stacked panes. The capture below pairs it with an `Expander`: ``` auto& exp = root.add("More options"); exp.set_open(true); auto& inner = exp.add(); inner.set_gap(8); inner.add("Compress", true); inner.add("Overwrite", false); auto& split = root.add(); split.set_fraction(0.45f); auto& l = split.add(); l.set_padding(12).set_radius(8); l.add("left pane").set_color(ctx.theme().accent); auto& r = split.add(); r.set_padding(12).set_radius(8); r.add("right pane").set_color(ctx.theme().warning); ``` ``` exp = root.add(slikui.Expander, open=True) exp.set_title("More options") inner = exp.add(slikui.Column, gap=8) inner.add(slikui.Checkbox, "Compress", True) inner.add(slikui.Checkbox, "Overwrite", False) split = root.add(slikui.Splitter, fraction=0.45) l = split.add(slikui.Panel, padding=12, radius=8) l.add(slikui.Label, "left pane").set_color(ui.ctx.theme.accent) r = split.add(slikui.Panel, padding=12, radius=8) r.add(slikui.Label, "right pane").set_color(ui.ctx.theme.warning) ``` ## Window resizing Layout is recomputed from scratch every tick, so resizes reflow automatically: the backend emits a frame-resize event, `ScrollArea` clamps its offset, labels re-wrap to the available width, and popups re-clamp to the frame. HiDPI is a `theme().scale` change - layout stays in logical points, each sink maps them to device pixels (see [Theming](https://jamesgregson.github.io/slikui/guide/theming/index.md)). API details: [Containers](https://jamesgregson.github.io/slikui/reference/widgets-containers/index.md). # Text & fonts slikui rasterizes TrueType text itself - vendored public-domain stb_truetype/stb_rect_pack compiled with internal linkage, no system dependencies, no icon fonts. ## Loading a font A `Context` has exactly one active font. Load it from a file, or from memory: ``` #include // find_system_font() #include // optional bundled subset ctx.load_font_file(slikui::find_system_font()); // system TTF // or, for identical text everywhere - even on machines with no fonts: ctx.load_font_memory(slikui::text::default_font_data(), slikui::text::default_font_size()); ``` ``` import slikui ctx.load_font_file(slikui.find_system_font()) ctx.load_default_font() # bundled DejaVu Sans subset ``` `slikui::find_system_font()` searches the usual per-platform paths and returns an empty string when nothing is found - check the return of `load_font_file` and fall back to the bundled font. ## Font families and styles Beyond the body font, register more faces by family name. Three names are roles every text call understands - `"body"` (what `load_font_file` loads), `"heading"` and `"mono"` - and any other name is your own. An unregistered family falls back to body. ``` ctx.add_font("mono", "/path/JetBrainsMono-Regular.ttf"); ctx.add_font("body", "/path/Inter-Bold.ttf", slikui::text::FontStyle::Bold); // Installed fonts by role and style (.ttc faces resolved for you): if (auto f = slikui::find_system_font_face("mono")) ctx.add_font("mono", f.path, slikui::text::FontStyle::Regular, f.face); ``` ``` ctx.add_font("mono", "/path/JetBrainsMono-Regular.ttf") ctx.add_font("body", "/path/Inter-Bold.ttf", slikui.FontStyle.Bold) f = slikui.find_system_font_face("mono", slikui.FontStyle.Bold) if f: ctx.add_font("mono", f.path, slikui.FontStyle.Bold, f.face) ``` Bold and italic never need a font file: when a family has no face for the requested style, slikui synthesizes it from the closest face it has (italic slants the outline, bold thickens the glyph). Real faces look better, so register them when you ship them. Underline and strikethrough use the font's own placement metrics and draw in the text color. `Label` takes all of these as setters: ``` root.add("Warning").set_bold().set_underline(); root.add("x = 3.14").set_font("mono"); ``` ``` root.add(slikui.Label, "Warning", bold=True, underline=True) root.add(slikui.Label, "x = 3.14", font="mono") ``` Custom widgets draw text with the same options through `env.text` - see [Custom widgets](https://jamesgregson.github.io/slikui/guide/custom-widgets/#drawing-text). ## The bundled font The single-header `dist/slikui.hpp` bakes in a ~35 KB DejaVu Sans subset (ASCII, Latin-1 + punctuation) so text renders identically everywhere, even on headless containers. Building from the include tree the same font stays **opt-in**: `#include `. The Python wheels use it as the fallback whenever no system font exists. Licence: `third_party/fonts/LICENSE-DejaVu.txt` - ship it with your app. ## How glyphs reach the screen - Each font face owns its TTF bytes, an stb_truetype fontinfo, a glyph cache and an alpha8 atlas of 512x512 pages. Glyphs rasterize on demand; when a page fills, a new page (with its own texture id) is added, and dirty pages are pushed to the sink. - The cache is keyed by glyph, size (rounded to 1/4 px) and synthesized style, so bold and regular text at the same size coexist. - `layout(text, px, max_width, flags)` produces positioned glyphs with word wrapping, per-line byte ranges, and underline/strikethrough bars; `advance_upto` powers caret hit-testing in text fields. - Layouts are cached per widget (`Label`, `ListView`, `Tabs`) and invalidated on text or size changes; `env.text` layouts are cached by the context and dropped after about two seconds unused. - Whitespace glyphs are never drawn. - Glyphs re-rasterize automatically when `theme().scale` changes (window dragged between displays). ## Sizing and wrapping Theme metrics set the base size (`theme().base_font_px`); individual widgets override with `set_font_size`. `Label` word-wraps with `set_wrap_width`; with no explicit width it wraps to the constraint width, so narrower windows produce taller text blocks automatically. API details: [Label](https://jamesgregson.github.io/slikui/reference/widgets-controls/#label), [TextField](https://jamesgregson.github.io/slikui/reference/widgets-inputs/index.md). # Theming `ctx.theme()` is a plain struct widgets read on every paint - there is no cached styled state to invalidate. Change it any time, including per frame. ## The Theme struct Three groups of fields: - **Palette** - `background`, `surface`, `surface_alt`, `border`, `text`, `text_dim`, `accent`, `accent_text`, `danger`, `success`, `warning`. - **Metrics** - `base_font_px`, `radius`, `border_width`, `gap`, font sizes, `scale`. - **Derive helpers** - `hover()`, `press()`, `dimmed()` used by widgets for transitions. ## Built-in presets Eight presets ship with the library - each varies the palette *and* the corner radius, so every scheme gets its own character: Dark, Light, Nord, Dracula, Gruvbox, Mocha (Catppuccin), Solarized, and Phosphor (green CRT terminal, square corners). ``` ctx.theme() = slikui::Theme::nord(); // simplest - resets scale too slikui::use_theme(ctx.theme(), slikui::Theme::mocha()); // keeps your `scale` slikui::apply_preset(ctx.theme(), 5); // by index, wraps around // Build a picker from the registry: for (const auto& p : slikui::theme_presets()) names.push_back(p.name); header.add().set_items(names) .on_select([&](size_t i) { slikui::apply_preset(ctx.theme(), i); }); ``` ``` import slikui ui.ctx.theme = slikui.Theme.mocha() # or by index: apply_preset for preset in slikui.theme_presets(): print(preset.name) # build a picker from this ``` Each card in the strip is real output - `tools/components_capture.cpp` renders one card per built-in preset from this tree (`p` is the preset being rendered): ``` root.add(p.name).set_font_size(16); auto& r1 = root.add(); r1.set_gap(8); r1.add("Primary").set_variant(slikui::Button::Variant::Primary); r1.add("Ghost").set_variant(slikui::Button::Variant::Ghost); auto& r2 = root.add(); r2.set_gap(12); r2.add("Snap", true); r2.add("Wi-Fi", true); r2.add().set_checked(true); ``` ## Custom themes Anything not in the preset list is one struct away - assign the palette fields by hand. `Color::from_hex(0xRRGGBB)` builds colors; derive helpers give you the hover/press/dim variants widgets expect. ``` ctx.theme().accent = slikui::Color::from_hex(0xE060B0); // your brand ctx.theme().radius = 4.f; // squarer corners ``` ``` ui.ctx.theme.accent = slikui.Color.from_hex(0xE060B0) ui.ctx.theme.radius = 4.0 ``` ## HiDPI and scaling Layout runs in **logical points**; each sink maps them to device pixels: ``` ctx.theme().scale = 2.f; // retina-class density sink.set_scale(ctx.theme().scale); ``` ``` ui = slikui.App(480, 320, scale=2) # framebuffer 960x640, layout 480x320 ``` `theme().scale` is picked up on the next frame; glyphs re-rasterize at the new size automatically, so dragging a window between displays just works. Every screenshot on this site is rendered at 2x density through exactly this path (`theme().scale` + `sink.set_scale()`), which is why glyphs stay crisp. # Reference # Widget index Every widget class, grouped by reference page. All are exported from `slikui/widgets/all.hpp` in C++ and the `slikui` module in Python. For the callbacks each widget offers (`on_click`, `on_change`, ...) and the arguments they receive, see the table in [Callbacks](https://jamesgregson.github.io/slikui/guide/callbacks/#every-callback). ## Controls - [widgets-controls.md](https://jamesgregson.github.io/slikui/reference/widgets-controls/index.md) | Widget | Purpose | | ----------------------------- | ---------------------------------------------- | | `Button` | four variants: Default, Primary, Danger, Ghost | | `Checkbox`, `Radio`, `Switch` | bool controls with `on_change` | | `Slider` | float range, built-in label + live value row | | `Segmented` | compact radio-style row | | `ProgressBar` | clamped 0-1 fraction | | `Spinner` | animated forever, driven by `tick` | | `Label` | static text, size/color/wrap | ## Text inputs - [widgets-inputs.md](https://jamesgregson.github.io/slikui/reference/widgets-inputs/index.md) | Widget | Purpose | | ------------ | ----------------------------------------- | | `TextField` | single-line editing, selection, clipboard | | `TextArea` | multiline editing | | `ScrollArea` | scrolling viewport for one child | | `SearchBox` | TextField + magnifier + clear button | | `GroupBox` | titled panel | ## Editors - [widgets-editors.md](https://jamesgregson.github.io/slikui/reference/widgets-editors/index.md) | Widget | Purpose | | ---------------------------------- | --------------------------------------------------------- | | `DragValue` | drag-to-scrub number field (Blender-style) | | `Vec2Edit`, `Vec3Edit`, `Vec4Edit` | per-axis editors over a borrowed `float[N]` / numpy array | | `ColorEdit` | swatch + SV/hue popup | | `Vec2Pad` | 2D pad with draggable dot | ## Data display - [widgets-data.md](https://jamesgregson.github.io/slikui/reference/widgets-data/index.md) | Widget | Purpose | | -------------- | -------------------------------------------- | | `ListView` | selectable item list | | `Tabs` | tab bar | | `Dropdown` | click-to-open selection popup | | `Plot` | lines/bars/fill + markers, autoscale | | `TreeView` | flat `(label, depth, expandable)` rows | | `Table` | columns + header + selectable rows | | `PropertyGrid` | inspector with fixed label column + sections | | `Image` | PNG/JPEG/pixels, `Stretch`/`Contain`/`Cover` | ## Containers - [widgets-containers.md](https://jamesgregson.github.io/slikui/reference/widgets-containers/index.md) | Widget | Purpose | | --------------- | ---------------------------------------- | | `Column`, `Row` | main-axis stacks | | `Panel` | bordered, rounded container | | `Spacer` | soaks up remaining main-axis space | | `Divider` | rule between siblings | | `Expander` | titled collapsible section | | `Accordion` | stack of expanders, exclusive by default | | `Splitter` | two panes + draggable divider | ## Shells & dialogs - [widgets-shells.md](https://jamesgregson.github.io/slikui/reference/widgets-shells/index.md) | Widget | Purpose | | ---------------------- | --------------------------------------- | | `Dialog`, `MessageBox` | floating shells, optional modal | | `Toast` | auto-dismissing corner notice | | `StatusBar` | status text + right-side widgets | | `LogView` | severity-colored autoscrolling console | | `FileBrowser` | real-directory Open/Save | | `ImageView` | pan/zoom bitmap over a checkerboard | | `CompareView` | two images split by a draggable divider | ## Menus & toolbars - [widgets-menus.md](https://jamesgregson.github.io/slikui/reference/widgets-menus/index.md) | Widget | Purpose | | ----------------------------- | ------------------------------------------------------- | | `MenuBar`, `Menu`, `MenuItem` | menus, checkables, submenus, shortcut hints | | `Toolbar`, `IconButton` | icon strips with a procedural icon set (`slikui::Icon`) | | `IconPainter` | custom icon drawing for `IconButton::set_icon_painter` | ## Base class | Class | Purpose | | ----------- | --------------------------------------------------------------------------- | | `Widget` | tree, protocol (`measure`/`arrange`/`paint`/`on_event`/`tick`), state flags | | `Container` | padding/gap/cross-axis base for layouts | | `PaintEnv` | draw list + theme + text (`text`, `text_in`, `draw`) handed to `paint` | # slikui architecture ## Module map ``` include/slikui/ |-- core/ math (Vec2/Rect/Padding), Color, Event, Time, utf8 |-- layout/ Constraints, CrossMode, flex distribution |-- render/ DrawList (display list), IRenderSink (the only backend contract) |-- style/ Theme (palette + metrics), Anim (tween), easing |-- text/ Font (stb_truetype), glyph atlas, layout/wrap/measure |-- widgets/ Widget base + the widget set (containers, controls, | inputs, views, Image; textures flow through collect_uploads) |-- context.hpp Context: tree ownership, input routing, focus, popups, | hover tooltips, frame loop `-- backends/ |-- software/ CPU rasterizer over raw uint32_t pixels |-- opengl/ GL 3.3 core renderer (system headers, no loader) |-- glfw/ optional GLFW input translation + window (guarded by __has_include) `-- sdl/ optional SDL3 input translation + window (guarded by __has_include) ``` Dependency direction is strictly downward: widgets depend on render/text/style, nothing depends on a specific backend except `context.hpp` (which only knows the `IRenderSink` interface). ## The frame pipeline ``` ctx.handle(event); // 1. input ctx.tick({now, dt}); // 2. attach -> layout -> animation ctx.render(); // 3. paint -> sink ``` 1. **Input** - backends translate native events into one `slikui::Event` vocabulary. `Context::handle` routes them: hit-test the deepest visible widget containing the pointer, then dispatch the event **up the parent chain** until consumed. Key/text events go to the focused widget. Clicking focuses the nearest focusable ancestor of the hit; Tab cycles focusables in tree order. Clicking outside a popup dismisses it (destroyed at the end of `handle`, never during dispatch). 1. **Tick** - `attach_tree` gives every widget a `Context*` (fonts/theme) on first sight. Then the root is measured and arranged top-down: every widget implements ``` Size measure(const Constraints&); // intrinsic size under bounds void arrange(const Rect& abs); // assign own absolute frame + children ``` Frames are **absolute framebuffer coordinates**, which makes hit-testing, painting and clipping trivial. Finally each widget's `tick(Time)` runs - animation state (`Anim`) advances here. 1. **Paint** - `paint_tree` walks the tree; widgets append commands to a `DrawList` via `PaintEnv` (draw list + theme + font). Containers may provide `clip_rect()` to clip their subtree. The finished list goes to the sink; popups are painted after the root. ## Layout model Flexbox-flavoured: `Column`/`Row` stack children along their main axis with a `gap` and `padding`; cross-axis alignment is `Stretch`/`Start`/`Center`. Children that report `expands_main()` (Spacer) split leftover main-axis space. `distribute()` in `layout/layout.hpp` holds the shared math and is unit-tested. ## Text pipeline `text::Font` is one face: the TTF bytes, an stb_truetype fontinfo, a glyph cache keyed by (glyph, 1/4-px size, synthesized style) and a growable atlas of 512x512 alpha8 pages, each pushed to the sink when dirty. `text::FontLibrary` (owned by `Context`) maps family names to faces, synthesizes missing bold/italic, and caches the layouts behind `env.text`. `layout(text, px, max_width, flags)` produces positioned glyphs with word wrapping, line/byte tables and underline/strikethrough bars; `advance_upto` powers caret hit-testing. Widget layouts are cached per widget (`Label`, `ListView`, `Tabs`) and invalidated on text/size changes. ## Extension points - **New widget**: subclass `Widget`, implement `measure`, `arrange` (default assigns `bounds`), `paint`, `on_event`, optionally `tick`, `focusable`, `clip_rect`, `expands_main`. - **New backend**: implement `IRenderSink` - see [guide/backends.md](https://jamesgregson.github.io/slikui/guide/backends/index.md). ~100-400 lines. - **Theming**: mutate `Context::theme()`; widgets read it every paint. There is no cached styled state to invalidate. ## Threading Single-threaded. One `Context` per thread; don't touch a context from other threads. The example loop drives everything from the main thread. ## Resize Layout is recomputed from scratch every tick, so window resizes reflow automatically - there is no cached geometry to invalidate. The pieces that make resize correct: - The backend emits `Event::FrameResize` with the **framebuffer** size; `Context::handle` converts it to the logical layout frame by dividing by `Theme::scale` (apps may also call `set_frame_size(logical)` directly). - Labels re-wrap to their available width: with no explicit `wrap_width`, a Label wraps to `Constraints::max.x`, so narrower windows produce taller blocks. - `ScrollArea` clamps its scroll offset whenever content/viewport heights change; popups are re-measured and re-clamped to the frame every tick. - `GlfwWindow::set_min_size(w, h)` optionally floors the window size. - HiDPI scale changes (window dragged between displays) are picked up on the next frame; glyphs re-rasterize at the new size automatically. ## Memory The tree is `std::unique_ptr`-owned (`Context::set_root`, `Widget::add`). Callbacks (`on_click`, `on_change`, ...) capture app state by reference/pointer - keep captures valid or remove the widget first. Popup widgets are owned by the context until the end of the event that closes them. # Context `slikui::Context` owns the tree, routes input, lays out, animates and paints. One context per thread; drive it with [handle -> tick -> render](https://jamesgregson.github.io/slikui/guide/core-concepts/#the-frame-loop). ## Tree | API | Notes | | ----------------------------------- | ----------------------------------------- | | `set_root(args...) -> T&` | construct + own the root | | `set_root(std::unique_ptr)` | take ownership of a pre-built tree | | `root()` | current root or `nullptr` | | `find(id)` | search the tree for `Widget::id` | | `clear_tree()` | destroy the tree now (releases callbacks) | ## Frame | API | Notes | | --------------------------- | ------------------------------------------------------------ | | `handle(const Event&)` | route one event; popups close at the end, never mid-dispatch | | `tick(Time{now, dt})` | attach -> measure -> arrange -> animation | | `render(bool clear = true)` | paint the tree + popups + shells into the sink | | `set_frame_size(Vec2)` | logical frame size (backends derive it from resize events) | ## Popups Owned by the context; destroyed at the end of the event that closes them. | API | Notes | | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `push_popup(widget, pos)` | unique_ptr or borrowed reference overload (Python: kept alive while open) | | `push_popup(widget, anchor, PopupDir)` | anchored popups (`Below`, `Right`, ...) | | `open_context_menu(widget, pos)` | open a `Menu` as a floating popup | | `close_popups()` / `close_topmost_popup()` / `close_popups_above(widget)` | dismissal | | `hold_while_open(widget, std::shared_ptr)` | keep a token alive while a popup/dialog is open; released after it closes (the Python bindings pin borrowed widgets with it) | | `has_popups()` / `popup_count()` / `popup(i)` / `popup_open(w)` | inspection | ## Dialogs, toasts The shell layer between the tree and popups - see [Shells & dialogs](https://jamesgregson.github.io/slikui/reference/widgets-shells/index.md). Layers, bottom to top: tree, toasts, modal dim, dialogs, popups. A `Dropdown`, popover or tooltip opened inside a dialog therefore shows over it. Opening or closing a dialog closes the popup stack, and Escape closes the topmost popup before the topmost dialog. While a modal dialog is open, presses outside it and its popups are ignored, and Tab cycles only through it, the dialogs above it and the popups. | API | Notes | | ------------------------------ | --------------------------------------------------------- | | `open_dialog(unique_ptr)` | owned dialog | | `open_dialog(D&)` | borrowed; in Python the context keeps it alive while open | | `close_dialog(widget)` | explicit close | | `dialog_count()` / `dialog(i)` | inspection | | `push_toast(widget, seconds)` | auto-dismissing corner notice; returns the widget | | `toast_count()` / `toast(i)` | inspection | Toasts are their own passive layer (above the tree, below dialogs and popups): never hit-tested, so clicks pass through them, and they neither close nor are closed by the popup stack. Several toasts stack upward from the bottom-right corner, newest lowest. ## Focus, capture, shortcuts | API | Notes | | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `focused()` / `set_focus(widget*)` | key/text routing target | | `focus_visible()` / `set_focus_visible(bool)` | whether focus rings show: true after keyboard navigation (Tab, arrows, Home/End, PageUp/PageDown), false after a mouse press | | `open_menu_bar()` | what F10 does: open the active layer's MenuBar with focus on its title; focus returns when the menus close. False without a menu bar | | `reveal_rect(widget, rect)` | scroll `widget`'s scrolling ancestors so `rect` is in view | | `capture_mouse(widget*)` / `release_mouse(widget*)` | receive every move/release while dragging | | `add_shortcut(Key, mods, fn)` | global accelerator; fires before widget dispatch, modifier required | | `clear_shortcuts()` | | ## Theme, font, clipboard, cursor | API | Notes | | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `theme() -> Theme&` | mutate freely; widgets read it every paint ([Theming](https://jamesgregson.github.io/slikui/guide/theming/index.md)) | | `load_font_file(path)` / `load_font_memory(data, len)` | the body font ([Text & fonts](https://jamesgregson.github.io/slikui/guide/text-fonts/index.md)) | | `add_font(family, path, style, face)` / `add_font_memory(...)` / `has_font(family)` | more faces by family name: `"heading"`, `"mono"`, your own | | `text_size(s, opts)` / `text_metrics(opts)` | measure text for `measure()` ([Drawing text](https://jamesgregson.github.io/slikui/guide/custom-widgets/#drawing-text)) | | `text_layout(s, wrap_width, opts) -> TextBlock` | a kept layout: draw, hit-test, caret, selection | | `set_clipboard_source(fn)` / `set_clipboard_sink(fn)` | host clipboard for text fields | | `clipboard_text()` / `set_clipboard_text(str)` | direct clipboard access | | `set_cursor_host(fn)` | map `set_cursor` requests to system cursors | | `next_texture_id()` | ids for custom `TexUpload`s - never reused for different content | Tooltips need no context API: any widget's `set_tooltip` (or `tooltip_at` override) makes the context show a popup after a ~0.6 s hover. `tooltip_text()` returns the text of the tooltip showing now (`""` if none). # Python bindings The `slikui` PyPI package binds the C++ API 1:1 through nanobind (`slikui._slikui`), then adds a thin Pythonic surface in `slikui._py`: kwargs-to-setters, the `App` shell, event constructors and pixel helpers. New widgets land C++-first so both languages get them. ## App shell `App` holds Target + Sink + Context and every owner, so the C++ side never sees a dangling backend: ``` import slikui ui = slikui.App(320, 200, scale=1.0) # + font=..., theme=... root = ui.set_root(slikui.Column, padding=16, gap=8) root.add(slikui.Label, "Hello, slikui!", font_size=26) root.add(slikui.Button, "Save", variant=slikui.ButtonVariant.Primary) ui.tick(0.0, 1 / 60) # layout + animation frame = ui.render() # zero-copy (H, W) uint32 ndarray ``` - `App(width, height, *, font=None, scale=1.0, theme=None)` - the logical frame is `width x height`; the framebuffer carries the scale. Font defaults to the system font, falling back to the bundled DejaVu subset when none exists (headless containers). - `resize(w, h)` - re-targets both. - `close()` - destroys the tree and releases the Python callbacks it holds; run automatically by `with App(...) as ui:` and at exit. Safe to call twice. GUI apps that keep their UI until interpreter shutdown can silence the leak report with `slikui.set_leak_warnings(False)`. - `render()` returns the framebuffer as a zero-copy `numpy` array, 0xAABBGGRR packing; `slikui.to_rgba(frame)` and `slikui.save_image(frame, path)` convert/save. ## Builder sugar `container.add(cls, *args, **props)` constructs the widget and applies kwargs: `foo=` resolves to `set_foo`, or to the attribute/method `foo` itself when there is no setter (e.g. `on_click=`). A wrong name is a loud `AttributeError`, not a silent no-op. A tuple that the setter won't take as one value is spread across its arguments: `range=(0, 100)` calls `set_range(0, 100)`, while `items=("a", "b")` still passes the tuple whole. Setters applied this way don't fire callbacks, so `on_change=` and `value=` can come in any order. Same for `ctx.set_root(cls, ...)`. For your own widget classes, kwargs named in `__init__` go to the constructor and the rest to setters: `row.add(Knob, value=3, tooltip="t")` calls `Knob(value=3)`, then `set_tooltip("t")`. Values: `Color(r, g, b, a=255)` takes 0..255 ints; use `Color.from_float(r, g, b, a=1.0)` for normalized floats. `Constraints(min, max)` builds arbitrary constraints (also `loose`, `tight`). If type-level patching is unavailable, module-level `slikui.add(container, ...)` / `slikui.set_root(context, ...)` are the fallbacks. ## Events Real `Event` values drive the real dispatch path - simulated-input tests use them: ``` ui.handle(slikui.mouse_press((60, 40))) # click through hit-testing ui.handle(slikui.text_input("h")) # into the focused TextField ui.handle(slikui.scroll(pos, (0, -1))) # wheel, "ctrl+shift" mods supported ui.handle(slikui.key_press(slikui.Key.S, slikui.mods("ctrl"))) ui.handle(slikui.frame_resize(960, 640)) # framebuffer pixels ``` Constructors: `mouse_move`, `mouse_press`, `mouse_release`, `mouse_click`, `scroll`, `key_press`, `key_release`, `text_input`, `text_input_str`, `focus_lost`, `frame_resize`; `mods("ctrl+shift")` builds the modifier mask. ## Your own renderer `slikui.RenderSink` is a trampoline over C++ `IRenderSink`: subclass it, implement `upload(tex)` and `render(commands, fb_size)`, and slikui hands you every frame as a flat command list - point it at pygame, moderngl, PIL, anything. ``` class MySink(slikui.RenderSink): def upload(self, up): # up.pixels: zero-copy read-only view, (H, W) uint8 for Alpha8, # (H, W, 4) for Rgba8. Valid during this call only: copy or upload. self.textures[up.id] = make_texture(up.id, up.pixels) def release(self, tex_id): # optional: the owning widget died self.textures.pop(tex_id).free() def render(self, cmds, fb_size): a = cmds.as_array() # (N,) slikui.DRAWCMD_DTYPE, zero-copy rects = a[a["type"] == slikui.DrawCmdType.Rect.value] ... # a["rect"] (N, 4) f32, a["color"] (N, 4) u8 ``` - **`cmds.as_array()`** is the fast path: one read-only structured view over the C++ command storage (fields `type rect radius thickness hollow color tex_id uv`, see `slikui.DRAWCMD_DTYPE`), about 18x cheaper than `for c in cmds` on the gallery. Like `up.pixels` it borrows C++ memory valid only during the call - `.copy()` to keep it. - **`release(tex_id)`** is called when an `Image`, `ImageView` or `CompareView` is destroyed. It can run outside `render()` (e.g. from `ctx.clear_tree()`), so a GPU sink should queue the delete until a context is current. Exceptions raised there are reported as unraisable, not propagated. The default is a no-op. - **`ctx.invalidate_textures()`**: call after your sink lost its textures (GL context recreated); the next `render()` re-uploads the font atlas and every live widget texture. `slikui.CanvasSink` is a worked example: a pure-numpy rasterizer producing **pixel-identical** output to the C++ software backend (same blend/SDF/ sampling math, verified by test): ``` sink = slikui.CanvasSink(320, 240) ctx = slikui.Context(sink) # any RenderSink subclass works here ctx.set_frame_size(320, 240) ctx.load_default_font() # or load_font_file(path) # ... build the tree, tick ... ctx.render() frame = sink.buffer # (240, 320) uint32, 0xAABBGGRR ``` See it side by side: `python python/examples/pyrenderer_demo.py` renders one tree through both renderers and reports the pixel diff (it is 0). ## OpenGL: `GlApp` and `GLSink` For a PyOpenGL host (glfw, pygame, Qt, ...) the UI can draw straight into your GL 3.3 context - no CPU framebuffer, no per-frame texture upload: ``` app = slikui.GlApp(960, 640, scale=fb_w / win_w) # GL context current root = app.set_root(slikui.Column, padding=12) ... while running: app.set_scale(fb_w / win_w); app.resize(win_w, win_h) # before tick app.tick(now, dt) draw_scene() app.render(clear=False) # over the scene; clear=True paints the background swap_buffers() app.close() # BEFORE destroying the window (frees GL objects) ``` `GlApp` wraps `slikui.GLSink`, a `RenderSink` built on the C++ `slikui.GpuBatcher`: each frame is one buffer upload plus one instanced draw per scissor/texture batch (a handful per frame). On the gallery it renders in ~0.5 ms/frame at 1x and ~0.6 ms at 2x, against ~3 ms / ~11 ms for the C++ software sink, before that path's texture upload (`python/benchmarks/bench_render.py`). - **GL state**: `render()` sets viewport, program, VAO, texture unit 0, blending and scissor, disables depth/cull/stencil, and leaves them - set what your next pass needs. `GLSink(preserve_state=True)` saves and restores them instead (slower: `glGet*` per frame). - **Lifecycle**: `init()` / `shutdown()` need the context current; `release()` only queues texture deletes. After a lost/recreated context, `app.reset()` (or `sink.reset(ctx)`) rebuilds GL objects and re-uploads. One sink per `Context`, one GL context per sink. - `slikui.read_framebuffer(w, h)` reads the bound framebuffer in `Target.pixels()` layout (tests, screenshots). - `--window` examples use `GlApp`; add `--software` for the CPU path. **Input from your GLFW window** (`slikui.glfw_input`, pyGLFW; `import slikui` never imports glfw): ``` inp = slikui.GlfwInput(win, app) # chains to callbacks you set earlier slikui.glfw_input.attach_services(app.ctx, win) # clipboard + cursors ... glfw.poll_events() # events reach app.handle() as they arrive ... inp.close() # restore your callbacks (window alive) ``` `GlfwInput(win)` without a target queues events (`inp.take()`) for hosts that route them (UI vs scene). Or skip it and call the builders from your own callbacks: `slikui.glfw_input.mouse_button_event(win, button, action, mods)`, `cursor_pos_event`, `scroll_event`, `key_event`, `char_event`, `focus_event`, `framebuffer_size_event` - `python/examples/glfw_demo.py` does this. Always map buttons through them (or `map_button`): GLFW's RIGHT=1/MIDDLE=2 are slikui's MouseMiddle=1/MouseRight=2 swapped. **Input from your SDL3 window** (`slikui.sdl_input`, PySDL3; `import slikui` never imports sdl3): `inp = slikui.SdlInput(window, app)`, then `inp.process(ev)` for each polled event (returns False for events slikui doesn't use). `translate(ev)` is the stateless builder; `attach_services(ctx)` wires clipboard and cursors. Full host: `python/examples/sdl_demo.py`. **Routing between UI and scene**: `app.ctx.wants_mouse(x, y)` and `app.ctx.wants_keyboard()` say whether an event belongs to the UI (layout widgets - Column, Row, Spacer - let the pointer through; a custom widget can return True from `mouse_transparent()` to do the same). **moderngl hosts**: `slikui.ModernGLSink(mgl_ctx, scale=...)` is the same sink over a `moderngl.Context` (`pip install moderngl`) - lower per-call overhead than PyOpenGL (~0.36 ms/frame on the gallery vs ~0.6 ms). It draws into `mgl_ctx.fbo` and leaves `enable_only(BLEND)` in effect; wrap the call in `mgl_ctx.scope(...)` to keep your own state. ``` sink = slikui.ModernGLSink(mgl, scale=fb_w / win_w).init() ctx = slikui.Context(sink) ... ctx.render(False) # over your scene, into mgl.fbo ... ctx.clear_tree(); sink.shutdown() ``` `slikui.GpuBatcher().build(list, frame, scale)` returns the arrays zero-copy - `(N, 20)` float32 instances and `(M, 7)` int32 batches - with `slikui.GPU_VERTEX_SHADER` / `GPU_FRAGMENT_SHADER`, for other APIs (wgpu, Vulkan via Python, ...). See [Render backends](https://jamesgregson.github.io/slikui/guide/backends/index.md). ## Custom widgets in Python Subclass `slikui.Widget` and implement `measure` / `paint` / `on_event` (plus opt-in `tick`, `stretch_cross`, `expands_main`, `focusable`, `widget_type`) - the C++ core lays out, paints, hit-tests and dispatches events to your class. Full details: [Custom widgets](https://jamesgregson.github.io/slikui/guide/custom-widgets/index.md). Rules: `super().__init__()` is required. `Panel`, `Column` and `Row` can be subclassed the same way (overrides dispatch, and `super().paint(env)` / `super().measure(c)` reach the built-in behaviour) - e.g. a `Panel` subclass as a popup root that sees `PopupClosed`. Other bound widget types (`Button`, `Slider`, ...) have no override seam: defining `on_event`, `paint`, ... on such a subclass raises `TypeError` when the class is created. Add instances with `container.add_widget(obj)` or `container.add(Meter, ...)`; a custom root is `context.set_root_widget(...)`. Wrappers of built-in widgets are views of widgets the C++ tree owns. Once the tree destroys one (`remove`, `clear_children`, `App.close()`), using an old wrapper raises `TypeError` (with a "nanobind: attempted to access an uninitialized instance" `RuntimeWarning`) instead of touching freed memory. ## Threads and the GIL `Context.tick`, `render` and `handle` release the GIL for the C++ part of the frame, so other Python threads aren't starved. Python overrides, callbacks and a Python `RenderSink` take the GIL back when they're called. Touch widgets only from the UI thread; see [Threading](https://jamesgregson.github.io/slikui/guide/core-concepts/#threading). ## Versions, wheels, sources - PyPI: `pip install slikui-python` - wheels for Python 3.10-3.14 on Linux x86_64/aarch64, macOS arm64, Windows x64; no wheel -> pip builds from the sdist (needs a C++20 compiler). - The same files are attached to every GitHub Release; the C++ side is header-only, nothing to link. - Source layout: `python/slikui/_slikui` (compiled bindings), `slikui/_py` (App, builder, events, pixels, CanvasSink), `slikui/examples` (shipped demos), `python/tests`, `python/examples` (repo-only interactive twins). # Containers The layout primitives. Usage patterns and worked examples live in [Layout](https://jamesgregson.github.io/slikui/guide/layout/index.md); this page is the API reference. ## Container The shared base: padding/gap/cross-axis. All containers stack children along their main axis, distribute extra main-axis space to children whose `expands_main()` is true, and align the cross axis with `set_cross`. | API | Signature | | ----------------- | ---------------------------------------------- | | `set_padding` | `(float all)` | | `set_gap` | `(float px)` | | `set_cross` | `(CrossMode m)` - `Stretch`, `Start`, `Center` | | `add(args...)` | construct + own a child, returns `T&` | Every `Widget` (not only containers) also has: | API | Notes | | ------------------------- | ----------------------------------------------------------------------- | | `set_expand(bool = true)` | share leftover main-axis space in a Column/Row (Python: `expand=True`) | | `remove(child)` | detach + destroy a direct child and its subtree; `false` if not a child | | `clear_children()` | `remove()` every child | `remove` is safe from event handlers and callbacks (even a button removing itself in `on_click`): focus (with `FocusLost`), hover, mouse capture, press targets and popup anchors in the subtree are dropped at once, and the widgets are destroyed when the running `handle()`/`tick()` returns. Don't call it from inside the parent's own `measure`/`arrange`/`paint`. A `ScrollArea` forwards both to its content column. In Python, handles to removed built-in widgets are invalid afterwards; a removed custom widget object survives (empty) and can be added again with `add_widget`. ## Column / Row `Column` stacks top-to-bottom, `Row` left-to-right. Children with `stretch_cross() == true` (the default) stretch across the cross axis; fixed-size controls like buttons and switches opt out and hug. ## Panel A bordered, rounded container - a `Container` that paints a surface. | API | Signature | | ---------------- | --------- | | `set_background` | `(Color)` | | `set_border` | `(Color)` | | `set_radius` | `(float)` | ## Spacer / Divider `Spacer` soaks up remaining main-axis space (its `expands_main()` is true). `Divider` draws a rule between siblings. Neither takes children. ## Expander / Accordion Keyboard: Space or Enter toggles a focused Expander. Only its header takes focus; clicks in the body don't. | API | Signature | | -------------------------- | ------------------------------------ | | `Expander::set_title` | `(std::string)` | | `Expander::set_open` | `(bool, bool fire_callback = false)` | | `Expander::on_toggle` | `(std::function)` | | `Accordion::add_section` | `(title, open = false) -> Expander&` | | `Accordion::set_exclusive` | `(bool)` - default `true` | Closed `Expander` children get zero frames and skip hit-testing - collapsing is free. ## Splitter Keyboard: Tab or a click on the divider focuses the Splitter (clicks in the panes don't). The arrow keys along the split then move the divider 10 px (Shift: 50 px), and Home/End move it to the ends. | API | Signature | | -------------------- | --------------------------------------- | | `Splitter(vertical)` | construct with `true` for stacked panes | | `set_fraction` | `(float 0-1)` | | `on_change` | `(std::function)` | # Controls Buttons, toggles, sliders, progress and labels. All follow the same pattern: fluent setters returning `Widget&`, theme-driven colors, animated hover/press transitions, keyboard focus support. Common to every widget (from the [`Widget`](#widget-base-class) base): `set_tooltip`, `set_context_menu`, `set_cursor`, the state flags `visible`, `enabled`, `focused`, and the optional `id` used by `ctx.find(id)`. Each image below is real output: `tools/components_capture.cpp` builds the tree from the snippet with the software backend, simulates a second of interaction, and dumps the framebuffer. ## Button Four variants: `Default`, `Primary` (accent fill), `Danger`, `Ghost` (borderless, quiet action). `on_click` fires on release inside the widget; hover/press transitions are animated by the theme. ``` auto& row = root.add(); row.set_gap(10); row.add("Default"); row.add("Primary").set_variant(slikui::Button::Variant::Primary); row.add("Danger").set_variant(slikui::Button::Variant::Danger); row.add("Ghost").set_variant(slikui::Button::Variant::Ghost); ``` ``` row = root.add(slikui.Row, gap=10) row.add(slikui.Button, "Default") row.add(slikui.Button, "Primary", variant=slikui.ButtonVariant.Primary) row.add(slikui.Button, "Danger", variant=slikui.ButtonVariant.Danger) row.add(slikui.Button, "Ghost", variant=slikui.ButtonVariant.Ghost) ``` | API | Signature | | ------------- | ------------------------- | | `set_text` | `(std::string)` | | `set_variant` | `(Button::Variant)` | | `set_padding` | `(float h, float v)` | | `on_click` | `(std::function)` | ## Checkbox, Radio, Switch Keyboard: Space toggles a focused Checkbox, Radio or Switch; Enter toggles a Switch too. All three are bool controls with `set_checked(bool, bool fire_callback = false)` and `on_change(void(bool))`. `Radio` gives you the visuals; exclusivity within a group is yours to wire (set the others false in the callback). ``` auto& row = root.add(); row.set_gap(18); row.add("Sync files", true); row.add("Compress", false); row.add("Wi-Fi", true); row.add("Ethernet", false); row.add().set_checked(true); row.add().set_checked(false); ``` ``` row = root.add(slikui.Row, gap=18) row.add(slikui.Checkbox, "Sync files", True) row.add(slikui.Checkbox, "Compress", False) row.add(slikui.Radio, "Wi-Fi", True) row.add(slikui.Radio, "Ethernet", False) row.add(slikui.Switch, checked=True) row.add(slikui.Switch, checked=False) ``` | API | Signature | | ------------- | -------------------------------------------- | | `set_checked` | `(bool checked, bool fire_callback = false)` | | `on_change` | `(std::function)` | ## Slider, ProgressBar, Spinner Keyboard (focused Slider): arrow keys one step, PageUp/PageDown a tenth of the range, Home/End the ends. `Slider` drives a float range (`set_range`, `set_value`, `on_change`) and can carry its own caption row - `set_label` adds a title with a live formatted value on the right (`set_format`, e.g. `"%.2f"`), `set_log_scale` makes picking across magnitudes sane, and `set_step` quantizes clicks and wheel ticks. `ProgressBar` shows a clamped 0-1 fraction; `Spinner` animates forever and takes `set_speed` (degrees per second) - it is driven by the time you pass to `ctx.tick`, so it pauses with your app. ``` auto& cap = root.add(); cap.set_gap(8); cap.add("Volume"); cap.add(); cap.add("62%").set_color(ctx.theme().text_dim); root.add(0.f, 100.f).set_value(62.f); root.add().set_value(0.72f); auto& busy = root.add(); busy.set_gap(10); busy.add(); busy.add("Compiling shaders...").set_color(ctx.theme().text_dim); ``` ``` cap = root.add(slikui.Row, gap=8) cap.add(slikui.Label, "Volume") cap.add(slikui.Spacer) cap.add(slikui.Label, "62%").set_color(ui.ctx.theme.text_dim) root.add(slikui.Slider, 0, 100, value=62) root.add(slikui.ProgressBar, value=0.72) busy = root.add(slikui.Row, gap=10) busy.add(slikui.Spinner) busy.add(slikui.Label, "Compiling shaders...").set_color(ui.ctx.theme.text_dim) ``` | API | Signature | | ------------------------ | --------------------------------------------------------------- | | `Slider::set_range` | `(float min, float max)` | | `Slider::set_value` | `(float, bool fire_callback = false)` | | `Slider::set_label` | `(std::string)` - built-in caption row, live value on the right | | `Slider::set_format` | `(const char* printf_format)` | | `Slider::set_log_scale` | `(bool)` | | `Slider::set_step` | `(float)` | | `Slider::on_change` | `(std::function)` | | `ProgressBar::set_value` | `(float 0-1)` | | `Spinner::set_speed` | `(float degrees/sec)` | The built-in caption row is demonstrated in the [Editors](https://jamesgregson.github.io/slikui/reference/widgets-editors/index.md) example (`Roughness %.2f`). ## Label Static text. `set_font_size` overrides the theme's base size, `set_color` overrides the theme text color, `set_wrap_width` word-wraps. `set_bold`, `set_italic`, `set_underline`, `set_strike` and `set_font(family)` style it ([Text & fonts](https://jamesgregson.github.io/slikui/guide/text-fonts/#font-families-and-styles)). ``` root.add("Title - 26 px").set_font_size(26); root.add("Body label at the default 15 px size."); root.add("Dim secondary text.").set_color(ctx.theme().text_dim); root.add("Accent-colored label.").set_color(ctx.theme().accent); ``` ``` root.add(slikui.Label, "Title - 26 px", font_size=26) root.add(slikui.Label, "Body label at the default 15 px size.") root.add(slikui.Label, "Dim secondary text.").set_color(ui.ctx.theme.text_dim) root.add(slikui.Label, "Accent-colored label.").set_color(ui.ctx.theme.accent) ``` | API | Signature | | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | `set_text` | `(std::string)` | | `set_font_size` | `(float px)` | | `set_color` | `(Color)` | | `set_wrap_width` | `(float px)` | | `set_bold` / `set_italic` / `set_underline` / `set_strike` | `(bool on = true)` | | `set_font` | `(std::string family)` - `"body"`, `"heading"`, `"mono"` or a registered name | | `set_align` | `(TextAlign)` - each line within the label's width; Python also takes `"left"` / `"center"` / `"right"` | | `set_valign` | `(TextVAlign)` - the text within the label's height; Python also takes `"top"` / `"middle"` / `"bottom"` | Alignment only shows when the label is bigger than its text, for example stretched across a Column (labels stretch by default) or given a Row's height. Wrapped lines are aligned one by one. Text taller than the label stays top-aligned. ## Widget base class Every widget inherits from `slikui::Widget`: | Member | Kind | | -------------------------------------------------- | -------------------------------------------- | | `add(args...)` | construct + own a child, returns `T&` | | `find(id)` | search subtree by `id` | | `set_tooltip` / `set_context_menu` / `set_cursor` | hover text / right-click menu / cursor shape | | `visible`, `enabled`, `focused`, `id`, `bounds` | public state | | `parent`, `children` | tree links | | `focusable()`, `expands_main()`, `stretch_cross()` | layout/focus opt-ins (virtual) | Setter chaining Setters return `Widget&` (no deducing-this before C++23), so base-class setters like `set_tooltip` must come **last** in a fluent chain. # Data display The data-display family for demo panels: lists, trees, tables, the property inspector, plots and images. Series and rows accept `numpy` arrays in Python and `std::vector` in C++. Each image is real output from `tools/components_capture.cpp` - the snippets are the capture code. ## ListView, Tabs, Dropdown `ListView` is a selectable item list (`on_select(void(size_t))`). `Tabs` is a tab bar (`set_tabs`, `on_change`). `Dropdown` opens its selection popup on click - the screenshot shows it after a simulated press: ``` auto& row = root.add(); row.set_gap(24); auto& list = row.add(); list.set_items({"alpha", "beta", "gamma", "delta"}).set_selected(1); auto& col = row.add(); col.set_gap(10); col.add().set_tabs({"Home", "Edits", "View"}).set_selected(1); col.add().set_items({"Linear", "Nearest", "Cubic", "Lanczos"}) .set_placeholder("Filter...").set_selected(0); ``` ``` row = root.add(slikui.Row, gap=24) row.add(slikui.ListView, items=["alpha", "beta", "gamma", "delta"], selected=1) col = row.add(slikui.Column, gap=10) col.add(slikui.Tabs, tabs=["Home", "Edits", "View"], selected=1) col.add(slikui.Dropdown, items=["Linear", "Nearest", "Cubic", "Lanczos"], placeholder="Filter...", selected=0) ``` | API | Signature | | ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- | | `ListView::set_items` | `(std::vector)` | | `ListView::set_selected` | `(long index)` | | `ListView::on_select` | `(std::function)` | | `ListView::on_activate` | `(std::function)` - double-click (after `on_select`), or Enter / Space on the selection | | `ListView::set_single_click_activate` | `(bool)` - a single click activates too (pick lists) | | `Tabs::set_tabs` | `(std::vector)` | | `Tabs::set_selected` / `on_change` | tab index | | `Dropdown::set_items` / `set_placeholder` / `set_selected` / `on_select` | like ListView | | `Dropdown::popup_list` | `() -> ListView*` - the open popup's list, null while closed | Keyboard, when focused: | Widget | Keys | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ListView` | Up/Down move the selection, Home/End jump to the ends, PageUp/PageDown move by a screenful (each move fires `on_select` and scrolls the row into view); Enter/Space fire `on_activate` | | `Dropdown` (closed) | Up/Down step the selection, Home/End jump to the ends (firing `on_select`); Space, Enter or Alt+Down open the list | | `Tabs` | Left/Right select the previous/next tab (wrapping), Home/End the first/last | | `Dropdown` (open) | Up/Down/Home/End/PageUp/PageDown move the highlight; Enter or a click commits; Escape cancels. Focus then returns to the Dropdown | ## Plot Line series with autoscale (or `set_x_range`/`set_y_range`), grid + tick labels, optional area fill, markers - and `set_bars` turns series 0 into a histogram. ``` auto& plot = left.add().set_fill(true); std::vector pts; for (int i = 0; i < 48; ++i) { float x = float(i) / 47.f * 6.2831f; pts.push_back({x, std::sin(x) * std::exp(-x / 6.f)}); } plot.add_series(pts, ctx.theme().accent); ``` ``` import numpy as np xs = np.linspace(0, 6.2831, 48) ys = (np.sin(xs) * np.exp(-xs / 6)).astype(np.float32) plot = left.add(slikui.Plot, fill=True) plot.set_series(ys, ui.ctx.theme.accent) ``` | API | Signature | | --------------------------------------- | --------------------------------------------------------------- | | `set_series` | C++ `(std::vector, color)` | | `add_series` | extra series (C++ also `(xs_array, ys_array, color)` in Python) | | `set_x_range` / `set_y_range` | `(min, max)` - disable autoscale | | `set_bars` / `set_fill` / `set_markers` | `(bool)` | ## Vec2Pad Keyboard: the arrow keys nudge a focused pad by 1% of the range (Shift: 10%); Up raises y. A 2D pad with a draggable dot - light directions, UV offsets. Pictured bottom left of the capture below. ``` left.add().set_value({0.35f, 0.4f}); ``` ``` left.add(slikui.Vec2Pad).set_value(slikui.Vec2(0.35, 0.4)) ``` | API | Signature | | ----------- | ------------------------------------ | | `set_value` | `(Vec2, bool fire_callback = false)` | | `set_range` | `(Vec2 min, Vec2 max)` | | `on_change` | `(std::function)` | ## TreeView Takes a flat `(label, depth, expandable)` row list; expansion state lives in the widget, chevron clicks toggle, rows select. ``` right.add().set_rows({ {"Scene", 0, true}, {"Dragon", 1}, {"Suzanne", 1}, {"Lights", 0, true}, {"Sun", 1}, {"Rim", 1}, }); ``` ``` right.add(slikui.TreeView, rows=[ slikui.TreeView.Row("Scene", 0, True), slikui.TreeView.Row("Dragon", 1), slikui.TreeView.Row("Suzanne", 1), slikui.TreeView.Row("Lights", 0, True), slikui.TreeView.Row("Sun", 1), slikui.TreeView.Row("Rim", 1), ]) ``` Large trees stay fast. Paint draws only the rows on screen. The natural width measures each label once, when its row first becomes visible, so labels under collapsed parents cost nothing. `set_natural_width(w)` fixes the width and skips measuring entirely. | API | Notes | | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Row{label, depth, expandable, expanded, tooltip}` | `expanded` (default true) is the row's initial state, read by `set_rows`; `tooltip` is the row's hover text (default: the full label when the row is cut off) | | `set_rows(rows)` | replaces the rows and their expansion state; clears the selection | | `set_expanded(i, open, fire_callback = false)` / `expanded(i)` | fires `on_toggle` only when asked and the state changes | | `on_select(fn(i))` | a row was selected (click or keys) | | `on_toggle(fn(i, open))` | an arrow click or Left/Right key opened or closed row `i` | | `on_activate(fn(i))` | double-click, or Enter/Space on the selection | | `set_natural_width(w)` | fixed natural width (logical px); 0 = widest visible row | | `visible_count()` / `row_rect(i)` | rows not under a collapsed parent; a row's rect for `scroll_to` | Keyboard, when focused: Up/Down move through the visible rows, Home/End and PageUp/PageDown jump. Right opens a closed row, or steps into an open one's first child. Left closes an open row, or steps to the parent. Moves scroll the row into view. ## Table Columns + header + selectable rows with per-column alignment and cell clipping. `set_columns` takes `(title, width, right_align?)` specs. ``` auto& table = right.add(); table.set_columns({{"Mesh", 100, false}, {"Tris", 60, true}, {"Pass", 44, true}}); table.set_rows({{"Dragon", "870k", "4"}, {"Suzanne", "50k", "2"}, {"Bunny", "69k", "2"}}); table.set_selected(1); ``` ``` table = right.add(slikui.Table) table.set_columns([ slikui.Table.ColumnSpec("Mesh", 100), slikui.Table.ColumnSpec("Tris", 60, right_align=True), slikui.Table.ColumnSpec("Pass", 44, right_align=True), ]) table.set_rows([["Dragon", "870k", "4"], ["Suzanne", "50k", "2"], ["Bunny", "69k", "2"]]) table.set_selected(1) ``` | API | Notes | | -------------------- | ------------------------------------------------------- | | `on_select(fn(i))` | a row was selected (click or keys) | | `on_activate(fn(i))` | double-click, or Enter/Space on the selection | | `row_rect(i)` | a row's absolute rect, e.g. for `ScrollArea::scroll_to` | Keyboard, when focused: Up/Down, Home/End and PageUp/PageDown move the row selection and scroll it into view. ## PropertyGrid The inspector: `add_property(label)` rows with a fixed label column (drop any editor into the returned row) and collapsible `add_section`s. ``` auto& grid = root.add(); grid.add_property("Roughness").add(0.f, 1.f).set_value(0.35f, false); grid.add_property("Samples").add(64.f); grid.add_section("Advanced"); ``` ``` grid = root.add(slikui.PropertyGrid) grid.add_property("Roughness").add(slikui.Slider, 0, 1, value=0.35) grid.add_property("Samples").add(slikui.DragValue, 64) grid.add_section("Advanced") ``` ## Image Decodes PNG/JPEG via vendored stb_image. Feed it pixels you already have (`set_pixels`), a file (`set_file`), or an encoded memory blob (`set_memory`). `set_fit` chooses how the source maps into the widget rect. Textures upload through the same `TexUpload` channel as the font atlas, so every backend gets it for free. ``` auto& row = root.add(); row.set_gap(16); const char* names[3] = {"Stretch", "Contain", "Cover"}; slikui::Image::Fit fits[3] = {slikui::Image::Fit::Stretch, slikui::Image::Fit::Contain, slikui::Image::Fit::Cover}; for (int i = 0; i < 3; ++i) { auto& cell = row.add(); cell.set_gap(6).set_cross(slikui::CrossMode::Center); cell.add("gradient").set_pixels(64, 48, grad_rgba) .set_size(150, 110).set_fit(fits[i]); cell.add(names[i]).set_color(ctx.theme().text_dim); } ``` ``` row = root.add(slikui.Row, gap=16) for name, fit in [("Stretch", slikui.ImageFit.Stretch), ("Contain", slikui.ImageFit.Contain), ("Cover", slikui.ImageFit.Cover)]: cell = row.add(slikui.Column, gap=6, cross=slikui.CrossMode.Center) cell.add(slikui.Image, "gradient").set_pixels(64, 48, grad_rgba) \ .set_size(150, 110).set_fit(fit) cell.add(slikui.Label, name).set_color(ui.ctx.theme.text_dim) ``` # Editors Widgets for tuning numbers and colors in demo panels - all C++ core, so the Python bindings get the same surface (see `python/tests/test_editors.py`). `DragValue` scrubs a value like a Blender number field: drag horizontally to change it, click to type, Enter commits, Escape cancels, arrows nudge when focused. `Vec2Edit`/`Vec3Edit`/`Vec4Edit` give one labeled field per axis and **borrow** the caller's `float[N]` - edits write into it and external writes mirror back on the next tick (numpy arrays work as-is). `ColorEdit` is a swatch that opens an SV square + hue popup with hex and RGBA fields. `Segmented` is a compact radio-style row. When focused, Left/Right select the previous/next segment (wrapping) and Home/End the first/last. ## The family, as pictured Every image on this site is real output: `tools/components_capture.cpp` builds this exact tree with the software backend, hovers and clicks the middle color chip so the picker popup is open, and dumps the framebuffer. ``` root.add().set_items({"Cube", "Sphere", "Torus"}) .set_selected(1); static float light_dir[3] = {0.60f, 0.40f, 0.70f}; root.add(light_dir, "XYZ"); // borrows the array root.add(1.5f).set_prefix("exp ").set_suffix(" EV"); root.add(0.f, 1.f).set_label("Roughness") // built-in caption row .set_format("%.2f").set_value(0.35f); auto& colors = root.add(); colors.set_gap(8); colors.add(slikui::Color::from_hex(0xBF5C38)); colors.add(slikui::Color::from_hex(0x3F6FBF)); colors.add(slikui::Color::from_hex(0x46A758)); colors.add("#BF5C38 #3F6FBF #46A758") .set_color(ctx.theme().text_dim); ``` ``` import numpy as np root.add(slikui.Segmented, items=["Cube", "Sphere", "Torus"], selected=1) light_dir = np.array([0.60, 0.40, 0.70], dtype=np.float32) root.add(slikui.Vec3Edit, light_dir, "XYZ") # borrows the array root.add(slikui.DragValue, 1.5, prefix="exp ", suffix=" EV") root.add(slikui.Slider, 0, 1, label="Roughness", format="%.2f", value=0.35) colors = root.add(slikui.Row, gap=8) colors.add(slikui.ColorEdit, color=slikui.Color.from_hex(0xBF5C38)) colors.add(slikui.ColorEdit, color=slikui.Color.from_hex(0x3F6FBF)) colors.add(slikui.ColorEdit, color=slikui.Color.from_hex(0x46A758)) colors.add(slikui.Label, "#BF5C38 #3F6FBF #46A758") \ .set_color(ui.ctx.theme.text_dim) ``` Note The labeled `Slider` in this tree demonstrates `Slider`'s built-in caption row; the full `Slider` API lives on [Controls](https://jamesgregson.github.io/slikui/reference/widgets-controls/#slider-progressbar-spinner). ## Segmented | API | Signature | | -------------- | --------------------------------------------------------------------- | | `set_items` | `(std::vector)` | | `set_selected` | `(long index, bool fire_callback = false)` | | `on_select` | `(std::function)` | | `set_fill` | `(bool on = true)` - span the parent instead of hugging the labels | | `segment_rect` | `(size_t index) -> Rect` - a segment's rect, e.g. to anchor a popover | By default a Segmented hugs its labels. With `set_fill()` it spans the parent: the full width of a Column, or the leftover width in a Row. Its segments share the width as evenly as their labels allow; a label wider than an equal share keeps its natural width. When there isn't room for every label, short labels stay whole and long ones elide. `set_speed` scales drag sensitivity (value change per pixel), `set_step` quantizes, `set_int_mode` makes it an integer field, and `set_prefix`/`set_suffix`/`set_format` dress the readout - the example above reads `exp 1.50 EV`. | API | Signature | | ------------------------------------------ | ------------------------------------- | | `set_value` | `(float, bool fire_callback = false)` | | `set_range` | `(float min, float max)` | | `set_speed` | `(float)` | | `set_step` | `(float)` | | `set_int_mode` | `(bool)` | | `set_prefix` / `set_suffix` / `set_format` | readout decoration | | `on_change` | `(std::function)` | ## Vec2Edit, Vec3Edit, Vec4Edit One labeled field per axis over a **borrowed** buffer: edits write into it and external writes mirror back on the next tick. ``` static float light_dir[3] = {0.60f, 0.40f, 0.70f}; root.add(light_dir, "XYZ"); // borrows the array, mirrors it each tick ``` ``` import numpy as np light_dir = np.array([0.60, 0.40, 0.70], dtype=np.float32) root.add(slikui.Vec3Edit, light_dir, "XYZ") # numpy arrays work as-is ``` | API | Signature | | --------------------------- | ----------------------------------- | | `set_labels` | `(std::string)` - one char per axis | | `set_range` | `(float min, float max)` - all axes | | `set_axis_range` | `(int axis, float min, float max)` | | `set_int_mode` / `set_step` | like DragValue | | `on_change` | `(std::function)` | ## ColorEdit Keyboard: Space or Enter opens the picker with focus on its R field. Tab walks R, G, B, A and hex, and Escape closes the picker and returns focus to the swatch. A swatch that opens an SV square + hue popup with hex and RGBA fields. ``` root.add(slikui::Color::from_hex(0xBF5C38)) .on_change([](slikui::Color c) { /* repaint */ }); ``` ``` root.add(slikui.ColorEdit, color=slikui.Color.from_hex(0xBF5C38)) ``` | API | Signature | | ----------- | ------------------------------------- | | `set_color` | `(Color, bool fire_callback = false)` | | `on_change` | `(std::function)` | # Text inputs Single-line and multiline editing, wrapping scroll areas, and the two composites that dress them up (`SearchBox`, `GroupBox`). ## TextField Single-line editing with caret, drag/Shift+arrow selection, Home/End/arrow navigation, and auto-scroll. `on_change` fires on every edit, `on_submit` on Enter. `set_password` masks the field. Ctrl/Cmd+A/C/X/V read and write the host clipboard via `ctx.set_clipboard_source/sink` (the GLFW backend wires the system clipboard; without a host the shortcuts are silent no-ops). ``` root.add().set_text("jane@example.com").set_placeholder("you@host"); root.add().set_placeholder("Search..."); ``` ``` root.add(slikui.TextField, text="jane@example.com", placeholder="you@host") root.add(slikui.TextField, placeholder="Search...") ``` ## TextArea The multiline variant: same editing model plus wrapped rows. `set_rows` suggests a height in lines. ``` root.add().set_rows(3) .set_text("slikui renders this entirely on the CPU -\n" "no GPU, no window, no dependencies."); ``` ``` root.add(slikui.TextArea, rows=3, text="slikui renders this entirely on the CPU -\n" "no GPU, no window, no dependencies.") ``` | API (both) | Signature | | ----------------- | ----------------------------------------------------------------------------------------------- | | `set_text` | `(std::string)` - Python: also the `text` property | | `set_placeholder` | `(std::string)` - elided with an ellipsis when wider than the field | | `on_change` | `(std::function)` | | `set_password` | TextField only - `(bool)` | | `on_submit` | TextField only - `(std::function)` - fires on Enter | | `scroll_x` | TextField only - `() -> float` - horizontal scroll; long text scrolls to keep the caret in view | | `set_rows` | TextArea only - `(int)` | ## ScrollArea A scrolling viewport for one child. The child is measured at its natural size; wheel and drag scroll it, and the offset clamps whenever content or viewport heights change (including window resizes). ``` auto& scroll = root.add(); for (int i = 1; i <= 12; ++i) scroll.add("Item " + std::to_string(i) + " - laid out, painted and clipped on the CPU"); ``` ``` scroll = root.add(slikui.ScrollArea) for i in range(1, 13): scroll.add(slikui.Label, f"Item {i} - laid out, painted and clipped on the CPU") ``` | API | Notes | | ---------------------------------------------------------- | -------------------------------------------------------------------------------- | | `scroll_y()` / `max_scroll()` | content px above the viewport / its limit (as of the last layout) | | `set_scroll_y(y)`, `scroll_to_top()`, `scroll_to_bottom()` | applied and clamped at the next tick | | `scroll_to(rect)` / `scroll_to(widget)` | least scroll that brings it into view; returns the distance moved | | `remove(child)` / `clear_children()` | act on the content column | | `hint_w_` / `hint_h_` (Python `hint_w` / `hint_h`) | size hint; `set_expand()` to fill a Column instead | | `set_content_insets(left, right)` | viewport edge to content (default 2, 2); the bar gutter is added while scrolling | The thumb sits 2 px from the ScrollArea's right edge. To put it at a pane's edge, give the pane no right padding (Python: `pane.set_padding(8, 8, 0, 8)`) and pad the other children instead. Rows inside list widgets aren't widgets: `TreeView::row_rect(i)` and `ListView::row_rect(i)` give a row's rect for `scroll_to`, e.g. revealing the selected lesson in a sidebar: ``` scroll.scroll_to(tree.row_rect(tree.selected)) ``` ## SearchBox and GroupBox These two dress up the inputs above, but they are pictured with the shells family (a GroupBox + SearchBox + LogView row in the capture) - see [Shells & dialogs](https://jamesgregson.github.io/slikui/reference/widgets-shells/#groupbox). Note `SearchBox` wraps `TextField` (`set_placeholder`, `on_change` on every edit, `on_submit` on Enter); `GroupBox` is a titled `Panel`. # Menus & toolbars ## MenuBar and Menu `MenuBar` is a top strip of menu titles: click to open, click again to close, and with a menu open, hovering another title switches to it. `Menu` holds items (`add_item`, `add_checkable`, `add_submenu`, `add_separator`) with right-aligned shortcut hints; disabled items swallow clicks. Menus are **borrowed** popups - build once, open many times. Checkmark state is read through a callback at paint time and `on_open` fires before each show so you can refresh enabled flags; `on_close` fires whenever the menu leaves the screen (item chosen, click outside, Escape, another menu opened, focus lost), after the event that closed it. Escape unwinds submenus one level per press. The capture below opens the **File** menu by simulating a click on it: ``` auto& bar = root.add(); auto& file = bar.add_menu("File"); file.add_item("Open...", open_fn, "Ctrl+O"); file.add_item("Save", save_fn, "Ctrl+S"); file.add_separator(); file.add_item("Quit", quit_fn, "Ctrl+Q"); auto& edit = bar.add_menu("Edit"); edit.add_item("Undo", undo_fn, "Ctrl+Z"); edit.add_item("Redo", redo_fn, "Ctrl+Shift+Z", /*enabled=*/false); ``` ``` bar = root.add(slikui.MenuBar) file = bar.add_menu("File") file.add_item("Open...", open_fn, hint="Ctrl+O") file.add_item("Save", save_fn, hint="Ctrl+S") file.add_separator() file.add_item("Quit", quit_fn, hint="Ctrl+Q") edit = bar.add_menu("Edit") edit.add_item("Undo", undo_fn, hint="Ctrl+Z") edit.add_item("Redo", redo_fn, hint="Ctrl+Shift+Z", enabled=False) ``` | API | Signature | | ------------------------------------------ | ------------------------------------------------------------------------------- | | `MenuBar::add_menu` | `(title) -> Menu&` | | `MenuBar::set_background` | `(Color)` - default transparent: the window background shows, as with `Toolbar` | | `Menu::add_item` | `(label, fn, hint = "", enabled = true)` | | `Menu::add_checkable` | `(label, is_checked_fn, on_toggle_fn)` | | `Menu::add_submenu` | `(label) -> Menu&` | | `Menu::add_separator` | `()` | | `Menu::active_item` | `() -> MenuItem*` - the highlighted row (hover or keys), or null | | `Menu::highlight_first` / `highlight_last` | `()` - light the first / last enabled row | ### Keyboard An open menu gets key presses (and typed text) before the focused widget, so it works the same whether it was opened by a click, a right-click or the keyboard. Focus does not move into it. | Where | Keys | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Open menu | Up/Down move the highlight (wrapping, skipping disabled rows and separators), Home/End jump to the ends, a letter jumps to the next row starting with it, Enter/Space choose, Right opens a submenu, Left closes it, Escape closes one level. Other keys are swallowed; Ctrl/Cmd chords still reach shortcuts | | MenuBar menu | as above, and at the top level Right/Left switch to the next/previous menu | | Anywhere | F10 opens the menu bar of the active window or modal dialog (the title used last), with the first row lit; when its menus close, focus returns where it was. F10 again closes. `Context::open_menu_bar()` does the same for other keys | | MenuBar title | the bar is a single Tab stop (the title last used); Left/Right move between titles, Down/Enter/Space open the menu with its first row lit, Up with its last | ## Context menus and global shortcuts Any widget can carry a right-click menu: `widget.set_context_menu(&menu)` - the nearest ancestor with one wins. Global accelerators live on the Context: `ctx.add_shortcut(Key, mods, fn)` fires before widget dispatch (a modifier is required, so typing never triggers one). ``` viewport.set_context_menu(&view_menu); // right-click ctx.add_shortcut(slikui::Key::R, slikui::ModCtrl, render_fn); ``` ``` viewport.set_context_menu(view_menu) # right-click ui.ctx.add_shortcut(slikui.Key.R, slikui.mods("ctrl"), render_fn) ``` ## Toolbar, IconButton `Toolbar` is a strip of `IconButton`s - Button interaction (hover/press animation, keyboard activation, variants) with a procedural icon instead of text. `Toolbar::add_button(icon, fn, tip?)` renders an icon button; `add_button(icon, label, fn)` renders a small caption under the icon. ``` auto& bar = root.add(); bar.add_button(slikui::Icon::Play, run_fn, "Run"); bar.add_button(slikui::Icon::Pause, pause_fn); bar.add_button(slikui::Icon::StepForward, step_fn); bar.add_separator(); bar.add_button(slikui::Icon::Grid, grid_fn, "Toggle grid"); bar.add_button(slikui::Icon::Camera, camera_fn, "Screenshot"); bar.add_button(slikui::Icon::Save, "Save", save_fn); // labeled root.add("ghost fill fades in on hover"); ``` ``` bar = root.add(slikui.Toolbar) bar.add_button(slikui.Icon.Play, run_fn, tip="Run") bar.add_button(slikui.Icon.Pause, pause_fn) bar.add_button(slikui.Icon.StepForward, step_fn) bar.add_separator() bar.add_button(slikui.Icon.Grid, grid_fn, tip="Toggle grid") bar.add_button(slikui.Icon.Camera, camera_fn, tip="Screenshot") bar.add_labeled_button(slikui.Icon.Save, "Save", save_fn) root.add(slikui.Label, "ghost fill fades in on hover") ``` | API | Signature | | ----------------------------------------- | ------------------------------------------ | | `Toolbar::add_button` | `(Icon, fn, tip)` - returns `IconButton&` | | `Toolbar::add_button` (labeled) | `(Icon, label, fn)` | | `Toolbar::set_icon_px` / `set_background` | strip styling | | `IconButton::set_icon` | `(Icon)` | | `IconButton::set_icon_painter` | `(IconPainter)` - a custom icon, see below | ### Built-in icons `slikui::Icon` (Python: `slikui.Icon`) has 156 procedural icons. They're drawn from `DrawList` lines and shapes on a 24x24 grid, so they take the theme colour and stay sharp at any size. The labels below are `icon_name(icon)`. The enum names are the CamelCase form, so `more_horizontal` is `Icon::MoreHorizontal`. New icons are added at the end, so existing enum values don't change. To draw an icon in a custom widget, call `paint_icon(env.list, icon, rect, color)` (Python: `slikui.paint_icon`; `slikui.icon_name(icon)` gives the name). `icon_count` is the number of icons, so `static_cast(i)` is valid for every `i` in `[0, icon_count)`. ## The icon set The icon set in `slikui/widgets/icons.hpp` (~26 icons: play, pause, step, grid, camera, save, refresh, search, ...) is painted from DrawList primitives - no icon font, no assets, resolution-independent and theme-tinted. The full list is the `slikui::Icon` enum (`slikui.Icon.*` in Python). ### Custom icons For an icon the set doesn't have, give the button a painter. It's called each frame with the icon's square `area` and the `color` a built-in icon would get (theme text, accent text on Primary/Danger, dimmed when disabled), so a custom icon follows the theme like the rest. Draw on the same 24x24 grid as the built-ins by scaling with `area.w / 24`, or start from a built-in and add to it. `set_icon(Icon)` switches back. ``` auto& pin = bar.add_button(slikui::Icon::Pin, toggle_pin); pin.set_icon_painter([](slikui::DrawList& l, slikui::Rect a, slikui::Color c) { slikui::paint_icon(l, slikui::Icon::Pin, a, c); l.circle({a.x + a.w * .85f, a.y + a.h * .15f}, a.w * .15f, c); // a badge }); ``` ``` def pinned_icon(lst, area, color): slikui.paint_icon(lst, slikui.Icon.Pin, area, color) lst.circle(slikui.Vec2(area.x + area.w * .85, area.y + area.h * .15), area.w * .15, color) # a badge bar.add_button(slikui.Icon.Pin, toggle_pin).set_icon_painter(pinned_icon) ``` In Python the list handed to the painter is valid only during the call. # Shells & dialogs Floating shells live on their own layer above the tree and below popups (so a dropdown list inside a dialog shows over it): dialogs and message boxes, toasts, the status bar, the log console, and the image viewers. `GroupBox` and `SearchBox` are pictured here too - they are simple composites (a titled `Panel` and a `TextField` with magnifier/clear) that share the family's capture. ## Dialog and MessageBox `Dialog` has a draggable title bar with a close button and a `content()` column. `MessageBox` adds an action-button row. A **modal** dialog dims the app and traps presses outside it. Escape or the X button closes. ``` auto mb = std::make_unique("Delete", "Remove 'dragon.obj'?"); mb->set_modal(true); mb->add_button("Delete", [&] { remove_item(); }); mb->add_button("Cancel", nullptr); ctx.open_dialog(std::move(mb)); // owned; or open_dialog(mb) to borrow ``` ``` mb = slikui.MessageBox("Delete", "Remove 'dragon.obj'?") mb.set_modal(True) mb.add_button("Delete", lambda: remove_item()) mb.add_button("Cancel", lambda: None) ui.ctx.open_dialog(mb) # kept alive by the context while open ``` | API | Signature | | -------------- | ------------------------------------------------------------------------------------------------------------------ | | `set_title` | `(std::string)` | | `set_modal` | `(bool)` | | `set_position` | `(Vec2)` | | `on_close` | `(std::function)` - once per close, however it closes (X, Escape, `close_dialog`), after the closing event | | `add_button` | MessageBox - `(label, fn)` | ## Toast Auto-dismissing corner notices: `ctx.push_toast(std::make_unique("Saved"), 3.0)` - the second argument is the lifetime in seconds. `set_icon(Icon)` adds a procedural icon. Toasts never take input: clicks pass through to whatever is under them, and open menus/popups are unaffected. Several stack upward. ``` ui.ctx.push_toast("Saved", 3.0) ``` ## GroupBox A titled panel - a `Panel` with a caption, for grouping related controls. ``` auto& gb = left.add("Light"); gb.add("Enabled", true); gb.add(0.f, 1.f); ``` ``` gb = left.add(slikui.GroupBox, "Light") gb.add(slikui.Checkbox, "Enabled", True) gb.add(slikui.Slider, 0, 1) ``` ## SearchBox The magnifier is decorative and not a Tab stop. If you give `icon_button()` an action, call `set_focusable(true)` on it. A `TextField` with a magnifier icon and a clear button. `on_change` fires on every edit, `on_submit` on Enter. ``` left.add().set_placeholder("Search assets..."); ``` ``` left.add(slikui.SearchBox, placeholder="Search assets...") ``` ## LogView Scrollback: the wheel scrolls, and so do Up/Down (a line), PageUp/PageDown (a page), Home (the oldest line) and End (back to the newest) while the log is focused or hovered. At the newest line the view follows new entries; scrolled back, it holds its place. `scrollback()` / `set_scrollback(lines)`. A severity-colored autoscrolling console - pair it with `StatusBar` for feedback, or feed it event logs from demo panels (the showcase does exactly this). ``` auto& log = top.add(); log.log(slikui::LogView::Level::Info, "loaded scene.dragon (24 ms)"); log.log(slikui::LogView::Level::Warning, "missing texture: bark_d"); log.log(slikui::LogView::Level::Error, "shader compile failed"); log.log(slikui::LogView::Level::Success, "thumbnail bake complete"); ``` ``` log = top.add(slikui.LogView) log.log(slikui.LogView.Level.Info, "loaded scene.dragon (24 ms)") log.log(slikui.LogView.Level.Warning, "missing texture: bark_d") log.log(slikui.LogView.Level.Error, "shader compile failed") log.log(slikui.LogView.Level.Success, "thumbnail bake complete") ``` ## StatusBar Status text with transient messages plus right-side widgets - a typical home for `Spinner`s or scale indicators. ``` root.add().set_text("60 fps | 1,440 objects"); ``` ``` root.add(slikui.StatusBar).set_text("60 fps | 1,440 objects") ``` ## FileBrowser Lists real directories for Open/Save flows. `set_path` starts it somewhere; `on_pick(path)` receives the result. Click a file to choose it; double-click a file to pick it at once, or a folder to enter it (Enter in the name field picks too). The list scrolls inside the dialog, which shrinks to fit the window, so the buttons stay reachable in big folders. `Mode::Folder` picks a directory instead. Only folders are listed, there is no name field, and the button reads **Choose**. Double-clicking a folder still enters it. Choose picks the selected folder, or the folder being shown when nothing (or `..`) is selected, so it always picks something. ``` auto fb = std::make_unique(slikui::FileBrowser::Mode::Open); fb->on_pick([](const std::string& path) { load_file(path); }); ctx.open_dialog(std::move(fb)); ``` ``` fb = slikui.FileBrowser(slikui.FileBrowser.Mode.Open) fb.on_pick(lambda path: load_file(path)) ui.ctx.open_dialog(fb) ``` | API | Signature | | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `set_path` / `path` | `(std::string)` / `() -> std::string` | | `set_filters` | `(std::vector)` - globs (`*`, `?`, case-insensitive) a file must match one of; empty = all. Folders always show | | `set_show_hidden` | `(bool)` - dotfiles are hidden by default | | `selection` | `() -> std::string` - chosen file, `""` if none; follows `list().set_selected(i)` too. Folder mode: the chosen folder (never empty) | | `commit` | `() -> bool` - pick the selection, as the Open/Save/Choose button does | | `mode` | `() -> Mode` - `Open`, `Save` or `Folder` | | `on_pick` | `(std::function)` | | `list` / `list_scroll` / `name_field` / `open_button` | the parts | ## ImageView and CompareView `ImageView` pans/zooms RGBA bitmaps over a checkerboard; `CompareView` splits two images with a draggable divider (`set_fraction`). Both take pixels via `set_pixels` / `set_pixels_a` / `set_pixels_b`. ``` auto& views = root.add(); views.set_gap(10); views.add().set_pixels(64, 48, grad.data()); auto& cv = views.add(); cv.set_pixels_a(64, 48, grad.data()); cv.set_pixels_b(64, 48, grad2.data()); cv.set_fraction(.62f); ``` ``` views = root.add(slikui.Row, gap=10) views.add(slikui.ImageView).set_pixels(64, 48, grad) cv = views.add(slikui.CompareView) cv.set_pixels_a(64, 48, grad) cv.set_pixels_b(64, 48, grad_rb) cv.set_fraction(0.62) ``` ## As pictured Every image on this site is real output from `tools/components_capture.cpp` (`gradient_rgba()` there builds a small RGBA test bitmap). The capture opens the MessageBox dialog and posts a toast, so both appear over the panel: ``` auto grad = gradient_rgba(); // helper in the capture tool std::vector grad2 = grad; for (std::size_t i = 0; i < grad2.size(); i += 4) std::swap(grad2[i], grad2[i + 2]); // R/B swapped for image B auto& top = root.add(); top.set_gap(10); auto& left = top.add(); left.set_gap(8); auto& gb = left.add("Light"); gb.add("Enabled", true); gb.add(0.f, 1.f); left.add().set_placeholder("Search assets..."); auto& log = top.add(); log.log(slikui::LogView::Level::Info, "loaded scene.dragon (24 ms)"); log.log(slikui::LogView::Level::Warning, "missing texture: bark_d"); log.log(slikui::LogView::Level::Error, "shader compile failed"); log.log(slikui::LogView::Level::Success, "thumbnail bake complete"); auto mb = std::make_unique("Export", "Render 128 frames at 4K?"); mb->add_button("Export", nullptr); mb->add_button("Cancel", nullptr); mb->set_position({300, 26}); ctx.open_dialog(std::move(mb)); auto toast = std::make_unique("Screenshot saved"); toast->set_icon(slikui::Icon::Camera); ctx.push_toast(std::move(toast), 60.0); auto& views = root.add(); views.set_gap(10); views.add().set_pixels(64, 48, grad.data()); auto& cv = views.add(); cv.set_pixels_a(64, 48, grad.data()); cv.set_pixels_b(64, 48, grad2.data()); cv.set_fraction(.62f); root.add().set_text("60 fps | 1,440 objects"); ``` ``` grad, grad_rb = ... # small RGBA gradients - see slikui/examples/gallery.py # (python -m slikui.examples.gallery) top = root.add(slikui.Row, gap=10) left = top.add(slikui.Column, gap=8) gb = left.add(slikui.GroupBox, "Light") gb.add(slikui.Checkbox, "Enabled", True) gb.add(slikui.Slider, 0, 1) left.add(slikui.SearchBox, placeholder="Search assets...") log = top.add(slikui.LogView) log.log(slikui.LogView.Level.Info, "loaded scene.dragon (24 ms)") log.log(slikui.LogView.Level.Warning, "missing texture: bark_d") log.log(slikui.LogView.Level.Error, "shader compile failed") log.log(slikui.LogView.Level.Success, "thumbnail bake complete") mb = slikui.MessageBox("Export", "Render 128 frames at 4K?") mb.add_button("Export", lambda: None) mb.add_button("Cancel", lambda: None) mb.set_position(slikui.Vec2(300, 26)) ui.ctx.open_dialog(mb) ui.ctx.push_toast("Screenshot saved", 60.0) # icon: Toast.set_icon in C++ views = root.add(slikui.Row, gap=10) views.add(slikui.ImageView).set_pixels(64, 48, grad) cv = views.add(slikui.CompareView) cv.set_pixels_a(64, 48, grad) cv.set_pixels_b(64, 48, grad_rb) cv.set_fraction(0.62) root.add(slikui.StatusBar).set_text("60 fps | 1,440 objects") ``` Tip Widgets can request cursor shapes via `set_cursor` - hosts map them to system cursors (`GlfwWindow::attach` does this). See [Input & events](https://jamesgregson.github.io/slikui/guide/input-events/#cursor-shapes). # Development # Development Building, testing and regenerating everything in the repo. ## Build & test ``` cmake -S . -B build cmake --build build -j ctest --test-dir build # golden-image pixel checks included ``` CI matrices C++ across gcc/clang/MSVC on Linux/macOS/Windows, checks that every header compiles standalone, runs the suite under ASan + UBSan, and compile-checks the GL/GLFW backends. Python CI builds the sdist + wheels (cibuildwheel) and runs pytest inside each wheel. ## Before opening a PR Run what CI runs, plus the regeneration steps CI can't do for you. From the repo root: 1. **C++ build and tests**: `cmake --build build -j && ctest --test-dir build --output-on-failure`. Golden-image tests fail on any pixel change, so a rendering change needs its goldens re-captured on purpose, never just to make the test pass. 1. **Sanitizers**: run the suite in an ASan + UBSan build. This is the build that catches use-after-free when widgets are removed or popups closed mid-event. ``` cmake -S . -B build-asan -DCMAKE_BUILD_TYPE=Debug -DSLIKUI_BUILD_EXAMPLES=OFF \ "-DCMAKE_CXX_FLAGS=-fsanitize=address,undefined -fno-sanitize-recover=undefined -fno-omit-frame-pointer" cmake --build build-asan -j && ctest --test-dir build-asan --output-on-failure ``` 1. **Standalone headers**: `./tools/check_headers.sh`. Each header must include what it uses. 1. **Python**: rebuild the extension first (`pip install -e .`) so the tests run against your bindings, not a stale build. Then run `python -m pytest python/tests`. 1. If you changed bindings, run `python tools/gen_stubs.py` and commit the regenerated stub. `test_stubs.py` fails if the stub drifts from the built extension. 1. C++ and Python showcase `--smoke` transcripts must stay byte-identical. Change both twins together. 1. **Amalgamation**: run `python tools/amalgamate.py` and commit `dist/slikui.hpp`. CI doesn't rebuild it, so a stale copy ships as-is. 1. **Docs**: 1. Run `python tools/doc_check.py`, and `mkdocs build --strict` if you edited `docs/`. 1. Update the reference page for any public API you added or changed. 1. If you edited example code, run `tools/extract_snippets.py`. 1. If a widget looks different, regenerate its screenshot (see [Regenerating the docs images](#regenerating-the-docs-images)). 1. **Changelog**: add an entry under `## Unreleased` in `CHANGELOG.md`, in Added / Changed / Fixed. Call out behaviour changes that existing apps might notice, such as callback ordering or timing. 1. **Version**: leave `include/slikui/version.hpp` alone unless the PR is a release. It's the single source of truth for the version, and the release workflow checks the tag against it. New behaviour needs tests: C++ in `tests/` and, if the feature is exposed to Python, in `python/tests/`. Bug fixes belong in `python/tests/test_regressions.py` or the matching C++ test file. Each new test should fail without the fix. ## Examples ``` ./build/examples/01_hello # GLFW+GL hello window ./build/examples/02_raw_pixels # headless, writes a PPM ./build/examples/03_gallery/slikui_gallery ./build/examples/04_glfw_opengl # 3D shape viewer: orbit + zoom + accordion panel ./build/examples/04_glfw_software # same UI, CPU-rasterized scene ./build/examples/05_showcase/slikui_showcase ./build/examples/05_showcase/slikui_showcase --smoke showcase.png # headless scripted pass ./build/examples/07_text # text styles, fonts, custom widgets drawing text ./build/examples/07_text --smoke text.ppm # headless scripted pass ``` - `04_glfw_opengl` renders a lit reference shape (cube, sphere or torus) over a procedural sky, editing material/environment/light/camera live from an accordion control panel. - `05_showcase` puts every component in one window - menu bar, toolbar, splitter with six tabbed pages, status bar - logging each state change on-screen, plus two custom widgets (`Fill`, `LevelMeter`) demonstrating the measure/paint/event/tick contract. Its `--smoke` transcript is byte-identical to the Python twin's (`python/examples/showcase.py`). - `07_text` is the C++ twin of `python -m slikui.examples.text`: Label styles and font families, plus four custom widgets that draw text with `env.text_in` and a kept `TextBlock` (drag to select). ## Python ``` pip install -e . python -m pytest python/tests python -m slikui.examples --smoke all # shipped suite: scripted self-checks python -m slikui.examples.gallery # full-surface gallery -> gallery.png python python/examples/pyrenderer_demo.py # C++ vs CanvasSink pixel diff (0) python -m slikui.examples.paint --docs-image custom_widget docs/images/custom_widget.png python tools/extract_snippets.py # regenerate docs/includes/examples/ after editing demo code python tools/gen_stubs.py # regenerate the committed type stub after binding changes for n in hello gallery events paint controls keyboard renderer window text; do python -m slikui.examples.$n --smoke docs/images/examples-$n.png done # the examples page's screenshots python tools/examples_gif.py # examples-snake.gif, examples-clock.gif ``` `python/tests/test_stubs.py` fails when the committed stub drifts from the built extension; `test_examples.py` runs every smoke pass in a fresh interpreter and fails on nanobind's shutdown leak report. ## Regenerating the docs images Every screenshot in this site is real output: `tools/components_capture.cpp` builds each tree with the **software backend**, simulates a second of interaction, and dumps the framebuffer - the snippets on the widget pages are the actual capture code. ``` clang++ -std=c++20 -Iinclude tools/components_capture.cpp -o /tmp/ccap /tmp/ccap docs/images # writes PPMs for f in docs/images/*.ppm; do python3 tools/ppm2png.py "$f" "${f%.ppm}.png"; done ``` ## Amalgamation & release - `tools/amalgamate.py` produces `dist/slikui.hpp` (bakes in the ~35 KB DejaVu Sans subset). - `tools/check_headers.sh` - every public header must compile standalone. - `tools/embed_font.py` - regenerate the embedded font subset. - Tagging `v*` triggers the Python workflow: GitHub Release with sdist + wheels + `dist/slikui.hpp`, then PyPI via Trusted Publishing. ## Docs The site is MkDocs Material; sources live in `docs/`, nav in `mkdocs.yml`. Build locally with `mkdocs serve` or `mkdocs build --strict` (CI deploys to GitHub Pages on push to main). `tools/doc_check.py` verifies the widget pages stay in sync with the headers and `python/slikui/__init__.py`.