Support caller-owned application threads and asynchronous file execution
This commit is contained in:
parent
858bf52a09
commit
894e3dee59
41
README.md
41
README.md
|
|
@ -136,6 +136,47 @@ are not implemented. Native UTF-16 path bytes are kept separately from the WTF-8
|
|||
paths passed to Zig I/O. If a native path cannot be exported losslessly as a shell
|
||||
URI, URI export returns `UNSUPPORTED`; native-path export still preserves it.
|
||||
|
||||
## Application lifecycle
|
||||
|
||||
Set `uhdk_app_desc.use_application_thread` before `uhdk_app_create`:
|
||||
|
||||
| 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` |
|
||||
|
||||
With `0`, main calls `create`, `start`, runs its poll/update/render loop, then
|
||||
calls `stop` and `destroy`. With `1`, main calls `create` and `start`, 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,
|
||||
calls `stop`, then `destroy`. If creating the thread fails, stop and destroy the
|
||||
started app without entering `run_native`. Start is attempted once; failure leaves
|
||||
an app destroyable. Attachment is once per app, with no thread migration.
|
||||
|
||||
The convenience `uhdk_app_run(app, entry, user)` starts/stops services and invokes
|
||||
entry with application ownership already established. It honors the flag, creating
|
||||
and joining the application thread when enabled. Its callback owns its loop and
|
||||
must not attach/detach/stop. Create and destroy still belong to the caller.
|
||||
|
||||
The caller decides when to poll, update, and render; there are no application tick
|
||||
APIs. 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/stop. Native
|
||||
services remain alive for this cleanup. Early detach/stop abandons undelivered
|
||||
results but retires internal requests before destruction. A fatal native-loop
|
||||
failure is persistent and wakes waiting polls; detach/join/stop still apply.
|
||||
|
||||
## Borrowed event payloads
|
||||
|
||||
Events and request results carry `const void *data` plus `data_size` instead of
|
||||
|
|
|
|||
|
|
@ -38,11 +38,12 @@
|
|||
* 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/destroy belong to OS main. run invokes one application entry on
|
||||
* a second thread. All other calls belong to that application thread except
|
||||
* app_wake, which is thread-safe. Native work is queued to the main thread.
|
||||
* - File operations are async to the caller and executed in bounded platform
|
||||
* batches. Individual filesystem calls can still delay native input collection.
|
||||
* - create/start/run/run_native/stop/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.
|
||||
* - 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.
|
||||
|
|
@ -224,16 +225,40 @@ typedef struct uhdk_app_desc {
|
|||
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);
|
||||
UHDK_API uhdk_status UHDK_CALL uhdk_app_create(const uhdk_app_desc *desc, uhdk_app **out);
|
||||
/* OS main. Start once; does not enter a loop or create an application thread.
|
||||
* Failure rolls back startup and leaves the app destroyable, not restartable. */
|
||||
UHDK_API uhdk_status UHDK_CALL uhdk_app_start(uhdk_app *app);
|
||||
/* Requires use_application_thread=1 and successful start. 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);
|
||||
/* OS main, after application cleanup. With a separate application thread,
|
||||
* detach and join it first and let run_native return. Also valid if no thread
|
||||
* attached and run_native was never entered. Drains teardown and joins I/O.
|
||||
* STOPPED still permits GL/resource cleanup until detach/stop. */
|
||||
UHDK_API uhdk_status UHDK_CALL uhdk_app_stop(uhdk_app *app);
|
||||
/* Convenience runner on a newly created app: start, invoke entry, stop.
|
||||
* With use_application_thread=1 also creates/attaches/joins the app thread and
|
||||
* runs native services on main. Entry must not call attach/detach/stop.
|
||||
* Returns ready for destroy, including startup/worker-creation failures. */
|
||||
UHDK_API uhdk_status UHDK_CALL uhdk_app_run(
|
||||
uhdk_app *app,
|
||||
uhdk_app_main_fn main_fn,
|
||||
void *user
|
||||
); /* Once. */
|
||||
/* Zero timeout does not wait; finite timeouts use monotonic nanoseconds.
|
||||
/* 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,
|
||||
|
|
@ -251,7 +276,8 @@ UHDK_API uint64_t UHDK_CALL uhdk_app_get_time_ns(uhdk_app *app);
|
|||
* 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);
|
||||
UHDK_API void UHDK_CALL uhdk_app_destroy(uhdk_app *app); /* After run; releases child objects. */
|
||||
UHDK_API void UHDK_CALL uhdk_app_destroy(uhdk_app *app
|
||||
); /* After stop/run or failed start; releases child objects. */
|
||||
/* 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. */
|
||||
|
|
@ -259,40 +285,20 @@ 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);
|
||||
|
||||
/* Application-thread CPU execution time in nanoseconds, not elapsed wall time.
|
||||
* Bracket user update/input processing with begin_tick/end_tick, AFTER polling
|
||||
* events and BEFORE rendering. Nested ticks return BUSY; end without begin is
|
||||
* INVALID_ARGUMENT. Polling/idle time outside the bracket is not counted.
|
||||
* Render timing uses GL begin_frame/end_frame brackets containing a successful
|
||||
* swap_buffers. Setup/cleanup brackets without presentation are not frames.
|
||||
* Blocked waits (including GPU waits), sleep, and time spent descheduled are
|
||||
* excluded. The entire swap_buffers call is excluded, including driver spinning
|
||||
* during presentation/vsync. Other CPU work in GL/driver calls is counted;
|
||||
* this does not measure GPU execution or CPU work on other threads.
|
||||
* tick_time_ns and render_time_ns are the most recent completed phase samples.
|
||||
* frame_time_ns captures the latest completed tick + render at presentation's
|
||||
* end_frame; it stays unchanged until another presented frame completes.
|
||||
* frames_per_second is the reciprocal of elapsed wall time between the last two
|
||||
* presented end_frame calls, across all contexts. It includes idle time, vsync,
|
||||
* and GPU waits; it is NOT derived from CPU frame_time_ns or monitor refresh.
|
||||
* It is zero until two frames complete, then retains the last sample while idle.
|
||||
* Counts are cumulative; timings are zero until a sample is available. Calls
|
||||
* do not generate events. Read the previous frame to display stats while drawing.
|
||||
*/
|
||||
/* Rendering CPU time excludes swap_buffers, blocked waits and descheduling.
|
||||
* A presented begin_frame/end_frame bracket updates render_time_ns/frame_count.
|
||||
* 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 {
|
||||
uint32_t struct_size;
|
||||
uint32_t reserved;
|
||||
uint64_t tick_count;
|
||||
uint64_t frame_count;
|
||||
uint64_t event_count;
|
||||
uint64_t tick_time_ns;
|
||||
uint64_t render_time_ns;
|
||||
uint64_t frame_time_ns;
|
||||
float frames_per_second;
|
||||
} uhdk_app_stats;
|
||||
|
||||
UHDK_API uhdk_status UHDK_CALL uhdk_app_begin_tick(uhdk_app *app);
|
||||
UHDK_API uhdk_status UHDK_CALL uhdk_app_end_tick(uhdk_app *app);
|
||||
UHDK_API uhdk_status UHDK_CALL uhdk_app_get_stats(uhdk_app *app, uhdk_app_stats *out);
|
||||
|
||||
/* Logical coordinates: top-left origin, x right, y down. Window geometry uses
|
||||
|
|
|
|||
|
|
@ -14,12 +14,23 @@ io: std.Io,
|
|||
io_backend: ?*std.Io.Threaded = null,
|
||||
mutex: std.Io.Mutex = .init,
|
||||
available: std.Io.Event = .unset,
|
||||
in_tick: bool = false,
|
||||
in_dispatch: bool = false,
|
||||
objects: ?*Resource = null,
|
||||
queue_head: ?*Request = null,
|
||||
queue_tail: ?*Request = null,
|
||||
requests: ?*Request = null,
|
||||
io_active: ?*Request = null,
|
||||
io_completed_head: ?*Request = null,
|
||||
io_completed_tail: ?*Request = null,
|
||||
io_pending: usize = 0,
|
||||
io_worker: ?std.Thread = null,
|
||||
io_available: std.Io.Event = .unset,
|
||||
io_exit: bool = false,
|
||||
// Test-only gate permits deterministic blocked-filesystem scheduling tests.
|
||||
io_test_hook: if (@import("builtin").is_test) ?struct {
|
||||
context: *anyopaque,
|
||||
before: *const fn (*anyopaque) void,
|
||||
} else void = if (@import("builtin").is_test) null else {},
|
||||
io_head: ?*Request = null,
|
||||
io_tail: ?*Request = null,
|
||||
pending_head: ?*Event = null,
|
||||
|
|
@ -32,6 +43,12 @@ 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_error: abi.Status = abi.OK,
|
||||
application_pool: ?*anyopaque = null,
|
||||
has_run: bool = false,
|
||||
stopping: bool = false,
|
||||
stopped_sent: bool = false,
|
||||
|
|
@ -43,7 +60,6 @@ entry: c.uhdk_app_main_fn = null,
|
|||
user: ?*anyopaque = null,
|
||||
preferences: c.uhdk_preferences = std.mem.zeroes(c.uhdk_preferences),
|
||||
stats: c.uhdk_app_stats = std.mem.zeroes(c.uhdk_app_stats),
|
||||
tick_start: ?u64 = null,
|
||||
last_frame_time: ?u64 = null,
|
||||
pub fn create(gpa: std.mem.Allocator, io: std.Io, name: []const u8) !*Application {
|
||||
const self = try gpa.create(Application);
|
||||
|
|
@ -62,4 +78,7 @@ pub fn unlock(self: *Application) void {
|
|||
}
|
||||
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();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! One platform-thread file operation. Each step transfers at most one chunk.
|
||||
//! One I/O-worker file operation. Each step transfers at most one chunk.
|
||||
const FileOperation = @This();
|
||||
|
||||
const std = @import("std");
|
||||
|
|
@ -36,9 +36,15 @@ pub fn init(
|
|||
return .{ .gpa = gpa, .io = io, .kind = kind, .path = path, .input = input, .limit = limit };
|
||||
}
|
||||
|
||||
pub fn deinit(self: *FileOperation) void {
|
||||
pub fn close(self: *FileOperation) void {
|
||||
if (self.file) |file| file.close(self.io);
|
||||
self.file = null;
|
||||
if (self.atomic_file) |*file| file.deinit(self.io);
|
||||
self.atomic_file = null;
|
||||
}
|
||||
|
||||
pub fn deinit(self: *FileOperation) void {
|
||||
self.close();
|
||||
self.contents.deinit(self.gpa);
|
||||
self.* = undefined;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,3 +19,8 @@ cancelled: bool = false,
|
|||
native_deferred: bool = false,
|
||||
pins: std.ArrayList(*Resource) = .empty,
|
||||
file_operation: ?FileOperation = null,
|
||||
|
||||
io_status: abi.Status = abi.OK,
|
||||
io_result: c.z_request_result = std.mem.zeroes(c.z_request_result),
|
||||
|
||||
io_prepared: ?*anyopaque = null,
|
||||
|
|
|
|||
182
src/api/app.zig
182
src/api/app.zig
|
|
@ -23,6 +23,7 @@ pub export fn uhdk_app_create(desc: [*c]const c.uhdk_app_desc, out: [*c]?*c.uhdk
|
|||
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;
|
||||
|
|
@ -44,20 +45,18 @@ pub export fn uhdk_app_create(desc: [*c]const c.uhdk_app_desc, out: [*c]?*c.uhdk
|
|||
return abi.OOM;
|
||||
};
|
||||
application.io_backend = backend;
|
||||
application.use_application_thread = desc.*.use_application_thread != 0;
|
||||
singleton = true;
|
||||
out.* = runtime.toAppHandle(application);
|
||||
return abi.OK;
|
||||
}
|
||||
|
||||
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;
|
||||
pub export fn uhdk_app_start(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.has_run) return abi.UNAVAILABLE;
|
||||
if (application.has_run) return abi.INVALID;
|
||||
application.has_run = true;
|
||||
profile.thread("UHDK platform");
|
||||
const ready = runtime.prepareReady(application) catch return abi.OOM;
|
||||
const status = c.z_native_start(handle, abi.textSpan(application.name));
|
||||
|
|
@ -65,19 +64,123 @@ pub export fn uhdk_app_run(
|
|||
runtime.destroyEvent(ready);
|
||||
return status;
|
||||
}
|
||||
runtime.publishReady(application, ready);
|
||||
application.entry = entry;
|
||||
application.user = user;
|
||||
application.running = true;
|
||||
application.has_run = true;
|
||||
const worker = std.Thread.spawn(.{}, runtime.applicationMain, .{application}) catch {
|
||||
application.running = false;
|
||||
application.io_worker = std.Thread.spawn(.{}, runtime.ioMain, .{application}) catch {
|
||||
runtime.destroyEvent(ready);
|
||||
c.z_native_finish();
|
||||
return abi.OOM;
|
||||
};
|
||||
application.running = true;
|
||||
if (!application.use_application_thread) application.worker_id = std.Thread.getCurrentId();
|
||||
runtime.publishReady(application, ready);
|
||||
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;
|
||||
const status = uhdk_app_start(handle);
|
||||
if (status != abi.OK) return status;
|
||||
const application = runtime.fromAppHandle(handle);
|
||||
application.entry = entry;
|
||||
application.user = user;
|
||||
if (application.use_application_thread) {
|
||||
const worker = std.Thread.spawn(.{}, runtime.applicationMain, .{application}) catch {
|
||||
_ = uhdk_app_stop(handle);
|
||||
return abi.OOM;
|
||||
};
|
||||
const run_status = uhdk_app_run_native(handle);
|
||||
worker.join();
|
||||
application.running = false;
|
||||
const stop_status = uhdk_app_stop(handle);
|
||||
return if (run_status != abi.OK) run_status else stop_status;
|
||||
}
|
||||
entry.?(handle, user);
|
||||
return uhdk_app_stop(handle);
|
||||
}
|
||||
|
||||
pub export fn uhdk_app_stop(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) return abi.INVALID;
|
||||
application.lock();
|
||||
if (application.native_running or (application.use_application_thread and application.worker_id != null)) {
|
||||
application.unlock();
|
||||
return c.UHDK_STATUS_BUSY;
|
||||
}
|
||||
application.unlock();
|
||||
if (runtime.hasFrame(application)) return c.UHDK_STATUS_BUSY;
|
||||
_ = 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) {
|
||||
runtime.dispatch(handle);
|
||||
application.lock();
|
||||
const drained = application.requests == null and application.queue_head == null;
|
||||
application.unlock();
|
||||
if (drained) break;
|
||||
c.z_native_pump(10 * std.time.ns_per_ms);
|
||||
}
|
||||
application.lock();
|
||||
application.io_exit = true;
|
||||
application.io_available.set(application.io);
|
||||
application.unlock();
|
||||
if (application.io_worker) |worker| worker.join();
|
||||
application.io_worker = null;
|
||||
// Native sources stop before any of their Zig records can be released.
|
||||
var cursor = application.objects;
|
||||
while (cursor) |object| : (cursor = object.next) {
|
||||
|
|
@ -101,7 +204,9 @@ pub export fn uhdk_app_run(
|
|||
}
|
||||
}
|
||||
c.z_native_finish();
|
||||
return abi.OK;
|
||||
application.running = false;
|
||||
application.worker_id = null;
|
||||
return application.native_error;
|
||||
}
|
||||
|
||||
pub export fn uhdk_app_poll_events(
|
||||
|
|
@ -112,14 +217,23 @@ pub export fn uhdk_app_poll_events(
|
|||
if (handle == null or out == null) return abi.INVALID;
|
||||
const application = runtime.fromAppHandle(handle);
|
||||
if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
|
||||
if (runtime.hasFrame(application)) return c.UHDK_STATUS_BUSY;
|
||||
const poll_zone = profile.begin(@src(), "UHDK poll events (includes wait)");
|
||||
defer poll_zone.end();
|
||||
runtime.destroyEvents(application.published);
|
||||
application.published = null;
|
||||
application.scratch.reset();
|
||||
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);
|
||||
}
|
||||
application.lock();
|
||||
defer application.unlock();
|
||||
if (application.native_error != abi.OK) return application.native_error;
|
||||
if (application.stopped_seen) return abi.UNAVAILABLE;
|
||||
if (application.deadline != 0 and runtime.now(application.io) - application.epoch >= application.deadline) {
|
||||
application.deadline = 0;
|
||||
|
|
@ -127,9 +241,7 @@ pub export fn uhdk_app_poll_events(
|
|||
runtime.simpleEvent(application, c.UHDK_EVENT_WAKE);
|
||||
application.lock();
|
||||
}
|
||||
const start = runtime.now(application.io);
|
||||
const end = start +| timeout;
|
||||
while (application.pending_head == null and application.event_error == abi.OK) {
|
||||
while (application.pending_head == null and application.event_error == abi.OK and application.native_error == abi.OK) {
|
||||
const current = runtime.now(application.io);
|
||||
if (application.deadline != 0 and current - application.epoch >= application.deadline) {
|
||||
application.deadline = 0;
|
||||
|
|
@ -145,6 +257,12 @@ pub export fn uhdk_app_poll_events(
|
|||
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,
|
||||
|
|
@ -157,6 +275,7 @@ pub export fn uhdk_app_poll_events(
|
|||
};
|
||||
application.lock();
|
||||
}
|
||||
if (application.native_error != abi.OK) return application.native_error;
|
||||
if (application.event_error != abi.OK) {
|
||||
const err = application.event_error;
|
||||
application.event_error = abi.OK;
|
||||
|
|
@ -195,26 +314,6 @@ pub export fn uhdk_app_poll_events(
|
|||
return abi.OK;
|
||||
}
|
||||
|
||||
pub export fn uhdk_app_begin_tick(handle: ?*c.uhdk_app) 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;
|
||||
if (application.tick_start != null) return c.UHDK_STATUS_BUSY;
|
||||
application.tick_start = runtime.threadCpuTime(application.io);
|
||||
return abi.OK;
|
||||
}
|
||||
|
||||
pub export fn uhdk_app_end_tick(handle: ?*c.uhdk_app) 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;
|
||||
const start = application.tick_start orelse return abi.INVALID;
|
||||
application.stats.tick_time_ns = runtime.threadCpuTime(application.io) -| start;
|
||||
application.stats.tick_count +|= 1;
|
||||
application.tick_start = null;
|
||||
return abi.OK;
|
||||
}
|
||||
|
||||
pub export fn uhdk_app_get_stats(handle: ?*c.uhdk_app, out: [*c]c.uhdk_app_stats) abi.Status {
|
||||
if (handle == null) return abi.INVALID;
|
||||
const application = runtime.fromAppHandle(handle);
|
||||
|
|
@ -232,7 +331,10 @@ pub export fn uhdk_app_quit(handle: ?*c.uhdk_app) void {
|
|||
}
|
||||
|
||||
pub export fn uhdk_app_wake(handle: ?*c.uhdk_app) void {
|
||||
if (handle != null) runtime.simpleEvent(runtime.fromAppHandle(handle), c.UHDK_EVENT_WAKE);
|
||||
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 {
|
||||
|
|
|
|||
|
|
@ -55,7 +55,6 @@ pub export fn uhdk_gl_context_end_frame(handle: ?*c.uhdk_gl_context) abi.Status
|
|||
const stats = &object.app.stats;
|
||||
const elapsed = runtime.threadCpuTime(object.app.io) -| object.payload.gl.frame_cpu_start;
|
||||
stats.render_time_ns = elapsed -| object.payload.gl.swap_cpu_time;
|
||||
stats.frame_time_ns = stats.tick_time_ns +| stats.render_time_ns;
|
||||
stats.frame_count +|= 1;
|
||||
const now = runtime.now(object.app.io);
|
||||
if (object.app.last_frame_time) |previous| {
|
||||
|
|
|
|||
|
|
@ -104,6 +104,15 @@ 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_tick(handle: ?*c.uhdk_app) void {
|
||||
runtime.tick(handle);
|
||||
export fn z_dispatch(handle: ?*c.uhdk_app) void {
|
||||
runtime.dispatch(handle);
|
||||
}
|
||||
|
||||
export fn z_native_failed(handle: ?*c.uhdk_app, status: abi.Status) void {
|
||||
const app = runtime.fromAppHandle(handle);
|
||||
app.lock();
|
||||
app.native_error = status;
|
||||
app.stopping = true;
|
||||
app.notify();
|
||||
app.unlock();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ 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();
|
||||
const command = try runtime.createCommand(application, c.Z_CLIP_READ, null);
|
||||
var request_id: u64 = 0;
|
||||
|
|
@ -63,7 +64,7 @@ test "accepted request gets one terminal result when cancellation wins" {
|
|||
application.lock();
|
||||
command.cancelled = true;
|
||||
application.unlock();
|
||||
runtime.tick(runtime.toAppHandle(application));
|
||||
runtime.dispatch(runtime.toAppHandle(application));
|
||||
try std.testing.expect(application.requests == null);
|
||||
try std.testing.expect(application.queue_head == null);
|
||||
const event = application.pending_head.?;
|
||||
|
|
@ -81,30 +82,12 @@ test "invalid UTF-8 spans and partial scalar ranges are rejected" {
|
|||
try std.testing.expect(abi.boundary("a😀b", 5));
|
||||
}
|
||||
|
||||
test "tick statistics exclude blocked time" {
|
||||
const app_api = @import("api/app.zig");
|
||||
const application = try Application.create(std.testing.allocator, std.testing.io, "stats");
|
||||
defer destroyApplication(application);
|
||||
application.running = true;
|
||||
application.worker_id = std.Thread.getCurrentId();
|
||||
const handle = runtime.toAppHandle(application);
|
||||
const wall_start = runtime.now(application.io);
|
||||
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_begin_tick(handle));
|
||||
try (std.Io.Clock.Duration{ .raw = .fromMilliseconds(40), .clock = .awake }).sleep(application.io);
|
||||
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_end_tick(handle));
|
||||
const wall_time = runtime.now(application.io) - wall_start;
|
||||
var stats = std.mem.zeroes(c.uhdk_app_stats);
|
||||
stats.struct_size = @sizeOf(c.uhdk_app_stats);
|
||||
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_get_stats(handle, &stats));
|
||||
try std.testing.expectEqual(@as(u64, 1), stats.tick_count);
|
||||
try std.testing.expect(stats.tick_time_ns < wall_time / 2);
|
||||
}
|
||||
|
||||
test "public payload scratch lifetime empty polls and resource pins" {
|
||||
const app_api = @import("api/app.zig");
|
||||
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();
|
||||
const handle = runtime.toAppHandle(application);
|
||||
const file = try runtime.createObject(application, c.Z_KIND_FILE);
|
||||
|
|
@ -137,6 +120,7 @@ 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();
|
||||
const handle = runtime.toAppHandle(application);
|
||||
var bytes = [_]u8{42} ** 20000;
|
||||
|
|
@ -219,3 +203,108 @@ test "desktop edit defaults preserve modifiers and selection intent" {
|
|||
for ([_]u32{ c.UHDK_EDIT_BACKTAB, c.UHDK_EDIT_LINE_BREAK, c.UHDK_EDIT_CUT, c.UHDK_EDIT_DELETE_WORD_FORWARD, c.UHDK_EDIT_REDO }) |command|
|
||||
try std.testing.expectEqual(@as(c_int, 0), c.z_edit_extends_selection(command, shift));
|
||||
}
|
||||
|
||||
const IoGate = struct {
|
||||
io: std.Io,
|
||||
entered: std.Io.Event = .unset,
|
||||
release: std.Io.Event = .unset,
|
||||
fn block(context: *anyopaque) void {
|
||||
const self: *IoGate = @ptrCast(@alignCast(context));
|
||||
self.entered.set(self.io);
|
||||
self.release.waitUncancelable(self.io);
|
||||
}
|
||||
};
|
||||
|
||||
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();
|
||||
const handle = runtime.toAppHandle(application);
|
||||
var gate: IoGate = .{ .io = application.io };
|
||||
application.io_test_hook = .{ .context = &gate, .before = IoGate.block };
|
||||
const file = try runtime.createObject(application, c.Z_KIND_FILE);
|
||||
defer runtime.release(file);
|
||||
const worker = try std.Thread.spawn(.{}, runtime.ioMain, .{application});
|
||||
defer {
|
||||
gate.release.set(application.io);
|
||||
application.lock();
|
||||
application.io_exit = true;
|
||||
application.io_available.set(application.io);
|
||||
application.unlock();
|
||||
worker.join();
|
||||
}
|
||||
const command = try runtime.createCommand(application, abi.IO_INFO, file);
|
||||
command.kind = c.UHDK_REQUEST_FILE_INFO;
|
||||
var id: u64 = 0;
|
||||
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, command, &id));
|
||||
runtime.dispatch(handle);
|
||||
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(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);
|
||||
runtime.dispatch(handle);
|
||||
try std.testing.expect(!application.stopped_sent);
|
||||
gate.release.set(application.io);
|
||||
const deadline = runtime.now(application.io) + 5 * std.time.ns_per_s;
|
||||
while (true) {
|
||||
runtime.dispatch(handle);
|
||||
application.lock();
|
||||
const done = application.requests == null;
|
||||
application.unlock();
|
||||
if (done) break;
|
||||
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(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(usize, 0), application.io_pending);
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
const file = try runtime.createObject(application, c.Z_KIND_FILE);
|
||||
defer runtime.release(file);
|
||||
for (0..64) |_| {
|
||||
const command = try runtime.createCommand(application, abi.IO_INFO, file);
|
||||
var id: u64 = 0;
|
||||
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, command, &id));
|
||||
}
|
||||
const excess = try runtime.createCommand(application, abi.IO_INFO, file);
|
||||
var id: u64 = 0;
|
||||
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, excess, &id));
|
||||
try std.testing.expectEqual(@as(u64, 0), id);
|
||||
application.stopping = true;
|
||||
while (application.requests != null) runtime.dispatch(runtime.toAppHandle(application));
|
||||
try std.testing.expectEqual(@as(usize, 0), application.io_pending);
|
||||
}
|
||||
|
||||
test "fatal native failure persists and wakes subsequent polls" {
|
||||
const app_api = @import("api/app.zig");
|
||||
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();
|
||||
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));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -103,8 +103,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. GL work runs
|
||||
on the application thread. Main-thread drawable updates use a nonblocking lock
|
||||
- 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.
|
||||
- Hiding replaces the EGL presentation surface so an outstanding frame callback
|
||||
|
|
|
|||
|
|
@ -17,8 +17,7 @@ pub const Watch = struct {
|
|||
fn b() *native.Backend {
|
||||
return native.instance.?;
|
||||
}
|
||||
pub fn create(cmd: *const n.z_command, result: *n.z_request_result) u32 {
|
||||
const root: ?*n.uhdk_file = @ptrCast(cmd.target);
|
||||
pub fn prepare(root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, out: *?*anyopaque) u32 {
|
||||
const path = b().app.gpa.dupeZ(u8, abi.bytes(n.z_file_path(root))) catch return abi.OOM;
|
||||
defer b().app.gpa.free(path);
|
||||
const kind = c.z_linux_is_directory(path);
|
||||
|
|
@ -32,16 +31,20 @@ pub fn create(cmd: *const n.z_command, result: *n.z_request_result) u32 {
|
|||
_ = c.close(fd);
|
||||
return n.UHDK_STATUS_OS_ERROR;
|
||||
}
|
||||
const w = allocate(fd, root, @ptrCast(cmd.other), directory, if (kind == 1) "" else std.fs.path.basename(path)) catch {
|
||||
const w = allocate(fd, root, handle, directory, if (kind == 1) "" else std.fs.path.basename(path)) catch {
|
||||
_ = c.close(fd);
|
||||
return abi.OOM;
|
||||
};
|
||||
w.next = b().watches;
|
||||
b().watches = w;
|
||||
n.z_object_set_native(cmd.other, w);
|
||||
result.value.watch = w.handle;
|
||||
out.* = w;
|
||||
return abi.OK;
|
||||
}
|
||||
pub fn commit(handle: ?*n.uhdk_watch, prepared: *anyopaque) void {
|
||||
const w: *Watch = @ptrCast(@alignCast(prepared));
|
||||
w.next = b().watches;
|
||||
b().watches = w;
|
||||
n.z_object_set_native(handle, w);
|
||||
}
|
||||
|
||||
fn allocate(fd: c_int, root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, directory: []const u8, name: []const u8) !*Watch {
|
||||
const gpa = b().app.gpa;
|
||||
const w = try gpa.create(Watch);
|
||||
|
|
|
|||
|
|
@ -231,17 +231,19 @@ fn fail(b: *Backend) void {
|
|||
if (b.failed.swap(true, .acq_rel)) return;
|
||||
b.app.lock();
|
||||
b.app.stopping = true;
|
||||
b.app.native_error = n.UHDK_STATUS_OS_ERROR;
|
||||
b.app.notify();
|
||||
b.app.unlock();
|
||||
Popup.deinit();
|
||||
runtime.simpleEvent(b.app, n.UHDK_EVENT_QUIT_REQUESTED);
|
||||
}
|
||||
export fn z_native_run() void {
|
||||
const b = instance.?;
|
||||
export fn z_native_pump(timeout_ns: u64) void {
|
||||
const b = instance orelse return;
|
||||
var fds: std.ArrayList(c.struct_pollfd) = .empty;
|
||||
defer fds.deinit(b.app.gpa);
|
||||
while (b.running) {
|
||||
pump: {
|
||||
if (!b.failed.load(.acquire) and c.z_wl_display_dispatch_pending.?(b.display) < 0) fail(b);
|
||||
n.z_tick(runtime.toAppHandle(b.app));
|
||||
n.z_dispatch(runtime.toAppHandle(b.app));
|
||||
var cursor = b.windows;
|
||||
var timeout: c_int = Input.tick();
|
||||
Watch.tick();
|
||||
|
|
@ -264,17 +266,17 @@ export fn z_native_run() void {
|
|||
}
|
||||
if (!b.failed.load(.acquire)) apply(w);
|
||||
}
|
||||
if (!b.running) break;
|
||||
if (!b.running) return;
|
||||
var reading = false;
|
||||
var display_events: c_short = c.POLLIN;
|
||||
if (!b.failed.load(.acquire)) {
|
||||
if (c.z_wl_display_prepare_read.?(b.display) != 0) continue;
|
||||
if (c.z_wl_display_prepare_read.?(b.display) != 0) break :pump;
|
||||
reading = true;
|
||||
if (c.z_wl_display_flush.?(b.display) < 0) {
|
||||
if (c.z_linux_errno() == c.EAGAIN) display_events |= c.POLLOUT else {
|
||||
c.z_wl_display_cancel_read.?(b.display);
|
||||
fail(b);
|
||||
continue;
|
||||
break :pump;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -285,27 +287,34 @@ export fn z_native_run() void {
|
|||
}) catch {
|
||||
if (reading) c.z_wl_display_cancel_read.?(b.display);
|
||||
fail(b);
|
||||
continue;
|
||||
break :pump;
|
||||
};
|
||||
Data.poll(&fds) catch {
|
||||
if (reading) c.z_wl_display_cancel_read.?(b.display);
|
||||
fail(b);
|
||||
continue;
|
||||
break :pump;
|
||||
};
|
||||
Watch.poll(&fds) catch {
|
||||
if (reading) c.z_wl_display_cancel_read.?(b.display);
|
||||
fail(b);
|
||||
continue;
|
||||
break :pump;
|
||||
};
|
||||
Portal.poll(&fds) catch {
|
||||
if (reading) c.z_wl_display_cancel_read.?(b.display);
|
||||
fail(b);
|
||||
continue;
|
||||
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);
|
||||
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)));
|
||||
if (budget >= 0) timeout = if (timeout < 0) budget else @min(timeout, budget);
|
||||
const ready = c.z_linux_poll(fds.items.ptr, fds.items.len, timeout);
|
||||
if (reading) {
|
||||
if (ready > 0 and fds.items[0].revents & c.POLLIN != 0) {
|
||||
if (c.z_wl_display_read_events.?(b.display) < 0) fail(b);
|
||||
if (c.z_wl_display_read_events.?(b.display) < 0 or
|
||||
c.z_wl_display_dispatch_pending.?(b.display) < 0) fail(b);
|
||||
} else c.z_wl_display_cancel_read.?(b.display);
|
||||
}
|
||||
if (ready < 0 and c.z_linux_errno() != c.EINTR) fail(b);
|
||||
|
|
@ -317,6 +326,11 @@ export fn z_native_run() 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);
|
||||
|
|
@ -568,7 +582,6 @@ export fn z_native_execute(_: ?*n.uhdk_app, raw: [*c]const n.z_command, id: u64,
|
|||
if (cmd.op == n.Z_POPUP) return Popup.request(cmd, id);
|
||||
if (cmd.op == n.Z_ICON) return Desktop.setIcon(cmd.image);
|
||||
if (cmd.op == n.Z_DIALOG or cmd.op == n.Z_URL) return Portal.request(cmd, id);
|
||||
if (cmd.op == n.Z_WATCH) return Watch.create(cmd, &result.*);
|
||||
if (cmd.op == n.Z_CLIP_WRITE) return Data.write(cmd.text);
|
||||
if (cmd.op == n.Z_CLIP_READ) return Data.read(id, cmd.limit);
|
||||
const ptr = if (cmd.target != null) n.z_object_native(cmd.target) else null;
|
||||
|
|
@ -674,3 +687,10 @@ export fn z_native_gl_proc(ptr: ?*anyopaque, name: n.uhdk_text, out: [*c]n.uhdk_
|
|||
export fn z_native_file_init(file: ?*n.uhdk_file, path: n.uhdk_bytes, uri: n.uhdk_text, grant: ?*anyopaque) u32 {
|
||||
return @import("Files.zig").init(file, path, uri, grant);
|
||||
}
|
||||
|
||||
export fn z_native_watch_prepare(root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, out: *?*anyopaque) u32 {
|
||||
return Watch.prepare(root, handle, out);
|
||||
}
|
||||
export fn z_native_watch_commit(handle: ?*n.uhdk_watch, prepared: *anyopaque) void {
|
||||
Watch.commit(handle, prepared);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -90,7 +90,7 @@ static ZHost *host;
|
|||
static CFRunLoopSourceRef source;
|
||||
static void sourcePerform(void *info) {
|
||||
@autoreleasepool {
|
||||
z_tick(info);
|
||||
z_dispatch(info);
|
||||
}
|
||||
}
|
||||
static NSRange safeRange(NSRange r, NSUInteger length) {
|
||||
|
|
@ -1160,7 +1160,8 @@ static void watchEvents(ConstFSEventStreamRef stream, void *info, size_t count,
|
|||
uhdk_file_release(child);
|
||||
}
|
||||
}
|
||||
static uhdk_status createWatch(uhdk_file *root, uhdk_watch *handle) {
|
||||
uhdk_status z_native_watch_prepare(uhdk_file *root, uhdk_watch *handle, void **out) {
|
||||
@autoreleasepool {
|
||||
NSURL *url = fileURL(root);
|
||||
struct stat st;
|
||||
if (stat(url.fileSystemRepresentation, &st) != 0)
|
||||
|
|
@ -1173,24 +1174,35 @@ static uhdk_status createWatch(uhdk_file *root, uhdk_watch *handle) {
|
|||
ZWatch *watch = [ZWatch new];
|
||||
watch.root = root;
|
||||
watch.handle = handle;
|
||||
watch.path = [NSFileManager.defaultManager stringWithFileSystemRepresentation:resolved
|
||||
watch.path =
|
||||
[NSFileManager.defaultManager stringWithFileSystemRepresentation:resolved
|
||||
length:strlen(resolved)];
|
||||
watch.directory = S_ISDIR(st.st_mode);
|
||||
watch.observed = watch.directory ? watch.path : watch.path.stringByDeletingLastPathComponent;
|
||||
watch.observed =
|
||||
watch.directory ? watch.path : watch.path.stringByDeletingLastPathComponent;
|
||||
FSEventStreamContext context = {0, (__bridge void *)watch, NULL, NULL, NULL};
|
||||
watch.stream = FSEventStreamCreate(
|
||||
NULL, watchEvents, &context, (__bridge CFArrayRef) @[ watch.observed ],
|
||||
kFSEventStreamEventIdSinceNow, 0.05,
|
||||
NULL,
|
||||
watchEvents,
|
||||
&context,
|
||||
(__bridge CFArrayRef) @[ watch.observed ],
|
||||
kFSEventStreamEventIdSinceNow,
|
||||
0.05,
|
||||
kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagUseCFTypes |
|
||||
kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagNoDefer);
|
||||
kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagNoDefer
|
||||
);
|
||||
if (!watch.stream)
|
||||
return UHDK_STATUS_OS_ERROR;
|
||||
FSEventStreamSetDispatchQueue(watch.stream, dispatch_get_main_queue());
|
||||
if (!FSEventStreamStart(watch.stream))
|
||||
return UHDK_STATUS_OS_ERROR;
|
||||
z_object_set_native(handle, (__bridge_retained void *)watch);
|
||||
*out = (__bridge_retained void *)watch;
|
||||
return UHDK_STATUS_OK;
|
||||
}
|
||||
}
|
||||
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) {
|
||||
if (host.panel)
|
||||
|
|
@ -1311,21 +1323,52 @@ void z_native_run(void) {
|
|||
[NSApp run];
|
||||
}
|
||||
}
|
||||
void z_native_pump(uint64_t timeout_ns) {
|
||||
@autoreleasepool {
|
||||
NSDate *until = timeout_ns == UINT64_MAX
|
||||
? [NSDate distantFuture]
|
||||
: [NSDate dateWithTimeIntervalSinceNow:(double)timeout_ns / 1e9];
|
||||
for (unsigned i = 0; i < 64; ++i) {
|
||||
NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny
|
||||
untilDate:i == 0 ? until : [NSDate distantPast]
|
||||
inMode:NSDefaultRunLoopMode
|
||||
dequeue:YES];
|
||||
if (!event)
|
||||
break;
|
||||
[NSApp sendEvent:event];
|
||||
}
|
||||
[NSApp updateWindows];
|
||||
}
|
||||
}
|
||||
void z_native_wake(void) {
|
||||
@autoreleasepool {
|
||||
if (source) {
|
||||
CFRunLoopSourceSignal(source);
|
||||
CFRunLoopWakeUp(CFRunLoopGetMain());
|
||||
// A source can run without nextEvent returning. Post an event as well so
|
||||
// caller-owned polling observes worker completions promptly.
|
||||
[NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined
|
||||
location:NSZeroPoint
|
||||
modifierFlags:0
|
||||
timestamp:0
|
||||
windowNumber:0
|
||||
context:nil
|
||||
subtype:0
|
||||
data1:0
|
||||
data2:0]
|
||||
atStart:NO];
|
||||
}
|
||||
}
|
||||
}
|
||||
void z_native_again(void) {
|
||||
if (host.workTimer)
|
||||
if (!host || host.workTimer)
|
||||
return;
|
||||
host.workTimer = [NSTimer timerWithTimeInterval:0.001
|
||||
repeats:NO
|
||||
block:^(NSTimer *timer) {
|
||||
(void)timer;
|
||||
host.workTimer = nil;
|
||||
z_tick(host.app);
|
||||
z_dispatch(host.app);
|
||||
}];
|
||||
[NSRunLoop.mainRunLoop addTimer:host.workTimer forMode:NSRunLoopCommonModes];
|
||||
}
|
||||
|
|
@ -1649,7 +1692,7 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
|
|||
host.popup = menu;
|
||||
host.popupID = request;
|
||||
host.popupSelected = NO;
|
||||
// Run outside z_tick: tracking runs a nested loop and must service cancellation.
|
||||
// Run outside z_dispatch: tracking runs a nested loop and must service cancellation.
|
||||
NSPoint point = NSMakePoint(cmd->point.x, cmd->point.y);
|
||||
CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopCommonModes, ^{
|
||||
if (host.popupID != request)
|
||||
|
|
@ -1664,6 +1707,18 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
|
|||
z_native_wake();
|
||||
});
|
||||
CFRunLoopWakeUp(CFRunLoopGetMain());
|
||||
// A source can run without nextEvent returning. Post an event as well so
|
||||
// caller-owned polling observes worker completions promptly.
|
||||
[NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined
|
||||
location:NSZeroPoint
|
||||
modifierFlags:0
|
||||
timestamp:0
|
||||
windowNumber:0
|
||||
context:nil
|
||||
subtype:0
|
||||
data1:0
|
||||
data2:0]
|
||||
atStart:NO];
|
||||
return Z_DEFERRED;
|
||||
}
|
||||
case Z_ICON: {
|
||||
|
|
@ -1698,12 +1753,6 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
|
|||
return UHDK_STATUS_OS_ERROR;
|
||||
break;
|
||||
}
|
||||
case Z_WATCH: {
|
||||
uhdk_status status = createWatch(cmd->target, cmd->other);
|
||||
if (status == UHDK_STATUS_OK)
|
||||
result->value.watch = cmd->other;
|
||||
return status;
|
||||
}
|
||||
case Z_DESTROY: {
|
||||
uint32_t kind = z_object_kind(cmd->target);
|
||||
void *native = z_object_native(cmd->target);
|
||||
|
|
|
|||
|
|
@ -108,6 +108,10 @@ typedef struct z_command {
|
|||
} z_command;
|
||||
uhdk_status z_native_start(uhdk_app *, uhdk_text name);
|
||||
void z_native_run(void);
|
||||
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);
|
||||
|
|
@ -123,7 +127,7 @@ void z_native_handles(void *, uhdk_native_window *);
|
|||
/* Pure path conversions (no file access); copied synchronously by z_file_init. */
|
||||
uhdk_status z_native_file_init(uhdk_file *, uhdk_bytes path, uhdk_text uri, void *grant);
|
||||
/* Zig callbacks, always return before native temporary spans expire. */
|
||||
void z_tick(uhdk_app *);
|
||||
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_object_native(void *);
|
||||
|
|
@ -137,4 +141,7 @@ 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 *);
|
||||
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);
|
||||
|
||||
#endif
|
||||
|
|
|
|||
126
src/runtime.zig
126
src/runtime.zig
|
|
@ -34,6 +34,8 @@ 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;
|
||||
}
|
||||
|
||||
|
|
@ -240,6 +242,12 @@ pub fn submit(application: *Application, command: *Request, out: [*c]u64) abi.St
|
|||
abandon(command);
|
||||
return abi.UNAVAILABLE;
|
||||
}
|
||||
if ((command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) and application.io_pending >= 64) {
|
||||
application.unlock();
|
||||
abandon(command);
|
||||
return c.UHDK_STATUS_BUSY;
|
||||
}
|
||||
if (command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) application.io_pending += 1;
|
||||
command.id = application.next_id;
|
||||
application.next_id += 1;
|
||||
out.* = command.id;
|
||||
|
|
@ -296,6 +304,7 @@ pub fn finish(
|
|||
node.event.data.request.diagnostic = .{ .ptr = null, .len = 0 };
|
||||
};
|
||||
application.lock();
|
||||
if (command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) application.io_pending -= 1;
|
||||
var link = &application.requests;
|
||||
while (link.*) |request| {
|
||||
if (request == command) {
|
||||
|
|
@ -309,21 +318,71 @@ pub fn finish(
|
|||
destroyCommand(command);
|
||||
}
|
||||
|
||||
pub fn hasFrame(application: *Application) bool {
|
||||
application.lock();
|
||||
defer application.unlock();
|
||||
var cursor = application.objects;
|
||||
while (cursor) |object| : (cursor = object.next) {
|
||||
if (object.payload == .gl and object.payload.gl.bracket) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
pub fn applicationMain(application: *Application) void {
|
||||
const app_api = @import("api/app.zig");
|
||||
const handle = toAppHandle(application);
|
||||
profile.thread("UHDK application/render");
|
||||
const pool = c.z_native_pool_push();
|
||||
defer c.z_native_pool_pop(pool);
|
||||
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 {
|
||||
profile.thread("UHDK file I/O");
|
||||
while (true) {
|
||||
application.lock();
|
||||
application.worker_id = std.Thread.getCurrentId();
|
||||
const command = application.io_head orelse {
|
||||
const done = application.io_exit;
|
||||
application.io_available.reset();
|
||||
application.unlock();
|
||||
application.entry.?(toAppHandle(application), application.user);
|
||||
if (@import("builtin").os.tag == .windows or @import("builtin").os.tag == .linux) _ = c.z_native_gl(null, 4, null);
|
||||
if (done) return;
|
||||
application.io_available.waitUncancelable(application.io);
|
||||
continue;
|
||||
};
|
||||
application.io_head = command.queued_next;
|
||||
if (application.io_head == null) application.io_tail = null;
|
||||
command.queued_next = null;
|
||||
application.io_active = command;
|
||||
application.unlock();
|
||||
if (comptime @import("builtin").is_test) {
|
||||
if (application.io_test_hook) |hook| hook.before(hook.context);
|
||||
}
|
||||
if (command.data.op == c.Z_WATCH) {
|
||||
if (isCancelled(application, command)) {
|
||||
command.io_status = abi.CANCELLED;
|
||||
} else {
|
||||
command.io_status = c.z_native_watch_prepare(@ptrCast(command.data.target), @ptrCast(command.data.other), &command.io_prepared);
|
||||
command.io_result.value.watch = @ptrCast(command.data.other);
|
||||
}
|
||||
} else while (!fileStep(application, command)) {}
|
||||
// Close OS file handles on the worker, before result retirement on main.
|
||||
// Read results remain owned by FileOperation until main copies them.
|
||||
if (command.file_operation) |*operation| operation.close();
|
||||
application.lock();
|
||||
application.stopping = true;
|
||||
application.worker_done = true;
|
||||
application.io_active = null;
|
||||
if (application.io_completed_tail) |tail| tail.queued_next = command else application.io_completed_head = command;
|
||||
application.io_completed_tail = command;
|
||||
application.unlock();
|
||||
c.z_native_wake();
|
||||
}
|
||||
}
|
||||
|
||||
fn finishIo(command: *Request, status: abi.Status, value: ?*const c.z_request_result) void {
|
||||
command.io_status = status;
|
||||
if (value) |v| command.io_result = v.*;
|
||||
}
|
||||
|
||||
pub fn createObjectCommand(handle: anytype, kind: u32, op: u32) !*Request {
|
||||
if (handle == null) return error.Invalid;
|
||||
|
|
@ -477,7 +536,7 @@ pub fn fileStep(application: *Application, command: *Request) bool {
|
|||
const zone = profile.begin(@src(), "UHDK file operation batch");
|
||||
defer zone.end();
|
||||
if (isCancelled(application, command)) {
|
||||
finish(application, command, abi.CANCELLED, null);
|
||||
finishIo(command, abi.CANCELLED, null);
|
||||
return true;
|
||||
}
|
||||
if (command.file_operation == null) {
|
||||
|
|
@ -496,7 +555,7 @@ pub fn fileStep(application: *Application, command: *Request) bool {
|
|||
);
|
||||
}
|
||||
const result = command.file_operation.?.step() catch |err| {
|
||||
finish(application, command, fileError(err), null);
|
||||
finishIo(command, fileError(err), null);
|
||||
return true;
|
||||
};
|
||||
var value = std.mem.zeroes(c.z_request_result);
|
||||
|
|
@ -515,7 +574,7 @@ pub fn fileStep(application: *Application, command: *Request) bool {
|
|||
.reserved = 0,
|
||||
},
|
||||
}
|
||||
finish(application, command, abi.OK, &value);
|
||||
finishIo(command, abi.OK, &value);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -635,14 +694,34 @@ pub fn complete(
|
|||
application.unlock();
|
||||
}
|
||||
|
||||
pub fn tick(handle: ?*c.uhdk_app) void {
|
||||
pub fn dispatch(handle: ?*c.uhdk_app) void {
|
||||
const zone = profile.begin(@src(), "UHDK platform dispatch");
|
||||
defer zone.end();
|
||||
const application = fromAppHandle(handle);
|
||||
// Native tracking loops can reenter the run loop; never reenter application command.
|
||||
if (application.in_tick) return;
|
||||
application.in_tick = true;
|
||||
defer application.in_tick = false;
|
||||
if (application.in_dispatch) return;
|
||||
application.in_dispatch = true;
|
||||
defer application.in_dispatch = false;
|
||||
while (true) {
|
||||
application.lock();
|
||||
const completed = application.io_completed_head orelse {
|
||||
application.unlock();
|
||||
break;
|
||||
};
|
||||
application.io_completed_head = completed.queued_next;
|
||||
if (application.io_completed_head == null) application.io_completed_tail = null;
|
||||
application.unlock();
|
||||
if (completed.io_prepared) |prepared| {
|
||||
const object = fromObjectHandle(completed.data.other);
|
||||
c.z_native_watch_commit(@ptrCast(object), prepared);
|
||||
if (isCancelled(application, completed) or !object.alive) {
|
||||
c.z_native_destroy(c.Z_KIND_WATCH, prepared);
|
||||
object.native = null;
|
||||
completed.io_status = abi.CANCELLED;
|
||||
}
|
||||
}
|
||||
finish(application, completed, completed.io_status, &completed.io_result);
|
||||
}
|
||||
const start = now(application.io);
|
||||
var count: usize = 0;
|
||||
while (count < 64 and now(application.io) - start < 2_000_000) : (count += 1) {
|
||||
|
|
@ -663,9 +742,12 @@ pub fn tick(handle: ?*c.uhdk_app) void {
|
|||
finish(application, command, abi.CANCELLED, null);
|
||||
continue;
|
||||
}
|
||||
if (command.data.op >= abi.IO_READ) {
|
||||
if (command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) {
|
||||
application.lock();
|
||||
if (application.io_tail) |tail| tail.queued_next = command else application.io_head = command;
|
||||
application.io_tail = command;
|
||||
application.io_available.set(application.io);
|
||||
application.unlock();
|
||||
continue;
|
||||
}
|
||||
var result = std.mem.zeroes(c.z_request_result);
|
||||
|
|
@ -692,16 +774,6 @@ pub fn tick(handle: ?*c.uhdk_app) void {
|
|||
finish(application, command, status, &result);
|
||||
}
|
||||
}
|
||||
if (application.io_active == null) {
|
||||
if (application.io_head) |command| {
|
||||
application.io_head = command.queued_next;
|
||||
if (application.io_head == null) application.io_tail = null;
|
||||
application.io_active = command;
|
||||
}
|
||||
}
|
||||
if (application.io_active) |command| {
|
||||
if (fileStep(application, command)) application.io_active = null;
|
||||
}
|
||||
// Only operations dispatched to native code need native cancellation hooks.
|
||||
application.lock();
|
||||
var cursor = application.requests;
|
||||
|
|
@ -726,7 +798,7 @@ pub fn tick(handle: ?*c.uhdk_app) void {
|
|||
application.stopped_sent = true;
|
||||
}
|
||||
const done = application.worker_done and empty;
|
||||
const again = application.queue_head != null or application.io_head != null or application.io_active != null or node == ids.len;
|
||||
const again = application.queue_head != null or application.io_completed_head != null or node == ids.len;
|
||||
application.unlock();
|
||||
if (done) c.z_native_stop() else if (again) c.z_native_again();
|
||||
if (done and application.native_running) c.z_native_stop() else if (again) c.z_native_again();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -454,7 +454,7 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
|
|||
if (hwnd == host.dispatch) {
|
||||
switch (msg) {
|
||||
case Z_WAKE:
|
||||
z_tick(host.app);
|
||||
z_dispatch(host.app);
|
||||
return 0;
|
||||
case Z_DIALOG_MESSAGE:
|
||||
showDialog();
|
||||
|
|
@ -1214,7 +1214,7 @@ static BOOL armWatch(Watch *watch) {
|
|||
NULL, &watch->overlapped, NULL);
|
||||
return watch->pending;
|
||||
}
|
||||
static uhdk_status createWatch(uhdk_file *root, uhdk_watch *handle) {
|
||||
uhdk_status z_native_watch_prepare(uhdk_file *root, uhdk_watch *handle, void **out) {
|
||||
WCHAR *path = filePath(root);
|
||||
if (!path)
|
||||
return UHDK_STATUS_OUT_OF_MEMORY;
|
||||
|
|
@ -1263,10 +1263,14 @@ static uhdk_status createWatch(uhdk_file *root, uhdk_watch *handle) {
|
|||
profileFree(watch);
|
||||
return status;
|
||||
}
|
||||
*out = watch;
|
||||
return UHDK_STATUS_OK;
|
||||
}
|
||||
void z_native_watch_commit(uhdk_watch *handle, void *prepared) {
|
||||
Watch *watch = prepared;
|
||||
watch->next = host.watches;
|
||||
host.watches = watch;
|
||||
z_object_set_native(handle, watch);
|
||||
return UHDK_STATUS_OK;
|
||||
}
|
||||
static void watchEvent(Watch *watch, uint32_t flags, uhdk_status status) {
|
||||
z_event e = {0};
|
||||
|
|
@ -1387,22 +1391,33 @@ uhdk_status z_native_start(uhdk_app *app, uhdk_text name) {
|
|||
preferences();
|
||||
return UHDK_STATUS_OK;
|
||||
}
|
||||
void z_native_run(void) {
|
||||
MSG message;
|
||||
while (host.running) {
|
||||
int result = GetMessageW(&message, NULL, 0, 0);
|
||||
if (result <= 0) {
|
||||
z_event e = {0};
|
||||
e.type = UHDK_EVENT_QUIT_REQUESTED;
|
||||
z_emit(host.app, &e);
|
||||
if (result < 0)
|
||||
break;
|
||||
continue;
|
||||
void z_native_pump(uint64_t timeout_ns) {
|
||||
uint64_t milliseconds = timeout_ns / 1000000 + (timeout_ns % 1000000 != 0);
|
||||
DWORD timeout = timeout_ns == UINT64_MAX
|
||||
? INFINITE
|
||||
: (DWORD)(milliseconds >= INFINITE ? INFINITE - 1 : milliseconds);
|
||||
DWORD result = MsgWaitForMultipleObjectsEx(0, NULL, timeout, QS_ALLINPUT, MWMO_INPUTAVAILABLE);
|
||||
if (result == WAIT_FAILED) {
|
||||
z_native_failed(host.app, UHDK_STATUS_OS_ERROR);
|
||||
host.running = FALSE;
|
||||
return;
|
||||
}
|
||||
MSG message;
|
||||
for (unsigned i = 0; i < 64 && PeekMessageW(&message, NULL, 0, 0, PM_REMOVE); ++i) {
|
||||
if (message.message == WM_QUIT) {
|
||||
z_event event = {0};
|
||||
event.type = UHDK_EVENT_QUIT_REQUESTED;
|
||||
z_emit(host.app, &event);
|
||||
} else {
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
|
|
@ -1854,12 +1869,6 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
|
|||
profileFree(url);
|
||||
return status > 32 ? UHDK_STATUS_OK : UHDK_STATUS_OS_ERROR;
|
||||
}
|
||||
case Z_WATCH: {
|
||||
uhdk_status status = createWatch(cmd->target, cmd->other);
|
||||
if (status == UHDK_STATUS_OK)
|
||||
result->value.watch = cmd->other;
|
||||
return status;
|
||||
}
|
||||
case Z_DESTROY: {
|
||||
void *native = z_object_native(cmd->target);
|
||||
z_object_set_native(cmd->target, NULL);
|
||||
|
|
|
|||
Loading…
Reference in New Issue