ui

tape
@profile(t2);
import ui from "ui";
import gfx from "gfx";

component Swatch {
    @tape { ui.drawable(); }
    prop bg: color = #3366CC;

    fn paint(s: *gfx.Surface, x: i64, y: i64, w: i64, h: i64) {
        s.fill_rect(x, y, w, h, bg);
    }
}

pub fn main() -> i32 {
    ui.run(Swatch {}, 200, 200, "Swatch") or { return 1; };
    return 0;
}

ui runs the component model: it updates the tree when state changes, lays it out, paints it on a gfx.Surface, and delivers pointer and keyboard input.

Showing a tree

FunctionDoes
run(root, w, h, title) -> void or UiErrorOpen a window and run until it is closed
run_window(root, Window { ... }) -> void or UiErrorThe same, with the window placed, frameless or on top
quit()End run after the event being handled, as if the window were closed
headless(root, w, h, alpha: false) -> Screen or UiErrorThe same tree offscreen, rendered into its own surface; alpha: true for one that shows through where the tree paints nothing (over a game)

run_window takes a ui.Window; every field has a default:

FieldDefault
width, height800, 600The client area, in pixels
title"tape"UTF-8; any character the font can show
x, ynullThe window’s outer top-left on the screen; null lets the platform choose (a frameless window is centered)
framelessfalseNo title bar or border: the client area is the whole window
topmostfalseStays above other windows
background#00000000What a repainted area is filled with before your components paint; zero: the theme’s window color. An app painted on a light pane gives its surface (theme.current().surface) so no dark frame ever shows
icon[]The window’s icon, set before it shows: one picture in several sizes, each a gfx.Surface (The window’s icon); empty: the platform’s own
keep_runningfalseClosing the window doesn’t end run: the program keeps running with no window until ui.quit() or, on macOS, the user quits the app (Running with no window)
hiddenfalseWith keep_running: start with no window open
tape
ui.run_window(Deck {}, ui.Window {
    width: 1280; height: 720; title: "Deck";
    x: 0; y: 0; frameless: true; topmost: true;
}) or { return 1; };

Call ui.quit() from a handler (a key, a click, a timer) to close the window and return from run. On Linux the placement, frame and stacking are requests the window manager may ignore; on Uusi the compositor places windows itself.

Running with no window

A program with a status icon, a messenger say, keeps running when its window is closed. Give run_window keep_running: true: closing the window then destroys it and run goes on. Your components keep their state, and timers, watched handles, thread results and the icon’s clicks still come. ui.show_window() opens the window again, and only ui.quit() ends the run.

FunctionDoes
show_window()Open run’s window again after it was closed; an open one is brought forward (activate_window)
close_window()Close it after the event being handled, as the user’s close does
window_open() -> boolWhether the window is open now
window_active() -> boolWhether the window is open, not minimised, and in front with the keyboard
activate_window()Restore it if minimised, bring it to the front and make it active; open it again if closed
reduce_motion() -> boolWhether the user asked the system for less motion (below)
tape
fn on_tray(ev: tray.TrayEvent) {
    if (ev.kind == tray.TrayEventKind.Click) { ui.show_window(); }
    else if (ev.index == 1) { ui.quit(); }          // the menu's "Quit"
}

ui.run_window(App {}, ui.Window { title: "Chat"; keep_running: true; }) or { return 1; };

Notifying only when the user isn’t looking

ui.window_active() is true while the window is the one the user is using: open, not minimised, in front. When it changes the whole tree is evaluated again, so a view that reads it stays right. A messenger notifies of a new message only when it is false, and the notification’s click calls ui.activate_window():

tape
var g_open_chat: i64 = 0;      // the chat the window shows

fn on_message(chat: i64, from: []const u8, text: []const u8) {
    if (ui.window_active() && chat == g_open_chat) { return; }   // the user is reading it
    notify.show(notify.Note { title: "{from}"; body: "{text}"; }) or {};
}

// on a click of the notification (notify.next's event)
fn on_notification_click() { ui.activate_window(); }

activate_window() restores a minimised window, brings it to the front and gives it the keyboard; a closed one (keep_running) opens again. Windows lets a program take the front only when the user just acted through it (a click on its notification does) or another program passed it the right (a second start of the program handing its arguments over with launch.claim does); otherwise the taskbar button flashes. Window managers on Linux may also decline, and mark the window urgent instead. In tests, a headless Screen has sc.set_active(true): window_active() says what it was given while that Screen is the one being driven (outside run it is otherwise false).

Less motion

ui.reduce_motion() is true when the user has asked the system for less motion: “Animation effects” off on Windows, Reduce motion on macOS, the desktop’s reduced-motion setting on Linux (through the desktop portal; GNOME’s “Animations” switch where the portal has no such setting). Uusi says false. A decorative animation (a fade, a slide, a bounce) then jumps to where it ends; one that tells the user something (a progress bar, a spinner, a scroll following the hand) keeps moving. The widgets’ color transitions already do this.

tape
var g_panel_x: f64 = -300.0;    // a side panel sliding in to 0

// a frame of the slide (an animated component's frame calls it)
fn slide(dt_ms: f64) {
    if (ui.reduce_motion()) { g_panel_x = 0.0; return; }   // there at once
    g_panel_x = g_panel_x + (0.0 - g_panel_x) * dt_ms / 120.0;
}

When the setting changes while run runs, the whole tree is evaluated again, as for window_active(). On Linux the desktop portal is asked without waiting: the answer is false for the first moment, and when the portal replies the tree is drawn again with it. Outside run it answers the system’s setting too (on Linux a call right at the start may still be false). In tests, sc.set_reduce_motion(true) on a headless Screen is what it says while that Screen is the one being driven.

hidden: true starts with no window at all, only the icon. The components mount when the window first opens, so a ui.Timer in the tree ticks from then; work a hidden program does before that goes through ui.watch or the icon’s handler. hidden without keep_running traps. On macOS the Dock icon goes with the window. While the window is open, the program has its Dock icon and menu bar. While it is closed, the program is only in the menu bar, through its tray icon, as a menu-bar app is. Quitting the app itself (Cmd+Q, or the Quit in the app menu or the Dock) ends run even with keep_running, as ui.quit() does. Closing the window does not.

The window’s icon

ui.set_icon(images) -> bool changes the icon of run’s window while it runs; ui.Window.icon sets it before the window shows. The same call is set_icon on a window.Window, a gl.Window and a gpu.Device.

  • images is one picture in several sizes (16, 32, 48, 256 …); the platform shows the one that fits best. Each is a gfx.Surface, what image.decode gives for a PNG, from 1 to ui.MAX_ICON_SIZE (1024) pixels each way, at most ui.MAX_ICON_IMAGES (16) of them. Alpha is kept; an Rgbx surface is opaque.
  • The pixels are copied: free the surfaces when you like.
  • An empty list gives the platform’s default back. True when the platform took it; false outside run, and on Uusi.
  • A side outside 1..1024 (a freed surface is 0 x 0) or more than 16 images traps.
tape
let png = fs.read_file("icon.png") or { return 1; };
var img = image.decode(png) or { return 1; };
ui.run_window(App {}, ui.Window { title: "App"; icon: [img]; }) or { return 1; };
img.free();
Where it shows
WindowsThe title bar (the small icon) and the taskbar and Alt+Tab (the large one), each chosen from your sizes for the window’s DPI
LinuxWherever the window manager shows _NET_WM_ICON, which gets every size. Under Wayland the program is an X11 client (XWayland): KWin shows it; GNOME shows a .desktop file’s icon when one matches the program
macOSThe Dock. macOS has no icon per window, so this sets the application’s: the last call wins, and it stays until the program ends

The icon of the .exe file itself (Explorer, a pinned taskbar button) is what @exeicon embeds when you build.

Waking on your own handles

A window that also follows something else (a log, a timer, a pipe, a network connection) names what run should wait on besides the window, and a function to call when it can be read:

tape
var g_view: *u8 = null;

fn on_log(h: i64) {
    let n: i64 = read_some(h);            // read what is there now
    append_lines(n);
    ui.invalidate(g_view);                // the view reads module state
}

pub fn main() -> i32 {
    let v = LogView {};
    g_view = v as *u8;
    ui.watch(log_handle, on_log) or { return 1; };
    ui.run(v, 640, 400, "Log") or { return 2; };
    return 0;
}
FunctionDoes
watch(handle, on_ready: fn(i64)) -> void or UiErrorCall on_ready(handle) whenever the handle can be read
unwatch(handle)Stop
watch_socket(handle, want, on_ready) -> void or UiErrorThe same for a net socket (stream.h, listener.h); want is net.READABLE, net.WRITABLE or both
unwatch_socket(handle)Stop
watch_count()Handles and sockets watched (at most ui.MAX_WATCHES, 15; one more is UiError.TooManyWatches)

A handle is the platform’s: a Win32 HANDLE (an event, a waitable timer, a process), a Linux or macOS file descriptor, a Uusi kernel handle (a channel, devices/log, devices/timer). run waits on the window and the handles together, so nothing polls: the callback runs as soon as one is ready, then the window repaints what the callback changed, as after a click. Sockets are checked every ui.POLL_MS (10 ms) while any is watched; on macOS watched descriptors are too.

The callback does the reading. A handle stays ready, and its callback keeps being called, until it has been read (or reset, for a Win32 event that resets by hand), so read what is there or unwatch it. Watch before run or from any handler or callback while it runs; a callback may unwatch its own handle. Watching a handle again replaces its callback.

Headless, screen.ready(handle) does what run does for a ready handle (its callback, then a frame) and screen.poll_sockets() what it does every POLL_MS (the ready sockets’ callbacks, then a frame).

Those two need the handle, or work on sockets alone. A module’s own watches (launch’s name, notify’s connection) are private: a test can’t name them. screen.poll_watches() services them all: it checks every watched handle and every watched socket without waiting, calls each ready one’s callback as run would (the handles in the order watched, then the sockets; a callback that unwatches another means that one is not called), then paints one frame if any callback ran, and says how many ran. Nothing ready: 0, and no frame. advance never touches I/O (a test stays deterministic), so a headless test loop that wants both time and I/O calls both:

tape
screen.advance(16);
screen.poll_watches();

On Windows a ready auto-reset event (or waitable timer) is reset by the check, as by run’s wait.

on_ready is a module function. A component’s own method can’t go there: it needs its instance, which a plain function value doesn’t carry, so ui.watch(h, tick) inside a component is a compile error. A component puts a ui.Watch or ui.Timer in its view instead (next section).

Timers and watches in a component

A component that samples something (a clock, a device, a socket) has the loop call one of its own methods, the way a button calls one: ui.Timer and ui.Watch are components with an event, and the method is bound to it. They have no size and paint nothing. The state stays in the component’s vars, and the children get it as props:

tape
@profile(t2);
import ui from "ui";
import gfx from "gfx";

// A bar as long as `percent`: knows nothing of where it comes from
component Meter {
    @tape { ui.drawable(); }
    prop percent: i64 = 0;

    fn paint(s: *gfx.Surface, x: i64, y: i64, w: i64, h: i64) {
        s.fill_rect(x, y, w, h, #202020);
        s.fill_rect(x, y, w * percent / 100, h, #33CC66);
    }
}

component Monitor {
    var cpu: i64 = 0;
    var mem: i64 = 0;

    fn sample() {                    // this Monitor's, once a second
        cpu = cpu_percent();
        mem = memory_percent();
    }

    view {
        ui.Column {
            ui.Timer { every: 1000; on_tick: sample; }
            Meter { percent: cpu; }
            Meter { percent: mem; }
        }
    }
}

pub fn main() -> i32 {
    ui.run(Monitor {}, 300, 80, "Activity") or { return 1; };
    return 0;
}

Each tick changes cpu and mem; the frame after it repaints the two meters and nothing else.

ComponentPropsEvent
ui.Timerevery: i64 (milliseconds), repeat: bool = trueon_tick() every every ms (once, with repeat: false)
ui.Watchhandle: i64, want: u8 = 0on_ready(handle: i64) whenever handle can be read
  • A Timer counts from when it is mounted, and again from when every or repeat change; every of 0 or less never ticks. A tick that comes late (a long handler) is not caught up: the timer goes on from then.
  • A Watch watches while it is mounted, again when handle or want change; a negative handle watches nothing. want: 0 is a platform handle as ui.watch takes; net.READABLE / net.WRITABLE make it a socket as ui.watch_socket takes. It counts in ui.watch_count().
  • Either stops when it leaves the view (an if turning false, its component unmounted).
  • ui.Column and ui.Row give them no space. A layout of your own skips them with ui.takes_space(child).

Headless, time moves only when you say: screen.advance(ms) moves the ui clock (ui.clock_ms()) on, and every timer due on the way ticks, each followed by a frame (it returns the ticks):

tape
let m = Monitor {};
var screen: ui.Screen = ui.headless(m, 300, 80) or { return 1; };
@assert(screen.advance(999) == 0);
@assert(screen.advance(1) == 1);            // one second after mounting
@assert(ui.frame_painted() == 2);           // the two meters

Making components draw and react

A component opts into what it needs with the dispatch groups:

Call in the bodyMethods it then implements
@tape { ui.drawable(); }fn paint(s: *gfx.Surface, x: i64, y: i64, w: i64, h: i64); gets bounds_x/y/w/h
@tape { ui.layoutable(); }fn layout(x: i64, y: i64, w: i64, h: i64): place the children (ui.layout_tree on each)
@tape { ui.interactive(); }fn handle_pointer(ev: *ui.PointerEvent), fn handle_key(ev: ui.KeyEvent); optionally fn focus_changed(focused: bool), fn handle_paste(text: []const u8), fn handle_paste_kinds(ev: ui.Paste)
@tape { ui.focusable(); }Nothing required: makes it a Tab stop; optionally fn skip_tab() -> bool, fn keeps_tab() -> bool
@tape { ui.cursored(); }fn cursor_at(x: i64, y: i64) -> ui.Cursor: the pointer’s image over it (below)

A pointer event goes to the component under the pointer and bubbles to its parents until one sets ev.handled = true. Only components that draw are hit: one without paint (a wrapper, a ui.Column) lets the pointer through to its children. A press makes the component that handled it capture the pointer and take focus: it gets the Move events and the release (Up if released over it, Cancel otherwise). Keys go to the focused component. ev.kind is Down, Up, Cancel, Move, Enter, Leave, Wheel or ContextMenu (below); ev.modifiers holds the ui.Modifier bits (Shift, Ctrl, Alt, Meta) held at the event, and ev.clicks counts presses in a row on one component (2 for a double click): close together, within ui.DOUBLE_CLICK_MS (500) and ui.DOUBLE_CLICK_PX (4). ev.button is the button of a Down, Up or Cancel (null for the others): the tree clicks with the left button only, so it is always ui.MouseButton.Left there. The other buttons are read with ui.mouse_down(b) and its edges; a gl or gpu window’s events carry them all. Key events carry ui.Key codes and ui.Modifier bits.

A Wheel event carries the scroll as it came: ev.wheel_y (positive toward the end, the content moving up) and ev.wheel_x (positive to the right), in 1/120 of a wheel’s notch (ui.WHEEL_NOTCH): a touchpad sends a few units at a time. ev.delta is whole notches, positive away from the user, with the rest of a notch carried to the next event. ui.ScrollArea follows the fine amount, both ways.

Context menus

A ContextMenu event is a context menu asked for: handle it to offer one (a message’s actions, a field’s cut, copy and paste). ui gives one per gesture, when the platform’s convention says so:

PlatformMouse (ev.button is Right)Keyboard (ev.button is null)
WindowsThe right button’s release (WM_CONTEXTMENU)The Menu key, Shift+F10
Linux (X11)The right button’s pressThe Menu key, Shift+F10
macOSThe right button’s press, Ctrl+clickShift+F10

It is a kind of its own, so a handler that takes any Down or Up as a click doesn’t react to the right button; on macOS a Ctrl+click is the menu and no left click. The mouse’s goes to the component under the pointer and bubbles like a press, but takes no capture and moves no focus; ev.x, ev.y are the pointer. The keyboard’s goes to the focused component (the root when nothing is focused) at its top-left plus ui.CONTEXT_KEY_OFFSET (8) each way. ui opens no menu itself.

tape
fn handle_pointer(ev: *ui.PointerEvent) {
    if (ev.kind == ui.PointerKind.ContextMenu) {
        open_menu_at(ev.x, ev.y);        // your own menu: a dialog, a popup component
        ev.handled = true;
    }
}

The mouse and the cursor

Over a component the pointer’s image is the component’s to choose. Opt in with ui.cursored() and answer cursor_at:

tape
component Link {
    @tape { ui.drawable(); ui.cursored(); }
    fn paint(s: *gfx.Surface, x: i64, y: i64, w: i64, h: i64) { s.fill_rect(x, y, w, h, #303090); }
    fn cursor_at(x: i64, y: i64) -> ui.Cursor { return ui.Cursor.Hand; }
}

Auto asks its parent, and so up; last comes the arrow. It is asked as the pointer moves, so the answer may depend on where in the component it is, or on its state. Moving off, the cursor changes with the hover. A drag keeps its component’s cursor outside it. A program that asks for nothing has the arrow it always had. A component answers a shape: it can’t return a custom cursor in this version.

tape
pub enum Cursor : u8 {
    Auto = 0;           // says nothing: the next one asked decides, the arrow last
    Arrow = 1; Hand = 2; Text = 3; Crosshair = 4;
    ResizeH = 5; ResizeV = 6; ResizeNWSE = 7; ResizeNESW = 8; ResizeAll = 9;
    NotAllowed = 10; Wait = 11;
}
pub struct CustomCursor { h: i64 = 0; }     // make_cursor's; empty once freed
pub enum MouseButton : u8 { Left = 0; Right = 1; Middle = 2; X1 = 3; X2 = 4; }
pub type Point = gfx.Point;     // x, y: a place, a motion, a wheel's turn
pub const MAX_CURSOR_SIZE: i64 = 256;

While ui.run runs (from on_mount on), its window answers to these. Outside run there is no window: nothing is done and nothing is read.

FunctionDoes
ui.set_cursor(c)The program’s own shape, over every component’s; ui.Cursor.Auto gives the choice back, and clears a custom cursor too
ui.set_custom_cursor(c)A custom cursor, at the same level: the most recent of it and set_cursor wins
ui.show_cursor(on)Whether the pointer shows over the window
ui.native_window() -> i64The platform’s handle of run’s window (HWND, NSView, X11 Window), 0 when none is open: what dialog and notify attach to
ui.make_cursor(argb, w, h, hot_x, hot_y) -> ?ui.CustomCursorA custom cursor: w x h pixels, 0xAARRGGBB not premultiplied, row 0 at the top; the hot spot is the pixel that points. Null when the platform makes none. Traps on a size outside 1..MAX_CURSOR_SIZE, a hot spot outside it, or too few pixels
ui.free_cursor(&c)Frees it and empties it; twice is fine. Freed while selected, the selection falls back to Auto
ui.confine_cursor(on) -> boolKeeps the pointer inside the window while it is in front; false when the platform can’t
ui.warp_cursor(x, y)Moves the pointer, in the window’s pixels, while it is in front
ui.set_relative_mouse(on) -> boolThe pointer hidden and held, its motion read with mouse_delta; given back while the window is behind. False when the platform can’t
ui.mouse_delta() -> ui.PointThe motion since the last call (see gl for its units)
ui.mouse_pos() -> ui.PointWhere the pointer was last seen, in the window’s pixels
ui.mouse_down(b) -> bool, ui.key_down(k) -> boolHeld, as the messages read so far say
ui.mouse_pressed(b), ui.mouse_released(b), ui.key_pressed(k), ui.key_released(k)It went down, or came up, in this frame
ui.mouse_wheel() -> ui.PointThe wheel since the last call, in 1/ui.WHEEL_NOTCH notches: y > 0 toward the end, x > 0 to the right
tape
component Game {
    @tape { ui.drawable(); ui.animated(); }
    var marker: ui.CustomCursor = ui.CustomCursor {};

    fn on_mount() {
        ui.animate(__self);
        var px: [16]u32;
        for (i in 0..16) { px[i] = 0xFFFF00FF; }
        marker = ui.make_cursor(px[..], 4, 4, 0, 0) or { return; };
        ui.set_custom_cursor(marker);
    }

    fn frame(dt_ms: f64) -> bool {
        if (ui.mouse_pressed(ui.MouseButton.Right)) { ui.warp_cursor(10, 10); }
        let p = ui.mouse_pos();
        if (ui.key_pressed(ui.Key.Space) && p.x > 100) { ui.show_cursor(false); }
        let scrolled = ui.mouse_wheel();
        let moved = ui.mouse_delta();
        return true;
    }

    fn paint(s: *gfx.Surface, x: i64, y: i64, w: i64, h: i64) { s.fill_rect(x, y, w, h, #101010); }
}

Who wins, highest first: relative mode or show_cursor(false) (nothing shows); what the program selected, set_cursor or set_custom_cursor, the most recent; the hovered component’s; the arrow.

This frame. ui has no poll, so its frames are its ticks: with a ui.Timer armed or something animating, the edges last until the end of the pass that ticked, so a frame(dt_ms) or a timer’s handler sees every press since the last pass. With neither there are no frames: each message is one, and a handler sees what that message did.

A Screen has the same names as methods, with no window behind them, for tests and for a ui tree drawn over a game: screen.cursor() is what it would show, never Auto, and a game passes it to its own window once a frame, so the window is the one owner of the cursor (gl). It is a shape: a custom cursor over an overlay is for the game to select on its window:

tape
dev.overlay_cursor(hud.cursor());

What these are made of is public, for your own loop or your tests. ui.pick_cursor(set, chosen) is the rule above for shapes: what was set, else what was chosen, else the arrow. ui.CursorState is one owner’s selection: select_shape(c), select_custom(c), apply(wnd, chosen) (uwm told when it changes; wnd 0: nobody), free_custom(wnd, &c). ui.Cursored asks whether a component has the group (comp is ui.Cursored). ui.cursor_on(wnd, argb, w, h, hot_x, hot_y) is make_cursor on a uwm window handle. ui.InputFrame holds what is polled: told of events, it answers the same questions, and you say when a frame ends:

tape
@assert(ui.pick_cursor(ui.Cursor.Auto, ui.Cursor.Text) == ui.Cursor.Text);

var cursors = ui.CursorState { .. };
var mine = ui.CustomCursor { h: 5; };             // as a window's make_cursor gave it
cursors.select_custom(mine);
cursors.apply(0, ui.Cursor.Hand);
cursors.free_custom(0, &mine);                    // freed while selected: back to Auto
cursors.select_shape(ui.Cursor.Wait);
cursors.apply(0, ui.Cursor.Hand);
@assert(cursors.shape == ui.Cursor.Wait);

var input = ui.InputFrame { .. };
input.key_event(ui.Key.A as i64, true);               // keycode, down
input.button_event(ui.MouseButton.Left, true);
@assert(input.key_down(ui.Key.A) && input.key_pressed(ui.Key.A));
@assert(input.mouse_down(ui.MouseButton.Left) && input.mouse_pressed(ui.MouseButton.Left));
input.end_frame();                                    // the edges start over
@assert(!input.key_pressed(ui.Key.A) && !input.key_released(ui.Key.A));
input.let_go();                                       // the window left the front: all keys up
var words: [7]i64 = [10, 20, 1, 1, 0, 0, 120];        // uwm.mouse_state's, or a test's
input.take(&words[0]);
@assert(!input.mouse_released(ui.MouseButton.Left) && input.take_wheel().y == 120);
// input.sample(wnd) is take(), from a uwm window

The clipboard

tape
fn handle_key(ev: ui.KeyEvent) {
    if (ui.is_copy_key(ev)) { ui.set_clipboard(selected_text()); }
    if (ui.is_paste_key(ev)) { ui.paste(); }    // handle_paste gets the text
}
fn handle_paste(text: []const u8) { insert(text); }

ev.key is the key as a ui.Key (ev.key == ui.Key.Escape, ui.Key.A, ui.Key.F5), ui.Key.Other for a code the enum does not name; ev.keycode is the raw code, the same on every platform (ui.key_of(code) maps one). A typed character (KeyKind.Char) is a Unicode code point in ev.codepoint, whatever the keyboard layout; widgets.TextInput keeps its text as UTF-8 and moves its cursor by characters.

ui.set_clipboard(text) puts text on the system’s clipboard (and keeps it as the program’s own). ui.paste() asks for it: the focused component’s handle_paste gets it after the current event, or when the system answers. On Leivos reading the clipboard needs the user’s paste gesture, so call paste from the paste key’s (or a click’s) handler. ui.is_copy_key, is_cut_key and is_paste_key tell the usual keys (Ctrl or Command with C, X, V; Shift+Insert, Shift+Delete). widgets.TextInput copies, cuts and pastes with them. When the system’s clipboard is empty or holds no text, a paste gives nothing.

Pictures and files go on the clipboard too. ui.set_clipboard_picture(&s) copies a surface (other programs paste it as PNG, and on Windows as a bitmap), ui.set_clipboard_files(paths) a list of files (a file manager pastes them as files, a text field as their paths). ui.paste_kinds(kinds) asks for any of text, a picture and files, and the focused component’s handle_paste_kinds gets a ui.Paste with each that is there:

tape
fn handle_key(ev: ui.KeyEvent) {
    if (ui.is_paste_key(ev)) { ui.paste_kinds(ui.CLIP_ALL); }
}
fn handle_paste_kinds(ev: ui.Paste) {
    if (ev.has_picture) {                     // a screenshot, a copied image
        var s: gfx.Surface = image.decode(ev.picture) or { return; };
        attach_picture(&s);
        s.free();
    } else if (ev.has_files) {
        for (p in ev.paths) { attach_file("{p}"); }
    } else if (ev.has_text) {
        insert(ev.text);
    }
}

A widgets.TextInput or widgets.Editor does this for you when its paste_other names the kinds you take: they reach its on_paste_other (widgets). ui.ClipKind.Text, Picture and Files are the bits of kinds (ui.CLIP_ALL is all three). A Paste is what a ui.Drop carries: the text, the picture as an image file’s bytes (PNG, JPEG, or a BMP made of a Windows bitmap: image.decode reads them all), the files’ full paths, each a view valid while the handler runs, so copy what you keep. A screenshot pastes on every system: Windows’ PrintScreen and Snipping Tool, GNOME’s screenshots, macOS’s Cmd+Ctrl+Shift+4. On Linux the clipboard is X11’s: what the program copied stays pasteable while its window is open, and after it closes when a clipboard manager runs. On Leivos the clipboard holds text only.

A test that pastes must not touch the user’s clipboard. ui.paste_text(text) pastes text into the focused component exactly as if its paste key had read it from the clipboard, and never reads or writes the clipboard:

tape
fn script_step() {                    // a ui.Timer's tick in an end-to-end test
    ui.paste_text("a recovery code");  // the focused field pastes it, after this tick
}

The component gets it after the current event, in handle_paste_kinds (a ui.Paste with the text alone) when it writes one, else in handle_paste, so a widgets.TextInput (controlled or not), an Editor or a picker’s field takes it as a real paste: made one line by a field, on_change called, refused by a controlled field’s owner. With nothing focused nothing happens. ui.paste_text works in ui.run with the window open and does nothing outside it; drive a headless screen with screen.paste_text(text) instead (§Testing without a window).

Drag and drop

Files, text and pictures dragged onto the window from a file manager, a browser or an editor go to the component under the pointer. A component takes them with ui.droppable() and answers what the drop would do:

tape
component Attach {
    @tape { ui.drawable(); ui.droppable(); }
    var lit: bool = false;
    var names: string = "";

    fn handle_drop(ev: ui.Drop) -> ui.DropEffect {
        if (!ev.has_files || ev.kind == ui.DropKind.Leave) {
            lit = false;
            return ui.DropEffect.None;       // not here
        }
        lit = ev.kind != ui.DropKind.Drop;   // show it is a target while it hovers
        if (ev.kind == ui.DropKind.Drop) {
            for (i in 0..ev.paths.len) { names = "{names}{ev.paths[i]}\n"; }
        }
        return ui.DropEffect.Copy;
    }

    fn paint(s: *gfx.Surface, x: i64, y: i64, w: i64, h: i64) {
        var bg: color = #202428;
        if (lit) { bg = #1E5A28; }
        s.fill_rect(x, y, w, h, bg);
    }
}

handle_drop is asked as the drag moves over the component (Enter, then Over), and with Drop when it is let go there. Answering DropEffect.None says no: the component’s parent is asked next, and the source shows that nothing can be dropped. Answering Copy (or Move, Link) makes the component the drag’s target; when the drag goes on to another component or out of the window, or the user gives it up, the target is told Leave. So a highlight is on from an accepted Enter or Over until Leave or Drop.

What is dragged is known at every event (has_files, has_text, has_picture); the data only at Drop: paths (full paths), text (UTF-8) and picture (an image file’s bytes: image.decode(ev.picture)). They are only valid while handle_drop runs, so copy what you keep, as "{ev.paths[i]}" does. ev.allows(ui.DropEffect.Move) tells whether the source lets you move; ev.modifiers the keys held (file managers move with Shift); ev.x, ev.y where, in the window’s pixels.

Every window ui.run opens takes drags; a headless Screen gets them from screen.drag(ev), routed the same way, for tests. Windows, Linux (X11) and macOS; not yet on Leivos. programs/drop_demo.tape shows everything it is given.

Focus

One component at a time has the keyboard focus. When the window opens with nothing focused, the first focusable component in view order gets it, as one Tab would, so a window whose only focusable component is its root handles keys at once; ui.focus from on_mount chooses another (null: none). A press moves it to the component that handled the press; a press that nothing handles (an empty area) takes it away, so two fields never both show a caret. focus_changed(true) and focus_changed(false) tell the component that gets and the one that loses it: draw a caret or a focus ring while it is focused.

tape
component Field {
    @tape { ui.drawable(); ui.interactive(); ui.focusable(); }
    state focused: bool = false;
    fn focus_changed(f: bool) { focused = f; }
    // paint draws the caret while focused ...
}
FunctionDoes
ui.has_focus(c)Whether c has the focus
ui.focus(c)Give c the focus (null: take it away). Called before the window opens (from on_mount), it takes effect when input starts, instead of the default first Tab stop: an app’s second field, or null for none

Tab and Shift+Tab move the focus between the ui.focusable() components, in view order, wrapping round. One whose skip_tab() returns true is passed by (a disabled field); one whose keeps_tab() returns true gets Tab in handle_key while it has the focus (an editor that indents). The Char event a Tab also makes is not delivered when the Tab moved the focus. widgets.TextInput is focusable and keeps its caret only while focused.

The focus stays on a field while the view around it updates: an invalidate, a list growing above or below it and a binding read again keep the same instance. When an update builds the field again (an if that switches to a branch with the same form), the new field at the same place gets the focus. A component that goes away takes the focus with it, and nothing else gets it until a press, Tab or ui.focus gives it.

A key goes to the focused component’s handle_key. A component that doesn’t write a handle_key of its own (a Slider, a Button) passes the key on to the nearest component above it that does, so clicking a slider doesn’t stop your window’s shortcuts. A component with a handle_key takes every key that reaches it.

Layout containers: ui.Column, ui.Row and ui.ScrollArea (below), ui.WindowLayer (overlapping windows, ui.raise). ui.show_dialog(d) paints d over everything and gives it the pointer until ui.close_dialog().

Column and Row

ui.Column stacks its children top to bottom, ui.Row left to right. Each has four props of its own:

PropDefaultDoes
gap0Pixels between two children
padding0Pixels kept free inside every edge
alignui.Align.StretchWhere a child with a fixed size sits across: Start, Center, End; Stretch fills the width (a Column) or the height (a Row)
sizes[]The children’s sizes along the axis, in order: an entry above 0 is that child’s width (a Row) or height (a Column); 0, or a child past the list, sizes itself as below

Their children size themselves with three more props, width, height and grow, which every widget, ui.Column, ui.Row and ui.ScrollArea have:

  • width: 120 (in a Row) or height: 32 (in a Column) is a fixed size;
  • the children without one share what is left, in proportion to their grow (1 unless given): grow: 2 takes twice its siblings’ share, grow: 0 none;
  • across, a fixed size is kept and placed by the container’s align.
tape
ui.Column { padding: 12; gap: 8;
    widgets.Label { text: "Name"; height: 20; }
    widgets.TextInput { height: 28; }
    widgets.Panel {}                                   // grows: the rest of the height
    ui.Row { height: 32; gap: 8; align: ui.Align.Center;
        widgets.Panel {}                               // pushes the buttons right
        widgets.Button { label: "Cancel"; width: 90; height: 28; }
        widgets.Button { label: "Save"; width: 90; height: 28; }
    }
}

grow: 0 with no fixed size gives a child its own size, the one it measures: a Button as wide as its label, a Label as tall as its text. With an align other than Stretch it takes its own size across too. ui.Column and ui.Row measure as well (their children, gaps and padding), so a ui.Row { grow: 0; ... } in a Column is as tall as its tallest child:

tape
ui.Row { grow: 0; gap: 8; padding: 8;
    widgets.Button { label: "Open"; grow: 0; }
    widgets.Button { label: "Save as..."; grow: 0; }
    widgets.Panel {}                                   // the rest
}

sizes sets them from the container, for a bar of fixed parts and a flexible middle:

tape
var cols: [3]i64 = [200, 0, 36];
ui.Row { sizes: cols[0..3];
    widgets.Pane { bg: #F4F5F7; }                      // 200 wide
    widgets.Pane {}                                    // the rest
    widgets.IconButton { icon: "M3 7H11"; }            // 36 wide
}

With none of them given, the children share the space equally, as before. Your own component takes the three sizing props with @tape { ui.sizable(); }; a component without them is laid out as one with grow: 1. It measures itself with @tape { ui.measurable(); } and a fn measure(max_w: i64, max_h: i64) -> ui.Size; ui.natural_size(child, max_w, max_h) is what a layout asks (fixed sizes first, then the measure). Being props, all of them can be set by #style rules (ui.Row { gap: 8; }), so a module’s spacing can live in one place. A layout of your own reads a child’s through if (child is ui.Sizable) { ... child.width ... }, or hands its children to ui.layout_line(__self, vertical, x, y, w, h, gap, padding, align), the one Column and Row use (ui.layout_sized(..., sizes) with sizes).

ScrollArea

ui.ScrollArea is a view over content taller or wider than it, with scrollbars: the one scroll container (widgets.Scrollable was merged into it).

tape
ui.ScrollArea { on_scroll: scrolled;
    widgets.Stack { gap: 8; pad: 12;                   // as tall as it measures
        widgets.Paragraph { text: intro; }
        widgets.Section { title: "Sound"; }
    }
}
ui.ScrollArea { content_w: 2000; content_h: 1500;  // fixed: a picture's size
    widgets.Image { src: &photo; }
}
PropDefaultDoes
directionui.ScrollDir.BothThe ways it may scroll: Vertical, Horizontal, Both
content_h0The content’s height; 0: what the children measure
content_w0The content’s width, when wider than the view
reveal, reveal_h-1, 0A y in the content (and a height) scrolled into view whenever reveal changes

Its children are stacked top to bottom: each as tall as it measures (a Stack, a Paragraph, a Section; the last one is stretched to the view), or content_h shared between them when you give it. They are as wide as the view less the scrollbar, or content_w. Content longer than the view one way scrolls that way, with a scrollbar along that edge, drawn by look in the theme’s palette.

It scrolls with the wheel and a touchpad (ui.SCROLL_STEP, 40 pixels, a notch; sideways by a sideways scroll, or by an ordinary one when only its width overflows), by dragging a scrollbar’s thumb, by a click on the track (a page), and with Page Up, Page Down, Space, the arrows, Home and End once it has the focus (a click inside it gives it). on_scroll(offset) reports each new vertical offset; scroll_to(sx, sy) scrolls it from code, and scroll_x, scroll_y read where it is. The arithmetic is yours for a list that scrolls itself: ui.clamp_scroll, ui.thumb_of, ui.drag_scroll, ui.reveal_scroll, ui.wheel_steps.

Animating

A component that moves with time is @tape { ui.animated(); } with a fn frame(dt_ms: f64) -> bool: after ui.animate(comp), ui calls it every frame (16 ms) until it returns false. Step tweens there and assign what the view reads. ui.stop_animation(comp) stops it, and screen.advance(ms) runs the frames headless. See tween and easing.

Keeping a view current

Keep what a view shows in the component’s vars, change it in the component’s own methods (bound to events: a click, a key, a ui.Watch or ui.Timer for handles and timers), and hand it down as props:

tape
import widgets from "widgets";

component Clicks {
    var count: i64 = 0;
    fn bump() { count = count + 1; }

    view {
        ui.Column {
            widgets.Label { text: "clicks: {count}"; }
            widgets.Button { label: "+1"; on_click: bump; }
        }
    }
}

A binding (text: "clicks: {count}", size: count % 3, a prop handed on to a child’s own view) is evaluated again when a var, state or prop it reads changes, and the child it sets repaints if the value differs. Nothing else is needed. A var changes when it is assigned, when an element or field of it is, and when a method that may change it (one taking *self) is called on it: items.push(x) re-reads text: "{items.len()}".

For a list prop (a slice), “differs” means its contents: rebuilding a list in place with the same rows repaints nothing, and only the components whose rows changed repaint. Numbers, strings, nested lists, floats and optionals inside the rows all count. A pointer inside a row counts by the address it holds, not by what it points at: if that data changes, call ui.invalidate on the component.

ui.invalidate(comp) is the explicit way out, for views that read state changed outside the tree, such as a module variable a module function given to ui.watch updates (the sample above). A binding that reads a module variable or calls a function is evaluated when its instance is built and again only at ui.invalidate: ui doesn’t follow module state. invalidate(comp) evaluates every binding and if/for of comp and of the components under it on the next frame, and repaints comp’s area.

What gets repainted

A frame repaints only what changed. A component is dirty when one of its vars or states is assigned (an element or field of one included) or its parent gives it a new prop value; the frame repaints the dirty components’ bounds, the old and new bounds of anything layout moved, and where removed components were: those rectangles (at most ui.MAX_RECTS, 8) are cleared and every drawable that meets them is painted again in tree order, clipped to them, and a window presents just them. A pointer move that changes no state repaints and presents nothing. So:

  • paint draws inside the component’s bounds (gfx drawing is clipped there; code that writes s’s pixels itself keeps inside s.clip()) and from the component’s own state, props and bounds;
  • what paint or layout writes (a position kept for hit tests) is not a change;
  • a view or paint that reads something ui can’t see (a module variable, a theme switch) needs ui.invalidate(comp), which evaluates the view’s bindings again and repaints the component’s whole area (the whole window for the root).

Testing without a window

A Screen from headless works like a window that you drive yourself:

tape
let app = Counter {};
var screen: ui.Screen = ui.headless(app, 200, 100) or { return 1; };
screen.click(20, 50);                       // press and release
screen.type_text("hello");                  // keys for the focused component
screen.press(ui.Key.Return);
@assert(screen.pixel(5, 5) == #FFFFFF);
@assert(screen.checksum() == 1234567890);   // the whole picture
let r: gfx.Rect = ui.bounds(ui.child(app as *u8, 0));   // where layout put a child
screen.free();
MethodDoes
pointer(kind, x, y), click(x, y), wheel(x, y, delta), scroll(x, y, dx, dy)Pointer input (scroll: a touchpad’s amounts, 1/120 notch), then a new frame
context_menu(x, y), context_menu_key()A context menu asked for with the mouse at (x, y) (button Right), or with a key (to the focus), then a new frame
hold(modifiers)The ui.Modifier bits held for the pointer events that follow (a key event sets them too)
key(kind, keycode, codepoint, modifiers), press(key), type_text(text)Keyboard input, then a new frame
paste_text(text)A paste of text into the focused component, as from the clipboard but without touching it (§The clipboard), then a new frame
pixel(x, y), checksum(), focus()What the last frame shows; who has focus
frame()Render again (after changing state yourself)
resize(w, h) -> void or UiErrorA new surface of that size, the tree laid out over it and repainted
damage() -> []const gfx.Rect, clear_damage()What changed since the last clear_damage, over all the frames since
premultiplied(r) -> []const u8A rectangle’s pixels for a Bgra8 texture and Blend.Premultiplied
ready(handle), poll_sockets()A watched handle’s callback, or the ready sockets’, then a new frame
poll_watches() -> i64Every watched handle and socket checked without waiting: the ready ones’ callbacks, as run calls them, then a new frame if any ran; how many ran (the way to service a module’s private watches)
advance(ms)The ui clock moved on: each ui.Timer due ticks, then a new frame
set_cursor(c), cursor() -> ui.CursorThe program’s shape; the shape that would show now: set_cursor’s, else the hovered component’s, else the arrow
set_custom_cursor(c), custom_cursor() -> ?ui.CustomCursorThe same selection for a custom cursor, only kept: the most recent of it and set_cursor wins, cursor() goes on saying the shape
show_cursor(on), cursor_visible() -> boolKept, for the second to read: a screen shows no pointer
make_cursor(argb, w, h, hot_x, hot_y) -> ?ui.CustomCursorNull: a custom cursor belongs to a window. Its traps hold
free_cursor(&c)Empties it; selected, the selection falls back to Auto
confine_cursor(on), set_relative_mouse(on)False: no pointer to hold
warp_cursor(x, y), mouse_pos()Sets, and reads, the place; the tree hears of it with the next pointer event
mouse_delta(), mouse_wheel()Zero with no mouse; the wheel wheel and scroll were given
mouse_down(b), mouse_pressed(b), mouse_released(b)What pointer said of Left, button of the others
button(b, down)A button other than Left, for those; the tree hears nothing of it (Right makes no context menu: context_menu does)
key_down(k), key_pressed(k), key_released(k)What key said
free()Free the screen’s surface; the component tree stays (ui.unmount it)

What the last frame (of a screen or a window) did, for tests that count repaints:

FunctionIs
ui.frame_painted()Components it painted (0 when nothing had changed)
ui.frame_damage(), ui.frame_rect(i)The rectangles it repainted (0 to 8)
ui.paint_count()Components painted since the program started
tape
screen.pointer(ui.PointerKind.Move, 5, 5);  // into a button
@assert(ui.frame_painted() == 1);           // the button, nothing else
screen.pointer(ui.PointerKind.Move, 6, 5);  // still in it
@assert(ui.frame_damage() == 0);            // nothing repainted

No display is needed, so these tests run anywhere tape test does.

Drawing over a game

alpha: true gives the Screen an Argb surface. Where the tree paints nothing the surface stays transparent, and background is stored as you give it: #00000000, the default, is transparent and #00000040 a tint. (On an opaque Screen, #00000000 means the theme’s window color.) What the widgets paint keeps the surface’s alpha: an opaque panel stays opaque under its text, and text over nothing has the color you asked for with its coverage as alpha, so it doesn’t show what’s behind it.

A frame repaints only what changed, and the game uploads only that. Input methods render a frame each, so read damage(), which adds them up, rather than ui.frame_damage(), which says only the last:

tape
var hud: ui.Screen = ui.headless(root, w, h, alpha: true) or { return 1; };
var tex: gpu.Texture = dev.texture(w, h, gpu.Format.Bgra8, false) or { return 1; };

// each tick, after hud.pointer(...), hud.key(...) and hud.frame():
for (r in hud.damage()) {
    tex.write(&dev, r.x, r.y, r.w, r.h, hud.premultiplied(r), r.w * 4);
}
hud.clear_damage();
// then draw tex over the game with gpu.Blend.Premultiplied

// when the window changes size (and a texture of the new size):
hud.resize(new_w, new_h) or { return 1; };

premultiplied keeps its pixels in the Screen, valid until its next call. hud.pixel(x, y) reads the surface, as gfx keeps it: colours unmultiplied.

The tree

FunctionDoes
child(comp, i), child_total(comp), children(comp)The children, through if and for
parent(comp)The parent component
bounds(comp) -> gfx.RectWhere the last layout put a drawable component
invalidate(comp)Re-evaluate every binding and if/for of it and the components under it (module variables and calls included), and repaint its area, on the next frame
hit_test(root, x, y)The component under a point
unmount(comp)Destroy comp and everything under it: on_unmount, then its children, then its memory (see Lifecycle)

ui.update_tree, layout_tree, paint_tree, do_pointer and do_key are the passes run and Screen use, for frameworks of your own.

Last modified: