From 2e2a81061541c36dea9475c11e07929937b79e5e Mon Sep 17 00:00:00 2001 From: Peterino2 Date: Sat, 19 Sep 2026 13:43:11 -0700 Subject: [PATCH] removed dead loaders and bringing back in glad --- README.md | 95 ++++------- include/uhdk.h | 318 ++++++++++--------------------------- src/Application.zig | 24 +-- src/EventPayload.zig | 1 - src/api/app.zig | 165 ++++--------------- src/api/desktop.zig | 14 +- src/api/files.zig | 6 +- src/api/graphics.zig | 77 ++------- src/api/menus.zig | 6 +- src/api/session.zig | 90 ++++++----- src/api/windows.zig | 58 +++++-- src/callbacks.zig | 14 +- src/core_tests.zig | 66 +++----- src/gl_loader.c | 8 +- src/linux/Egl.zig | 14 +- src/linux/README.md | 18 +-- src/linux/native.zig | 29 +--- src/linux/tests/menus.c | 26 +-- src/linux/tests/native.c | 287 +++++++++++---------------------- src/linux/tests/popups.c | 12 +- src/linux/tests/services.c | 89 +++++------ src/macos/native.m | 46 +----- src/native.h | 41 +++-- src/root.zig | 1 - src/runtime.zig | 72 ++------- src/test_frame.h | 16 ++ src/windows/native.c | 32 +--- 27 files changed, 536 insertions(+), 1089 deletions(-) create mode 100644 src/test_frame.h diff --git a/README.md b/README.md index 65b1f50..b836134 100644 --- a/README.md +++ b/README.md @@ -30,10 +30,9 @@ 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. The lower-level window/context -API remains available for additional windows and custom thread layouts. Its create -calls return stable handles immediately, and native creation failures arrive as -`UHDK_EVENT_RESOURCE_FAILED`. +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. ## Experimental desktop input and window observations @@ -128,20 +127,17 @@ native-window handle API: ``` Presence enables each flag; leave it undefined to disable it. These flags select -header declarations, not library backends. UHDK's own context-management API is -always declared. The supplied Zig module enables both sections. The vendored GL +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. -The public header includes the GLAD declarations, while the application owns its -implementation. In exactly one translation unit, define -`UHDK_GLAD_GL_IMPLEMENTATION` before including `uhdk.h`. With a current context -inside `uhdk_gl_context_begin_frame` / `uhdk_gl_context_end_frame`, call -`gladLoadGLContextUserPtr` with a callback that resolves names using -`uhdk_gl_context_get_proc`. Keep a `GladGLContext` per native context; its members -are named `Clear`, `DrawArrays`, etc. Check `VERSION_3_3` after loading. +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 @@ -172,7 +168,6 @@ int main(void) { uhdk_session *session = 0; if (uhdk_open(&options, &session) != UHDK_STATUS_OK) return 1; - uhdk_app *app = uhdk_get_app(session); /* Create shaders, textures, etc. using uhdk_get_gl(session) here. */ uhdk_frame frame; uhdk_status status = UHDK_STATUS_OK; @@ -181,7 +176,7 @@ int main(void) { uint32_t type = frame.events.ptr[i].type; if (type == UHDK_EVENT_WINDOW_CLOSE_REQUESTED || type == UHDK_EVENT_QUIT_REQUESTED) - uhdk_app_quit(app); + uhdk_quit(session); } if (frame.drawable) { frame.gl->Viewport(0, 0, frame.metrics.framebuffer_width, @@ -205,67 +200,39 @@ All session/application/GL work stays on OS main. `next_frame` releases native G 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. Do not poll or manage GL brackets manually for -a session, and do not destroy its borrowed app/window/context handles separately. +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_app_wake` or a wake deadline can schedule application work. +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. -Accept close/quit requests with `uhdk_app_quit`. Keep iterating to drain request +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. -## Low-level application lifecycle +## Native-only sessions and additional windows -Set `uhdk_app_desc.use_application_thread` before `uhdk_app_create`: +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. -| Flag | Application loop | Native events | -| --- | --- | --- | -| `0` (default) | OS main thread | Pumped by `uhdk_app_poll_events` | -| `1` | One separate application thread | OS main runs `uhdk_app_run_native` | +`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. -With `0`, main calls `create`, runs its poll/update/render loop, then calls -`destroy`. With `1`, main calls `create`, creates a thread, and calls `run_native`. -The application thread calls `attach`, runs its loop and cleans up, then calls -`detach`. Main joins it after `run_native` returns and destroys the app. If thread -creation fails, destroy the app without entering `run_native`. - -Create initializes native services and I/O. Failure unwinds initialization and -sets the output handle to null; no destroy is needed. Destroy initiates shutdown, -drains teardown and joins internal I/O workers before releasing storage. It must -run on OS main, outside GL brackets, after any application thread is detached and -joined. Attachment is once per app, with no thread migration. - -The convenience `uhdk_app_run(app, entry, user)` invokes entry with application -ownership established. It honors the flag, creating and joining the application -thread when enabled. Its callback owns its loop and must not attach/detach/destroy. -The caller must destroy the app after run returns, including on run failure. - -Low-level applications decide when to poll, update, and render. Use `UHDK_PROFILE_BEGIN`/`UHDK_PROFILE_END` for application phases. Frame stats -report rendering CPU time and presentation cadence, not combined update time. -Poll outside GL frame brackets. Zero timeout does not intentionally wait; native -modal handling may exceed finite wait budgets. When app code runs on main, long -updates also delay native collection. - -File reads/writes/info and filesystem watch preparation run serially on an internal -I/O worker regardless of the flag. Up to 64 such requests may be outstanding; -additional submissions return `BUSY` without a request ID. Cancellation is best -effort and never frees storage underneath an active OS call. Final shutdown may -wait for that call, while normal native dispatch and polling remain independent. - -Accept shutdown with `uhdk_app_quit`; drain terminal request results until -`STOPPED`, clean up GL resources inside frame brackets, then detach/destroy. Native -services remain alive for this cleanup. Early detach/destroy abandons undelivered -results but retires internal requests before destruction. A fatal native-loop -failure is persistent and wakes waiting polls; detach/join/destroy still apply. +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 @@ -285,15 +252,15 @@ if (event->type == UHDK_EVENT_KEY && ``` One library-owned scratch arena holds the returned batch, its payload structs, -and nested spans. The next valid application-thread poll resets it, even if that -poll is empty or returns an error. Invalid arguments and wrong-thread calls do -not reset it. App destruction also invalidates everything. Rendering does not +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 a poll, +copies only its pointers. Retain file/menu references when needed beyond an iteration, but even retained handles cannot outlive the app. UHDK is pre-release: API and ABI compatibility with earlier revisions is not -guaranteed. Low-level app descriptors set `abi_version` to `UHDK_ABI_VERSION`; session options do not require it. Event envelopes have +guaranteed. Session options require only struct_size and the desired options. Event envelopes have a fixed array stride within each returned batch. The scratch arena is maintained as UHDK-owned code in diff --git a/include/uhdk.h b/include/uhdk.h index 9663625..8246a95 100644 --- a/include/uhdk.h +++ b/include/uhdk.h @@ -1,20 +1,6 @@ #ifndef UHDK_H_INCLUDED #define UHDK_H_INCLUDED -/* - * uhdk provides a bundled glad implementation for loading opengl - * - * Define UHDK_GLAD_GL_IMPLEMENTATION to bring it into your compile unit. - * This should only be defined in a single compile unit per program - * - * you can use this as a convenience or load your own opengl integration - * */ -#ifdef UHDK_GLAD_GL_IMPLEMENTATION -#define GLAD_GL_IMPLEMENTATION -#include "glad/gl.h" -#undef GLAD_GL_IMPLEMENTATION -#endif - /* * Uhdk desktop platform API — v0.1, macOS, Windows and Linux backends. * @@ -24,7 +10,7 @@ * Native OS frameworks may themselves depend on system runtimes. * * Header configuration (define before the first include): - * - UHDK_ENABLE_OPENGL: include bundled GLAD types and per-context loader API. + * - UHDK_ENABLE_OPENGL: include bundled GLAD types and session GL function-table declarations. * - UHDK_ENABLE_NATIVE: declare the experimental borrowed native-handle API. * - UHDK_PROFILE_BACKEND: quoted consumer instrumentation adapter header. * Presence enables each feature flag; leave it undefined to disable it. @@ -48,16 +34,12 @@ * - NULL is allowed for a span's pointer only when its length is zero. * - Input spans/descriptors are copied before return unless documented otherwise. * - No allocator ownership crosses the ABI. Release objects through Uhdk. - * - Event batches and spans are borrowed until the next valid poll on the - * application thread, or app destruction (whichever comes first). Copy spans - * or retain files/menus to keep them. Every such poll resets storage, including empty/error polls. - * Rendering does not reset storage. Each poll returns an immutable batch. - * - create/run/run_native/destroy belong to OS main. With - * use_application_thread=0, application calls also belong to OS main and poll - * pumps native work. With 1, attach/detach bind a separate application thread. - * Other calls belong to the application thread except thread-safe app_wake. - * - File reads/writes/info and watch preparation use an internal I/O worker. - * Completion is delivered by polling; final shutdown may wait for active I/O. + * - All calls belong to OS main except thread-safe uhdk_wake. Native dispatch + * runs at next_frame and synchronous creation boundaries. Filesystem work runs + * on an internal I/O worker; final shutdown may wait for active I/O. + * - Events and nested spans are borrowed until the next valid next_frame call or + * close. Copy spans or retain file/menu references to keep them. End_frame and + * synchronous window creation do not invalidate the current batch. * - Descriptors start with struct_size; zero-initialize them, set struct_size to * sizeof(the descriptor), then fill fields. Reserved fields must remain zero. * Unknown trailing fields are ignored; smaller descriptors are rejected. @@ -122,7 +104,6 @@ extern "C" { #endif - typedef char uhdk_bool; /* Values are UHDK_FALSE (0) or UHDK_TRUE (1). */ enum { UHDK_FALSE = 0, @@ -145,17 +126,15 @@ enum { UHDK_STATUS_BUFFER_TOO_SMALL = 11 }; -typedef struct uhdk_session uhdk_session; /* Opaque unless UHDK_ENABLE_OPENGL is defined; then this is the bundled * GladGLContext function table. Owned by the session and valid until close. */ typedef struct GladGLContext uhdk_gl_functions; -typedef struct uhdk_app uhdk_app; +typedef struct uhdk_session uhdk_session; typedef struct uhdk_window uhdk_window; -typedef struct uhdk_gl_context uhdk_gl_context; typedef struct uhdk_file uhdk_file; typedef struct uhdk_watch uhdk_watch; typedef struct uhdk_menu uhdk_menu; -typedef uint64_t uhdk_request_id; /* 0 is invalid; IDs never reused per app. */ +typedef uint64_t uhdk_request_id; /* 0 is invalid; IDs never reused per session. */ typedef struct uhdk_text { const char *ptr; @@ -228,110 +207,56 @@ enum { /* Every accepted async request returns a nonzero ID and exactly one terminal * REQUEST_DONE during normal draining. Failure to accept produces no event. * Cancellation is best effort; an operation already committed may succeed. - * Return from app_main early abandons undelivered results and initiates shutdown. + * Closing a session early abandons undelivered results and drains internal work. */ typedef struct uhdk_event uhdk_event; typedef struct uhdk_event_list { const uhdk_event *ptr; uint64_t len; } uhdk_event_list; -#define UHDK_WAIT_FOREVER UINT64_MAX -typedef void(UHDK_CALL *uhdk_app_main_fn)(uhdk_app *app, void *user); -typedef struct uhdk_app_desc { - uint32_t struct_size; - uint32_t abi_version; - uhdk_text application_id; - uhdk_text display_name; - uhdk_backend preferred_backend; - uint32_t reserved; - uhdk_bool use_application_thread; /* 0: OS main; 1: separate application thread. */ -} uhdk_app_desc; - -UHDK_API uint32_t UHDK_CALL uhdk_get_abi_version(void); -/* OS main. Allocate and initialize native services and the I/O worker. - * With use_application_thread=0 also establishes main as the application thread. - * Failure unwinds initialization and sets *out=NULL; no destroy is needed. */ -UHDK_API uhdk_status UHDK_CALL uhdk_app_create(const uhdk_app_desc *desc, uhdk_app **out); -/* Requires use_application_thread=1 and successful create. Attach exactly one - * non-main thread, once. Does not wait for run_native. */ -UHDK_API uhdk_status UHDK_CALL uhdk_app_attach(uhdk_app *app); -/* OS main, use_application_thread=1. Pump until detach and command drain. - * Caller creates/joins the application thread. Native failure wakes polls. */ -UHDK_API uhdk_status UHDK_CALL uhdk_app_run_native(uhdk_app *app); -/* Attached application thread, outside GL brackets. Initiates shutdown and - * relinquishes ownership; undelivered events may be abandoned. */ -UHDK_API uhdk_status UHDK_CALL uhdk_app_detach(uhdk_app *app); -/* Convenience runner on a newly created app; invokes entry once. - * With use_application_thread=1 creates/attaches/joins the app thread and runs - * native services on main. Entry must not attach/detach/destroy the app. - * Returning ends application execution; caller must still destroy the app. - * Failure to create the application thread also leaves the app destroyable. */ -UHDK_API uhdk_status UHDK_CALL uhdk_app_run( - uhdk_app *app, - uhdk_app_main_fn main_fn, - void *user -); /* Once. */ -/* Poll outside GL brackets. With use_application_thread=0 also pumps native work. - * Zero timeout does not intentionally wait; finite waits use monotonic nanoseconds. - * Native OS dispatch/modal handling may exceed the wait budget. - * STOPPED is delivered once; later polls return UNAVAILABLE. */ -UHDK_API uhdk_status UHDK_CALL uhdk_app_poll_events( - uhdk_app *app, - uint64_t timeout_ns, - uhdk_event_list *out -); -UHDK_API void UHDK_CALL uhdk_app_quit(uhdk_app *app); /* Accept/request shutdown. */ -UHDK_API void UHDK_CALL uhdk_app_wake(uhdk_app *app); /* Thread-safe, coalesced WAKE event. */ +UHDK_API void UHDK_CALL uhdk_quit(uhdk_session *session); /* Accept/request shutdown. */ +UHDK_API void UHDK_CALL uhdk_wake(uhdk_session *session); /* Thread-safe, coalesced WAKE event. */ /* Monotonic nanoseconds since app creation, in the same clock as event.time_ns. */ -UHDK_API uint64_t UHDK_CALL uhdk_app_get_time_ns(uhdk_app *app); -/* One pending deadline per app. Replaces any previous deadline; 0 cancels it. +UHDK_API uint64_t UHDK_CALL uhdk_get_time_ns(uhdk_session *session); +/* One pending deadline per session. Replaces any previous deadline; 0 cancels it. * A past deadline queues WAKE at the next dispatch. On expiry the deadline is * cleared before delivering WAKE. Explicit wakes may coalesce with expiry but * do not cancel a future deadline. No event is delivered inline. App code maintains * multiple timers by scheduling its earliest deadline. No real-time guarantee. */ -UHDK_API uhdk_status UHDK_CALL uhdk_app_set_wake_deadline(uhdk_app *app, uint64_t deadline_ns); -/* OS main, outside GL brackets and after application cleanup. Initiates shutdown, - * drains teardown, joins internal I/O, and releases all app/child storage. - * With use_application_thread=1 first detach and join the caller-owned thread - * and return from run_native (if entered). Never joins a caller-owned thread. - * Also valid immediately after create or failed app-thread creation. NULL is safe. - * May wait for an active filesystem call. Undelivered events are abandoned. */ -UHDK_API void UHDK_CALL uhdk_app_destroy(uhdk_app *app); +UHDK_API uhdk_status UHDK_CALL uhdk_set_wake_deadline(uhdk_session *session, uint64_t deadline_ns); /* Linux: AUTO/false before successful startup; thereafter the selected backend * and implemented, available mechanisms. Capabilities do not guarantee success * for a particular operation. Other platforms retain their fixed backend. */ -UHDK_API uhdk_backend UHDK_CALL uhdk_app_get_backend(uhdk_app *app); -UHDK_API uhdk_bool UHDK_CALL uhdk_app_has_capability(uhdk_app *app, uhdk_capability capability); -UHDK_API uhdk_status UHDK_CALL uhdk_request_cancel(uhdk_app *app, uhdk_request_id request_id); +UHDK_API uhdk_backend UHDK_CALL uhdk_get_backend(uhdk_session *session); +UHDK_API uhdk_bool UHDK_CALL uhdk_has_capability(uhdk_session *session, uhdk_capability capability); +UHDK_API uhdk_status UHDK_CALL uhdk_request_cancel( + uhdk_session *session, + uhdk_request_id request_id +); -/* Rendering CPU time excludes swap_buffers, blocked waits and descheduling. - * A presented begin_frame/end_frame bracket updates render_time_ns/frame_count. +/* A presented frame updates render_time_ns/frame_count. Frame CPU time excludes + * presentation, blocked waits and descheduling. * Session render_time_ns includes application update work within the iteration. * frames_per_second uses wall time between presented end_frame calls; it is zero * before two presentations and retains its last sample while idle. event_count * counts polled events. Use profiling markers for application-defined work. */ -typedef struct uhdk_app_stats { +typedef struct uhdk_stats { uint32_t struct_size; uint32_t reserved; uint64_t frame_count; uint64_t event_count; uint64_t render_time_ns; float frames_per_second; -} uhdk_app_stats; +} uhdk_stats; -UHDK_API uhdk_status UHDK_CALL uhdk_app_get_stats(uhdk_app *app, uhdk_app_stats *out); +UHDK_API uhdk_status UHDK_CALL uhdk_get_stats(uhdk_session *session, uhdk_stats *out); /* Logical coordinates: top-left origin, x right, y down. Window geometry uses * content-area units. Framebuffer dimensions are pixels; use reported sizes, * not a rounded logical-size * scale calculation. Global positions are not exposed. */ -typedef uint32_t uhdk_window_flags; -enum { - UHDK_WINDOW_OPENGL = 1u << 3 /* Prepare a drawable for uhdk_gl_context_create. */ -}; - /* Native decorations are the title bar, border, and standard window controls. * Disable them when the application paints and operates its own window chrome. */ typedef struct uhdk_window_style { @@ -351,7 +276,7 @@ enum { typedef struct uhdk_window_desc { uint32_t struct_size; - uhdk_window_flags flags; + uint32_t reserved; uhdk_window_style style; uhdk_text title; uhdk_size content_size; @@ -396,11 +321,10 @@ typedef struct uhdk_window_metrics { uhdk_bool suspended; } uhdk_window_metrics; -/* Primary application API. All session calls belong to OS main. Native events +/* Primary application API. All calls except wake belong to OS main. Native events * are pumped by next_frame; filesystem work runs independently on I/O workers. - * The session owns its app, first window and GL context. Borrowed handles must - * not be destroyed separately or used with app_run/poll or manual GL brackets. - * Use a low-level application for custom threading or multiple GL contexts. + * The session owns its primary window and optional GL context. The primary + * window cannot be destroyed separately; close releases all session resources. */ typedef uint32_t uhdk_render_mode; enum { @@ -421,6 +345,7 @@ typedef struct uhdk_options { uhdk_bool fixed_size; uhdk_bool disable_vsync; /* Zero requests vsync; unsupported control is tolerated. */ uhdk_bool request_focus; + uhdk_bool no_opengl; /* Native/external-renderer session; get_gl/frame.gl are NULL. */ uint64_t startup_timeout_ns; /* Native resource readiness wait; zero = 10 seconds. */ } uhdk_options; @@ -433,14 +358,16 @@ typedef struct uhdk_frame { /* NULL options selects defaults. Otherwise zero-initialize and set struct_size. * Creates native services, a visible window, and a current OpenGL >=3.3 core - * context before returning OK. Failure cleans up and sets *out=NULL. Startup - * pumps native events internally and preserves them for the first frame. + * context before returning OK, unless no_opengl is set. Failure cleans up and + * sets *out=NULL. Startup pumps native events internally and preserves them for + * the first frame. * GL resources may be created immediately with get_gl: the bundled OpenGL 3.3 * function table is already loaded. No application callbacks execute during setup. */ UHDK_API uhdk_status UHDK_CALL uhdk_open(const uhdk_options *options, uhdk_session **out); /* Begin one application iteration, including event-only iterations when hidden - * or minimized. Each successful call requires end_frame, even if not drawable. + * or minimized. Native-only sessions have a NULL GL table. Each successful call + * requires end_frame, even if not drawable. * Events remain borrowed until the next next_frame or close. Continuous mode * polls without waiting while drawable; on-demand mode waits for events/wakes. * The first iteration never waits. A drawable iteration should repaint the @@ -458,22 +385,24 @@ UHDK_API uhdk_bool UHDK_CALL uhdk_next_frame(uhdk_session *session, uhdk_frame * UHDK_API uhdk_status UHDK_CALL uhdk_end_frame(uhdk_session *session); UHDK_API uhdk_status UHDK_CALL uhdk_get_status(uhdk_session *session); UHDK_API const uhdk_gl_functions *UHDK_CALL uhdk_get_gl(uhdk_session *session); -UHDK_API uhdk_app *UHDK_CALL uhdk_get_app(uhdk_session *session); UHDK_API uhdk_window *UHDK_CALL uhdk_get_window(uhdk_session *session); -UHDK_API uhdk_gl_context *UHDK_CALL uhdk_get_context(uhdk_session *session); /* NULL safe. Discards an unfinished frame without presenting. Destroy app-owned * GL resources before close; all session handles become invalid on return. */ UHDK_API void UHDK_CALL uhdk_close(uhdk_session *session); -/* Queue native creation and return a stable handle immediately. Creation - * failures arrive as RESOURCE_FAILED; success is observed through normal - * window metrics/redraw events. */ +/* Synchronously create an additional native window for an external renderer. + * The session owns GL only for its primary window. The new window starts hidden. + * Call between iterations; BUSY during a frame. Native events collected during + * creation are preserved for next_frame. Failure sets *out=NULL and releases + * partial native resources. Parent handles must outlive their children. */ UHDK_API uhdk_status UHDK_CALL uhdk_window_create( - uhdk_app *app, + uhdk_session *session, const uhdk_window_desc *desc, uhdk_window **out ); -UHDK_API void UHDK_CALL uhdk_window_destroy(uhdk_window *window); +/* Destroy an additional window. The primary window is owned by close and cannot + * be destroyed separately. Pending events/requests follow the lifecycle rules. */ +UHDK_API uhdk_status UHDK_CALL uhdk_window_destroy(uhdk_window *window); UHDK_API uhdk_status UHDK_CALL uhdk_window_set_title(uhdk_window *window, uhdk_text title); UHDK_API uhdk_status UHDK_CALL uhdk_window_set_size(uhdk_window *window, uhdk_size size); UHDK_API uhdk_status UHDK_CALL uhdk_window_set_state(uhdk_window *window, uhdk_window_state state); @@ -492,87 +421,29 @@ UHDK_API uhdk_status UHDK_CALL uhdk_window_get_metrics( ); UHDK_API void UHDK_CALL uhdk_window_invalidate(uhdk_window *window); /* Coalesced redraw event. */ -/* Optional OpenGL context management (application/render thread). - * Define UHDK_ENABLE_OPENGL before including this header for bundled Khronos - * GL types, constants, and PFNGL* function-pointer types. Without that flag, - * no GL names are introduced. - * - * Creation requires UHDK_WINDOW_OPENGL and guarantees desktop OpenGL >= 3.3, - * core profile, with GLSL >= 3.30. macOS selects its 4.1 core profile because - * it cannot create an exact 3.3 profile. No legacy or OpenGL ES fallback. - * Initial framebuffer requirement: double-buffered RGBA8. Depth/stencil buffers - * are not required or guaranteed. No multisampling or sRGB is requested. - * Sharing, debug contexts and custom formats are future work. - * - * One context per window. Create does NOT change the current context. Explicitly - * begin_frame locks drawable updates and makes it current; end_frame unlocks. - * For low-level applications, ALL raw GL calls (including initialization and - * deletion) and presentation must be inside this bracket. Sessions manage these - * brackets internally; their context is current from open until close. - * Never wait for platform results inside a bracket. - * make_current/clear_current are also available inside a bracket. - * Contexts cannot migrate to another thread. Destroy detaches a current context; - * window destruction also destroys its context and invalidates the handle. - * Creation failures leave the window valid and release partially created state. - * Uhdk does not modify viewport/scissor or other application GL state on resize; - * use WINDOW_METRICS framebuffer dimensions to update these yourself. +/* The session owns one OpenGL >=3.3 core context and its loaded function table. + * Context ownership, native synchronization, and presentation are internal. + * Resource GL calls are valid from open until close on OS main. Draw to the + * window framebuffer only during drawable iterations. Applications own all + * offscreen buffers, textures, depth attachments and viewport/scissor state. + * Use get_gl for the bundled 3.3 API and get_gl_proc for additional procedures. */ #if defined(_WIN32) #define UHDK_GL_CALL __stdcall #else #define UHDK_GL_CALL #endif -/* A function pointer, never a data pointer. Cast to the matching Khronos PFNGL* - * type before calling. GL uses stdcall on Win32; Uhdk exports still use C ABI. */ typedef void(UHDK_GL_CALL *uhdk_gl_proc)(void); - -typedef struct uhdk_gl_frame { - uint32_t struct_size; - uhdk_bool drawable; - uint32_t reserved; - uhdk_window_metrics metrics; -} uhdk_gl_frame; - -UHDK_API uhdk_status UHDK_CALL uhdk_gl_context_create( - uhdk_window *window, - uhdk_gl_context **out -); -/* OK with drawable == 0 means the context or window is not ready to render. - * A drawable frame has made the context current and must be ended. */ -UHDK_API uhdk_status UHDK_CALL uhdk_gl_context_try_begin_frame( - uhdk_gl_context *context, - uhdk_gl_frame *out -); -UHDK_API uhdk_status UHDK_CALL uhdk_gl_context_begin_frame(uhdk_gl_context *context); -UHDK_API uhdk_status UHDK_CALL uhdk_gl_context_end_frame(uhdk_gl_context *context); -UHDK_API void UHDK_CALL uhdk_gl_context_destroy(uhdk_gl_context *context); -UHDK_API uhdk_status UHDK_CALL uhdk_gl_context_make_current(uhdk_gl_context *context); -UHDK_API uhdk_status UHDK_CALL uhdk_gl_clear_current(uhdk_app *app); -/* Actual negotiated version, not the requested minimum. */ -UHDK_API uhdk_status UHDK_CALL uhdk_gl_context_get_version( - uhdk_gl_context *context, - uint32_t *out_major, - uint32_t *out_minor -); -/* Wayland returns UNAVAILABLE while hidden or awaiting mapping configuration. */ -UHDK_API uhdk_status UHDK_CALL uhdk_gl_context_swap_buffers(uhdk_gl_context *context); -/* Explicitly set 0 (unsynchronized) or 1 (vsync); other values are invalid. - * No initial interval is guaranteed. Unsupported control returns UNSUPPORTED; - * compositor/driver policy may override presentation timing. */ -UHDK_API uhdk_status UHDK_CALL uhdk_gl_context_set_swap_interval( - uhdk_gl_context *context, - int32_t interval -); -/* Requires this context current. Accepts pointer+length ASCII GL symbol names. - * Missing symbols return NOT_FOUND. Pointers are valid until context destruction - * and must only be used with that context current. A non-NULL pointer alone does - * not prove extension/version support; check GL version/extension availability. - * Loads both platform-library exports and driver-provided GL entry points. */ -UHDK_API uhdk_status UHDK_CALL uhdk_gl_context_get_proc( - uhdk_gl_context *context, +/* ASCII symbol name. Missing symbols return NOT_FOUND. A non-null procedure + * does not establish extension support. Valid until close, on OS main only. */ +UHDK_API uhdk_status UHDK_CALL uhdk_get_gl_proc( + uhdk_session *session, uhdk_text name, uhdk_gl_proc *out ); +/* Request vsync (true) or unsynchronized presentation (false). Native compositor + * policy may override it. Unsupported control returns UNSUPPORTED. */ +UHDK_API uhdk_status UHDK_CALL uhdk_set_vsync(uhdk_session *session, uhdk_bool enabled); /* Keyboard events are not text. Physical key = USB HID keyboard-page usage; * 0 means unknown. Logical key = Unicode scalar, or UHDK_KEY_* below. @@ -721,12 +592,12 @@ enum { UHDK_FILE_NATIVE_PATH = 2 }; UHDK_API uhdk_status UHDK_CALL uhdk_file_create_from_native_path( - uhdk_app *app, + uhdk_session *session, uhdk_bytes path, uhdk_file **out ); UHDK_API uhdk_status UHDK_CALL uhdk_file_create_from_uri( - uhdk_app *app, + uhdk_session *session, uhdk_text uri, uhdk_file **out ); @@ -801,7 +672,7 @@ typedef struct uhdk_file_dialog_desc { uint64_t filters_len; } uhdk_file_dialog_desc; UHDK_API uhdk_status UHDK_CALL uhdk_file_dialog_show_async( - uhdk_app *app, + uhdk_session *session, const uhdk_file_dialog_desc *desc, uhdk_request_id *out ); @@ -812,12 +683,9 @@ UHDK_API uhdk_status UHDK_CALL uhdk_file_dialog_show_async( * max_bytes bounds the UTF-8 result; excess returns BUFFER_TOO_SMALL, never a * truncated string. A read remains async even when a backend can read instantly. */ -UHDK_API uhdk_status UHDK_CALL uhdk_clipboard_write_text( - uhdk_app *app, - uhdk_text text -); +UHDK_API uhdk_status UHDK_CALL uhdk_clipboard_write_text(uhdk_session *session, uhdk_text text); UHDK_API uhdk_status UHDK_CALL uhdk_clipboard_read_text_async( - uhdk_app *app, + uhdk_session *session, uint64_t max_bytes, uhdk_request_id *out ); @@ -866,7 +734,7 @@ typedef struct uhdk_menu_item { } uhdk_menu_item; UHDK_API uhdk_status UHDK_CALL uhdk_menu_create( - uhdk_app *app, + uhdk_session *session, const uhdk_menu_item *items, uint64_t len, uhdk_menu **out @@ -878,29 +746,23 @@ UHDK_API uhdk_status UHDK_CALL uhdk_menu_set_item_flags( ); UHDK_API void UHDK_CALL uhdk_menu_retain(uhdk_menu *menu); UHDK_API void UHDK_CALL uhdk_menu_release(uhdk_menu *menu); -UHDK_API uhdk_status UHDK_CALL uhdk_app_set_menu( - uhdk_app *app, +UHDK_API uhdk_status UHDK_CALL uhdk_set_menu( + uhdk_session *session, uhdk_menu *menu ); /* NULL clears. */ -UHDK_API uhdk_status UHDK_CALL uhdk_window_set_menu( - uhdk_window *window, - uhdk_menu *menu -); +UHDK_API uhdk_status UHDK_CALL uhdk_window_set_menu(uhdk_window *window, uhdk_menu *menu); UHDK_API uhdk_status UHDK_CALL uhdk_menu_popup_async( uhdk_menu *menu, uhdk_window *window, uhdk_point position, uhdk_request_id *out ); -UHDK_API uhdk_status UHDK_CALL uhdk_app_set_icon( - uhdk_app *app, - const uhdk_image *image -); +UHDK_API uhdk_status UHDK_CALL uhdk_set_icon(uhdk_session *session, const uhdk_image *image); /* Successful shell completion means handed off to the OS, not that a target * application finished loading. URLs are not shell command strings. */ UHDK_API uhdk_status UHDK_CALL uhdk_shell_open_url_async( - uhdk_app *app, + uhdk_session *session, uhdk_text url, uhdk_request_id *out ); @@ -939,7 +801,7 @@ typedef struct uhdk_preferences { uhdk_bool reduced_motion; uhdk_bool high_contrast; } uhdk_preferences; -UHDK_API uhdk_status UHDK_CALL uhdk_app_get_preferences(uhdk_app *app, uhdk_preferences *out); +UHDK_API uhdk_status UHDK_CALL uhdk_get_preferences(uhdk_session *session, uhdk_preferences *out); /* Event payloads. Window is NULL for app-wide events. time_ns is monotonic time * relative to app creation, not wall time. Do not persist event pointers. @@ -948,8 +810,7 @@ UHDK_API uhdk_status UHDK_CALL uhdk_app_get_preferences(uhdk_app *app, uhdk_pref */ typedef uint32_t uhdk_event_type; enum { - UHDK_EVENT_READY = 1, - UHDK_EVENT_STOPPED, + UHDK_EVENT_STOPPED = 1, UHDK_EVENT_WAKE, UHDK_EVENT_QUIT_REQUESTED, UHDK_EVENT_APP_ACTIVATION, @@ -972,22 +833,9 @@ enum { UHDK_EVENT_MENU_COMMAND, UHDK_EVENT_DROP_FILES, UHDK_EVENT_WATCH, - UHDK_EVENT_REQUEST_DONE, - UHDK_EVENT_RESOURCE_FAILED + UHDK_EVENT_REQUEST_DONE }; -typedef uint32_t uhdk_resource_kind; -enum { - UHDK_RESOURCE_WINDOW = 1, - UHDK_RESOURCE_GL_CONTEXT -}; - -typedef struct uhdk_resource_event { - uhdk_resource_kind kind; - uhdk_status status; - void *resource; /* Stable failed handle, selected by kind; valid until app destruction. */ -} uhdk_resource_event; - typedef uint32_t uhdk_request_kind; enum { UHDK_REQUEST_FILE_DIALOG = 1, @@ -1155,7 +1003,7 @@ typedef struct uhdk_request_result { * POINTER_MODE_CHANGED: uhdk_pointer_mode_event; SCROLL: uhdk_scroll_event; * TEXT_COMMIT/PREEDIT: uhdk_text_event; EDIT_COMMAND: uhdk_edit_event; * DROP_FILES: uhdk_drop_files_event; MENU_COMMAND: uhdk_menu_event; - * WATCH: uhdk_watch_event; RESOURCE_FAILED: uhdk_resource_event; + * WATCH: uhdk_watch_event; * REQUEST_DONE: uhdk_request_result. * All other events have NULL/0 data. */ @@ -1170,8 +1018,8 @@ struct uhdk_event { }; /* Lifecycle policy: close/quit requests are advisory. Destroy the window or call - * uhdk_app_quit() to accept; otherwise the application stays alive. Closing the - * last window does not automatically quit. App destruction invalidates ALL child + * uhdk_quit() to accept; otherwise the application stays alive. Closing the + * primary window closes only through quit/close; additional windows can be destroyed. Session close invalidates ALL child * handles, including retained files/menus; callers must stop other threads from * waking the app first. Native menu roles produce EDIT_COMMAND/QUIT_REQUESTED * where applicable; custom menu items produce MENU_COMMAND. A popup selection @@ -1192,8 +1040,8 @@ struct uhdk_event { * macOS: primary=NSWindow*, secondary=NSView*; Windows: primary=HWND. * Wayland: primary=wl_display*, secondary=wl_surface*. * X11: primary=Display*, value=XID. Lifetime ends with the Uhdk window. - * With UHDK_WINDOW_OPENGL, Uhdk owns drawable setup; do not replace its native - * view/surface or pixel format. Otherwise the external renderer owns setup. + * For the GL session primary window, Uhdk owns drawable setup; do not replace + * its native view/surface or pixel format. Otherwise the renderer owns setup. * Borrowing a handle does not change platform threading rules: AppKit window * and view operations still belong on the macOS main thread. */ @@ -1211,15 +1059,9 @@ UHDK_API uhdk_status UHDK_CALL uhdk_window_get_native(uhdk_window *window, uhdk_ } /* extern "C" */ #endif #ifdef UHDK_ENABLE_OPENGL -/* GLAD 2: OpenGL 3.3 core, no extensions, explicit per-context function table. - * Do not combine with platform GL headers or GL/glcorearb.h. - * The loader implementation is consumer-owned. Define - * UHDK_GLAD_GL_IMPLEMENTATION before including uhdk.h in exactly one translation - * unit, or provide another implementation of the bundled GLAD interface. - * Load a GladGLContext via gladLoadGLContextUserPtr and an adapter calling - * uhdk_gl_context_get_proc, inside a begin_frame/end_frame bracket. Keep one - * table per context and use it only while that context is current. - */ +/* GLAD 2: OpenGL 3.3 core function-table declarations. UHDK loads and owns the + * table returned by get_gl/frame.gl. No consumer loader implementation is needed. + * Do not combine with platform GL headers or GL/glcorearb.h. */ #include "glad/gl.h" #endif /* UHDK_ENABLE_OPENGL */ diff --git a/src/Application.zig b/src/Application.zig index d81d8d3..77580d3 100644 --- a/src/Application.zig +++ b/src/Application.zig @@ -12,7 +12,6 @@ const Application = @This(); gpa: std.mem.Allocator, io: std.Io, mutex: std.Io.Mutex = .init, -available: std.Io.Event = .unset, in_dispatch: bool = false, objects: ?*Resource = null, queue_head: ?*Request = null, @@ -42,32 +41,25 @@ epoch: u64, deadline: u64 = 0, next_id: u64 = 1, running: bool = false, -use_application_thread: bool = false, -attached_once: bool = false, -native_entered: bool = false, -native_running: bool = false, +native_started: bool = false, native_error: abi.Status = abi.OK, -application_pool: ?*anyopaque = null, -has_run: bool = false, stopping: bool = false, stopped_sent: bool = false, stopped_seen: bool = false, -worker_done: bool = false, event_error: abi.Status = abi.OK, -worker_id: ?std.Thread.Id = null, -entry: c.uhdk_app_main_fn = null, -user: ?*anyopaque = null, +main_thread: ?std.Thread.Id = null, preferences: c.uhdk_preferences = std.mem.zeroes(c.uhdk_preferences), -stats: c.uhdk_app_stats = std.mem.zeroes(c.uhdk_app_stats), +stats: c.uhdk_stats = std.mem.zeroes(c.uhdk_stats), last_frame_time: ?u64 = null, session_gl: c.uhdk_gl_functions = std.mem.zeroes(c.uhdk_gl_functions), session_window: ?*c.uhdk_window = null, -session_context: ?*c.uhdk_gl_context = null, +session_context: ?*c.z_gl_context = null, session_status: abi.Status = abi.OK, session_active: bool = false, session_drawable: bool = false, session_first: bool = true, session_on_demand: bool = false, +startup_timeout_ns: u64 = 10 * std.time.ns_per_s, pub fn create(gpa: std.mem.Allocator, io: std.Io, name: []const u8) !*Application { const self = try gpa.create(Application); errdefer gpa.destroy(self); @@ -84,8 +76,6 @@ pub fn unlock(self: *Application) void { self.mutex.unlock(self.io); } pub fn notify(self: *Application) void { - self.available.set(self.io); - // Native callbacks can publish while a caller-owned native pump is waiting. - // Wake that pump too; its OS wait is separate from the application semaphore. - if (!self.use_application_thread and self.running) c.z_native_wake(); + // Wake native dispatch for events and worker completions. + if (self.native_started) c.z_native_wake(); } diff --git a/src/EventPayload.zig b/src/EventPayload.zig index 0e4433b..b0f79e5 100644 --- a/src/EventPayload.zig +++ b/src/EventPayload.zig @@ -51,7 +51,6 @@ pub fn pack(allocator: std.mem.Allocator, source: c.z_event) !c.uhdk_event { }, c.UHDK_EVENT_MENU_COMMAND => try store(c.uhdk_menu_event, allocator, source.data.menu), c.UHDK_EVENT_WATCH => try store(c.uhdk_watch_event, allocator, source.data.watch), - c.UHDK_EVENT_RESOURCE_FAILED => try store(c.uhdk_resource_event, allocator, source.data.resource), c.UHDK_EVENT_REQUEST_DONE => try store(c.uhdk_request_result, allocator, try result(allocator, source.data.request)), else => .{}, }; diff --git a/src/api/app.zig b/src/api/app.zig index 779295d..53b44a9 100644 --- a/src/api/app.zig +++ b/src/api/app.zig @@ -14,31 +14,20 @@ const MinimalIo = @import("../MinimalIo.zig"); pub var singleton: bool = false; // OS-main-thread lifecycle gate. -pub export fn uhdk_get_abi_version() u32 { - return c.UHDK_ABI_VERSION; -} - -pub export fn uhdk_app_create(desc: [*c]const c.uhdk_app_desc, out: [*c]?*c.uhdk_app) abi.Status { - if (out != null) out.* = null; +pub fn create(desc: *const c.uhdk_options, out: *?*c.uhdk_session) abi.Status { + out.* = null; if (c.z_native_is_main_thread() == 0) return c.UHDK_STATUS_WRONG_THREAD; - if (!abi.validDescriptor(c.uhdk_app_desc, desc) or - out == null or - desc.*.abi_version != c.UHDK_ABI_VERSION or - desc.*.reserved != 0 or - (desc.*.use_application_thread != 0 and desc.*.use_application_thread != 1) or - !abi.validText(desc.*.display_name, true) or - !abi.validText(desc.*.application_id, true)) return abi.INVALID; - if (desc.*.preferred_backend != c.UHDK_BACKEND_AUTO and desc.*.preferred_backend != backend_kind) return c.UHDK_STATUS_UNSUPPORTED; + if (!abi.validText(desc.title, true) or !abi.validText(desc.application_id, true)) return abi.INVALID; + if (desc.preferred_backend != c.UHDK_BACKEND_AUTO and desc.preferred_backend != backend_kind) return c.UHDK_STATUS_UNSUPPORTED; if (singleton) return c.UHDK_STATUS_BUSY; const gpa = profile.allocator(); - const application = Application.create(gpa, MinimalIo.instance, abi.textBytes(desc.*.display_name)) catch return abi.OOM; - application.application_id = gpa.dupe(u8, abi.textBytes(desc.*.application_id)) catch { + const application = Application.create(gpa, MinimalIo.instance, abi.textBytes(desc.title)) catch return abi.OOM; + application.application_id = gpa.dupe(u8, abi.textBytes(desc.application_id)) catch { application.scratch.deinit(); gpa.free(application.name); gpa.destroy(application); return abi.OOM; }; - application.use_application_thread = desc.*.use_application_thread != 0; singleton = true; const status = initialize(application); if (status != abi.OK) { @@ -52,110 +41,26 @@ pub export fn uhdk_app_create(desc: [*c]const c.uhdk_app_desc, out: [*c]?*c.uhdk fn initialize(application: *Application) abi.Status { const handle = runtime.toAppHandle(application); profile.thread("UHDK platform"); - const ready = runtime.prepareReady(application) catch return abi.OOM; const status = c.z_native_start(handle, abi.textSpan(application.name)); if (status != abi.OK) { - runtime.destroyEvent(ready); return status; } application.io_worker = std.Thread.spawn(.{}, runtime.ioMain, .{application}) catch { - runtime.destroyEvent(ready); c.z_native_finish(); return abi.OOM; }; + application.native_started = true; application.running = true; - if (!application.use_application_thread) application.worker_id = std.Thread.getCurrentId(); - runtime.publishReady(application, ready); + application.main_thread = std.Thread.getCurrentId(); return abi.OK; } -pub export fn uhdk_app_attach(handle: ?*c.uhdk_app) abi.Status { - if (handle == null) return abi.INVALID; - const application = runtime.fromAppHandle(handle); - if (c.z_native_is_main_thread() != 0) return c.UHDK_STATUS_WRONG_THREAD; - application.lock(); - defer application.unlock(); - if (!application.running or !application.use_application_thread) return abi.INVALID; - if (application.worker_id != null) return c.UHDK_STATUS_BUSY; - if (application.attached_once) return abi.INVALID; - application.attached_once = true; - application.worker_id = std.Thread.getCurrentId(); - application.application_pool = c.z_native_pool_push(); - return abi.OK; -} - -pub export fn uhdk_app_detach(handle: ?*c.uhdk_app) abi.Status { - if (handle == null) return abi.INVALID; - const application = runtime.fromAppHandle(handle); - if (!application.use_application_thread) return abi.INVALID; - if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; - if (runtime.hasFrame(application)) return c.UHDK_STATUS_BUSY; - _ = c.z_native_gl(null, 4, null); - c.z_native_pool_pop(application.application_pool); - application.application_pool = null; - application.lock(); - application.stopping = true; - application.worker_done = true; - application.worker_id = null; - application.unlock(); - c.z_native_wake(); - return abi.OK; -} - -pub export fn uhdk_app_run_native(handle: ?*c.uhdk_app) abi.Status { - if (handle == null) return abi.INVALID; - if (c.z_native_is_main_thread() == 0) return c.UHDK_STATUS_WRONG_THREAD; - const application = runtime.fromAppHandle(handle); - if (!application.running or !application.use_application_thread or application.native_entered) return abi.INVALID; - application.native_entered = true; - application.native_running = true; - c.z_native_wake(); - c.z_native_run(); - application.native_running = false; - application.lock(); - defer application.unlock(); - if (!application.worker_done and application.native_error == abi.OK) { - application.native_error = c.UHDK_STATUS_OS_ERROR; - application.stopping = true; - application.notify(); - } - return application.native_error; -} - -pub export fn uhdk_app_run(handle: ?*c.uhdk_app, entry: c.uhdk_app_main_fn, user: ?*anyopaque) abi.Status { - if (handle == null or entry == null) return abi.INVALID; - if (c.z_native_is_main_thread() == 0) return c.UHDK_STATUS_WRONG_THREAD; - const application = runtime.fromAppHandle(handle); - if (application.has_run or application.attached_once or application.native_entered or application.stopping) return abi.INVALID; - application.has_run = true; - application.entry = entry; - application.user = user; - if (application.use_application_thread) { - const worker = std.Thread.spawn(.{}, runtime.applicationMain, .{application}) catch { - return abi.OOM; - }; - const run_status = uhdk_app_run_native(handle); - worker.join(); - return run_status; - } - entry.?(handle, user); - application.lock(); - application.stopping = true; - application.worker_done = true; - application.worker_id = null; - application.unlock(); - return application.native_error; -} - fn shutdown(application: *Application) void { const handle = runtime.toAppHandle(application); - std.debug.assert(!application.native_running); - std.debug.assert(!application.use_application_thread or application.worker_id == null); std.debug.assert(!runtime.hasFrame(application)); _ = c.z_native_gl(null, 4, null); application.lock(); application.stopping = true; - application.worker_done = true; application.unlock(); // Keep native services alive while cancellation, completion, and destruction drain. while (true) { @@ -195,12 +100,13 @@ fn shutdown(application: *Application) void { } } c.z_native_finish(); + application.native_started = false; application.running = false; - application.worker_id = null; + application.main_thread = null; } -pub export fn uhdk_app_poll_events( - handle: ?*c.uhdk_app, +pub fn poll( + handle: ?*c.uhdk_session, timeout: u64, out: [*c]c.uhdk_event_list, ) abi.Status { @@ -216,11 +122,9 @@ pub export fn uhdk_app_poll_events( out.* = .{ .ptr = null, .len = 0 }; const start = runtime.now(application.io); const end = start +| timeout; - if (!application.use_application_thread) { - runtime.dispatch(handle); - c.z_native_pump(0); - runtime.dispatch(handle); - } + runtime.dispatch(handle); + if (application.native_started) c.z_native_pump(0); + runtime.dispatch(handle); application.lock(); defer application.unlock(); if (application.native_error != abi.OK) return application.native_error; @@ -243,26 +147,11 @@ pub export fn uhdk_app_poll_events( if (current >= end) return abi.OK; const wake_time = if (application.deadline == 0) end else @min(end, application.epoch +| application.deadline); const ns = wake_time -| current; - application.available.reset(); application.unlock(); const wait_zone = profile.begin(@src(), "UHDK wait for events"); defer wait_zone.end(); - if (!application.use_application_thread) { - c.z_native_pump(ns); - runtime.dispatch(handle); - application.lock(); - continue; - } - application.available.waitTimeout(application.io, .{ .duration = .{ - .raw = .fromNanoseconds(ns), - .clock = .awake, - } }) catch |err| switch (err) { - error.Timeout => {}, - error.Canceled => { - application.lock(); - return abi.CANCELLED; - }, - }; + if (application.native_started) c.z_native_pump(ns); + runtime.dispatch(handle); application.lock(); } if (application.native_error != abi.OK) return application.native_error; @@ -304,14 +193,14 @@ pub export fn uhdk_app_poll_events( return abi.OK; } -pub export fn uhdk_app_get_stats(handle: ?*c.uhdk_app, out: [*c]c.uhdk_app_stats) abi.Status { +pub export fn uhdk_get_stats(handle: ?*c.uhdk_session, out: [*c]c.uhdk_stats) abi.Status { if (handle == null) return abi.INVALID; const application = runtime.fromAppHandle(handle); if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; - return abi.writeOutput(c.uhdk_app_stats, out, application.stats); + return abi.writeOutput(c.uhdk_stats, out, application.stats); } -pub export fn uhdk_app_quit(handle: ?*c.uhdk_app) void { +pub export fn uhdk_quit(handle: ?*c.uhdk_session) void { if (handle == null) return; const application = runtime.fromAppHandle(handle); application.lock(); @@ -320,19 +209,19 @@ pub export fn uhdk_app_quit(handle: ?*c.uhdk_app) void { c.z_native_wake(); } -pub export fn uhdk_app_wake(handle: ?*c.uhdk_app) void { +pub export fn uhdk_wake(handle: ?*c.uhdk_session) void { if (handle != null) { runtime.simpleEvent(runtime.fromAppHandle(handle), c.UHDK_EVENT_WAKE); c.z_native_wake(); } } -pub export fn uhdk_app_get_time_ns(handle: ?*c.uhdk_app) u64 { +pub export fn uhdk_get_time_ns(handle: ?*c.uhdk_session) u64 { const application = runtime.fromAppHandle(handle); return runtime.now(application.io) - application.epoch; } -pub export fn uhdk_app_set_wake_deadline(handle: ?*c.uhdk_app, deadline: u64) abi.Status { +pub export fn uhdk_set_wake_deadline(handle: ?*c.uhdk_session, deadline: u64) abi.Status { if (handle == null) return abi.INVALID; const application = runtime.fromAppHandle(handle); if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; @@ -343,12 +232,12 @@ pub export fn uhdk_app_set_wake_deadline(handle: ?*c.uhdk_app, deadline: u64) ab return abi.OK; } -pub export fn uhdk_app_get_backend(handle: ?*c.uhdk_app) c.uhdk_backend { +pub export fn uhdk_get_backend(handle: ?*c.uhdk_session) c.uhdk_backend { if (@import("builtin").os.tag == .linux) return @import("../linux/native.zig").backend(handle); return backend_kind; } -pub export fn uhdk_app_has_capability(handle: ?*c.uhdk_app, cap: c.uhdk_capability) c.uhdk_bool { +pub export fn uhdk_has_capability(handle: ?*c.uhdk_session, cap: c.uhdk_capability) c.uhdk_bool { if (@import("builtin").os.tag == .linux) return @import("../linux/native.zig").capability(handle, cap); return switch (cap) { c.UHDK_CAP_FILE_DIALOGS, c.UHDK_CAP_CLIPBOARD, c.UHDK_CAP_DROP_FILES, c.UHDK_CAP_APP_MENU, c.UHDK_CAP_CONTEXT_MENU, c.UHDK_CAP_APP_ICON, c.UHDK_CAP_POINTER_CAPTURE, c.UHDK_CAP_TEXT_INPUT, c.UHDK_CAP_OPENGL => 1, @@ -356,7 +245,7 @@ pub export fn uhdk_app_has_capability(handle: ?*c.uhdk_app, cap: c.uhdk_capabili }; } -pub export fn uhdk_request_cancel(handle: ?*c.uhdk_app, id: u64) abi.Status { +pub export fn uhdk_request_cancel(handle: ?*c.uhdk_session, id: u64) abi.Status { if (handle == null or id == 0) return abi.INVALID; const application = runtime.fromAppHandle(handle); if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; @@ -374,7 +263,7 @@ pub export fn uhdk_request_cancel(handle: ?*c.uhdk_app, id: u64) abi.Status { return c.UHDK_STATUS_NOT_FOUND; } -pub export fn uhdk_app_destroy(handle: ?*c.uhdk_app) void { +pub fn destroy(handle: ?*c.uhdk_session) void { if (handle == null) return; const application = runtime.fromAppHandle(handle); std.debug.assert(c.z_native_is_main_thread() != 0); diff --git a/src/api/desktop.zig b/src/api/desktop.zig index 97dc8a6..3961f27 100644 --- a/src/api/desktop.zig +++ b/src/api/desktop.zig @@ -5,7 +5,7 @@ const runtime = @import("../runtime.zig"); const abi = @import("../abi.zig"); pub export fn uhdk_clipboard_write_text( - handle: ?*c.uhdk_app, + handle: ?*c.uhdk_session, text: c.uhdk_text, ) abi.Status { if (!abi.validText(text, false)) return abi.INVALID; @@ -18,7 +18,7 @@ pub export fn uhdk_clipboard_write_text( } pub export fn uhdk_clipboard_read_text_async( - handle: ?*c.uhdk_app, + handle: ?*c.uhdk_session, limit: u64, out: [*c]u64, ) abi.Status { @@ -29,7 +29,7 @@ pub export fn uhdk_clipboard_read_text_async( } pub export fn uhdk_shell_open_url_async( - handle: ?*c.uhdk_app, + handle: ?*c.uhdk_session, text: c.uhdk_text, out: [*c]u64, ) abi.Status { @@ -43,8 +43,8 @@ pub export fn uhdk_shell_open_url_async( return runtime.submit(runtime.fromAppHandle(handle), command, out); } -pub export fn uhdk_app_set_icon( - handle: ?*c.uhdk_app, +pub export fn uhdk_set_icon( + handle: ?*c.uhdk_session, image: [*c]const c.uhdk_image, ) abi.Status { if (!abi.validDescriptor(c.uhdk_image, image)) return abi.INVALID; @@ -67,8 +67,8 @@ pub export fn uhdk_app_set_icon( return runtime.submitCommand(runtime.fromAppHandle(handle), command); } -pub export fn uhdk_app_get_preferences( - handle: ?*c.uhdk_app, +pub export fn uhdk_get_preferences( + handle: ?*c.uhdk_session, out: [*c]c.uhdk_preferences, ) abi.Status { if (handle == null) return abi.INVALID; diff --git a/src/api/files.zig b/src/api/files.zig index 15baa8a..0bf1e5c 100644 --- a/src/api/files.zig +++ b/src/api/files.zig @@ -5,7 +5,7 @@ const runtime = @import("../runtime.zig"); const abi = @import("../abi.zig"); pub export fn uhdk_file_dialog_show_async( - handle: ?*c.uhdk_app, + handle: ?*c.uhdk_session, desc: [*c]const c.uhdk_file_dialog_desc, out: [*c]u64, ) abi.Status { @@ -31,7 +31,7 @@ pub export fn uhdk_file_dialog_show_async( } pub export fn uhdk_file_create_from_native_path( - handle: ?*c.uhdk_app, + handle: ?*c.uhdk_session, path: c.uhdk_bytes, out: [*c]?*c.uhdk_file, ) abi.Status { @@ -53,7 +53,7 @@ pub export fn uhdk_file_create_from_native_path( } pub export fn uhdk_file_create_from_uri( - handle: ?*c.uhdk_app, + handle: ?*c.uhdk_session, uri: c.uhdk_text, out: [*c]?*c.uhdk_file, ) abi.Status { diff --git a/src/api/graphics.zig b/src/api/graphics.zig index a59b4da..a4b035e 100644 --- a/src/api/graphics.zig +++ b/src/api/graphics.zig @@ -1,11 +1,11 @@ -//! C ABI entry points for graphics. +//! Private GL ownership and presentation for session boundaries. const std = @import("std"); const profile = @import("profile"); const c = @import("native"); const runtime = @import("../runtime.zig"); const abi = @import("../abi.zig"); -pub export fn uhdk_gl_context_create(handle: ?*c.uhdk_window, out: [*c]?*c.uhdk_gl_context) abi.Status { +pub fn create(handle: ?*c.uhdk_window, out: [*c]?*c.z_gl_context) abi.Status { if (out == null) return abi.INVALID; const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_GL) catch |err| return runtime.objectError(err); const w = runtime.fromObjectHandle(handle); @@ -21,18 +21,11 @@ pub export fn uhdk_gl_context_create(handle: ?*c.uhdk_window, out: [*c]?*c.uhdk_ w.payload.window.context = object; command.data.other = object; const status = runtime.submitResource(w.app, command); - if (status == abi.OK) out.* = runtime.castHandle(*c.uhdk_gl_context, object); + if (status == abi.OK) out.* = runtime.castHandle(*c.z_gl_context, object); return status; } -pub export fn uhdk_gl_context_destroy(handle: ?*c.uhdk_gl_context) void { - if (handle == null) return; - const object = runtime.fromObjectHandle(handle); - if (object.payload.gl.owner) |w| w.payload.window.context = null; - runtime.destroyObject(object); -} - -pub export fn uhdk_gl_context_begin_frame(handle: ?*c.uhdk_gl_context) abi.Status { +pub fn acquire(handle: ?*c.z_gl_context) abi.Status { const zone = profile.begin(@src(), "UHDK acquire GL context"); defer zone.end(); if (handle == null) return abi.INVALID; @@ -48,32 +41,7 @@ pub export fn uhdk_gl_context_begin_frame(handle: ?*c.uhdk_gl_context) abi.Statu return status; } -pub export fn uhdk_gl_context_try_begin_frame( - handle: ?*c.uhdk_gl_context, - out: [*c]c.uhdk_gl_frame, -) abi.Status { - if (!abi.validDescriptor(c.uhdk_gl_frame, out)) return abi.INVALID; - out.*.drawable = 0; - out.*.reserved = 0; - out.*.metrics = std.mem.zeroes(c.uhdk_window_metrics); - out.*.metrics.struct_size = @sizeOf(c.uhdk_window_metrics); - if (handle == null) return abi.INVALID; - const object = runtime.fromObjectHandle(handle); - const valid = runtime.checkObject(object, c.Z_KIND_GL); - if (valid != abi.OK) return valid; - const owner = object.payload.gl.owner orelse return abi.UNAVAILABLE; - object.app.lock(); - out.*.metrics = owner.payload.window.metrics; - object.app.unlock(); - out.*.metrics.struct_size = @sizeOf(c.uhdk_window_metrics); - if (object.native == null or out.*.metrics.visible == 0 or - out.*.metrics.framebuffer_width == 0 or out.*.metrics.framebuffer_height == 0) return abi.OK; - const status = uhdk_gl_context_begin_frame(handle); - if (status == abi.OK) out.*.drawable = 1; - return status; -} - -pub export fn uhdk_gl_context_end_frame(handle: ?*c.uhdk_gl_context) abi.Status { +pub fn release(handle: ?*c.z_gl_context) abi.Status { const status = runtime.glCall(handle, 2, null); if (status == abi.OK) { const object = runtime.fromObjectHandle(handle); @@ -94,32 +62,7 @@ pub export fn uhdk_gl_context_end_frame(handle: ?*c.uhdk_gl_context) abi.Status return status; } -pub export fn uhdk_gl_context_make_current(handle: ?*c.uhdk_gl_context) abi.Status { - return runtime.glCall(handle, 3, null); -} - -pub export fn uhdk_gl_clear_current(handle: ?*c.uhdk_app) abi.Status { - if (handle == null) return abi.INVALID; - if (runtime.checkThread(runtime.fromAppHandle(handle)) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; - return c.z_native_gl(null, 4, null); -} - -pub export fn uhdk_gl_context_get_version( - handle: ?*c.uhdk_gl_context, - major: [*c]u32, - minor: [*c]u32, -) abi.Status { - if (major == null or minor == null) return abi.INVALID; - var version: [2]u32 = undefined; - const status = runtime.glCall(handle, 5, &version); - if (status == abi.OK) { - major.* = version[0]; - minor.* = version[1]; - } - return status; -} - -pub export fn uhdk_gl_context_swap_buffers(handle: ?*c.uhdk_gl_context) abi.Status { +pub fn present(handle: ?*c.z_gl_context) abi.Status { const zone = profile.begin(@src(), "UHDK present (includes vsync)"); defer zone.end(); if (handle == null) return abi.INVALID; @@ -135,8 +78,8 @@ pub export fn uhdk_gl_context_swap_buffers(handle: ?*c.uhdk_gl_context) abi.Stat return status; } -pub export fn uhdk_gl_context_set_swap_interval( - handle: ?*c.uhdk_gl_context, +pub fn setSwapInterval( + handle: ?*c.z_gl_context, interval: i32, ) abi.Status { if (interval != 0 and interval != 1) return abi.INVALID; @@ -144,8 +87,8 @@ pub export fn uhdk_gl_context_set_swap_interval( return runtime.glCall(handle, 7, &value); } -pub export fn uhdk_gl_context_get_proc( - handle: ?*c.uhdk_gl_context, +pub fn getProc( + handle: ?*c.z_gl_context, name: c.uhdk_text, out: [*c]c.uhdk_gl_proc, ) abi.Status { diff --git a/src/api/menus.zig b/src/api/menus.zig index cc7e96a..70fae86 100644 --- a/src/api/menus.zig +++ b/src/api/menus.zig @@ -5,7 +5,7 @@ const runtime = @import("../runtime.zig"); const abi = @import("../abi.zig"); pub export fn uhdk_menu_create( - handle: ?*c.uhdk_app, + handle: ?*c.uhdk_session, items: [*c]const c.uhdk_menu_item, len: u64, out: [*c]?*c.uhdk_menu, @@ -61,8 +61,8 @@ pub export fn uhdk_menu_release(handle: ?*c.uhdk_menu) void { if (handle != null) runtime.release(runtime.fromObjectHandle(handle)); } -pub export fn uhdk_app_set_menu( - handle: ?*c.uhdk_app, +pub export fn uhdk_set_menu( + handle: ?*c.uhdk_session, menu: ?*c.uhdk_menu, ) abi.Status { return runtime.attachMenu(handle, null, menu); diff --git a/src/api/session.zig b/src/api/session.zig index b31d473..929987a 100644 --- a/src/api/session.zig +++ b/src/api/session.zig @@ -11,20 +11,20 @@ const graphics = @import("graphics.zig"); fn state(session: *c.uhdk_session) *Application { return @ptrCast(@alignCast(session)); } -fn handle(a: *Application) *c.uhdk_app { +fn handle(a: *Application) *c.uhdk_session { return runtime.toAppHandle(a); } -fn acquire(a: *Application) abi.Status { - const context = a.session_context orelse return abi.UNAVAILABLE; +pub fn acquire(a: *Application) abi.Status { + const context = a.session_context orelse return abi.OK; if (runtime.fromObjectHandle(context).payload.gl.bracket) return abi.OK; - return graphics.uhdk_gl_context_begin_frame(context); + return graphics.acquire(context); } -fn release(a: *Application) abi.Status { +pub fn release(a: *Application) abi.Status { const context = a.session_context orelse return abi.OK; if (!runtime.fromObjectHandle(context).payload.gl.bracket) return abi.OK; - return graphics.uhdk_gl_context_end_frame(context); + return graphics.release(context); } -fn ready(a: *Application, resource: anytype, deadline: u64) abi.Status { +pub fn ready(a: *Application, resource: anytype, deadline: u64) abi.Status { const object = runtime.fromObjectHandle(resource); while (!object.ready) { if (!object.alive) return if (object.creation_status == abi.OK) abi.UNAVAILABLE else object.creation_status; @@ -51,42 +51,41 @@ pub export fn uhdk_open(options: [*c]const c.uhdk_options, out: [*c]?*c.uhdk_ses (opts.undecorated != 0 and opts.undecorated != 1) or (opts.fixed_size != 0 and opts.fixed_size != 1) or (opts.disable_vsync != 0 and opts.disable_vsync != 1) or - (opts.request_focus != 0 and opts.request_focus != 1)) return abi.INVALID; - var desc = std.mem.zeroes(c.uhdk_app_desc); - desc.struct_size = @sizeOf(c.uhdk_app_desc); - desc.abi_version = c.UHDK_ABI_VERSION; - desc.application_id = opts.application_id; - desc.display_name = if (opts.title.len == 0) abi.textSpan("UHDK") else opts.title; - desc.preferred_backend = opts.preferred_backend; - var application: ?*c.uhdk_app = null; - var status = app.uhdk_app_create(&desc, &application); + (opts.request_focus != 0 and opts.request_focus != 1) or + (opts.no_opengl != 0 and opts.no_opengl != 1)) return abi.INVALID; + if (opts.title.len == 0) opts.title = abi.textSpan("UHDK"); + var application: ?*c.uhdk_session = null; + var status = app.create(&opts, &application); if (status != abi.OK) return status; const a = runtime.fromAppHandle(application); var success = false; defer if (!success) { _ = release(a); - app.uhdk_app_destroy(application); + app.destroy(application); }; a.session_on_demand = opts.render_mode == c.UHDK_RENDER_ON_DEMAND; - var window = std.mem.zeroes(c.uhdk_window_desc); - window.struct_size = @sizeOf(c.uhdk_window_desc); - window.title = desc.display_name; - window.flags = c.UHDK_WINDOW_OPENGL; + var window = std.mem.zeroes(c.z_window_desc); + window.struct_size = @sizeOf(c.z_window_desc); + window.title = opts.title; + window.flags = if (opts.no_opengl == 0) c.Z_WINDOW_OPENGL else 0; window.style = .{ .struct_size = @sizeOf(c.uhdk_window_style), .decorated = 1 - opts.undecorated, .resizable = 1 - opts.fixed_size, .reserved = 0 }; window.content_size = opts.content_size; if (window.content_size.width == 0) window.content_size.width = 800; if (window.content_size.height == 0) window.content_size.height = 600; window.min_size = opts.min_size; window.max_size = opts.max_size; - const deadline = runtime.now(a.io) +| (if (opts.startup_timeout_ns == 0) 10 * std.time.ns_per_s else opts.startup_timeout_ns); - status = windows.uhdk_window_create(application, &window, &a.session_window); + if (opts.startup_timeout_ns != 0) a.startup_timeout_ns = opts.startup_timeout_ns; + const deadline = runtime.now(a.io) +| a.startup_timeout_ns; + status = windows.queueCreate(application, &window, &a.session_window); if (status != abi.OK) return status; status = ready(a, a.session_window, deadline); if (status != abi.OK) return status; - status = graphics.uhdk_gl_context_create(a.session_window, &a.session_context); - if (status != abi.OK) return status; - status = ready(a, a.session_context, deadline); - if (status != abi.OK) return status; + if (opts.no_opengl == 0) { + status = graphics.create(a.session_window, &a.session_context); + if (status != abi.OK) return status; + status = ready(a, a.session_context, deadline); + if (status != abi.OK) return status; + } status = windows.uhdk_window_set_visible(a.session_window, 1); if (status != abi.OK) return status; if (opts.request_focus != 0) { @@ -98,9 +97,11 @@ pub export fn uhdk_open(options: [*c]const c.uhdk_options, out: [*c]?*c.uhdk_ses if (a.native_error != abi.OK) return a.native_error; status = acquire(a); if (status != abi.OK) return status; - status = graphics.uhdk_gl_context_set_swap_interval(a.session_context, 1 - @as(i32, opts.disable_vsync)); - if (status != abi.OK and status != c.UHDK_STATUS_UNSUPPORTED) return status; - if (c.z_gl_load(a.session_context, &a.session_gl) == 0) return c.UHDK_STATUS_UNSUPPORTED; + if (opts.no_opengl == 0) { + status = graphics.setSwapInterval(a.session_context, 1 - @as(i32, opts.disable_vsync)); + if (status != abi.OK and status != c.UHDK_STATUS_UNSUPPORTED) return status; + if (c.z_gl_load(runtime.fromObjectHandle(a.session_context).native, &a.session_gl) == 0) return c.UHDK_STATUS_UNSUPPORTED; + } out.* = @ptrCast(a); success = true; return abi.OK; @@ -121,14 +122,14 @@ pub export fn uhdk_next_frame(session: ?*c.uhdk_session, out: [*c]c.uhdk_frame) const wait = !a.session_first and (a.session_on_demand or !drawable(metrics)); a.session_status = release(a); if (a.session_status != abi.OK) return 0; - const poll_status = app.uhdk_app_poll_events(handle(a), if (wait) c.UHDK_WAIT_FOREVER else 0, &out.*.events); + const poll_status = app.poll(handle(a), if (wait) std.math.maxInt(u64) else 0, &out.*.events); // Restore GL ownership even after polling fails so cleanup can delete resources. const acquire_status = acquire(a); a.session_status = if (poll_status != abi.OK) poll_status else acquire_status; if (a.session_status != abi.OK) return 0; a.session_status = windows.uhdk_window_get_metrics(a.session_window, &metrics); if (a.session_status != abi.OK) return 0; - out.*.gl = &a.session_gl; + out.*.gl = if (a.session_context != null) &a.session_gl else null; out.*.metrics = metrics; a.session_drawable = !a.stopping and drawable(metrics); out.*.drawable = @intFromBool(a.session_drawable); @@ -153,7 +154,7 @@ pub export fn uhdk_end_frame(session: ?*c.uhdk_session) abi.Status { if (!a.session_active) return c.UHDK_STATUS_BUSY; a.session_active = false; var status: abi.Status = abi.OK; - if (a.session_drawable and !a.stopping) status = graphics.uhdk_gl_context_swap_buffers(a.session_context); + if (a.session_drawable and !a.stopping and a.session_context != null) status = graphics.present(a.session_context); const end_status = release(a); const begin_status = if (end_status == abi.OK) acquire(a) else end_status; a.session_status = if (status != abi.OK) status else begin_status; @@ -166,20 +167,27 @@ pub export fn uhdk_get_status(session: ?*c.uhdk_session) abi.Status { return a.session_status; } pub export fn uhdk_get_gl(session: ?*c.uhdk_session) [*c]const c.uhdk_gl_functions { - return &state(session orelse return null).session_gl; -} -pub export fn uhdk_get_app(session: ?*c.uhdk_session) ?*c.uhdk_app { - return handle(state(session orelse return null)); + const a = state(session orelse return null); + return if (a.session_context != null) &a.session_gl else null; } pub export fn uhdk_get_window(session: ?*c.uhdk_session) ?*c.uhdk_window { return state(session orelse return null).session_window; } -pub export fn uhdk_get_context(session: ?*c.uhdk_session) ?*c.uhdk_gl_context { - return state(session orelse return null).session_context; -} pub export fn uhdk_close(session: ?*c.uhdk_session) void { const a = state(session orelse return); std.debug.assert(runtime.checkThread(a) == abi.OK); _ = release(a); - app.uhdk_app_destroy(handle(a)); + app.destroy(handle(a)); +} + +pub export fn uhdk_get_gl_proc(session: ?*c.uhdk_session, name: c.uhdk_text, out: [*c]c.uhdk_gl_proc) abi.Status { + const a = state(session orelse return abi.INVALID); + if (a.session_context == null) return c.UHDK_STATUS_UNSUPPORTED; + return graphics.getProc(a.session_context, name, out); +} +pub export fn uhdk_set_vsync(session: ?*c.uhdk_session, enabled: c.uhdk_bool) abi.Status { + const a = state(session orelse return abi.INVALID); + if (enabled != 0 and enabled != 1) return abi.INVALID; + if (a.session_context == null) return c.UHDK_STATUS_UNSUPPORTED; + return graphics.setSwapInterval(a.session_context, enabled); } diff --git a/src/api/windows.zig b/src/api/windows.zig index 10fbe9d..2bbd39b 100644 --- a/src/api/windows.zig +++ b/src/api/windows.zig @@ -4,12 +4,12 @@ const c = @import("native"); const runtime = @import("../runtime.zig"); const abi = @import("../abi.zig"); -pub export fn uhdk_window_create( - handle: ?*c.uhdk_app, - desc: [*c]const c.uhdk_window_desc, +pub fn queueCreate( + handle: ?*c.uhdk_session, + desc: [*c]const c.z_window_desc, out: [*c]?*c.uhdk_window, ) abi.Status { - if (handle == null or !abi.validDescriptor(c.uhdk_window_desc, desc)) return abi.INVALID; + if (handle == null or !abi.validDescriptor(c.z_window_desc, desc)) return abi.INVALID; if (out == null) return abi.INVALID; const d = desc.*; if (!validStyle(&d.style) or @@ -19,7 +19,7 @@ pub export fn uhdk_window_create( d.content_size.height == 0 or !abi.finiteSize(d.min_size) or !abi.finiteSize(d.max_size) or - d.flags & ~@as(u32, c.UHDK_WINDOW_OPENGL) != 0) return abi.INVALID; + d.flags & ~@as(u32, c.Z_WINDOW_OPENGL) != 0) return abi.INVALID; if ((d.max_size.width != 0 and d.max_size.width < d.min_size.width) or (d.max_size.height != 0 and d.max_size.height < d.min_size.height)) return abi.INVALID; if (d.parent != null and (runtime.fromObjectHandle(d.parent).app != runtime.fromAppHandle(handle) or @@ -50,10 +50,6 @@ fn validStyle(style: [*c]const c.uhdk_window_style) bool { style.*.reserved == 0; } -pub export fn uhdk_window_destroy(handle: ?*c.uhdk_window) void { - if (handle) |_| runtime.destroyObject(runtime.fromObjectHandle(handle)); -} - pub export fn uhdk_window_set_title(handle: ?*c.uhdk_window, title: c.uhdk_text) abi.Status { return runtime.textCommandValue(handle, c.Z_KIND_WINDOW, c.Z_TITLE, title); } @@ -117,3 +113,47 @@ pub export fn uhdk_window_get_native( c.z_native_handles(object.native, out); return abi.OK; } + +pub export fn uhdk_window_create(handle: ?*c.uhdk_session, desc: [*c]const c.uhdk_window_desc, out: [*c]?*c.uhdk_window) abi.Status { + if (out == null) return abi.INVALID; + out.* = null; + if (handle == null or !abi.validDescriptor(c.uhdk_window_desc, desc) or desc.*.reserved != 0) return abi.INVALID; + const a = runtime.fromAppHandle(handle); + if (runtime.checkThread(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; + if (a.session_active) return c.UHDK_STATUS_BUSY; + const session = @import("session.zig"); + const d: c.z_window_desc = .{ + .struct_size = @sizeOf(c.z_window_desc), + .flags = 0, + .style = desc.*.style, + .title = desc.*.title, + .content_size = desc.*.content_size, + .min_size = desc.*.min_size, + .max_size = desc.*.max_size, + .parent = desc.*.parent, + }; + var status = session.release(a); + if (status != abi.OK) return status; + var window: ?*c.uhdk_window = null; + status = queueCreate(handle, &d, &window); + if (status == abi.OK) status = session.ready(a, window, runtime.now(a.io) +| a.startup_timeout_ns); + if (status != abi.OK and window != null) runtime.destroyObject(runtime.fromObjectHandle(window)); + const restored = session.acquire(a); + if (restored != abi.OK) { + a.session_status = restored; + if (status == abi.OK) runtime.destroyObject(runtime.fromObjectHandle(window)); + return restored; + } + if (status == abi.OK) out.* = window; + return status; +} + +pub export fn uhdk_window_destroy(window: ?*c.uhdk_window) abi.Status { + if (window == null) return abi.OK; + const object = runtime.fromObjectHandle(window); + const status = runtime.checkObject(object, c.Z_KIND_WINDOW); + if (status != abi.OK) return status; + if (object.app.session_window == window) return abi.INVALID; + runtime.destroyObject(object); + return abi.OK; +} diff --git a/src/callbacks.zig b/src/callbacks.zig index 3446d48..e9cf712 100644 --- a/src/callbacks.zig +++ b/src/callbacks.zig @@ -4,12 +4,12 @@ const c = @import("native"); const abi = @import("abi.zig"); const runtime = @import("runtime.zig"); -export fn z_emit(handle: ?*c.uhdk_app, event: [*c]const c.z_event) void { +export fn z_emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void { runtime.emit(handle, event); } export fn z_complete( - handle: ?*c.uhdk_app, + handle: ?*c.uhdk_session, id: u64, status: abi.Status, result: [*c]const c.z_request_result, @@ -29,7 +29,7 @@ export fn z_object_kind(handle: ?*anyopaque) u32 { return runtime.fromObjectHandle(handle).kind(); } -export fn z_object_app(handle: ?*anyopaque) ?*c.uhdk_app { +export fn z_object_app(handle: ?*anyopaque) ?*c.uhdk_session { return runtime.toAppHandle(runtime.fromObjectHandle(handle).app); } @@ -45,7 +45,7 @@ export fn z_metrics(handle: ?*c.uhdk_window, value: [*c]const c.uhdk_window_metr c.z_emit(runtime.toAppHandle(object.app), &event); } -export fn z_preferences(handle: ?*c.uhdk_app, value: [*c]const c.uhdk_preferences) void { +export fn z_preferences(handle: ?*c.uhdk_session, value: [*c]const c.uhdk_preferences) void { const application = runtime.fromAppHandle(handle); application.lock(); application.preferences = value.*; @@ -81,7 +81,7 @@ export fn z_file_init( } export fn z_file_from_url( - handle: ?*c.uhdk_app, + handle: ?*c.uhdk_session, path: c.uhdk_bytes, grant: ?*anyopaque, ) ?*c.uhdk_file { @@ -104,11 +104,11 @@ export fn z_menu_items(handle: ?*c.uhdk_menu, len: [*c]u64) [*c]const c.uhdk_men return object.payload.menu.items.ptr; } -export fn z_dispatch(handle: ?*c.uhdk_app) void { +export fn z_dispatch(handle: ?*c.uhdk_session) void { runtime.dispatch(handle); } -export fn z_native_failed(handle: ?*c.uhdk_app, status: abi.Status) void { +export fn z_native_failed(handle: ?*c.uhdk_session, status: abi.Status) void { const app = runtime.fromAppHandle(handle); app.lock(); app.native_error = status; diff --git a/src/core_tests.zig b/src/core_tests.zig index d506a78..11297f6 100644 --- a/src/core_tests.zig +++ b/src/core_tests.zig @@ -55,8 +55,8 @@ test "accepted request gets one terminal result when cancellation wins" { const application = try Application.create(std.testing.allocator, std.testing.io, "requests"); defer destroyApplication(application); application.running = true; - application.use_application_thread = true; - application.worker_id = std.Thread.getCurrentId(); + + application.main_thread = std.Thread.getCurrentId(); const command = try runtime.createCommand(application, c.Z_CLIP_READ, null); var request_id: u64 = 0; try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_OK), runtime.submit(application, command, &request_id)); @@ -87,8 +87,8 @@ test "public payload scratch lifetime empty polls and resource pins" { const application = try Application.create(std.testing.allocator, std.testing.io, "payloads"); defer destroyApplication(application); application.running = true; - application.use_application_thread = true; - application.worker_id = std.Thread.getCurrentId(); + + application.main_thread = std.Thread.getCurrentId(); const handle = runtime.toAppHandle(application); const file = try runtime.createObject(application, c.Z_KIND_FILE); defer runtime.release(file); @@ -99,16 +99,16 @@ test "public payload scratch lifetime empty polls and resource pins" { runtime.emit(handle, &event); try std.testing.expectEqual(@as(usize, 2), file.refs); var batch: c.uhdk_event_list = undefined; - try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_poll_events(handle, 0, &batch)); + try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch)); try std.testing.expectEqual(@as(u64, 1), batch.len); try std.testing.expectEqual(@as(u64, @sizeOf(c.uhdk_file_list)), batch.ptr[0].data_size); const payload: *const c.uhdk_file_list = @ptrCast(@alignCast(batch.ptr[0].data.?)); try std.testing.expectEqual(@intFromPtr(file), @intFromPtr(payload.ptr[0].?)); try std.testing.expectEqual(@as(usize, 2), file.refs); // Invalid calls must not reset a borrow. Valid empty polls must release it. - try std.testing.expectEqual(@as(abi.Status, abi.INVALID), app_api.uhdk_app_poll_events(handle, 0, null)); + try std.testing.expectEqual(@as(abi.Status, abi.INVALID), app_api.poll(handle, 0, null)); try std.testing.expectEqual(@as(u64, 1), payload.len); - try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_poll_events(handle, 0, &batch)); + try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch)); try std.testing.expectEqual(@as(u64, 0), batch.len); try std.testing.expectEqual(@as(usize, 1), file.refs); try std.testing.expectEqual(@as(usize, 0), application.scratch.usage()); @@ -120,8 +120,8 @@ test "poll allocation failure keeps queued terminal completion retryable" { const application = try Application.create(failing.allocator(), std.testing.io, "retry"); defer destroyApplication(application); application.running = true; - application.use_application_thread = true; - application.worker_id = std.Thread.getCurrentId(); + + application.main_thread = std.Thread.getCurrentId(); const handle = runtime.toAppHandle(application); var bytes = [_]u8{42} ** 20000; var event = std.mem.zeroes(c.z_event); @@ -131,11 +131,11 @@ test "poll allocation failure keeps queued terminal completion retryable" { @memset(&bytes, 0); failing.fail_index = failing.alloc_index; var batch: c.uhdk_event_list = undefined; - try std.testing.expectEqual(@as(abi.Status, abi.OOM), app_api.uhdk_app_poll_events(handle, 0, &batch)); + try std.testing.expectEqual(@as(abi.Status, abi.OOM), app_api.poll(handle, 0, &batch)); try std.testing.expectEqual(@as(u64, 0), batch.len); try std.testing.expect(application.pending_head != null); failing.fail_index = std.math.maxInt(usize); - try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_poll_events(handle, 0, &batch)); + try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch)); try std.testing.expectEqual(@as(u64, 1), batch.len); const result: *const c.uhdk_request_result = @ptrCast(@alignCast(batch.ptr[0].data.?)); try std.testing.expectEqual(@as(u64, 123), result.id); @@ -145,28 +145,10 @@ test "poll allocation failure keeps queued terminal completion retryable" { try std.testing.expect(application.pending_head == null); // Producer payload storage has been freed; the public copy is in scratch. try std.testing.expectEqual(@as(usize, 0), application.published.?.arena.queryCapacity()); - try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_poll_events(handle, 0, &batch)); + try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch)); try std.testing.expectEqual(@as(u64, 0), batch.len); } -test "READY precedes native startup events without being published on failed startup" { - const application = try Application.create(std.testing.allocator, std.testing.io, "startup"); - defer destroyApplication(application); - const failed = try runtime.prepareReady(application); - try std.testing.expect(application.pending_head == null); - runtime.destroyEvent(failed); - const ready = try runtime.prepareReady(application); - runtime.simpleEvent(application, c.UHDK_EVENT_PREFERENCES_CHANGED); - const preferences = application.pending_head.?; - runtime.publishReady(application, ready); - runtime.simpleEvent(application, c.UHDK_EVENT_WAKE); - try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_READY), application.pending_head.?.event.type); - try std.testing.expect(ready.next == preferences); - try std.testing.expect(ready.event.time_ns <= preferences.event.time_ns); - try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_WAKE), preferences.next.?.event.type); - try std.testing.expect(application.pending_tail == preferences.next); -} - test { _ = @import("linux/WindowState.zig"); } @@ -217,12 +199,12 @@ const IoGate = struct { test "blocked file execution leaves event polling live and cancellation drains once" { const app_api = @import("api/app.zig"); - for ([_]bool{ false, true }) |threaded| { + { const application = try Application.create(std.testing.allocator, std.testing.io, "io gate"); defer destroyApplication(application); application.running = true; - application.use_application_thread = threaded; - application.worker_id = std.Thread.getCurrentId(); + + application.main_thread = std.Thread.getCurrentId(); const handle = runtime.toAppHandle(application); var gate: IoGate = .{ .io = application.io }; application.io_test_hook = .{ .context = &gate, .before = IoGate.block }; @@ -245,11 +227,11 @@ test "blocked file execution leaves event polling live and cancellation drains o try gate.entered.waitTimeout(application.io, .{ .duration = .{ .raw = .fromSeconds(5), .clock = .awake } }); runtime.simpleEvent(application, c.UHDK_EVENT_WAKE); var events: c.uhdk_event_list = undefined; - try std.testing.expectEqual(@as(u32, abi.OK), app_api.uhdk_app_poll_events(handle, 0, &events)); + try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events)); try std.testing.expectEqual(@as(u64, 1), events.len); try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_WAKE), events.ptr[0].type); // Shutdown is requested while the OS operation is still blocked. - app_api.uhdk_app_quit(handle); + app_api.uhdk_quit(handle); runtime.dispatch(handle); try std.testing.expect(!application.stopped_sent); gate.release.set(application.io); @@ -263,13 +245,13 @@ test "blocked file execution leaves event polling live and cancellation drains o try std.testing.expect(runtime.now(application.io) < deadline); try (std.Io.Clock.Duration{ .raw = .fromMilliseconds(1), .clock = .awake }).sleep(application.io); } - try std.testing.expectEqual(@as(u32, abi.OK), app_api.uhdk_app_poll_events(handle, 0, &events)); + try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events)); try std.testing.expectEqual(@as(u64, 2), events.len); const result: *const c.uhdk_request_result = @ptrCast(@alignCast(events.ptr[0].data.?)); try std.testing.expectEqual(id, result.id); try std.testing.expectEqual(@as(u32, abi.CANCELLED), result.status); try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_STOPPED), events.ptr[1].type); - try std.testing.expectEqual(@as(u32, abi.UNAVAILABLE), app_api.uhdk_app_poll_events(handle, 0, &events)); + try std.testing.expectEqual(@as(u32, abi.UNAVAILABLE), app_api.poll(handle, 0, &events)); try std.testing.expectEqual(@as(usize, 0), application.io_pending); } } @@ -278,8 +260,8 @@ test "file queue saturation rejects without accepting an ID" { const application = try Application.create(std.testing.allocator, std.testing.io, "io limit"); defer destroyApplication(application); application.running = true; - application.use_application_thread = true; - application.worker_id = std.Thread.getCurrentId(); + + application.main_thread = std.Thread.getCurrentId(); const file = try runtime.createObject(application, c.Z_KIND_FILE); defer runtime.release(file); for (0..64) |_| { @@ -301,10 +283,10 @@ test "fatal native failure persists and wakes subsequent polls" { const application = try Application.create(std.testing.allocator, std.testing.io, "native failure"); defer destroyApplication(application); application.running = true; - application.use_application_thread = true; - application.worker_id = std.Thread.getCurrentId(); + + application.main_thread = std.Thread.getCurrentId(); const handle = runtime.toAppHandle(application); c.z_native_failed(handle, c.UHDK_STATUS_OS_ERROR); var events: c.uhdk_event_list = undefined; - for (0..2) |_| try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_OS_ERROR), app_api.uhdk_app_poll_events(handle, c.UHDK_WAIT_FOREVER, &events)); + for (0..2) |_| try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_OS_ERROR), app_api.poll(handle, std.math.maxInt(u64), &events)); } diff --git a/src/gl_loader.c b/src/gl_loader.c index 39981ee..cc0c068 100644 --- a/src/gl_loader.c +++ b/src/gl_loader.c @@ -2,18 +2,20 @@ #define gladLoadGLContextUserPtr z_gladLoadGLContextUserPtr #define gladLoadGLContext z_gladLoadGLContext #define UHDK_ENABLE_OPENGL -#define UHDK_GLAD_GL_IMPLEMENTATION +#define GLAD_GL_IMPLEMENTATION +#include "glad/gl.h" +#undef GLAD_GL_IMPLEMENTATION #include "native.h" #include static GLADapiproc resolve(void *user, const char *name) { uhdk_gl_proc proc = NULL; uhdk_text symbol = {name, strlen(name)}; - if (uhdk_gl_context_get_proc(user, symbol, &proc) != UHDK_STATUS_OK) + if (z_native_gl_proc(user, symbol, &proc) != UHDK_STATUS_OK) return NULL; return (GLADapiproc)proc; } -int32_t z_gl_load(uhdk_gl_context *context, uhdk_gl_functions *functions) { +int32_t z_gl_load(void *context, uhdk_gl_functions *functions) { return gladLoadGLContextUserPtr(functions, resolve, context) && functions->VERSION_3_3; } diff --git a/src/linux/Egl.zig b/src/linux/Egl.zig index f902fbf..5ddfd5a 100644 --- a/src/linux/Egl.zig +++ b/src/linux/Egl.zig @@ -43,7 +43,7 @@ pub fn finish(b: *native.Backend) void { } } pub fn create(b: *native.Backend, w: *native.Window, object: ?*anyopaque) u32 { - if (b.egl_display == null or w.flags & n.UHDK_WINDOW_OPENGL == 0) return n.UHDK_STATUS_UNSUPPORTED; + if (b.egl_display == null or w.flags & n.Z_WINDOW_OPENGL == 0) return n.UHDK_STATUS_UNSUPPORTED; if (w.egl != null) return n.UHDK_STATUS_BUSY; if (c.z_eglBindAPI.?(c.EGL_OPENGL_API) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR; const attrs = [_]c.EGLint{ c.EGL_CONTEXT_MAJOR_VERSION, 3, c.EGL_CONTEXT_MINOR_VERSION, 3, c.EGL_CONTEXT_OPENGL_PROFILE_MASK, c.EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, c.EGL_NONE }; @@ -120,18 +120,6 @@ pub fn call(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 { n.z_native_wake(); return abi.OK; }, - 3 => return if (makeCurrent(b, ctx)) abi.OK else n.UHDK_STATUS_OS_ERROR, - 5 => { - if (c.z_eglGetCurrentContext.?() != ctx.context) return n.UHDK_STATUS_BUSY; - const address = c.z_eglGetProcAddress.?("glGetIntegerv") orelse return n.UHDK_STATUS_NOT_FOUND; - const get_integer: *const fn (c_uint, *c_int) callconv(.c) void = @ptrCast(address); - var major: c_int = 0; - var minor: c_int = 0; - get_integer(0x821B, &major); // GL_MAJOR_VERSION - get_integer(0x821C, &minor); // GL_MINOR_VERSION - const version: *[2]u32 = @ptrCast(@alignCast(out.?)); - version.* = .{ @intCast(major), @intCast(minor) }; - }, 6 => { if (b.failed.load(.acquire)) return abi.UNAVAILABLE; if (!ctx.window.visible or !ctx.window.configured) return abi.UNAVAILABLE; diff --git a/src/linux/README.md b/src/linux/README.md index 4324c87..4d322f7 100644 --- a/src/linux/README.md +++ b/src/linux/README.md @@ -41,7 +41,7 @@ means the mechanism is available, not that every context creation must succeed. `AUTO` selects Wayland; explicit X11 requests return `UNSUPPORTED`. Before a successful run, the Linux backend query returns `AUTO` and all capabilities are -false. Startup discovers the registry before publishing `READY`. The protocol +false. Startup discovers the registry before `uhdk_open` returns. The protocol handshake and initial window configure have five-second deadlines. Display failure requests shutdown and cancels pending work; it never switches backends. @@ -88,7 +88,7 @@ NixOS with Plasma 6.5.6 and Mesa 25.2.6; other systems are not runtime-qualified lacks it returns `UNSUPPORTED`; a libdecor adapter is future work. Undecorated windows remain possible, and `uhdk_window_set_style` can switch the decoration request at runtime. No desktop-name checks or Qt/KDE linkage are used. -- The application ID is copied from `uhdk_app_desc` and sent as the xdg-toplevel +- The application ID is copied from `uhdk_options` and sent as the xdg-toplevel app ID. Applications own their desktop-file and icon installation. - A window is created hidden after its first configure. Showing requests mapping; the first successful buffer swap supplies its content. `visible` is the @@ -105,13 +105,11 @@ NixOS with Plasma 6.5.6 and Mesa 25.2.6; other systems are not runtime-qualified integer buffer scale is used when wl_surface v6 is available. Older compositors without those mechanisms currently use scale 1. Fractional/mixed-DPI behavior still needs runtime validation. -- Native requests and protocol dispatch run on the OS main thread. With - `use_application_thread=0`, application polling pumps that work on main; with - `1`, a separate application thread polls the event queue while main runs native - services. File execution/watch preparation use an internal worker in either - layout. GL work runs on the selected application thread. Main-thread drawable updates use a nonblocking lock - attempt; the dispatcher never waits behind an in-progress swap. End-frame wakes - it to retry deferred updates. +- Native requests, protocol dispatch and application GL work run on OS main. + The session frame boundaries release GL ownership before pumping native work. + File execution/watch preparation use an independent internal worker. Long + application updates delay native dispatch; there is no attached render thread. + - Hiding replaces the EGL presentation surface so an outstanding frame callback cannot hang remapping. The GL context and its application-owned resources survive. Swapping a hidden/unconfigured window returns `UNAVAILABLE`. @@ -155,7 +153,7 @@ NixOS with Plasma 6.5.6 and Mesa 25.2.6; other systems are not runtime-qualified support filters, initial directories, suggested names and multiple selection. A private D-Bus connection subscribes before submission, correlates early responses, closes cancelled requests, and handles portal-owner changes. - Portal discovery is asynchronous, so its capability can appear after `READY`. + Portal discovery is asynchronous, so its capability can appear after `uhdk_open` returns. Connection/method setup is bounded; human interaction has no timeout. URL handoff includes an activation token when recent focused input permits it. - Portal Settings supplies appearance, contrast and reduced-motion preferences diff --git a/src/linux/native.zig b/src/linux/native.zig index 17e9c18..50b1979 100644 --- a/src/linux/native.zig +++ b/src/linux/native.zig @@ -1,5 +1,5 @@ //! Wayland platform owner. Protocol dispatch and native commands stay on the OS -//! thread; the application thread holds each window's lock only while rendering. +//! thread; session boundaries release GL ownership before native dispatch. const std = @import("std"); const c = @import("linux_c"); const n = @import("native"); @@ -83,12 +83,12 @@ pub const Backend = struct { pub var instance: ?*Backend = null; var wake_fd: std.atomic.Value(c_int) = .init(-1); -pub fn backend(handle: ?*n.uhdk_app) u32 { +pub fn backend(handle: ?*n.uhdk_session) u32 { if (handle == null) return n.UHDK_BACKEND_AUTO; const app = runtime.fromAppHandle(handle); return if (app.has_run) n.UHDK_BACKEND_WAYLAND else n.UHDK_BACKEND_AUTO; } -pub fn capability(handle: ?*n.uhdk_app, cap: u32) n.uhdk_bool { +pub fn capability(handle: ?*n.uhdk_session, cap: u32) n.uhdk_bool { if (handle == null) return 0; const b = instance orelse return 0; if (b.app != runtime.fromAppHandle(handle) or !b.app.running or b.failed.load(.acquire)) return 0; @@ -103,7 +103,7 @@ pub fn setCapability(cap: u32, available: bool) void { export fn z_native_is_main_thread() c_int { return c.z_linux_is_main_thread(); } -export fn z_native_start(handle: ?*n.uhdk_app, _: n.uhdk_text) u32 { +export fn z_native_start(handle: ?*n.uhdk_session, _: n.uhdk_text) u32 { const app = runtime.fromAppHandle(handle); if (c.z_linux_libraries_open() == 0) return abi.UNAVAILABLE; const b = app.gpa.create(Backend) catch { @@ -149,7 +149,7 @@ export fn z_native_start(handle: ?*n.uhdk_app, _: n.uhdk_text) u32 { return abi.OK; } // Startup also uses a bounded read/flush/poll handshake: an unresponsive -// compositor must not trap app_run before the application thread even starts. +// compositor must not trap uhdk_open before returning a session. fn initialRegistry(b: *Backend) bool { var done = false; const callback = c.wl_display_sync(b.display) orelse return false; @@ -220,14 +220,6 @@ export fn z_native_wake() void { export fn z_native_again() void { z_native_wake(); } -export fn z_native_stop() void { - if (instance) |b| b.running = false; -} -export fn z_native_pool_push() ?*anyopaque { - return null; -} -export fn z_native_pool_pop(_: ?*anyopaque) void {} - fn fail(b: *Backend) void { if (b.failed.swap(true, .acq_rel)) return; b.app.lock(); @@ -306,7 +298,7 @@ export fn z_native_pump(timeout_ns: u64) void { break :pump; }; b.app.lock(); - const queued = !b.app.use_application_thread and (b.app.pending_head != null or b.app.native_error != abi.OK); + const queued = (b.app.pending_head != null or b.app.native_error != abi.OK); b.app.unlock(); const wait_ns: u64 = if (queued) 0 else timeout_ns; const budget: c_int = if (wait_ns == std.math.maxInt(u64)) -1 else @intCast(@min(std.math.maxInt(c_int), wait_ns / std.time.ns_per_ms + @intFromBool(wait_ns % std.time.ns_per_ms != 0))); @@ -327,11 +319,6 @@ export fn z_native_pump(timeout_ns: u64) void { } } -export fn z_native_run() void { - const b = instance.?; - while (b.running and !b.failed.load(.acquire)) z_native_pump(std.math.maxInt(u64)); -} - fn registryGlobal(data: ?*anyopaque, registry: ?*c.struct_wl_registry, name: u32, interface: [*c]const u8, version: u32) callconv(.c) void { const b: *Backend = @ptrCast(@alignCast(data.?)); const str = std.mem.span(interface); @@ -490,7 +477,7 @@ fn createWindow(b: *Backend, command: *const n.z_command, id: u64) u32 { c.wl_surface_commit(w.surface); // Empty initial commit; wait for configure. return n.Z_DEFERRED; } -fn setupWindow(b: *Backend, w: *Window, desc: n.uhdk_window_desc) u32 { +fn setupWindow(b: *Backend, w: *Window, desc: n.z_window_desc) u32 { const title = b.app.gpa.dupeZ(u8, abi.textBytes(desc.title)) catch return abi.OOM; defer b.app.gpa.free(title); const app_id = b.app.gpa.dupeZ(u8, b.app.application_id) catch return abi.OOM; @@ -580,7 +567,7 @@ fn destroyWindow(w: *Window) void { if (w.surface != null) c.wl_surface_destroy(w.surface); w.owner.gpa.destroy(w); } -export fn z_native_execute(_: ?*n.uhdk_app, raw: [*c]const n.z_command, id: u64, _: [*c]n.z_request_result) u32 { +export fn z_native_execute(_: ?*n.uhdk_session, raw: [*c]const n.z_command, id: u64, _: [*c]n.z_request_result) u32 { const b = instance.?; const cmd: *const n.z_command = &raw.*; if (cmd.op == n.Z_DESTROY) { diff --git a/src/linux/tests/menus.c b/src/linux/tests/menus.c index 9e669d6..49d3f88 100644 --- a/src/linux/tests/menus.c +++ b/src/linux/tests/menus.c @@ -1,19 +1,19 @@ /* Included by the service harness: all desktop traffic uses private fixtures. */ #define OPEN_ID UINT64_C(0x1234567800000065) -static void menu_phase(uhdk_app *app, uhdk_window *w, const char *phase) { +static void menu_phase(uhdk_session *app, uhdk_window *w, const char *phase) { OK(uhdk_window_set_title(w, text(phase))); uhdk_window_invalidate(w); for (;;) { uhdk_event_list events; - OK(uhdk_app_poll_events(app, 50000000, &events)); + OK(test_frame_events(app, &events)); for (uint64_t i = 0; i < events.len; ++i) if (events.ptr[i].type == UHDK_EVENT_WINDOW_REDRAW && events.ptr[i].window == w) return; } } -static void menus(uhdk_app *app) { +static void menus(uhdk_session *app) { wait_capability(app, UHDK_CAP_APP_MENU); - assert(!uhdk_app_has_capability(app, UHDK_CAP_CONTEXT_MENU)); + assert(!uhdk_has_capability(app, UHDK_CAP_CONTEXT_MENU)); uhdk_menu_item children[] = { {.command_id = OPEN_ID, .label = {"Open_file", 9}, @@ -37,7 +37,7 @@ static void menus(uhdk_app *app) { OK(uhdk_menu_create(app, roots, 2, &root)); uhdk_menu_release(child); uint64_t id; - OK(uhdk_app_set_menu(app, root)); + OK(uhdk_set_menu(app, root)); uhdk_window *a = window(app), *b = window(app); uhdk_menu_item overrides[] = { {.command_id = 200, .label = {"Window action", 13}}, @@ -57,9 +57,9 @@ static void menus(uhdk_app *app) { unsigned stage = 0, opens_a = 0, opens_b = 0, copies = 0, quits = 0, overrides_seen = 0, raw_o = 0; uint64_t end = deadline(app); - while (stage < 4 && uhdk_app_get_time_ns(app) < end) { + while (stage < 4 && uhdk_get_time_ns(app) < end) { uhdk_event_list events; - OK(uhdk_app_poll_events(app, 50000000, &events)); + OK(test_frame_events(app, &events)); int next = 0; for (uint64_t i = 0; i < events.len; ++i) { const uhdk_event *e = &events.ptr[i]; @@ -118,30 +118,30 @@ static void menus(uhdk_app *app) { OK(uhdk_menu_create(app, overrides, 2, &override)); OK(uhdk_window_set_menu(b, override)); uhdk_menu_release(override); - OK(uhdk_app_set_menu(app, NULL)); + OK(uhdk_set_menu(app, NULL)); uhdk_menu_release(root); uhdk_window_destroy(a); menu_phase(app, b, "detached-ready"); } } assert(stage == 4); - assert(!uhdk_app_has_capability(app, UHDK_CAP_APP_MENU)); + assert(!uhdk_has_capability(app, UHDK_CAP_APP_MENU)); uhdk_window_destroy(b); puts("Plasma menu routing/state/lifetime/shortcut fixture: PASS"); } #undef OPEN_ID -static void menus_unavailable(uhdk_app *app, int no_bus) { +static void menus_unavailable(uhdk_session *app, int no_bus) { uhdk_window *w = window(app); uhdk_menu_item item = {.command_id = 1, .label = {"Unavailable", 11}}; uhdk_menu *menu; OK(uhdk_menu_create(app, &item, 1, &menu)); (void)no_bus; - OK(uhdk_app_set_menu(app, menu)); + OK(uhdk_set_menu(app, menu)); OK(uhdk_window_set_menu(w, menu)); - assert(!uhdk_app_has_capability(app, UHDK_CAP_APP_MENU)); + assert(!uhdk_has_capability(app, UHDK_CAP_APP_MENU)); OK(uhdk_menu_set_item_flags(menu, 1, UHDK_MENU_CHECKED)); - OK(uhdk_app_set_menu(app, NULL)); + OK(uhdk_set_menu(app, NULL)); uhdk_menu_release(menu); uhdk_window_destroy(w); puts("Unavailable menu protocol/session bus: PASS"); diff --git a/src/linux/tests/native.c b/src/linux/tests/native.c index 17e253e..d1e5fce 100644 --- a/src/linux/tests/native.c +++ b/src/linux/tests/native.c @@ -1,236 +1,133 @@ #define UHDK_ENABLE_OPENGL #define UHDK_ENABLE_NATIVE #include "uhdk.h" +#include "../../test_frame.h" #include #include #include #include -#define OK(expression) \ - do { \ - uhdk_status status = (expression); \ - if (status != UHDK_STATUS_OK) { \ - fprintf(stderr, "%s:%d: %s returned %u\n", __FILE__, __LINE__, #expression, status); \ - abort(); \ - } \ - } while (0) +#define OK(expr) assert((expr) == UHDK_STATUS_OK) static uhdk_text text(const char *s) { return (uhdk_text){s, strlen(s)}; } -static int entered; - -static uhdk_window_metrics metrics(uhdk_window *w) { - uhdk_window_metrics m = {0}; - m.struct_size = sizeof(m); - OK(uhdk_window_get_metrics(w, &m)); - return m; -} - -static void wait_metrics(uhdk_app *app, uhdk_window *w, int visible, int width) { - uint64_t deadline = uhdk_app_get_time_ns(app) + 10000000000ull; - while (uhdk_app_get_time_ns(app) < deadline) { - uhdk_window_metrics m = metrics(w); - if (m.visible == visible && m.logical_size.width == width) - return; - uhdk_event_list events; - OK(uhdk_app_poll_events(app, 100000000ull, &events)); - } - fputs("Timed out awaiting metrics\n", stderr); - abort(); -} - -static uhdk_window_desc descriptor(void) { - uhdk_window_desc desc = {0}; - desc.struct_size = sizeof(desc); - desc.title = text("UHDK Linux lifecycle test"); - desc.flags = UHDK_WINDOW_OPENGL; - desc.style = (uhdk_window_style){sizeof(uhdk_window_style), 1, 1, 0}; - desc.content_size = (uhdk_size){320, 240}; - return desc; -} - -static uhdk_window *create_window(uhdk_app *app) { - uhdk_window_desc desc = descriptor(); - uhdk_window *result = NULL; - OK(uhdk_window_create(app, &desc, &result)); - wait_metrics(app, result, 0, 320); +static uhdk_window_metrics metrics(uhdk_window *window) { + uhdk_window_metrics result = {0}; + result.struct_size = sizeof(result); + OK(uhdk_window_get_metrics(window, &result)); return result; } - -static void begin_context(uhdk_app *app, uhdk_gl_context *context) { - uint64_t deadline = uhdk_app_get_time_ns(app) + 10000000000ull; - while (uhdk_app_get_time_ns(app) < deadline) { - uhdk_status status = uhdk_gl_context_begin_frame(context); - if (status == UHDK_STATUS_OK) +static void wait_metrics(uhdk_session *session, uhdk_window *window, int visible, int width) { + uint64_t deadline = uhdk_get_time_ns(session) + 10000000000ULL; + for (;;) { + uhdk_window_metrics m = metrics(window); + if (m.visible == visible && m.logical_size.width == width) return; - assert(status == UHDK_STATUS_UNAVAILABLE); + assert(uhdk_get_time_ns(session) < deadline); uhdk_event_list events; - OK(uhdk_app_poll_events(app, 100000000ull, &events)); - for (uint64_t i = 0; i < events.len; ++i) - if (events.ptr[i].type == UHDK_EVENT_RESOURCE_FAILED) - OK(((const uhdk_resource_event *)events.ptr[i].data)->status); + OK(test_frame_events(session, &events)); } - abort(); } - -static void test_main(uhdk_app *app, void *user) { - ++entered; - assert(uhdk_app_get_backend(app) == UHDK_BACKEND_WAYLAND); - assert(!uhdk_app_has_capability(app, UHDK_CAP_FILE_DIALOGS)); - uhdk_event_list ready; - OK(uhdk_app_poll_events(app, 0, &ready)); - assert(ready.len > 0 && ready.ptr[0].type == UHDK_EVENT_READY); - - // Pending creation can be destroyed before the first configure. - uhdk_window_desc desc = descriptor(); - uhdk_window *pending = NULL; - OK(uhdk_window_create(app, &desc, &pending)); - uhdk_window_destroy(pending); - - // Destroying a parent must also complete a child still awaiting configure. - uhdk_window *parent = create_window(app); - desc.parent = parent; - uhdk_window *child = NULL; - OK(uhdk_window_create(app, &desc, &child)); - uhdk_window_destroy(parent); - desc.parent = NULL; - - uhdk_window *w = create_window(app); - assert(metrics(w).visible == 0); +static void windows(uhdk_session *session) { + uhdk_window_desc desc = {0}; + desc.struct_size = sizeof(desc); + desc.title = text("UHDK additional window"); + desc.style = (uhdk_window_style){sizeof(uhdk_window_style), 1, 1, 0}; + desc.content_size = (uhdk_size){320, 240}; + uhdk_window *window = NULL; + OK(uhdk_window_create(session, &desc, &window)); + assert(metrics(window).logical_size.width == 320); /* Ready on return. */ + assert(!metrics(window).visible); uhdk_native_window native = {0}; native.struct_size = sizeof(native); - OK(uhdk_window_get_native(w, &native)); + OK(uhdk_window_get_native(window, &native)); assert(native.backend == UHDK_BACKEND_WAYLAND && native.primary && native.secondary); uhdk_window_style style = {sizeof(style), 0, 0, 0}; - OK(uhdk_window_set_style(w, &style)); - style.decorated = 1; - style.resizable = 1; - OK(uhdk_window_set_style(w, &style)); - + OK(uhdk_window_set_style(window, &style)); + style.decorated = style.resizable = 1; + OK(uhdk_window_set_style(window, &style)); + desc.parent = window; + uhdk_window *child = NULL; + OK(uhdk_window_create(session, &desc, &child)); + OK(uhdk_window_destroy(child)); + for (int pass = 0; pass < 3; ++pass) { + OK(uhdk_window_set_size(window, (uhdk_size){320 + pass * 20, 240})); + OK(uhdk_window_set_visible(window, 1)); + wait_metrics(session, window, 1, 320 + pass * 20); + OK(uhdk_window_set_visible(window, 0)); + wait_metrics(session, window, 0, 320 + pass * 20); + } + OK(uhdk_window_destroy(window)); + assert(uhdk_window_destroy(uhdk_get_window(session)) == UHDK_STATUS_INVALID_ARGUMENT); const uint8_t path[] = "/tmp/uhdk file-%\xff"; uhdk_file *file; - OK(uhdk_file_create_from_native_path(app, (uhdk_bytes){path, sizeof(path) - 1}, &file)); + OK(uhdk_file_create_from_native_path(session, (uhdk_bytes){path, sizeof(path) - 1}, &file)); uint8_t uri[256]; uint64_t len; OK(uhdk_file_copy_representation(file, UHDK_FILE_URI, uri, sizeof(uri), &len)); assert(len == strlen("file:///tmp/uhdk%20file-%25%FF")); assert(memcmp(uri, "file:///tmp/uhdk%20file-%25%FF", len) == 0); uhdk_file_release(file); - - if (!user) { - assert(uhdk_app_has_capability(app, UHDK_CAP_OPENGL)); - uhdk_gl_context *gl = NULL; - OK(uhdk_gl_context_create(w, &gl)); - begin_context(app, gl); - assert(uhdk_gl_context_begin_frame(gl) == UHDK_STATUS_BUSY); - uint32_t major, minor; - OK(uhdk_gl_context_get_version(gl, &major, &minor)); - assert(major > 3 || (major == 3 && minor >= 3)); - fprintf(stderr, "Linux context: OpenGL %u.%u\n", major, minor); - OK(uhdk_gl_clear_current(app)); - assert(uhdk_gl_context_get_version(gl, &major, &minor) == UHDK_STATUS_BUSY); - OK(uhdk_gl_context_make_current(gl)); - uhdk_gl_proc address; - OK(uhdk_gl_context_get_proc(gl, text("glClearColor"), &address)); - PFNGLCLEARCOLORPROC clear_color = (PFNGLCLEARCOLORPROC)address; - OK(uhdk_gl_context_get_proc(gl, text("glClear"), &address)); - PFNGLCLEARPROC clear = (PFNGLCLEARPROC)address; - OK(uhdk_gl_context_get_proc(gl, text("glReadPixels"), &address)); - PFNGLREADPIXELSPROC read_pixels = (PFNGLREADPIXELSPROC)address; - OK(uhdk_gl_context_set_swap_interval(gl, 1)); - assert(uhdk_gl_context_swap_buffers(gl) == UHDK_STATUS_UNAVAILABLE); - OK(uhdk_gl_context_end_frame(gl)); - - for (int pass = 0; pass < 3; ++pass) { - int width = 320 + pass * 20; - OK(uhdk_window_set_size(w, (uhdk_size){width, 240})); - OK(uhdk_window_set_visible(w, 1)); - wait_metrics(app, w, 1, width); - for (int frame = 0; frame < 4; ++frame) { - OK(uhdk_gl_context_begin_frame(gl)); - clear_color(0.25f, 0.5f, 0.75f, 1.0f); - clear(GL_COLOR_BUFFER_BIT); - unsigned char pixel[4] = {0}; - read_pixels(10, 10, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel); - assert( - pixel[0] >= 63 && pixel[0] <= 65 && pixel[1] >= 127 && pixel[1] <= 129 && - pixel[2] >= 190 && pixel[2] <= 192 - ); - OK(uhdk_gl_context_swap_buffers(gl)); - OK(uhdk_gl_context_end_frame(gl)); - } - OK(uhdk_window_set_visible(w, 0)); - wait_metrics(app, w, 0, width); +} +static void render(uhdk_session *session) { + const uhdk_gl_functions *gl = uhdk_get_gl(session); + assert(gl && gl->VERSION_3_3); + for (int i = 0; i < 4; ++i) { + uhdk_frame frame; + assert(uhdk_next_frame(session, &frame)); + if (frame.drawable) { + gl->ClearColor(0.25f, 0.5f, 0.75f, 1); + gl->Clear(GL_COLOR_BUFFER_BIT); + unsigned char pixel[4]; + gl->ReadPixels(10, 10, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel); + assert( + pixel[0] >= 63 && pixel[0] <= 65 && pixel[1] >= 127 && pixel[1] <= 129 && + pixel[2] >= 190 && pixel[2] <= 192 + ); } - uhdk_gl_context_destroy(gl); - // Destroying a context releases its reservation on the window. - OK(uhdk_gl_context_create(w, &gl)); - uhdk_gl_context_destroy(gl); + OK(uhdk_end_frame(session)); } - uhdk_window_destroy(w); - // Returning with a queued creation must cancel/drain it before native teardown. - OK(uhdk_window_create(app, &desc, &pending)); } - -static void disconnect_main(uhdk_app *app, void *user) { - (void)user; - ++entered; - puts("connected"); - fflush(stdout); - uint64_t deadline = uhdk_app_get_time_ns(app) + 5000000000ull; - int quit_seen = 0; - while (uhdk_app_get_time_ns(app) < deadline) { - uhdk_event_list events; - OK(uhdk_app_poll_events(app, 100000000ull, &events)); - for (uint64_t i = 0; i < events.len; ++i) { - if (events.ptr[i].type == UHDK_EVENT_QUIT_REQUESTED) - quit_seen = 1; - if (events.ptr[i].type == UHDK_EVENT_STOPPED) { - assert(quit_seen); - return; - } - } - } - abort(); -} - -static void should_not_run(uhdk_app *app, void *user) { - (void)app; - (void)user; - abort(); -} - int main(int argc, char **argv) { int failure = argc > 1 && strcmp(argv[1], "--startup-failure") == 0; int windows_only = argc > 1 && strcmp(argv[1], "--windows-only") == 0; int disconnect = argc > 1 && strcmp(argv[1], "--disconnect") == 0; - int passes = disconnect ? 1 : 2; - for (int pass = 0; pass < passes; ++pass) { - uhdk_app_desc desc = {0}; - desc.struct_size = sizeof(desc); - desc.abi_version = UHDK_ABI_VERSION; - desc.display_name = text("UHDK Linux test"); - char app_id[] = "org.uhdk.LifecycleTest"; - desc.application_id = text(app_id); - uhdk_app *app = NULL; - desc.preferred_backend = UHDK_BACKEND_X11; - assert(uhdk_app_create(&desc, &app) == UHDK_STATUS_UNSUPPORTED); - desc.preferred_backend = UHDK_BACKEND_AUTO; - OK(uhdk_app_create(&desc, &app)); - memset(app_id, 'x', sizeof(app_id) - 1); // Descriptor bytes are copied. - assert(uhdk_app_get_backend(app) == UHDK_BACKEND_AUTO); - assert(!uhdk_app_has_capability(app, UHDK_CAP_OPENGL)); + for (int pass = 0; pass < (disconnect ? 1 : 2); ++pass) { + uhdk_options options = {0}; + options.struct_size = sizeof(options); + options.title = text("UHDK Linux session test"); + options.application_id = text("org.uhdk.LifecycleTest"); + options.no_opengl = windows_only || disconnect || failure; + options.preferred_backend = UHDK_BACKEND_X11; + uhdk_session *session = NULL; + assert(uhdk_open(&options, &session) == UHDK_STATUS_UNSUPPORTED); + assert(!session); + options.preferred_backend = UHDK_BACKEND_AUTO; + uhdk_status status = uhdk_open(&options, &session); if (failure) { - assert(uhdk_app_run(app, should_not_run, NULL) != UHDK_STATUS_OK); - assert(uhdk_app_get_backend(app) == UHDK_BACKEND_AUTO); - } else if (disconnect) { - OK(uhdk_app_run(app, disconnect_main, NULL)); - } else - OK(uhdk_app_run(app, test_main, windows_only ? &windows_only : NULL)); - uhdk_app_destroy(app); + assert(status != UHDK_STATUS_OK && !session); + continue; + } + OK(status); + assert(uhdk_get_backend(session) == UHDK_BACKEND_WAYLAND); + if (disconnect) { + puts("connected"); + fflush(stdout); + uint64_t deadline = uhdk_get_time_ns(session) + 5000000000ULL; + uhdk_frame frame; + while (uhdk_next_frame(session, &frame)) { + assert(uhdk_get_time_ns(session) < deadline); + OK(uhdk_end_frame(session)); + } + assert(uhdk_get_status(session) != UHDK_STATUS_OK); + } else { + windows(session); + if (!windows_only) + render(session); + } + uhdk_close(session); } - assert(entered == (failure ? 0 : passes)); - fputs("Linux lifecycle: PASS\n", stderr); + puts("Linux session/window lifecycle: PASS"); return 0; } diff --git a/src/linux/tests/popups.c b/src/linux/tests/popups.c index fd81c93..acb314a 100644 --- a/src/linux/tests/popups.c +++ b/src/linux/tests/popups.c @@ -1,10 +1,10 @@ /* Included by services.c; driven by popup_fixture.py on a private compositor. */ #define POPUP_OPEN UINT64_C(0x1234567800000001) #define POPUP_CHILD UINT64_C(0xfedcba9800000002) -static void popups(uhdk_app *app) { +static void popups(uhdk_session *app) { uhdk_window *w = window(app); wait_capability(app, UHDK_CAP_CONTEXT_MENU); - assert(!uhdk_app_has_capability(app, UHDK_CAP_APP_MENU)); + assert(!uhdk_has_capability(app, UHDK_CAP_APP_MENU)); uint64_t id; OK(uhdk_window_set_visible(w, 1)); OK(uhdk_window_set_text_input(w, 1)); @@ -42,9 +42,9 @@ static void popups(uhdk_app *app) { uint64_t popup = 0, busy = 0, started = 0; unsigned commands = 0, complete = 0, busy_done = 0, changed = 0; uint64_t end = deadline(app); - while (!complete && uhdk_app_get_time_ns(app) < end) { + while (!complete && uhdk_get_time_ns(app) < end) { uhdk_event_list events; - OK(uhdk_app_poll_events(app, 20000000, &events)); + OK(test_frame_events(app, &events)); for (uint64_t j = 0; j < events.len; ++j) { const uhdk_event *e = &events.ptr[j]; if (e->type == UHDK_EVENT_POINTER_BUTTON) { @@ -53,7 +53,7 @@ static void popups(uhdk_app *app) { if (p->pressed) { assert(popup == 0); OK(uhdk_menu_popup_async(menu, w, p->position, &popup)); - started = uhdk_app_get_time_ns(app); + started = uhdk_get_time_ns(app); if (stage == 0) OK(uhdk_menu_popup_async(menu, w, p->position, &busy)); } @@ -85,7 +85,7 @@ static void popups(uhdk_app *app) { } else if (e->type == UHDK_EVENT_KEY || e->type == UHDK_EVENT_TEXT_COMMIT) assert(!"popup input leaked to application"); } - if (popup && !changed && uhdk_app_get_time_ns(app) - started > 100000000ull) { + if (popup && !changed && uhdk_get_time_ns(app) - started > 100000000ull) { if (stage == 5) OK(uhdk_request_cancel(app, popup)); if (stage == 6) { diff --git a/src/linux/tests/services.c b/src/linux/tests/services.c index fa039d2..8137935 100644 --- a/src/linux/tests/services.c +++ b/src/linux/tests/services.c @@ -1,5 +1,6 @@ #define _GNU_SOURCE #include "uhdk.h" +#include "../../test_frame.h" #include #include #include @@ -17,14 +18,14 @@ static uhdk_text text(const char *s) { return (uhdk_text){s, strlen(s)}; } -static uint64_t deadline(uhdk_app *app) { - return uhdk_app_get_time_ns(app) + 8000000000ull; +static uint64_t deadline(uhdk_session *app) { + return uhdk_get_time_ns(app) + 8000000000ull; } -static uhdk_request_result wait_result(uhdk_app *app, uint64_t id) { +static uhdk_request_result wait_result(uhdk_session *app, uint64_t id) { uint64_t end = deadline(app); - while (uhdk_app_get_time_ns(app) < end) { + while (uhdk_get_time_ns(app) < end) { uhdk_event_list events; - OK(uhdk_app_poll_events(app, 50000000, &events)); + OK(test_frame_events(app, &events)); for (uint64_t i = 0; i < events.len; ++i) if (events.ptr[i].type == UHDK_EVENT_REQUEST_DONE) { const uhdk_request_result *r = events.ptr[i].data; @@ -35,7 +36,7 @@ static uhdk_request_result wait_result(uhdk_app *app, uint64_t id) { fprintf(stderr, "request %lu timed out\n", (unsigned long)id); abort(); } -static uhdk_window *window(uhdk_app *app) { +static uhdk_window *window(uhdk_session *app) { uhdk_window_desc desc = {0}; desc.struct_size = sizeof(desc); desc.title = text("UHDK service tests"); @@ -44,25 +45,23 @@ static uhdk_window *window(uhdk_app *app) { uhdk_window *result = NULL; OK(uhdk_window_create(app, &desc, &result)); uint64_t end = deadline(app); - while (uhdk_app_get_time_ns(app) < end) { + while (uhdk_get_time_ns(app) < end) { uhdk_event_list events; - OK(uhdk_app_poll_events(app, 50000000, &events)); + OK(test_frame_events(app, &events)); for (uint64_t i = 0; i < events.len; ++i) { - if (events.ptr[i].type == UHDK_EVENT_RESOURCE_FAILED) - OK(((const uhdk_resource_event *)events.ptr[i].data)->status); if (events.ptr[i].type == UHDK_EVENT_WINDOW_METRICS && events.ptr[i].window == result) return result; } } abort(); } -static void wait_capability(uhdk_app *app, uint32_t cap) { +static void wait_capability(uhdk_session *app, uint32_t cap) { uint64_t end = deadline(app); - while (!uhdk_app_has_capability(app, cap) && uhdk_app_get_time_ns(app) < end) { + while (!uhdk_has_capability(app, cap) && uhdk_get_time_ns(app) < end) { uhdk_event_list events; - OK(uhdk_app_poll_events(app, 50000000, &events)); + OK(test_frame_events(app, &events)); } - assert(uhdk_app_has_capability(app, cap)); + assert(uhdk_has_capability(app, cap)); } static void write_file(const char *path, const char *bytes) { FILE *f = fopen(path, "wb"); @@ -70,11 +69,11 @@ static void write_file(const char *path, const char *bytes) { assert(fwrite(bytes, 1, strlen(bytes), f) == strlen(bytes)); assert(fclose(f) == 0); } -static void wait_change(uhdk_app *app, uhdk_watch *watch, uint32_t flag) { +static void wait_change(uhdk_session *app, uhdk_watch *watch, uint32_t flag) { uint64_t end = deadline(app); - while (uhdk_app_get_time_ns(app) < end) { + while (uhdk_get_time_ns(app) < end) { uhdk_event_list events; - OK(uhdk_app_poll_events(app, 50000000, &events)); + OK(test_frame_events(app, &events)); for (uint64_t i = 0; i < events.len; ++i) if (events.ptr[i].type == UHDK_EVENT_WATCH) { const uhdk_watch_event *e = events.ptr[i].data; @@ -87,7 +86,7 @@ static void wait_change(uhdk_app *app, uhdk_watch *watch, uint32_t flag) { fprintf(stderr, "watch flag %x timed out\n", flag); abort(); } -static void watches(uhdk_app *app) { +static void watches(uhdk_session *app) { char directory[] = "/tmp/uhdk-watch-XXXXXX"; assert(mkdtemp(directory)); char path[256], replacement[256]; @@ -119,11 +118,11 @@ static void watches(uhdk_app *app) { uhdk_file_release(file); puts("watch replacement/removal/recreation/invalidation: PASS"); } -static void real_desktop(uhdk_app *app) { +static void real_desktop(uhdk_session *app) { wait_capability(app, UHDK_CAP_FILE_DIALOGS); uhdk_preferences prefs = {0}; prefs.struct_size = sizeof(prefs); - OK(uhdk_app_get_preferences(app, &prefs)); + OK(uhdk_get_preferences(app, &prefs)); printf( "Portal available; appearance=%u, reduced_motion=%d, high_contrast=%d\n", prefs.appearance, @@ -139,12 +138,12 @@ static void real_desktop(uhdk_app *app) { image.height = 1; image.stride_bytes = 8; image.pixels = (uhdk_bytes){rgba, sizeof(rgba)}; - OK(uhdk_app_set_icon(app, &image)); + OK(uhdk_set_icon(app, &image)); // A hidden, unfocused window must not commandeer a later user's keystroke. OK(uhdk_clipboard_write_text(app, text("must not replace clipboard"))); uhdk_window_destroy(w); } -static void portals(uhdk_app *app) { +static void portals(uhdk_session *app) { wait_capability(app, UHDK_CAP_FILE_DIALOGS); uhdk_window *w = window(app); uhdk_file_dialog_desc desc = {0}; @@ -170,7 +169,7 @@ static void portals(uhdk_app *app) { assert(len == 14 && memcmp(bytes, "/tmp/a b%\xff.txt", 14) == 0); uhdk_preferences prefs = {0}; prefs.struct_size = sizeof(prefs); - OK(uhdk_app_get_preferences(app, &prefs)); + OK(uhdk_get_preferences(app, &prefs)); assert(prefs.appearance == UHDK_APPEARANCE_DARK && prefs.reduced_motion && prefs.high_contrast); uhdk_file *directory; OK( @@ -194,12 +193,12 @@ static void portals(uhdk_app *app) { OK(uhdk_file_dialog_show_async(app, &desc, &id)); // Allow method submission, then cancel while the mock withholds its reply. uhdk_event_list events; - OK(uhdk_app_poll_events(app, 100000000, &events)); + OK(test_frame_events(app, &events)); OK(uhdk_request_cancel(app, id)); assert(wait_result(app, id).status == UHDK_STATUS_CANCELLED); OK(uhdk_shell_open_url_async(app, text("https://example.org/test"), &id)); OK(wait_result(app, id).status); - OK(uhdk_app_get_preferences(app, &prefs)); + OK(uhdk_get_preferences(app, &prefs)); assert( prefs.appearance == UHDK_APPEARANCE_LIGHT && !prefs.reduced_motion && !prefs.high_contrast ); @@ -218,7 +217,7 @@ static void portals(uhdk_app *app) { assert(wait_result(app, id).status == UHDK_STATUS_CANCELLED); puts("portal results/cancellation/parent/restart: PASS"); } -static void window_observations(uhdk_app *app, int version) { +static void window_observations(uhdk_session *app, int version) { uhdk_window *w = window(app); uhdk_window_metrics metrics = {0}; metrics.struct_size = sizeof(metrics); @@ -234,9 +233,9 @@ static void window_observations(uhdk_app *app, int version) { uhdk_window_invalidate(w); int matched = 0, completed = 0; uint64_t end = deadline(app); - while (uhdk_app_get_time_ns(app) < end && !(matched && completed)) { + while (uhdk_get_time_ns(app) < end && !(matched && completed)) { uhdk_event_list events; - OK(uhdk_app_poll_events(app, 50000000, &events)); + OK(test_frame_events(app, &events)); for (uint64_t i = 0; i < events.len; ++i) { if (events.ptr[i].type == UHDK_EVENT_WINDOW_METRICS) { const uhdk_window_metrics *m = events.ptr[i].data; @@ -261,7 +260,7 @@ static void window_observations(uhdk_app *app, int version) { puts("Wayland versioned window observations/capabilities: PASS"); } -static void editing(uhdk_app *app) { +static void editing(uhdk_session *app) { uhdk_window *w = window(app); OK(uhdk_window_set_text_input(w, 1)); const struct { @@ -300,9 +299,9 @@ static void editing(uhdk_app *app) { int released = 0, completed = 0; unsigned commands = 0; uint64_t end = deadline(app); - while (uhdk_app_get_time_ns(app) < end && !(released && completed)) { + while (uhdk_get_time_ns(app) < end && !(released && completed)) { uhdk_event_list events; - OK(uhdk_app_poll_events(app, 50000000, &events)); + OK(test_frame_events(app, &events)); for (uint64_t j = 0; j < events.len; ++j) { const uhdk_event *event = &events.ptr[j]; assert(event->type != UHDK_EVENT_TEXT_COMMIT); @@ -326,7 +325,7 @@ static void editing(uhdk_app *app) { puts("Wayland editing defaults/selection/AltGr/no duplicate text: PASS"); } -static void input(uhdk_app *app) { +static void input(uhdk_session *app) { uhdk_window *w = window(app); uint64_t id; OK(uhdk_window_set_text_input(w, 1)); @@ -343,11 +342,11 @@ static void input(uhdk_app *app) { uint64_t acknowledged = 0; int published = 0; uint64_t end = deadline(app); - while (uhdk_app_get_time_ns(app) < end && + while (uhdk_get_time_ns(app) < end && !(key && repeat && commit >= 2 && preedit && pointer && scroll && dropped && copy && compose && captured && released)) { uhdk_event_list events; - OK(uhdk_app_poll_events(app, 50000000, &events)); + OK(test_frame_events(app, &events)); for (uint64_t i = 0; i < events.len; ++i) { const uhdk_event *e = &events.ptr[i]; if (e->input_id > acknowledged) @@ -453,7 +452,7 @@ static void input(uhdk_app *app) { assert(t->len == 11 && memcmp(t->ptr, "hello café", 11) == 0); OK(uhdk_clipboard_read_text_async(app, 100, &id)); uhdk_event_list pause; - OK(uhdk_app_poll_events(app, 100000000, &pause)); + OK(test_frame_events(app, &pause)); OK(uhdk_request_cancel(app, id)); assert(wait_result(app, id).status == UHDK_STATUS_CANCELLED); OK(uhdk_clipboard_read_text_async(app, 100, &id)); @@ -470,7 +469,7 @@ static void input(uhdk_app *app) { #include "menus.c" #include "popups.c" -static void run(uhdk_app *app, void *mode) { +static void run(uhdk_session *app, void *mode) { if (strcmp(mode, "popup") == 0) { popups(app); return; @@ -500,14 +499,14 @@ static void run(uhdk_app *app, void *mode) { } int main(int argc, char **argv) { assert(argc == 2); - uhdk_app_desc desc = {0}; - desc.struct_size = sizeof(desc); - desc.abi_version = UHDK_ABI_VERSION; - desc.display_name = text("UHDK service tests"); - desc.application_id = text("org.uhdk.ServiceTests"); - uhdk_app *app; - OK(uhdk_app_create(&desc, &app)); - OK(uhdk_app_run(app, run, argv[1])); - uhdk_app_destroy(app); + uhdk_options options = {0}; + options.struct_size = sizeof(options); + options.title = text("UHDK service tests"); + options.application_id = text("org.uhdk.ServiceTests"); + options.no_opengl = UHDK_TRUE; + uhdk_session *app; + OK(uhdk_open(&options, &app)); + run(app, argv[1]); + uhdk_close(app); return 0; } diff --git a/src/macos/native.m b/src/macos/native.m index 4205dd0..724192c 100644 --- a/src/macos/native.m +++ b/src/macos/native.m @@ -30,7 +30,7 @@ static uhdk_modifier_flags mods(NSEventModifierFlags f) { } @class ZWindow, ZView, ZGL; @interface ZHost : NSObject -@property(nonatomic) uhdk_app *app; +@property(nonatomic) uhdk_session *app; @property(nonatomic, strong) NSMutableArray *windows; @property(nonatomic, strong) NSMutableArray *observers; @property(nonatomic, strong) NSTimer *workTimer; @@ -1219,7 +1219,7 @@ void z_native_watch_commit(uhdk_watch *handle, void *prepared) { z_object_set_native(handle, prepared); } -static uhdk_status showPanel(uhdk_app *app, const uhdk_file_dialog_desc *d, uint64_t request) { +static uhdk_status showPanel(uhdk_session *app, const uhdk_file_dialog_desc *d, uint64_t request) { if (host.panel) return UHDK_STATUS_BUSY; NSSavePanel *panel; @@ -1292,7 +1292,7 @@ static uhdk_status showPanel(uhdk_app *app, const uhdk_file_dialog_desc *d, uint [panel beginWithCompletionHandler:completion]; return Z_DEFERRED; } -uhdk_status z_native_start(uhdk_app *app, uhdk_text name) { +uhdk_status z_native_start(uhdk_session *app, uhdk_text name) { @autoreleasepool { [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; @@ -1335,11 +1335,6 @@ uhdk_status z_native_start(uhdk_app *app, uhdk_text name) { return UHDK_STATUS_OK; } } -void z_native_run(void) { - @autoreleasepool { - [NSApp run]; - } -} void z_native_pump(uint64_t timeout_ns) { @autoreleasepool { NSDate *until = timeout_ns == UINT64_MAX @@ -1389,19 +1384,6 @@ void z_native_again(void) { }]; [NSRunLoop.mainRunLoop addTimer:host.workTimer forMode:NSRunLoopCommonModes]; } -void z_native_stop(void) { - [NSApp stop:nil]; - [NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined - location:NSZeroPoint - modifierFlags:0 - timestamp:0 - windowNumber:0 - context:nil - subtype:0 - data1:0 - data2:0] - atStart:YES]; -} void z_native_finish(void) { @autoreleasepool { [host.workTimer invalidate]; @@ -1468,17 +1450,11 @@ void z_native_destroy(uint32_t kind, void *native) { } extern void *objc_autoreleasePoolPush(void); extern void objc_autoreleasePoolPop(void *); -void *z_native_pool_push(void) { - return objc_autoreleasePoolPush(); -} -void z_native_pool_pop(void *p) { - objc_autoreleasePoolPop(p); -} int z_native_is_main_thread(void) { return NSThread.isMainThread; } uhdk_status z_native_execute( - uhdk_app *app, + uhdk_session *app, const z_command *cmd, uint64_t request, z_request_result *result @@ -1574,7 +1550,7 @@ uhdk_status z_native_execute( [w metrics]; break; case Z_GL: { - if (!(w.flags & UHDK_WINDOW_OPENGL)) + if (!(w.flags & Z_WINDOW_OPENGL)) return UHDK_STATUS_INVALID_ARGUMENT; NSOpenGLPixelFormatAttribute attrs[] = { NSOpenGLPFAOpenGLProfile, @@ -1838,19 +1814,9 @@ uhdk_status z_native_gl(void *native, uint32_t op, void *out) { CGLUnlockContext(gl.context.CGLContextObj); return UHDK_STATUS_OK; } - if (op == 3) { - [gl.context makeCurrentContext]; - return UHDK_STATUS_OK; - } if (NSOpenGLContext.currentContext != gl.context) return UHDK_STATUS_UNAVAILABLE; - if (op == 5) { - GLint major, minor; - glGetIntegerv(GL_MAJOR_VERSION, &major); - glGetIntegerv(GL_MINOR_VERSION, &minor); - ((uint32_t *)out)[0] = major; - ((uint32_t *)out)[1] = minor; - } else if (op == 6) + if (op == 6) [gl.context flushBuffer]; else if (op == 7) [gl.context setValues:out forParameter:NSOpenGLContextParameterSwapInterval]; diff --git a/src/native.h b/src/native.h index 2cded9e..964fd3d 100644 --- a/src/native.h +++ b/src/native.h @@ -7,7 +7,21 @@ #include "uhdk.h" #include #include "edit_keys.h" -int32_t z_gl_load(uhdk_gl_context *context, uhdk_gl_functions *functions); +typedef struct z_gl_context z_gl_context; +enum { + Z_WINDOW_OPENGL = 1u << 3 +}; +typedef struct z_window_desc { + uint32_t struct_size; + uint32_t flags; + uhdk_window_style style; + uhdk_text title; + uhdk_size content_size; + uhdk_size min_size; + uhdk_size max_size; + uhdk_window *parent; +} z_window_desc; +int32_t z_gl_load(void *context, uhdk_gl_functions *functions); /* Private producer storage. Converted to public pointer payloads at poll. */ typedef struct z_request_result { uhdk_request_id id; @@ -43,7 +57,6 @@ typedef struct z_event { uhdk_drop_files_event drop_files; uhdk_menu_event menu; uhdk_watch_event watch; - uhdk_resource_event resource; z_request_result request; } data; } z_event; @@ -102,27 +115,23 @@ typedef struct z_command { uhdk_bytes bytes; uhdk_size size; uhdk_point point; - uhdk_window_desc window; + z_window_desc window; uhdk_window_style style; uhdk_text_state text_state; uhdk_file_dialog_desc dialog; uhdk_image image; } z_command; -uhdk_status z_native_start(uhdk_app *, uhdk_text name); -void z_native_run(void); +uhdk_status z_native_start(uhdk_session *, uhdk_text name); void z_native_pump(uint64_t timeout_ns); /* File-worker preparation; native registration is committed on platform main. */ uhdk_status z_native_watch_prepare(uhdk_file *, uhdk_watch *, void **out); void z_native_watch_commit(uhdk_watch *, void *prepared); void z_native_wake(void); void z_native_again(void); -void z_native_stop(void); void z_native_finish(void); -uhdk_status z_native_execute(uhdk_app *, const z_command *, uint64_t, z_request_result *); +uhdk_status z_native_execute(uhdk_session *, const z_command *, uint64_t, z_request_result *); void z_native_cancel(uint64_t); void z_native_destroy(uint32_t kind, void *native); -void *z_native_pool_push(void); -void z_native_pool_pop(void *); uhdk_status z_native_gl(void *context, uint32_t op, void *out); uhdk_status z_native_gl_proc(void *context, uhdk_text, uhdk_gl_proc *); void z_native_handles(void *, uhdk_native_window *); @@ -174,21 +183,21 @@ uint32_t z_file_writer_write( uint32_t z_file_writer_commit(void *writer); void z_file_writer_close(void *writer); /* Zig callbacks, always return before native temporary spans expire. */ -void z_dispatch(uhdk_app *); -void z_emit(uhdk_app *, const z_event *); -void z_complete(uhdk_app *, uint64_t, uhdk_status, const z_request_result *); +void z_dispatch(uhdk_session *); +void z_emit(uhdk_session *, const z_event *); +void z_complete(uhdk_session *, uint64_t, uhdk_status, const z_request_result *); void *z_object_native(void *); void z_object_set_native(void *, void *); uint32_t z_object_kind(void *); -uhdk_app *z_object_app(void *); -uhdk_file *z_file_from_url(uhdk_app *, uhdk_bytes path, void *grant); +uhdk_session *z_object_app(void *); +uhdk_file *z_file_from_url(uhdk_session *, uhdk_bytes path, void *grant); uhdk_status z_file_init(uhdk_file *, uhdk_bytes, uhdk_text uri, uhdk_text display, void *grant); uhdk_bytes z_file_path(uhdk_file *); const uhdk_menu_item *z_menu_items(uhdk_menu *, uint64_t *len); void z_metrics(uhdk_window *, const uhdk_window_metrics *); -void z_preferences(uhdk_app *, const uhdk_preferences *); +void z_preferences(uhdk_session *, const uhdk_preferences *); int z_native_is_main_thread(void); /* Wake application polls on a fatal native-loop error. */ -void z_native_failed(uhdk_app *app, uhdk_status status); +void z_native_failed(uhdk_session *app, uhdk_status status); #endif diff --git a/src/root.zig b/src/root.zig index 4d19eef..57ad99d 100644 --- a/src/root.zig +++ b/src/root.zig @@ -6,7 +6,6 @@ comptime { checkExports(@import("api/app.zig")); checkExports(@import("api/session.zig")); checkExports(@import("api/windows.zig")); - checkExports(@import("api/graphics.zig")); checkExports(@import("api/input.zig")); checkExports(@import("api/files.zig")); checkExports(@import("api/menus.zig")); diff --git a/src/runtime.zig b/src/runtime.zig index f749817..f0c1e0e 100644 --- a/src/runtime.zig +++ b/src/runtime.zig @@ -9,7 +9,7 @@ const Resource = @import("Resource.zig"); const Application = @import("Application.zig"); const FileOperation = @import("FileOperation.zig"); -pub fn fromAppHandle(handle: ?*c.uhdk_app) *Application { +pub fn fromAppHandle(handle: ?*c.uhdk_session) *Application { return @ptrCast(@alignCast(if (@typeInfo(@TypeOf(handle)) == .optional) handle.? else handle)); } @@ -17,7 +17,7 @@ pub fn fromObjectHandle(handle: anytype) *Resource { return @ptrCast(@alignCast(if (@typeInfo(@TypeOf(handle)) == .optional) handle.? else handle)); } -pub fn toAppHandle(application: *Application) *c.uhdk_app { +pub fn toAppHandle(application: *Application) *c.uhdk_session { return @ptrCast(application); } @@ -36,7 +36,7 @@ pub fn threadCpuTime(io: std.Io) u64 { pub fn checkThread(application: *Application) abi.Status { application.lock(); defer application.unlock(); - return if (application.running and std.Thread.getCurrentId() == application.worker_id) abi.OK else c.UHDK_STATUS_WRONG_THREAD; + return if (application.running and std.Thread.getCurrentId() == application.main_thread) abi.OK else c.UHDK_STATUS_WRONG_THREAD; } pub fn checkObject(object: *Resource, kind: u32) abi.Status { @@ -154,27 +154,6 @@ pub fn copyPayload(node: *Event) !void { } } -// Reserve READY before native initialization, but expose it only after startup -// succeeds. Initial preferences/open-file events may arrive during that call. -pub fn prepareReady(application: *Application) !*Event { - const node = try application.gpa.create(Event); - node.* = .{ .gpa = application.gpa, .arena = .init(application.gpa) }; - node.event.type = c.UHDK_EVENT_READY; - node.event.struct_size = @sizeOf(c.z_event); - node.event.time_ns = now(application.io) - application.epoch; - return node; -} - -pub fn publishReady(application: *Application, node: *Event) void { - std.debug.assert(node.event.type == c.UHDK_EVENT_READY); - application.lock(); - defer application.unlock(); - node.next = application.pending_head; - application.pending_head = node; - if (application.pending_tail == null) application.pending_tail = node; - application.notify(); -} - pub fn simpleEvent(application: *Application, typ: u32) void { var event = std.mem.zeroes(c.z_event); event.type = typ; @@ -330,26 +309,7 @@ pub fn finish( }; break :request true; }, - .resource => resource: { - if (status == abi.OK) break :resource false; - const object = if (command.data.op == c.Z_WINDOW) - fromObjectHandle(command.data.target) - else - fromObjectHandle(command.data.other); - node.event.type = c.UHDK_EVENT_RESOURCE_FAILED; - node.event.window = if (object.payload == .window) - castHandle(?*c.uhdk_window, object) - else if (object.payload.gl.owner) |owner| - castHandle(?*c.uhdk_window, owner) - else - null; - node.event.data.resource = .{ - .kind = if (object.payload == .window) c.UHDK_RESOURCE_WINDOW else c.UHDK_RESOURCE_GL_CONTEXT, - .status = status, - .resource = object, - }; - break :resource true; - }, + .resource => false, .discard => false, }; application.lock(); @@ -380,15 +340,6 @@ pub fn hasFrame(application: *Application) bool { return false; } -pub fn applicationMain(application: *Application) void { - const app_api = @import("api/app.zig"); - const handle = toAppHandle(application); - profile.thread("UHDK application/render"); - std.debug.assert(app_api.uhdk_app_attach(handle) == abi.OK); - application.entry.?(handle, application.user); - std.debug.assert(app_api.uhdk_app_detach(handle) == abi.OK); -} - /// Execute file operations without touching native resources or publishing user /// events. The platform dispatcher owns completion and request retirement. pub fn ioMain(application: *Application) void { @@ -470,7 +421,7 @@ pub fn textCommandValue(handle: ?*c.uhdk_window, kind: u32, op: u32, text: c.uhd return submitCommand(fromObjectHandle(handle).app, command); } -pub fn createAppCommand(handle: ?*c.uhdk_app, op: u32) !*Request { +pub fn createAppCommand(handle: ?*c.uhdk_session, op: u32) !*Request { if (handle == null) return error.Invalid; if (checkThread(fromAppHandle(handle)) != abi.OK) return error.WrongThread; return createCommand(fromAppHandle(handle), op, null); @@ -523,7 +474,7 @@ pub fn destroyObject(object: *Resource) void { notifyCommand(object, c.Z_DESTROY); } -pub fn glCall(handle: ?*c.uhdk_gl_context, op: u32, out: ?*anyopaque) abi.Status { +pub fn glCall(handle: ?*c.z_gl_context, op: u32, out: ?*anyopaque) abi.Status { if (handle == null) return abi.INVALID; const object = fromObjectHandle(handle); const status = checkObject(object, c.Z_KIND_GL); @@ -629,7 +580,7 @@ pub fn validateMenu(object: *Resource, ids: *std.AutoHashMap(u64, void), depth: } pub fn attachMenu( - handle: ?*c.uhdk_app, + handle: ?*c.uhdk_session, w: ?*c.uhdk_window, menu: ?*c.uhdk_menu, ) abi.Status { @@ -672,7 +623,7 @@ pub fn setMenuFlags(object: *Resource, id: u64, flags: u32) bool { return false; } -pub fn emit(handle: ?*c.uhdk_app, event: [*c]const c.z_event) void { +pub fn emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void { const application = fromAppHandle(handle); const node = application.gpa.create(Event) catch { application.lock(); @@ -714,7 +665,7 @@ pub fn emit(handle: ?*c.uhdk_app, event: [*c]const c.z_event) void { } pub fn complete( - handle: ?*c.uhdk_app, + handle: ?*c.uhdk_session, id: u64, status: abi.Status, result: [*c]const c.z_request_result, @@ -732,7 +683,7 @@ pub fn complete( application.unlock(); } -pub fn dispatch(handle: ?*c.uhdk_app) void { +pub fn dispatch(handle: ?*c.uhdk_session) void { const zone = profile.begin(@src(), "UHDK platform dispatch"); defer zone.end(); const application = fromAppHandle(handle); @@ -847,8 +798,7 @@ pub fn dispatch(handle: ?*c.uhdk_app) void { application.lock(); application.stopped_sent = true; } - const done = application.worker_done and empty; const again = (!blocked_on_resource and application.queue_head != null) or application.io_completed_head != null or node == ids.len; application.unlock(); - if (done and application.native_running) c.z_native_stop() else if (again) c.z_native_again(); + if (again) c.z_native_again(); } diff --git a/src/test_frame.h b/src/test_frame.h new file mode 100644 index 0000000..8b177e7 --- /dev/null +++ b/src/test_frame.h @@ -0,0 +1,16 @@ +#ifndef UHDK_TEST_FRAME_H +#define UHDK_TEST_FRAME_H +#include "uhdk.h" +/* Native tests consume event batches through complete application iterations. + * Their sessions use continuous mode, so visible primary windows never wait. + * Event storage remains borrowed after end_frame, until the next iteration. */ +static uhdk_status test_frame_events(uhdk_session *session, uhdk_event_list *out) { + uhdk_frame frame; + if (!uhdk_next_frame(session, &frame)) { + uhdk_status status = uhdk_get_status(session); + return status == UHDK_STATUS_OK ? UHDK_STATUS_UNAVAILABLE : status; + } + *out = frame.events; + return uhdk_end_frame(session); +} +#endif diff --git a/src/windows/native.c b/src/windows/native.c index 4401331..ff93149 100644 --- a/src/windows/native.c +++ b/src/windows/native.c @@ -79,7 +79,7 @@ struct Watch { BOOL pending; }; static struct { - uhdk_app *app; + uhdk_session *app; HWND dispatch; Window *windows; Watch *watches; @@ -855,7 +855,7 @@ static PROC glProc(const char *name) { return p; } static uhdk_status createGraphics(Window *w, void *handle) { - if (!(w->flags & UHDK_WINDOW_OPENGL)) + if (!(w->flags & Z_WINDOW_OPENGL)) return UHDK_STATUS_INVALID_ARGUMENT; Graphics *g = profileCalloc(1, sizeof(*g)); if (!g) @@ -950,15 +950,8 @@ uhdk_status z_native_gl(void *native, uint32_t op, void *out) { LeaveCriticalSection(&g->lock); return ok ? UHDK_STATUS_OK : UHDK_STATUS_OS_ERROR; } - if (op == 3) - return wglMakeCurrent(g->dc, g->rc) ? UHDK_STATUS_OK : UHDK_STATUS_OS_ERROR; if (wglGetCurrentContext() != g->rc) return UHDK_STATUS_UNAVAILABLE; - if (op == 5) { - ((uint32_t *)out)[0] = g->major; - ((uint32_t *)out)[1] = g->minor; - return UHDK_STATUS_OK; - } if (op == 6) return SwapBuffers(g->dc) ? UHDK_STATUS_OK : UHDK_STATUS_OS_ERROR; if (op == 7) { @@ -1392,7 +1385,7 @@ int z_native_is_main_thread(void) { LONG previous = InterlockedCompareExchange(&main_thread, current, 0); return !previous || previous == current; } -uhdk_status z_native_start(uhdk_app *app, uhdk_text name) { +uhdk_status z_native_start(uhdk_session *app, uhdk_text name) { (void)name; memset(&host, 0, sizeof(host)); host.app = app; @@ -1457,10 +1450,6 @@ void z_native_pump(uint64_t timeout_ns) { } } } -void z_native_run(void) { - while (host.running) - z_native_pump(UINT64_MAX); -} void z_native_wake(void) { if (host.dispatch) PostMessageW(host.dispatch, Z_WAKE, 0, 0); @@ -1468,13 +1457,6 @@ void z_native_wake(void) { void z_native_again(void) { z_native_wake(); } -void z_native_stop(void) { - host.running = FALSE; - if (host.dialog) - IFileDialog_Close(host.dialog, HRESULT_FROM_WIN32(ERROR_CANCELLED)); - if (host.popup_id) - EndMenu(); -} void z_native_finish(void) { if (host.dispatch) { KillTimer(host.dispatch, 1); @@ -1499,12 +1481,6 @@ void z_native_finish(void) { host.com_initialized = FALSE; } } -void *z_native_pool_push(void) { - return NULL; -} -void z_native_pool_pop(void *pool) { - (void)pool; -} void z_native_cancel(uint64_t id) { if (host.pending_dialog_id == id) { host.pending_dialog = NULL; @@ -1680,7 +1656,7 @@ static uhdk_status setIcon(const uhdk_image *image) { return UHDK_STATUS_OK; } uhdk_status z_native_execute( - uhdk_app *app, + uhdk_session *app, const z_command *cmd, uint64_t request, z_request_result *result