# Uhdk A small desktop platform library written in Zig 0.17.1 with a C99 ABI. It provides windows, input and IME, clipboard, file dialogs, incoming file drops, menus, tray icons, async file operations, file watching, and OpenGL context creation. The macOS backend uses AppKit, OpenGL, and FSEvents through a private Objective-C bridge. File dialog filters accept suffixes without a leading dot, including compound suffixes such as `level.json`. Internal naming: `z_` means **Zig bridge**, identifying private bridge functions, types, and helpers connecting the Zig runtime with native platform code. Public C API symbols use `uhdk_`. macOS builds require Xcode Command Line Tools. The Windows Win32/WGL backend targets `x86_64-windows-gnu`. Demo applications have been tested under Wine and on a Windows 11 host with no issues observed so far. The backend requires Windows 10 version 1703 or later and an OpenGL 3.3-capable driver for GL sessions. The Linux Wayland preview implements windows, EGL/OpenGL, keyboard/pointer and text input, clipboard/file drops, portal dialogs/preferences, activation, icons, file watches, and Plasma app/window menu export, initially tested on KDE Plasma. Linux context menus use a small software renderer and a bundled 16px Roboto bitmap; X11 remains unsupported. Desktop dependencies are limited to vendored ABI headers/protocol bindings and runtime-loaded system libraries. Normal builds need Zig alone; the optional `shell.nix` supplies maintainer tools and NixOS runtime library paths. See [Linux support and limitations](src/linux/README.md). Window decoration and resizing are selected through `uhdk_window_style` when a window is created and can be changed later with `uhdk_window_set_style`. Set `decorated` to false for application-drawn chrome; on Wayland this requests client-side decoration instead of the compositor's usual title bar and border. The primary application path is `uhdk_open` followed by one `uhdk_next_frame`/`uhdk_end_frame` loop. It creates a visible window and current OpenGL context before returning, reports events and framebuffer metrics together, and handles presentation at the frame boundary. All services accept that same session handle. Additional native windows can be created synchronously between iterations for external rendering; they do not have independent UHDK GL contexts. On macOS, UHDK disables AppKit's conversion of command-line arguments into `UHDK_EVENT_OPEN_FILES` by default. Applications handle their own arguments; document-open requests from Finder and the Dock still arrive as events. ## Tray icons Create a session-owned `uhdk_tray` with `uhdk_tray_create`, replace its complete description with `uhdk_tray_update`, and remove it with `uhdk_tray_destroy`. Create/update belong between frames. The descriptor copies UTF-8 text and a 1–512 pixel RGBA8 image, and retains its optional `uhdk_menu`. Keep its nonempty `id` stable across updates and unique within the session. Set `hidden` to remove it temporarily, `menu_on_primary` to open its menu on primary activation, or `template_image` for a macOS template icon. Other backends ignore that hint. `UHDK_EVENT_TRAY_ACTIVATE` carries the tray and primary/secondary action. Menu commands carry their origin in `uhdk_menu_event.tray`, with a NULL window; ordinary window menu commands have a NULL tray. Tray menus support ordinary commands, submenus, separators, enabled/checked flags and the QUIT role. Other window-dependent roles are rejected. Menu shortcuts are not global shortcuts. Query `uhdk_tray_get_state` and handle `UHDK_EVENT_TRAY_STATE`. `available` means registered with the host, not guaranteed onscreen: the desktop may hide icons. `UHDK_CAP_TRAY` reports mechanism/host availability. On Linux, discovery is asynchronous; creation can succeed before a StatusNotifier host exists, then register automatically when one appears. Keep processing frames while windows are hidden. The session still opens with a visible primary window, which the application may hide once it has an available tray item. Backends use AppKit `NSStatusItem`, Win32 `Shell_NotifyIconW` (including Explorer restart recovery), and Linux StatusNotifierItem plus D-BusMenu. Linux needs a session bus and a compatible tray host; no GTK or Qt dependency is added. Session close removes all items. Destroy invalidates the handle immediately and suppresses queued tray events; native removal occurs at the next frame or close. ## Experimental desktop input and window observations macOS uses AppKit editing selectors. Windows and Wayland share Ctrl-based defaults for word deletion, paragraph/page movement, clipboard actions, undo/redo, Backtab, Shift+Enter and cancellation. Shift extends selection only for movement. Alt/Super combinations are not interpreted as Ctrl editing shortcuts. Clipboard shortcuts work without a menu, with menu actions taking precedence when available. Applications own execution, Unicode boundaries, layout and undo history. Commands without customary shortcuts (such as line-boundary deletion on Windows) have no invented default binding. Publish an acknowledged text snapshot after consuming text/edit events. On macOS, further native text input waits after semantic edits, including ignored commands; acknowledge asynchronous paste after applying its result. Disabling text input or losing window focus drops that deferred input. Windows IMM emits ordered text without surrounding-text replacement ranges. Wayland invalidates old IME snapshot serials after document/selection-changing commands; new surrounding text is published after acknowledgment. It does not apply AppKit's input-queue mechanism. `WINDOW_METRICS` is the resize and state-change hook. Geometry state is independent of minimization. Observation bits indicate which facts are known: | Backend | Known observations | | --- | --- | | macOS | Minimized, live resize, occluded | | Windows | Minimized, interactive size/move loop | | Wayland | Resizing; rendering suspension with xdg-shell v6+ | A clear observation bit means unknown, not false. Wayland cannot report minimized state or directly undo minimization, and suspension is not proof of occlusion. Explicitly unavailable Wayland window-manager actions complete with `UNSUPPORTED`. Render hints do not replace presentation pacing or event processing. UHDK is experimental and does not guarantee API or ABI compatibility between revisions. Rebuild consumers when updating the library and headers. Demo testing does not qualify every IME, window manager, display configuration or driver. ## Build ```sh zig build # zig-out/lib/libuhdk.a and zig-out/include/ zig build -Dshared=true # platform shared library and headers zig build test # run core library tests on the native target zig build -Dtarget=x86_64-windows-gnu zig build -Dtarget=x86_64-windows-gnu -Dshared=true zig build check -Dtarget=x86_64-windows-gnu # compile only ``` ## Use from Zig To use a local checkout at `vendor/uhdk`, add it to `build.zig.zon`: ```zig .dependencies = .{ .uhdk = .{ .path = "vendor/uhdk" }, }, ``` In your build, pass the application's target and optimization options: ```zig const uhdk = b.dependency("uhdk", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("uhdk", uhdk.module("uhdk")); ``` `@import("uhdk")` provides translated public C declarations, including the bundled OpenGL and experimental native-handle declarations, and links the library and required system frameworks. The `uhdk` artifact is also available through `uhdk.artifact("uhdk")` for C consumers or custom bindings. Set `.shared = true` to build a dynamic library; applications must arrange its runtime location/rpath. ## C interface - Guide and API reference: the full repository generates them from `uhdk.h` with `zig build docs-uhdk` (into `build/docs/uhdk/`). - [uhdk.h](include/uhdk.h): desktop API, lifecycle, ownership, and threading contracts. - [OPENGL-SOURCES.md](include/OPENGL-SOURCES.md): GLAD generation recipe and Khronos header provenance and licenses. All UHDK declarations live in `uhdk.h`. Before its first inclusion, define `UHDK_ENABLE_OPENGL` to include the bundled GLAD 2 OpenGL 3.3 core declarations and per-context loader table, and/or `UHDK_ENABLE_NATIVE` for the experimental native-window handle API: ```c #define UHDK_ENABLE_OPENGL #define UHDK_ENABLE_NATIVE #include "uhdk.h" ``` Presence enables each flag; leave it undefined to disable it. These flags select header declarations, not library backends. The session API is always declared. The supplied Zig module enables both sections. The vendored GL headers remain unmodified dependencies rather than being pasted into `uhdk.h`. The public interface uses pointer-and-length text, `char` booleans, and `float` coordinates. The native bridge is private; consumers do not need Objective-C. UHDK loads and owns the GL function table returned by `uhdk_get_gl` and `frame.gl`. Its members are named `Clear`, `DrawArrays`, etc. Use `uhdk_get_gl_proc(session, name, &proc)` for extension procedures and `uhdk_set_vsync(session, enabled)` to change presentation policy. No application loader implementation or current-context management is needed. On Windows, the static artifact is `zig-out/lib/uhdk.lib`; shared builds install `zig-out/bin/uhdk.dll` and its import library under `zig-out/lib/`. Keep the DLL beside your executable. The DLL links no C runtime and imports only Windows system DLLs; the static library expects the consumer's MinGW-w64 C runtime. The first lifecycle caller establishes the Windows platform thread; its message loop also owns COM dialogs, menus, clipboard and watch completion. Input uses IMM32 composition; TSF reconversion and pen/touch are not implemented. Native UTF-16 path bytes are kept separately from the WTF-8 paths passed to Zig I/O. If a native path cannot be exported losslessly as a shell URI, URI export returns `UNSUPPORTED`; native-path export still preserves it. ## Session loop `uhdk_open` is the default setup path. Pass NULL for defaults, or zero-initialize `uhdk_options`, set `struct_size`, and override the options you need. Successful setup returns a visible window, a current OpenGL 3.3-or-newer core context, and a loaded GL function table. Setup failures unwind all resources. ```c #define UHDK_ENABLE_OPENGL #include "uhdk.h" int main(void) { uhdk_options options = {0}; options.struct_size = sizeof(options); options.title = (uhdk_text){"Hello UHDK", 10}; options.content_size = (uhdk_size){800, 600}; uhdk_session *session = 0; if (uhdk_open(&options, &session) != UHDK_STATUS_OK) return 1; /* Create shaders, textures, etc. using uhdk_get_gl(session) here. */ uhdk_frame frame; uhdk_status status = UHDK_STATUS_OK; while (uhdk_next_frame(session, &frame)) { for (uint64_t i = 0; i < frame.events.len; ++i) { uint32_t type = frame.events.ptr[i].type; if (type == UHDK_EVENT_WINDOW_CLOSE_REQUESTED || type == UHDK_EVENT_QUIT_REQUESTED) uhdk_quit(session); } if (frame.drawable) { frame.gl->Viewport(0, 0, frame.metrics.framebuffer_width, frame.metrics.framebuffer_height); frame.gl->ClearColor(0.1f, 0.15f, 0.2f, 1.0f); frame.gl->Clear(GL_COLOR_BUFFER_BIT); } status = uhdk_end_frame(session); if (status != UHDK_STATUS_OK) break; } if (status == UHDK_STATUS_OK) status = uhdk_get_status(session); /* Delete application GL resources here, while the context is current. */ uhdk_close(session); return status == UHDK_STATUS_OK ? 0 : 1; } ``` All session/application/GL work stays on OS main. `next_frame` releases native GL locks, pumps native work and worker completions, then restores the current context. `end_frame` presents drawable iterations. Every successful `next_frame` needs an `end_frame`, including event-only iterations. `close` can discard an unfinished iteration without presenting it. The primary window belongs to the session and must not be destroyed separately. Continuous mode is the default and requests vsync. `UHDK_RENDER_ON_DEMAND` waits for events or wake deadlines after the first iteration. Repaint the complete framebuffer whenever `drawable` is true. Hidden/minimized windows still receive events, and `uhdk_wake` or a wake deadline can schedule application work. The first iteration never waits. Session GL calls are valid before, during and after iterations until close; drawing to the window is conditional on `drawable`. A fatal native/driver error may prevent further GL work, including cleanup. On macOS, vsync waits for a per-window CoreVideo display link before presenting, with the native OpenGL swap interval disabled. The link follows the window's display. Present waits only while no refresh has passed since the previous present, so a frame the driver already held until a refresh is not delayed by another. Each wait is bounded to 100 ms so a sleeping display cannot indefinitely block the frame loop; disabling vsync bypasses the wait. Accept close/quit requests with `uhdk_quit`. Keep iterating to drain request completions and `STOPPED`; then `next_frame` returns false and `get_status` returns OK. Failures also end the loop, with a non-OK status. An early `close` abandons undelivered results and drains internal teardown. File workers stay independent, although their results reach the application at frame boundaries. Long main-thread updates delay native event handling. ## Native-only sessions and additional windows Set `uhdk_options.no_opengl` for an external renderer or native-only integration. The event/frame lifecycle stays the same; `get_gl` and `frame.gl` return NULL, `end_frame` does not present, and procedure lookup/vsync return UNSUPPORTED. `uhdk_window_create` synchronously creates an additional hidden native window. Call it between iterations; a call during a frame returns BUSY. Creation may pump native work but preserves the current borrowed batch. No additional GL context is created. Use native handles to attach an external renderer. The session's primary window belongs to `close`; `uhdk_window_destroy` rejects attempts to destroy it. File reads/writes/info and watch preparation execute serially on an internal I/O worker. Up to 64 such requests can be outstanding; further submissions return BUSY without accepting an ID. Cancellation is best effort; final close may wait for an active filesystem call. Native dispatch delivers results at frame boundaries. ## Borrowed event payloads Events and request results carry `const void *data` plus `data_size` instead of public unions. Check the event type (or successful request kind), then read the corresponding named payload struct listed in `uhdk.h`. Check `data_size` before reading fields; unknown types can be ignored. Payload-free events and unsuccessful request results have NULL data and zero size. Failure diagnostics remain available in the request envelope. ```c if (event->type == UHDK_EVENT_KEY && event->data_size >= sizeof(uhdk_key_event)) { const uhdk_key_event *key = (const uhdk_key_event *)event->data; /* Read key->logical_key, key->pressed, etc. here. */ } ``` One library-owned scratch arena holds the returned batch, its payload structs, and nested spans. The next valid next_frame call resets it, even if it returns an empty batch or an error. Invalid arguments and wrong-thread calls do not reset it. Session close also invalidates everything. Rendering does not advance this lifetime. Copy data you need to keep; copying an envelope alone copies only its pointers. Retain file/menu references when needed beyond an iteration, but even retained handles cannot outlive the app. Event envelopes have a fixed array stride within each returned batch. The scratch arena is maintained as UHDK-owned code in [src/arenas.zig](src/arenas.zig), including its supporting storage and tests. It originated in Ribtech p2; the MIT license and attribution are retained in that file. ## Optional profiling `uhdk.h` provides scope, frame, thread-name and named allocation/ free macros. They compile away without evaluating arguments unless the consumer defines `UHDK_PROFILE_BACKEND` to a quoted adapter header before including UHDK. An adapter implements the macros documented in that header. Names require static lifetime; pair zones on the same thread in nesting order and report frees before releasing memory. Do not put allocation expressions inside profiling macros. Internal CPU and memory instrumentation is disabled by default. A static consumer can pass `.tracy = true` to `b.dependency("uhdk", ...)` (or `-Dtracy=true` when building the archive) and link its own Tracy 0.14.1 client configured with `TRACY_ENABLE` and `TRACY_ON_DEMAND`. UHDK never fetches or links Tracy itself. Shared instrumentation is unsupported. Run unit tests with the default configuration; enabled instrumentation requires the consumer's linked client. The `UHDK` memory pool measures requested Zig backing allocations, including objects and arena blocks. Win32 explicit calloc/free blocks use a separate `UHDK native` pool. OS/framework allocations and GPU memory are excluded. On-demand capture omits allocations made before connection, so it is not a full live-heap snapshot. Failed allocations emit nothing; in-place resizes emit free + alloc. Moving reallocations use alloc/copy/free to preserve event ordering. Disabled builds use the original allocator directly. ### Caller-chosen async request tags Every async operation takes a nonzero `uhdk_request_tag` chosen by the caller. Completions return it as `uhdk_request_result.tag`; cancellation takes the same tag. Tags are unique among requests whose completion has not yet been delivered, including completed requests queued for the next frame. Repeated tags return `BUSY`. Reuse a tag while handling its completion, or choose distinct tags for concurrent operations. Failure to start reserves nothing and produces no event. ```c enum { ReadModel = 1, ReadTexture = 2 }; uhdk_status status = uhdk_file_read_all_async(file, 128 * 1024 * 1024, ReadModel); /* Later, in REQUEST_DONE handling: switch (result->tag) { ... } */ ``` Components sharing a session must coordinate tags; pass a dedicated tag to each component that starts asynchronous work. ### Function-key policy Use `uhdk_window_set_function_key_policy(window, UHDK_FUNCTION_KEYS_APPLICATION)` to suppress Windows native defaults for unmodified F1–F24, including F10 menu activation. Key events still reach the application. `UHDK_FUNCTION_KEYS_NATIVE` restores the default behavior. Set the policy before the relevant press; it is applied at the next frame boundary, and a held key retains the handling selected at its initial press through repeats and release. Shift/Control/Alt/Super combinations, including Alt+F4, keep native handling. Registered UHDK menu shortcuts retain priority over raw key events. This policy is accepted on macOS and Wayland without an effect; it does not override global shortcuts, IME interception, or keyboard media-key settings. ### Cursor confinement Windows and Wayland compositors with pointer-constraints-v1 support keeping the cursor inside the window's content area. macOS currently reports this capability as unavailable. Request confinement while the window is visible and focused and the pointer is inside: ```c if (uhdk_has_capability(session, UHDK_CAP_POINTER_CONFINEMENT)) { uhdk_status status = uhdk_window_set_pointer_mode(window, UHDK_POINTER_CONFINED); /* Handle submission failure. POINTER_MODE_CHANGED confirms activation. */ (void)status; } ``` Set `UHDK_POINTER_NORMAL` to release active confinement or cancel a pending request. Confinement follows the content area as the window moves/resizes and preserves cursor shape and absolute pointer motion. Wayland activation depends on compositor policy and may never occur. Focus loss, hiding/minimizing, or native cancellation restores normal mode without automatic reactivation. Destruction and session close also release it. Capture and confinement are mutually exclusive. ### Errors and input lifecycles `uhdk_status_message(status)` returns a static UTF-8 text span, usable without a session and from any thread. It does not allocate or maintain a last-error slot. Failed async results always contain a nonempty `diagnostic`: native detail when available, otherwise the status message. Use status codes for decisions and text for display; successful requests may have an empty diagnostic. `uhdk_event.cycle_id` associates events within a pointer drag/capture/confinement, phased scroll gesture, or IME preedit composition. These library-generated IDs are unique per session and separate from caller request tags and native edit `input_id` values. Hover, discrete wheel events, ordinary typing and unrelated events use zero. Track the ID from the first relevant event; ignore updates from other cycles. `UHDK_EVENT_CYCLE_END` carries the ID, window, and a `uhdk_cycle_end_event` payload. Its `reason` distinguishes completion, cancellation, capture/confinement release or loss, focus loss, hiding, replacement and shutdown. It reports the first observed ending cause and retires the interaction, without deciding whether the application should commit or undo its work. Destruction invalidates cycles immediately; fatal errors or early close may prevent delivery of queued endings. The C API exposes spans and plain event payloads. `UHDK_EVENT_PAYLOAD` checks an event's type and payload size before returning a typed pointer; languages that cannot use C macros perform those checks explicitly.