Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-ui

Source of release 0.19.4

0.19.4 / src / application / module.lucb

## The native application: one window, its widget tree, commands, timers and
## frame callbacks, and the run loop that polls input, services timers, lays out
## and presents a frame only when something changed.
import core
from luce_std import crash
from luce_dialogs import dialogs
from luce_gpu import gpu
from luce_window import input
import interop
from luce_std import math
import ownership
import thread
import time
from luce_std import utf8
from luce_window import window
import result
import layout
import scheduler
import watches
import notifiers
import present_retry
from layout import Widget, Tree, Event
from theme import Theme
from command import Command, Commands

## Construction is platform-independent. run acquires native resources and owns
## their complete lifetime, including error unwinding and callback-driven stop.
pub struct Application:
    var title_text: interop.Owned[str]
    var tree: Tree
    var commands: Commands
    let frames: interop.Signal[f64]
    let appearances: interop.Signal[input.Appearance]
    var close_handler: interop.Callback[unit, bool]?
    var error_handler: interop.Callback[str, unit]?
    let width: i64
    let height: i64
    var running: bool
    var operating: bool
    var closed: bool
    var dirty: bool
    var last_epoch: u64
    var last_render: u64
    ## A digest of the render failure last reported, 0 after a clean frame: a
    ## widget that fails every frame is reported once, not once a frame.
    var render_failure: u64
    ## The same for the frame callbacks' failures, reported once while they repeat.
    var frame_failure: u64
    ## Whether the last `run` ended by a failure it showed in a window (`failure_shown`).
    var shown_failure: bool
    var timers: scheduler.Scheduler
    var watches: watches.Watches
    var notifiers: notifiers.Notifiers
    ## The monotonic instant `wake_at` asked the loop to run a turn by, 0 for none.
    var wake_deadline: u64
    ## When a frame the GPU skipped may be drawn again (present_retry.lucb).
    var retry: present_retry.PresentRetry
    var game: bool
    var target_fps: f64
    var fullscreen: bool
    ## How the window's surface blends (luce-gpu's `Blending`): linear light, or on encoded
    ## values, as web content and most native 2D drawing blend.
    var blending: gpu.Blending
    var session_host: window.Window
    ## The crash hooks `on_crash` added, which `close` removes.
    var crash_hooks: interop.Reference[crash.Hook][]
    var crash_hook_count: usize

    ## A process started to show a crash report (luce-std's `crash.report_to_show`) shows
    ## it here, in a window of its own, and ends: the program's own window never opens.
    ## `blending` is the window surface's (luce-gpu's `Surface.open`): `encoded` suits an
    ## application whose content blends on encoded values, such as a web browser's pages.
    pub func init(content: interop.Interface[Widget], title: str = "Luce", width: i64 = 800, height: i64 = 600, theme: Theme = Theme(), game: bool = false, fps: f64 = 70.0, fullscreen: bool = false,
                  blending: gpu.Blending = gpu.Blending.linear) -> !:
        if not showing_crash:
            let report = try crash.report_to_show()
            if report.value != "":
                show_crash_report(report.value)
            report.release()
        if not thread.is_main():
            error(interop.wrong_thread, "UI applications require the main thread")
        if width < 1 or width > 10000 or height < 1 or height > 10000 or not utf8.valid(title.bytes):
            error(result.invalid, "a window needs valid UTF-8 and dimensions in 1..10000")
        try check_fps(fps)
        try theme.validate()
        let copied = try interop.copy_text(title)
        errdefer copied.release()
        var tree = try Tree(content, theme)
        errdefer tree.close()
        let frames = try interop.Signal[f64]()
        errdefer frames.release()
        let appearances = try interop.Signal[input.Appearance]()
        errdefer appearances.release()
        self.title_text = copied
        self.tree = tree
        self.commands = Commands()
        self.frames = frames
        self.appearances = appearances
        self.close_handler = none
        self.error_handler = none
        self.width = width
        self.height = height
        self.running = false
        self.operating = false
        self.closed = false
        self.dirty = true
        self.last_epoch = 0
        self.render_failure = 0
        self.frame_failure = 0
        self.shown_failure = false
        self.last_render = 0
        self.timers = scheduler.Scheduler()
        self.watches = watches.Watches()
        self.notifiers = notifiers.Notifiers()
        self.wake_deadline = 0
        self.retry = present_retry.PresentRetry()
        self.game = game
        self.target_fps = fps
        self.fullscreen = fullscreen
        self.blending = blending
        self.session_host = window.Window()
        self.crash_hooks = try new interop.Reference[crash.Hook][2] --- in memory.heap
        self.crash_hook_count = 0

    func check() -> !:
        if self.closed:
            error(result.invalid, "the UI application is closed")

    ## Change the window's title, now while it runs, or for the next run.
    pub func set_title(title: str) -> !:
        try self.check()
        if not utf8.valid(title.bytes):
            error(result.invalid, "a window title must be valid UTF-8")
        let replacement = try interop.copy_text(title)
        let previous = self.title_text
        self.title_text = replacement
        previous.release()
        if self.running:
            try self.session_host.set_title(title)

    ## The window's title, as given at construction or by the last set_title.
    pub func title() -> interop.Owned[str]!:
        return try interop.copy_text(self.title_text.value)

    ## Present every frame and cap the loop to `fps` (0 is uncapped). This is a
    ## run-loop mode, not a game engine: the application still owns simulation.
    pub func set_game(game: bool):
        self.game = game
        if game:
            self.dirty = true

    pub func is_game() -> bool:
        return self.game

    pub func set_fps(fps: f64) -> !:
        try check_fps(fps)
        self.target_fps = fps

    pub func fps() -> f64:
        return self.target_fps

    ## Applied on the next run, or immediately while the native window exists.
    pub func set_fullscreen(enabled: bool) -> !:
        try self.check()
        self.fullscreen = enabled
        if self.running:
            try self.session_host.set_fullscreen(enabled)

    pub func is_fullscreen() -> bool:
        if self.running:
            return self.session_host.is_fullscreen() catch failure:
                recover self.fullscreen
        return self.fullscreen

    func begin_operation() -> !:
        try self.check()
        if self.operating:
            error(result.busy, "layout, drawing and input dispatch cannot reenter themselves")
        self.operating = true

    func end_operation():
        self.operating = false

    ## Request that the next loop iteration present a frame, for a change that no
    ## input event announced — a timer, a background result, or a script mutation.
    pub func invalidate():
        self.dirty = true

    ## Run a callback once, `seconds` from now, on the main loop. A UI change it
    ## makes is presented on its own, since mutating a widget marks the tree dirty.
    pub func after(seconds: f64, callback: interop.Callback[unit, unit]) -> i64!:
        try self.check()
        return try self.timers.after(seconds, callback)

    ## Run a callback every `seconds` on the main loop, until it is canceled. Drives
    ## periodic work — polling a file, checking a background task — without spinning.
    pub func every(seconds: f64, callback: interop.Callback[unit, unit]) -> i64!:
        try self.check()
        return try self.timers.every(seconds, callback)

    ## Run a callback on the next serviced turn, to defer work back to the main loop.
    pub func post(callback: interop.Callback[unit, unit]) -> i64!:
        try self.check()
        return try self.timers.post(callback)

    ## Stop a scheduled callback by the handle after/every/post returned.
    pub func cancel(id: i64):
        self.timers.cancel(id)

    ## Run a turn of the loop (its frame callbacks, timers and watches) no later than
    ## `instant`, a monotonic time in nanoseconds like `time.now()`, then sleep again.
    ## One request at a time: each call replaces the last, an instant already past
    ## runs a turn at once, and 0 drops the request. For an engine that knows when its
    ## next work is due without a callback for each timer; an earlier timer or event
    ## still runs first.
    pub func wake_at(instant: i64):
        self.wake_deadline = 0 if instant <= 0 else (u64)instant

    ## `wake_at`, `seconds` from now.
    pub func wake_after(seconds: f64):
        let delay = 0.0 if not (seconds > 0.0) else math.min(seconds, 31536000.0)
        self.wake_deadline = time.now() + (u64)(delay * 1000000000.0)

    ## Run `callback` on the main loop whenever `descriptor` (a socket, or outside
    ## Windows a pipe) is ready to read, or with `writable` to write; the loop
    ## sleeps until then instead of polling. Level-triggered: read or write until the
    ## descriptor would block, or the callback runs again on the next turn. Unwatch
    ## before closing it. Up to 64 at once; on Windows watching makes a socket
    ## nonblocking. Returns the handle `unwatch` takes.
    pub func watch(descriptor: i64, callback: interop.Callback[unit, unit], readable: bool = true, writable: bool = false) -> i64!:
        try self.check()
        return try self.watches.add(descriptor, callback, readable, writable)

    ## A callback any thread can ask to run on this loop: the notifier's `notify`, or a
    ## worker's `ui.notify_handle(notifier).notify()`, wakes the loop if it sleeps, and
    ## its next turn runs `callback` once however many notifies came first. A worker
    ## keeps its results itself (its own locked queue) and only says there are some,
    ## so the loop never polls for background work. `close` stops it. Up to 256.
    pub func notifier(callback: interop.Callback[unit, unit]) -> interop.Reference[notifiers.Notifier]!:
        try self.check()
        return try self.notifiers.add(callback)

    ## Stop a watch by the handle `watch` returned.
    pub func unwatch(id: i64):
        self.watches.remove(id)

    ## Frame callbacks receive elapsed seconds since the preceding iteration.
    pub func on_frame(callback: interop.Callback[f64, unit]) -> interop.Reference[interop.Connection]!:
        try self.check()
        return try self.frames.connect(callback)

    ## Whether the system shows light or dark, as CSS's `prefers-color-scheme` and
    ## AppKit's NSAppearance say it (luce-window's `window.appearance`). Answers before
    ## `run` too; light where the system offers no setting.
    pub func appearance() -> input.Appearance:
        if self.running:
            return self.session_host.appearance() catch failure:
                recover input.Appearance.light
        return window.appearance() catch failure:
            recover input.Appearance.light

    ## Call `callback` with the new appearance each time the system switches between
    ## light and dark while the application runs, on the main thread, between frames.
    ## Releasing the connection stops the calls.
    pub func on_appearance(callback: interop.Callback[input.Appearance, unit]) -> interop.Reference[interop.Connection]!:
        try self.check()
        return try self.appearances.connect(callback)

    ## Returning false keeps the native window open, for example while unsaved
    ## documents await an explicit Save or Discard action in the application.
    pub func set_close_handler(callback: interop.Callback[unit, bool]) -> !:
        try self.check()
        let replacement = callback.clone()
        # Replace, then release: a release can run the cycle collector, which traces this.
        let previous = self.close_handler
        self.close_handler = replacement
        if let old = previous:
            old.release()

    ## Recoverable input errors can be reported without discarding an editing
    ## session. Without a handler, run preserves its normal failure behavior.
    pub func set_error_handler(callback: interop.Callback[str, unit]) -> !:
        try self.check()
        let replacement = callback.clone()
        let previous = self.error_handler
        self.error_handler = replacement
        if let old = previous:
            old.release()

    ## Run `callback` when the program traps, before it ends: save what can be saved
    ## into `crash.recovery_directory()` and say so with `crash.note_recovery(path)`,
    ## and the crash window tells the user where it went. Hooks have five seconds in
    ## all; a fatal signal (a segmentation fault and the like) runs none. See
    ## luce-std's `crash.on_crash`. The application keeps the hook until `close`, which
    ## removes it, so what the callback captures does not outlive the application;
    ## the answer is the hook's handle, to `remove` it sooner or to drop.
    pub func on_crash(callback: interop.Callback[unit, unit]) -> interop.Reference[crash.Hook]!:
        try self.check()
        if self.crash_hook_count == self.crash_hooks.length:
            let grown = try new interop.Reference[crash.Hook][self.crash_hooks.length * 2] --- in memory.heap
            for index in 0..<self.crash_hook_count:
                grown[index] = self.crash_hooks[index]
            let previous = self.crash_hooks
            self.crash_hooks = grown
            free(previous) in memory.heap
        let hook = try crash.on_crash(callback)
        self.crash_hooks[self.crash_hook_count] = hook.clone()
        self.crash_hook_count += 1
        return hook

    ## Replace the registered commands whose shortcuts `dispatch` and `run` match
    ## before the widget tree sees a key.
    pub func set_commands(commands: const interop.Reference[Command][]) -> !:
        try self.check()
        try self.commands.set(commands)

    ## Get the desktop's open dialog ready, so the first `open_file`, `open_files`
    ## or `choose_folder` shows at once: macOS takes about a quarter of a second
    ## to make its first open panel. Call it once the window shows and the app is
    ## idle (a short `after` timer), not in a hurry. Elsewhere it does nothing.
    pub func prepare_dialogs() -> !:
        try self.check()
        try dialogs.prepare()

    ## Show the desktop's open-file dialog with `message` and return the chosen
    ## path, or an empty string when it was canceled.
    pub func open_file(message: str) -> interop.Owned[str]!:
        let chosen = try dialogs.open_file(message) else return try interop.copy_text("")
        return chosen

    ## Show the desktop's open-file dialog letting several files be chosen and
    ## return their paths one to a line, or an empty string when it was canceled.
    pub func open_files(message: str) -> interop.Owned[str]!:
        let chosen = try dialogs.open_files(message) else return try interop.copy_text("")
        return chosen

    ## Show the desktop's save-file dialog suggesting `name` and return the chosen
    ## path, or an empty string when it was canceled.
    pub func save_file(message: str, name: str) -> interop.Owned[str]!:
        let chosen = try dialogs.save_file(message, name) else return try interop.copy_text("")
        return chosen

    ## Show the desktop's folder dialog and return the chosen folder's path, or an
    ## empty string when it was canceled.
    pub func choose_folder(message: str) -> interop.Owned[str]!:
        let chosen = try dialogs.choose_folder(message) else return try interop.copy_text("")
        return chosen

    ## The registered command with this id, or none — for a keymap or script that
    ## drives the same commands the UI does. Trigger it, then release the reference.
    pub func command(id: str) -> interop.Reference[Command]?:
        return self.commands.find(id)

    pub func set_theme(theme: Theme) -> !:
        try self.check()
        try self.tree.set_theme(theme)

    pub func focus(target: interop.Reference[layout.Layout]) -> !:
        try self.check()
        self.tree.focus_layout(target)

    ## The cursor the widget under the pointer (or the capturing widget) asks for,
    ## after refreshing the layout.
    pub func cursor() -> input.Cursor!:
        try self.begin_operation()
        defer self.end_operation()
        let refreshed = self.tree.refresh()
        defer refreshed.release()
        try refreshed.get()
        return try self.tree.cursor()

    func update_cursor(host: window.Window) -> !:
        try host.set_cursor(try self.cursor())

    ## Arrange the widget tree for a window of this size.
    pub func layout(width: f64, height: f64) -> interop.Outcome[unit]:
        self.begin_operation() catch failure:
            return result.failure[unit](failure.code, failure.message)
        defer self.end_operation()
        return self.tree.arrange(width, height)

    ## Portable entry points allow embedding and deterministic input/drawing tests.
    ## An event with `cancelled` set becomes focus loss; otherwise command
    ## shortcuts see the event first (unless a popup is open), then the tree.
    pub func dispatch(event: Event) -> interop.Outcome[unit]:
        # An appearance change goes to `on_appearance`, outside any operation, so a
        # callback may restyle the tree.
        if event.kind == input.EventKind.appearance_changed:
            self.check() catch failure:
                return result.failure[unit](failure.code, failure.message)
            return self.appearances.emit(event.appearance)
        self.begin_operation() catch failure:
            return result.failure[unit](failure.code, failure.message)
        defer self.end_operation()
        if event.cancelled:
            return self.tree.dispatch(input.Event(kind = input.EventKind.focus_lost))
        if event.button < 0 or event.button > 31:
            return result.failure[unit](result.invalid, "a pointer button must be in 0..31")
        if event.codepoint < 0 or event.codepoint > 0x10FFFF or (event.codepoint >= 0xD800 and event.codepoint <= 0xDFFF):
            return result.failure[unit](result.invalid, "text input requires a Unicode scalar")
        return self.route(input.Event(kind = event.kind, key = event.key,
                                      x = event.x, y = event.y, button = (u32)event.button,
                                      repeated = event.repeated, modifiers = input.Modifiers(shift = event.shift,
                                                                                             control = event.control, alt = event.alt, super = event.meta), codepoint = (u32)event.codepoint,
                                      scroll_x = event.scroll_x, scroll_y = event.scroll_y, scroll_unit = event.scroll_unit), false)

    func dispatch_native(event: input.Event) -> interop.Outcome[unit]:
        self.begin_operation() catch failure:
            return result.failure[unit](failure.code, failure.message)
        defer self.end_operation()
        return self.route(event, true)

    ## `native` events come from the window; the others from `dispatch`, whose
    ## drags carry the files given to `set_drop_paths`.
    func route(event: input.Event, native: bool) -> interop.Outcome[unit]:
        if not self.tree.captured_move(event):
            let arranged = self.tree.refresh()
            if not arranged.is_success():
                return arranged
            arranged.release()
        if event.kind == input.EventKind.drag_entered or event.kind == input.EventKind.drag_moved or event.kind == input.EventKind.drag_left or event.kind == input.EventKind.drop:
            return self.route_drag(event, native)
        # Shortcuts wait while a modal popup is open, and a field taking text
        # keeps its plain keys (typing "b" in a name must not pick the brush) and
        # the editing chords: select all, copy, cut, paste, undo and redo.
        # An open dialog takes Escape and Enter before any shortcut does.
        let dialog_keyed = self.tree.dialog_key(event)
        defer dialog_keyed.release()
        let dialog_took = dialog_keyed.get() catch failure:
            return result.failure[unit](failure.code, failure.message)
        if dialog_took:
            return result.success[unit](())
        let primary = event.modifiers.control or event.modifiers.super
        # The editing chords are Cmd/Ctrl (and Shift for redo) on A, C, X, V, Z;
        # with Alt they are other commands (Ctrl+Alt+Z toggles wrapping in luced).
        let editing = not event.modifiers.alt and (event.key == input.Key.a or event.key == input.Key.c or event.key == input.Key.x or event.key == input.Key.v or event.key == input.Key.z)
        # Function keys type nothing, so they stay the commands' (F6 moves between panels).
        let function_key = (u16)event.key >= (u16)input.Key.f1 and (u16)event.key <= (u16)input.Key.f12
        let typing = self.tree.wants_text_input() and not function_key and (not primary or editing)
        if not self.tree.has_popup() and not typing:
            let dispatched = self.commands.dispatch(event)
            defer dispatched.release()
            let handled = dispatched.get() catch failure:
                return result.failure[unit](failure.code, failure.message)
            if handled:
                return result.success[unit](())
        return self.tree.dispatch(event)

    ## Files dragged from another application: the window's paths become what the
    ## drop areas read, the tree routes the drag, and the window learns whether a
    ## drop would be taken so the OS can say so.
    func route_drag(event: input.Event, native: bool) -> interop.Outcome[unit]:
        if event.kind == input.EventKind.drag_entered and native and self.running:
            let paths = self.session_host.drop_paths() catch failure:
                return result.failure[unit](failure.code, failure.message)
            layout.set_drop_payload(paths) catch failure:
                return result.failure[unit](failure.code, failure.message)
        let routed = self.tree.dispatch(event)
        if not routed.is_success():
            return routed
        routed.release()
        if native and self.running:
            self.session_host.set_drop_accepted(self.tree.drop_accepted()) catch failure:
                return result.failure[unit](failure.code, failure.message)
        return result.success[unit](())

    ## The files a drag carries, for tests and embedders that dispatch drag events
    ## themselves; a running window supplies them on its own.
    pub func set_drop_paths(paths: const str[]) -> !:
        try layout.set_drop_payload(paths)

    ## Arrange the tree at the target's size and draw it into the target. The
    ## caller acquires and presents the frame.
    pub func render(target: interop.View[gpu.RenderTarget]) -> interop.Outcome[unit]:
        self.begin_operation() catch failure:
            return result.failure[unit](failure.code, failure.message)
        defer self.end_operation()
        let native = target.get() catch failure:
            return result.failure[unit](failure.code, failure.message)
        let size = native.size() catch failure:
            return result.failure[unit](failure.code, failure.message)
        let arranged = self.tree.arrange(size.width, size.height)
        if not arranged.is_success():
            return arranged
        arranged.release()
        return self.tree.draw(target)

    ## Repaint one frame at the current window size during a live resize, when the OS
    ## modal resize loop starves the event pump. Best effort: reentrancy or a
    ## transient surface fault simply leaves the last frame until the loop resumes.
    func draw_resized(surface: gpu.Surface*) -> interop.Outcome[unit]:
        if not self.running:
            return result.success[unit](())
        let frame = surface.frame() catch failure:
            return result.failure[unit](failure.code, failure.message)
        defer frame.release()
        let target = frame.value().target() catch failure:
            return result.failure[unit](failure.code, failure.message)
        defer target.release()
        target.value().allow_draws(window_draws) catch failure:
            return result.failure[unit](failure.code, failure.message)
        let rendered = self.render(target)
        if not rendered.is_success():
            return rendered
        rendered.release()
        _ = frame.value().present(self.tree.theme().background) catch failure:
            return result.failure[unit](failure.code, failure.message)
        return result.success[unit](())

    ## Open the window and GPU surface and drive the loop until `stop`, `close` or
    ## an allowed close request. A positive `frame_limit` stops after that many
    ## iterations and never blocks waiting for input, for deterministic tests; 0
    ## runs until stopped. Fails when the application is already running.
    ##
    ## A failure of a callback (input, a frame, a timer, a watch) or of a render goes to
    ## the error handler (`set_error_handler`) and the run goes on. One that still ends the
    ## run once the window is open, with no handler or from the handler itself, is shown
    ## in a window like the crash window's, with Copy, Reopen and Quit, for `frame_limit`
    ## turns when that is positive, and then returned: a program's `main` still prints it.
    pub func run(frame_limit: i64 = 0) -> interop.Outcome[unit]:
        self.check() catch failure:
            return result.failure[unit](failure.code, failure.message)
        if self.running:
            return result.failure[unit](result.busy, "the application is already running")
        if frame_limit < 0:
            return result.failure[unit](result.invalid, "a frame limit must be nonnegative")
        self.shown_failure = false
        var opened = false
        let outcome = self.drive(frame_limit, &opened)
        if opened and not outcome.is_success() and not showing_crash:
            self.shown_failure = show_failure(outcome, frame_limit)
        return outcome

    ## Whether the last `run` ended by a failure it showed in a window.
    pub func failure_shown() -> bool:
        return self.shown_failure

    ## `run`'s loop; `opened` is set once the window is open.
    func drive(frame_limit: i64, opened: bool*) -> interop.Outcome[unit]:
        # A windowed program has nowhere to print a trap: report crashes under the
        # program's own name unless it chose one, and, in a run that is not a test's
        # bounded one nor run by a tool (LUCE_CRASH_WINDOW=0), show the report in a
        # window from a fresh process.
        if not core.crash_reports_enabled():
            crash.enable() catch failure:
                _ = failure
        if frame_limit == 0 and crash_window_wanted():
            crash.relaunch_on_crash() catch failure:
                _ = failure
        self.session_host = window.Window.open(window.Options(title = self.title_text.value, width = (u32)self.width, height = (u32)self.height, fullscreen = self.fullscreen)) catch failure:
            return result.failure[unit](failure.code, failure.message)
        defer self.session_host.destroy()
        *opened = true
        var device = gpu.Device.open() catch failure:
            return result.failure[unit](failure.code, failure.message)
        defer device.destroy()
        var surface = gpu.Surface.open(device, self.session_host, self.blending) catch failure:
            return result.failure[unit](failure.code, failure.message)
        defer surface.destroy()
        self.session_host.show() catch failure:
            return result.failure[unit](failure.code, failure.message)
        self.running = true
        defer self.stop()
        # Repaint from inside the OS live-resize loop so the window tracks the drag
        # instead of stretching its last frame. The bridge lives on this stack for
        # the window's whole lifetime, so its pointers stay valid for the callback.
        var bridge = ResizeBridge(application = &self, surface = &surface)
        self.session_host.set_redraw(resize_redraw, (void*)&bridge) catch failure:
            return result.failure[unit](failure.code, failure.message)
        var previous = time.now()
        var count: i64 = 0
        var blocking = false
        while self.running:
            # nothing is midway through replacing a traced field here: collect the cycles
            # that releases through native handles left waiting (`ownership.safe_point`)
            ownership.safe_point()
            # Block until an event, a timer deadline, a blinking caret, or a wake() from
            # a worker thread — so an idle window costs no CPU. The first pass renders at
            # once, and a frame_limit run never blocks so tests stay deterministic.
            if blocking:
                let woke = self.session_host.wait(self.wait_budget(frame_limit)) catch failure:
                    return result.failure[unit](failure.code, failure.message)
                if let event = woke:
                    let handled = self.handle_event(self.session_host, event)
                    if not handled.is_success():
                        return handled
                    handled.release()
                if not self.running:
                    break
            blocking = true
            let size = self.session_host.size() catch failure:
                return result.failure[unit](failure.code, failure.message)
            let arranged = self.layout(size.width, size.height)
            if not arranged.is_success():
                return arranged
            arranged.release()
            var events: usize = 0
            # Whether focus may have moved, so whether the window must learn again
            # if typing goes to a text field; a pointer move never moves it.
            var focus_may_move = true
            while events < 512 and self.running:
                if focus_may_move:
                    self.session_host.set_text_input(self.tree.wants_text_input()) catch failure:
                        return result.failure[unit](failure.code, failure.message)
                let polled = self.session_host.poll() catch failure:
                    return result.failure[unit](failure.code, failure.message)
                let event = polled else break
                focus_may_move = event.kind != input.EventKind.pointer_moved
                let handled = self.handle_event(self.session_host, event)
                if not handled.is_success():
                    return handled
                handled.release()
                events += 1
            # The cursor follows what is under the pointer once the batch is done.
            self.update_cursor(self.session_host) catch failure:
                return result.failure[unit](failure.code, failure.message)
            if not self.running:
                break
            let serviced = self.reported(self.timers.service(time.now()), none)
            if not serviced.is_success():
                return serviced
            serviced.release()
            if not self.running:
                break
            let watched = self.reported(self.watches.service(), none)
            if not watched.is_success():
                return watched
            watched.release()
            if not self.running:
                break
            let notified = self.reported(self.notifiers.service(), none)
            if not notified.is_success():
                return notified
            notified.release()
            if not self.running:
                break
            # This turn answers a wake_at that is due.
            if self.wake_deadline != 0 and self.wake_deadline <= time.now():
                self.wake_deadline = 0
            let current = time.now()
            let elapsed = (f64)(current - previous) / 1000000000.0
            previous = current
            let delivered = self.reported(self.frames.emit(elapsed), &self.frame_failure)
            if not delivered.is_success():
                return delivered
            delivered.release()
            if not self.running:
                break
            # Present only when something changed: an input event marked us dirty, a
            # widget bumped the layout epoch, or a focused caret is due to blink. An
            # idle window with no focused editor renders nothing and rests the GPU.
            # Game mode presents every serviced turn so a software renderer can run
            # at the requested fps without a layout mutation each frame.
            let epoch_now = layout.epoch()
            let moment = time.now()
            # A frame the GPU skipped (a locked screen, a sleeping display) waits out
            # its backoff before it is drawn again.
            let retrying = self.retry.waiting(moment)
            # A widget's wake-up (a blinking caret's next toggle) draws once, then rests;
            # while a skipped frame waits, the wake-up is taken and drawn with the retry.
            let caret_due = layout.take_due_wake(moment)
            if caret_due and retrying:
                self.dirty = true
            if not retrying and (self.game or self.dirty or epoch_now != self.last_epoch or caret_due):
                let frame = surface.frame() catch failure:
                    return result.failure[unit](failure.code, failure.message)
                defer frame.release()
                # The window may change size while a frame is drawn, not only at its
                # present: that frame is dropped and the next drawn at the new size.
                let target = frame.value().target() catch failure:
                    if failure.code != gpu.frame_resized:
                        return result.failure[unit](failure.code, failure.message)
                    self.dirty = true
                    continue
                defer target.release()
                # A whole window's widgets share the frame: an editor's panels pass
                # luce-gpu's default 4096 draws (wires and labels are a draw each).
                target.value().allow_draws(window_draws) catch failure:
                    return result.failure[unit](failure.code, failure.message)
                let rendered = self.render(target)
                if not rendered.is_success():
                    if rendered.code == gpu.frame_resized:
                        rendered.release()
                        self.dirty = true
                        continue
                    # A widget that could not draw (a document too big for some pass)
                    # is reported, not fatal: the app and its unsaved work go on.
                    let handler = self.error_handler else return rendered
                    let digest = Application.failure_digest(rendered)
                    if digest != self.render_failure:
                        self.render_failure = digest
                        let reported = Application.report_input_failure(rendered, handler)
                        if not reported.is_success():
                            return reported
                        reported.release()
                else:
                    self.render_failure = 0
                rendered.release()
                self.update_cursor(self.session_host) catch failure:
                    return result.failure[unit](failure.code, failure.message)
                var resized = false
                let presented = frame.value().present(self.tree.theme().background) catch failure:
                    if failure.code != gpu.frame_resized:
                        return result.failure[unit](failure.code, failure.message)
                    resized = true
                    recover gpu.PresentResult.skipped
                # A resize redraws at once at the new size; a skipped present stays
                # dirty and is retried after a backoff.
                if not resized:
                    self.retry.presented(presented, moment)
                self.dirty = presented == gpu.PresentResult.skipped
                self.last_epoch = epoch_now
                self.last_render = moment
            count += 1
            if frame_limit > 0 and count >= frame_limit:
                self.stop()
        surface.wait_idle() catch failure:
            return result.failure[unit](failure.code, failure.message)
        return result.success[unit](())

    ## A digest of a failed outcome's message; never 0.
    static func failure_digest(outcome: interop.Outcome[unit]) -> u64:
        _ = outcome.get() catch failure:
            var digest: u64 = 1469598103934665603
            for byte in failure.message.bytes:
                digest = (digest ^ (u64)byte) *% 1099511628211
            return digest if digest != 0 else 1
        return 1

    ## A callback's failure (a frame's, a timer's, a watch's) reported to the error
    ## handler, as an input's or a render's is, so the run goes on; without a handler it is
    ## returned and ends the run. With `last`, a failure repeated turn after turn is
    ## reported once: `last` holds the digest of the one reported, 0 after a success.
    func reported(outcome: interop.Outcome[unit], last: u64*?) -> interop.Outcome[unit]:
        if outcome.is_success():
            if let previous = last:
                *previous = 0
            return outcome
        let handler = self.error_handler else return outcome
        if let previous = last:
            let digest = Application.failure_digest(outcome)
            if digest == *previous:
                outcome.release()
                return result.success[unit](())
            *previous = digest
        let notified = Application.report_input_failure(outcome, handler)
        outcome.release()
        return notified

    static func report_input_failure(outcome: interop.Outcome[unit], handler: interop.Callback[str, unit]) -> interop.Outcome[unit]:
        _ = outcome.get() catch failure:
            return handler.invoke(failure.message)
        return result.success[unit](())

    ## Apply one event: request a close (honoring the close handler), re-layout on a
    ## resize, or dispatch it to the tree — routing a dispatch failure to the error
    ## handler when one is set. Every event marks the frame dirty so it is presented.
    func handle_event(host: window.Window, event: input.Event) -> interop.Outcome[unit]:
        self.dirty = true
        self.retry.interrupt()
        if event.kind == input.EventKind.close_requested:
            if let handler = self.close_handler:
                let permission = handler.invoke(())
                defer permission.release()
                let allowed = permission.get() catch failure:
                    return result.failure[unit](failure.code, failure.message)
                if allowed:
                    self.stop()
            else:
                self.stop()
            return result.success[unit](())
        if event.kind == input.EventKind.resized:
            let resized = host.size() catch failure:
                return result.failure[unit](failure.code, failure.message)
            return self.layout(resized.width, resized.height)
        let dispatched = self.appearances.emit(event.appearance) if event.kind == input.EventKind.appearance_changed else self.dispatch_native(event)
        if dispatched.is_success():
            return dispatched
        if let handler = self.error_handler:
            # Copy the message into the handler before releasing its owner.
            let notified = Application.report_input_failure(dispatched, handler)
            dispatched.release()
            return notified
        return dispatched

    ## How long the loop may block before it must run again: nothing when a frame is
    ## already pending or a frame_limit run wants every frame, otherwise the soonest of
    ## a timer deadline, a wake_at instant, a skipped frame's retry, a blinking caret's
    ## cadence, and a one-second safety ceiling. A wake(), an OS event or a watched
    ## descriptor ends the wait early.
    func wait_budget(frame_limit: i64) -> u64:
        if frame_limit > 0:
            return 0
        let retrying = self.retry.waiting(time.now())
        if self.game:
            if self.target_fps <= 0.0 and not retrying:
                return 0
            let now = time.now()
            var budget: u64 = 0
            if self.last_render != 0 and self.target_fps > 0.0:
                let interval = (u64)(1000000000.0 / self.target_fps)
                let next = self.last_render + interval
                if next > now:
                    budget = next - now
            if let deadline = self.next_deadline():
                if deadline <= now:
                    return 0
                let delta = deadline - now
                if budget == 0 or delta < budget:
                    budget = delta
            return budget
        # A widget that changed the layout while drawing (an accordion easing a
        # section open) wants the next frame at once, not after the next event.
        if not retrying and (self.dirty or self.tree.is_animating() or layout.epoch() != self.last_epoch):
            return 0
        # A notify that came during the turn: its wake may have been taken already.
        if self.notifiers.waiting():
            return 0
        let now = time.now()
        var budget: u64 = 1000000000
        if let deadline = self.next_deadline():
            if deadline <= now:
                return 0
            let delta = deadline - now
            if delta < budget:
                budget = delta
        # A widget's wake-up waits with a skipped frame: the retry draws it.
        let wake = 0 if retrying else layout.wake_deadline()
        if wake != 0:
            if wake <= now:
                return 0
            if wake - now < budget:
                budget = wake - now
        return budget

    ## The soonest of the timers' deadline, the wake_at instant and a skipped frame's
    ## retry.
    func next_deadline() -> u64?:
        var soonest = self.timers.next_deadline()
        var retry_at: u64 = 0
        if let instant = self.retry.deadline():
            retry_at = instant
        for candidate in [self.wake_deadline, retry_at]:
            if candidate != 0:
                if let current = soonest:
                    if candidate < current:
                        soonest = candidate
                else:
                    soonest = candidate
        return soonest

    ## End the run loop after the current iteration; the application stays usable.
    pub func stop():
        self.running = false

    ## Closing during a callback requests loop termination. Owned fields remain
    ## alive under the active invocation guard until that callback and run return.
    pub func close():
        self.stop()
        self.closed = true
        # Remove before releasing: a hook's callback may hold the last edge to an object.
        let count = self.crash_hook_count
        self.crash_hook_count = 0
        for index in 0..<count:
            self.crash_hooks[index].value().remove()
            self.crash_hooks[index].release()

    func dispose():
        self.close()
        if let handler = self.close_handler:
            self.close_handler = none
            handler.release()
        if let handler = self.error_handler:
            self.error_handler = none
            handler.release()
        self.commands.close()
        self.timers.close()
        self.watches.close()
        self.notifiers.close()
        self.frames.close()
        self.frames.release()
        self.appearances.close()
        self.appearances.release()
        self.tree.close()
        self.title_text.release()
        free(self.crash_hooks) in memory.heap

    func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        for index in 0..<self.crash_hook_count:
            self.crash_hooks[index].trace(visit, context)
        if let handler = self.close_handler:
            handler.trace(visit, context)
        if let handler = self.error_handler:
            handler.trace(visit, context)
        self.commands.trace(visit, context)
        self.timers.trace(visit, context)
        self.watches.trace(visit, context)
        self.notifiers.trace(visit, context)
        self.frames.trace(visit, context)
        self.appearances.trace(visit, context)
        self.tree.trace(visit, context)
        self.title_text.trace(visit, context)

func check_fps(fps: f64) -> !:
    if not math.is_finite(fps) or fps < 0.0 or fps > 1000.0:
        error(result.invalid, "game fps must be finite and in 0..1000")

## The draws a window's frame may record: luce-gpu's ceiling. Storage grows
## only with what is drawn.
let window_draws: usize = 65536

pub let application_type: interop.Type[Application] = interop.Type[Application]("UI application", Application.dispose, Application.trace, main_thread = true)

## Carries the running application and its surface to the window's live-resize
## callback. It lives on run's stack, which stays alive for the callback's lifetime.
struct ResizeBridge:
    var application: Application*
    var surface: gpu.Surface*

func resize_redraw(context: void*):
    let bridge = (ResizeBridge*)context
    let outcome = bridge.application.draw_resized(bridge.surface)
    outcome.release()