tagged lifetime requests

This commit is contained in:
Peterino2 2026-09-19 15:29:04 -07:00
parent 091fcee4ed
commit d24b46f883
23 changed files with 629 additions and 95 deletions

View File

@ -290,3 +290,45 @@ On-demand capture omits allocations made before connection, so it is not a full
live-heap snapshot. Failed allocations emit nothing; in-place resizes emit
free + alloc. Moving reallocations use alloc/copy/free to preserve event ordering.
Disabled builds use the original allocator directly.
### Caller-chosen async request tags
Every async operation takes a nonzero `uhdk_request_tag` chosen by the caller.
Completions return it as `uhdk_request_result.tag`; cancellation takes the same tag.
Tags are unique among requests whose completion has not yet been delivered,
including completed requests queued for the next frame. Repeated tags return
`BUSY`. Reuse a tag while handling its completion, or choose distinct tags for
concurrent operations. Failure to start reserves nothing and produces no event.
```c
enum { ReadModel = 1, ReadTexture = 2 };
uhdk_status status = uhdk_file_read_all_async(file, 128 * 1024 * 1024, ReadModel);
/* Later, in REQUEST_DONE handling: switch (result->tag) { ... } */
```
Components sharing a session must coordinate tags; pass a dedicated tag to each
component that starts asynchronous work.
### Errors and input lifecycles
`uhdk_status_message(status)` returns a static UTF-8 text span, usable without a
session and from any thread. It does not allocate or maintain a last-error slot.
Failed async results always contain a nonempty `diagnostic`: native detail when
available, otherwise the status message. Use status codes for decisions and text
for display; successful requests may have an empty diagnostic.
`uhdk_event.cycle_id` associates events within a pointer drag/capture, phased scroll
gesture, or IME preedit composition. These library-generated IDs are unique per
session and separate from caller request tags and native edit `input_id` values.
Hover, discrete wheel events, ordinary typing and unrelated events use zero.
Track the ID from the first relevant event; ignore updates from other cycles.
`UHDK_EVENT_CYCLE_END` carries the ID, window, and a `uhdk_cycle_end_event` payload.
Its `reason` distinguishes completion, cancellation, capture release/loss, focus
loss, hiding, replacement and shutdown. It reports the first observed ending
cause and retires the interaction, without deciding whether
the application should commit or undo its work. Destruction invalidates cycles
immediately; fatal errors or early close may prevent delivery of queued endings.
The C API exposes spans and plain event payloads. Typed payload helpers remain
consumer-owned; they are not part of the public header.

View File

@ -34,7 +34,7 @@
* - 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.
* - All calls belong to OS main except thread-safe uhdk_wake. Native dispatch
* - All calls belong to OS main except uhdk_wake and uhdk_status_message. 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
@ -134,13 +134,19 @@ typedef struct uhdk_window uhdk_window;
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 session. */
typedef uint64_t
uhdk_request_tag; /* Caller-chosen, nonzero; unique until completion is delivered. */
typedef struct uhdk_text {
const char *ptr;
uint64_t len;
} uhdk_text;
/* Human-readable English text for any status, including unknown values.
* Static library-owned UTF-8 span; valid for the library lifetime, no allocation,
* callable from any thread without a session. Never parse messages for logic. */
UHDK_API uhdk_text UHDK_CALL uhdk_status_message(uhdk_status status);
typedef struct uhdk_bytes {
const uint8_t *ptr;
uint64_t len;
@ -204,8 +210,12 @@ enum {
UHDK_CAP_OPENGL = 18
};
/* Every accepted async request returns a nonzero ID and exactly one terminal
/* Every accepted async request uses a caller-chosen nonzero tag and produces one terminal
* REQUEST_DONE during normal draining. Failure to accept produces no event.
* Tags are unique per session until REQUEST_DONE is delivered by next_frame.
* Duplicate tags return BUSY, including while completion is queued. Zero is invalid.
* Tags may be reused while handling their completion. Failure to accept reserves
* no tag and produces no completion. Private native IDs are never reused.
* Cancellation is best effort; an operation already committed may succeed.
* Closing a session early abandons undelivered results and drains internal work.
*/
@ -231,10 +241,9 @@ UHDK_API uhdk_status UHDK_CALL uhdk_set_wake_deadline(uhdk_session *session, uin
* for a particular operation. Other platforms retain their fixed backend. */
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
);
/* Best effort; the tag remains reserved until its completion is delivered.
* NOT_FOUND means no executing request has this tag (its result may be queued). */
UHDK_API uhdk_status UHDK_CALL uhdk_request_cancel(uhdk_session *session, uhdk_request_tag tag);
/* A presented frame updates render_time_ns/frame_count. Frame CPU time excludes
* presentation, blocked waits and descheduling.
@ -638,14 +647,14 @@ typedef struct uhdk_file_info {
UHDK_API uhdk_status UHDK_CALL uhdk_file_read_all_async(
uhdk_file *file,
uint64_t max_bytes,
uhdk_request_id *out
uhdk_request_tag tag
);
UHDK_API uhdk_status UHDK_CALL uhdk_file_write_all_async(
uhdk_file *file,
uhdk_bytes bytes,
uhdk_request_id *out
uhdk_request_tag tag
);
UHDK_API uhdk_status UHDK_CALL uhdk_file_get_info_async(uhdk_file *file, uhdk_request_id *out);
UHDK_API uhdk_status UHDK_CALL uhdk_file_get_info_async(uhdk_file *file, uhdk_request_tag tag);
typedef uint32_t uhdk_dialog_kind;
enum {
@ -674,7 +683,7 @@ typedef struct uhdk_file_dialog_desc {
UHDK_API uhdk_status UHDK_CALL uhdk_file_dialog_show_async(
uhdk_session *session,
const uhdk_file_dialog_desc *desc,
uhdk_request_id *out
uhdk_request_tag tag
);
/* Plain-text clipboard only. Writes copy UTF-8 before returning; empty text is
@ -687,7 +696,7 @@ UHDK_API uhdk_status UHDK_CALL uhdk_clipboard_write_text(uhdk_session *session,
UHDK_API uhdk_status UHDK_CALL uhdk_clipboard_read_text_async(
uhdk_session *session,
uint64_t max_bytes,
uhdk_request_id *out
uhdk_request_tag tag
);
/* Incoming file drops only. When enabled, Uhdk negotiates copy-only file drops
@ -755,7 +764,7 @@ UHDK_API uhdk_status UHDK_CALL uhdk_menu_popup_async(
uhdk_menu *menu,
uhdk_window *window,
uhdk_point position,
uhdk_request_id *out
uhdk_request_tag tag
);
UHDK_API uhdk_status UHDK_CALL uhdk_set_icon(uhdk_session *session, const uhdk_image *image);
@ -764,7 +773,7 @@ UHDK_API uhdk_status UHDK_CALL uhdk_set_icon(uhdk_session *session, const uhdk_i
UHDK_API uhdk_status UHDK_CALL uhdk_shell_open_url_async(
uhdk_session *session,
uhdk_text url,
uhdk_request_id *out
uhdk_request_tag tag
);
typedef uint32_t uhdk_change_flags;
@ -785,7 +794,7 @@ enum {
* Changes may coalesce and are hints, not a transaction log. Renames may arrive
* as remove/create; no rename pairing is promised. RESCAN_REQUIRED means inspect
* current state. Pending notifications are suppressed after destroy; already borrowed batches remain valid. */
UHDK_API uhdk_status UHDK_CALL uhdk_watch_create_async(uhdk_file *root, uhdk_request_id *out);
UHDK_API uhdk_status UHDK_CALL uhdk_watch_create_async(uhdk_file *root, uhdk_request_tag tag);
UHDK_API void UHDK_CALL uhdk_watch_destroy(uhdk_watch *watch);
typedef uint32_t uhdk_appearance;
@ -833,7 +842,8 @@ enum {
UHDK_EVENT_MENU_COMMAND,
UHDK_EVENT_DROP_FILES,
UHDK_EVENT_WATCH,
UHDK_EVENT_REQUEST_DONE
UHDK_EVENT_REQUEST_DONE,
UHDK_EVENT_CYCLE_END /* uhdk_cycle_end_event; cycle_id identifies the interaction. */
};
typedef uint32_t uhdk_request_kind;
@ -988,14 +998,46 @@ typedef struct uhdk_watch_result {
* SHELL, FILE_WRITE, MENU_POPUP and failures have NULL/0 data.
*/
typedef struct uhdk_request_result {
uhdk_request_id id;
uhdk_request_tag tag;
uhdk_request_kind kind;
uhdk_status status;
uhdk_text diagnostic; /* Optional; for humans, never parse for logic. */
uhdk_text diagnostic; /* Nonempty on failure: native detail or status_message fallback. */
const void *data;
uint64_t data_size;
} uhdk_request_result;
typedef uint32_t uhdk_cycle_end_reason;
enum {
UHDK_CYCLE_COMPLETED = 0, /* Last button release, scroll end, or committed composition. */
UHDK_CYCLE_CANCELLED, /* Native scroll cancellation or composition ended without commit. */
UHDK_CYCLE_CAPTURE_RELEASED, /* Application explicitly released capture. */
UHDK_CYCLE_CAPTURE_LOST, /* Capture was interrupted externally. */
UHDK_CYCLE_FOCUS_LOST, /* Window focus or application activation was lost. */
UHDK_CYCLE_HIDDEN, /* Window was hidden; takes precedence over simultaneous focus loss. */
UHDK_CYCLE_SUPERSEDED, /* A new native gesture replaced an unfinished one. */
UHDK_CYCLE_SHUTDOWN /* Session is draining normally. */
};
typedef struct uhdk_cycle_end_event {
uhdk_cycle_end_reason reason;
} uhdk_cycle_end_event;
/* cycle_id groups a pointer drag/capture, phased scroll gesture, or visible IME
* preedit composition. Independent kinds/windows never share IDs; IDs are not
* request tags or input_id values and are never reused within a session.
* A pointer cycle starts on first button-down or capture activation. It ends
* after the last release without capture, or capture is released/lost. Hover,
* discrete wheel ticks and ordinary typing have cycle_id=0.
* Each ended cycle produces CYCLE_END with its ID, window and cycle_end_event. This
* covers normal completion, cancellation, focus loss, hiding and normal shutdown.
* Markers follow native ending events; session deactivation and shutdown emit
* them before APP_ACTIVATION(false) and STOPPED. The reason reports the first
* observed terminating cause; later native cleanup does not replace it. They signal retirement, not
* whether an application operation should be committed or rolled back.
* Destroying a window or closing a session invalidates its cycles immediately;
* queued events may be discarded. Fatal errors can interrupt delivery.
*/
/* Event data mapping:
* APP_ACTIVATION: uhdk_activation_event; OPEN_FILES: uhdk_file_list;
* WINDOW_METRICS: uhdk_window_metrics; PREFERENCES_CHANGED: uhdk_preferences;
@ -1004,7 +1046,7 @@ typedef struct uhdk_request_result {
* 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;
* REQUEST_DONE: uhdk_request_result.
* REQUEST_DONE: uhdk_request_result; CYCLE_END: uhdk_cycle_end_event.
* All other events have NULL/0 data.
*/
struct uhdk_event {
@ -1012,6 +1054,7 @@ struct uhdk_event {
uhdk_event_type type;
uint64_t time_ns;
uint64_t input_id; /* Correlates raw key and native edit/text; zero for non-input. */
uint64_t cycle_id; /* Session-unique library identity for an input lifecycle; zero otherwise. */
uhdk_window *window;
const void *data;
uint64_t data_size;

View File

@ -13,6 +13,7 @@ gpa: std.mem.Allocator,
io: std.Io,
mutex: std.Io.Mutex = .init,
in_dispatch: bool = false,
next_cycle: u64 = 1,
objects: ?*Resource = null,
queue_head: ?*Request = null,
queue_tail: ?*Request = null,

259
src/Cycles.zig Normal file
View File

@ -0,0 +1,259 @@
//! Shared identities for multi-event input interactions; called under the app lock.
const std = @import("std");
const c = @import("native");
const Cycles = @This();
pointer: u64 = 0,
scroll: u64 = 0,
composition: u64 = 0,
composition_committed: bool = false,
buttons: u32 = 0,
captured: bool = false,
pub const Ended = struct {
ids: [3]u64 = @splat(0),
reasons: [3]c.uhdk_cycle_end_reason = @splat(c.UHDK_CYCLE_COMPLETED),
len: usize = 0,
fn take(self: *Ended, id: *u64, reason: c.uhdk_cycle_end_reason) void {
if (id.* == 0) return;
self.ids[self.len] = id.*;
self.reasons[self.len] = reason;
self.len += 1;
id.* = 0;
}
};
fn begin(id: *u64, next: *u64) !void {
if (id.* != 0) return;
if (next.* == std.math.maxInt(u64)) return error.Exhausted;
id.* = next.*;
next.* += 1;
}
pub fn endAll(self: *Cycles, reason: c.uhdk_cycle_end_reason) Ended {
var ended: Ended = .{};
ended.take(&self.pointer, reason);
ended.take(&self.scroll, reason);
ended.take(&self.composition, reason);
self.buttons = 0;
self.captured = false;
self.composition_committed = false;
return ended;
}
pub fn apply(self: *Cycles, next: *u64, event: *c.z_event) !Ended {
var ended: Ended = .{};
event.cycle_id = 0;
switch (event.type) {
c.UHDK_EVENT_POINTER_BUTTON => {
const p = event.data.pointer;
if (p.button == 0 or p.button >= 32) return ended;
const bit = @as(u32, 1) << @as(u5, @intCast(p.button));
if (p.pressed != 0) {
try begin(&self.pointer, next);
self.buttons |= bit;
} else self.buttons &= ~bit;
event.cycle_id = self.pointer;
if (self.buttons == 0 and !self.captured) ended.take(&self.pointer, c.UHDK_CYCLE_COMPLETED);
},
c.UHDK_EVENT_POINTER_ENTER, c.UHDK_EVENT_POINTER_LEAVE, c.UHDK_EVENT_POINTER_MOVE => event.cycle_id = self.pointer,
c.UHDK_EVENT_POINTER_MODE_CHANGED => {
self.captured = event.data.pointer_mode == c.UHDK_POINTER_CAPTURE;
if (self.captured) try begin(&self.pointer, next);
event.cycle_id = self.pointer;
if (!self.captured) {
self.buttons = 0;
ended.take(&self.pointer, event.cycle_end_reason);
}
},
c.UHDK_EVENT_SCROLL => {
const phase = event.data.scroll.phase;
if (phase != c.UHDK_SCROLL_DISCRETE) {
// A new native BEGIN retires an interrupted previous gesture.
if (phase == c.UHDK_SCROLL_BEGIN) ended.take(&self.scroll, c.UHDK_CYCLE_SUPERSEDED);
if (phase == c.UHDK_SCROLL_BEGIN or phase == c.UHDK_SCROLL_UPDATE) try begin(&self.scroll, next);
event.cycle_id = self.scroll;
if (phase == c.UHDK_SCROLL_END or phase == c.UHDK_SCROLL_CANCEL)
ended.take(&self.scroll, if (phase == c.UHDK_SCROLL_CANCEL) c.UHDK_CYCLE_CANCELLED else c.UHDK_CYCLE_COMPLETED);
}
},
c.UHDK_EVENT_TEXT_PREEDIT => {
if (self.composition == 0) self.composition_committed = false;
try begin(&self.composition, next);
event.cycle_id = self.composition;
},
c.UHDK_EVENT_TEXT_COMMIT => {
event.cycle_id = self.composition;
if (self.composition != 0) self.composition_committed = true;
},
c.UHDK_EVENT_TEXT_COMPOSITION_END => {
event.cycle_id = self.composition;
ended.take(&self.composition, if (self.composition_committed) c.UHDK_CYCLE_COMPLETED else c.UHDK_CYCLE_CANCELLED);
self.composition_committed = false;
},
c.UHDK_EVENT_WINDOW_METRICS => {
if (event.data.metrics.visible == 0) return self.endAll(c.UHDK_CYCLE_HIDDEN);
if (event.data.metrics.focused == 0) return self.endAll(c.UHDK_CYCLE_FOCUS_LOST);
},
else => {},
}
return ended;
}
test "drag and capture share a cycle and late releases cannot revive it" {
var state: Cycles = .{};
var next: u64 = 1;
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event);
const drag = event.cycle_id;
try std.testing.expect(drag != 0);
event.type = c.UHDK_EVENT_POINTER_MODE_CHANGED;
event.data.pointer_mode = c.UHDK_POINTER_CAPTURE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(drag, event.cycle_id);
event.type = c.UHDK_EVENT_POINTER_MOVE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(drag, event.cycle_id);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer = std.mem.zeroes(c.uhdk_pointer_event);
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
try std.testing.expectEqual(@as(usize, 0), (try state.apply(&next, &event)).len);
event.type = c.UHDK_EVENT_POINTER_MODE_CHANGED;
event.data.pointer_mode = c.UHDK_POINTER_NORMAL;
const ended = try state.apply(&next, &event);
try std.testing.expectEqual(@as(usize, 1), ended.len);
try std.testing.expectEqual(drag, ended.ids[0]);
event.type = c.UHDK_EVENT_POINTER_MOVE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(@as(u64, 0), event.cycle_id);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer = std.mem.zeroes(c.uhdk_pointer_event);
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(@as(u64, 0), event.cycle_id);
event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event);
try std.testing.expect(event.cycle_id != drag);
}
test "independent windows and kinds get distinct cycles and focus loss ends all" {
var state: Cycles = .{};
var other: Cycles = .{};
var next: u64 = 1;
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event);
const pointer = event.cycle_id;
_ = try other.apply(&next, &event);
try std.testing.expect(event.cycle_id != pointer);
event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_BEGIN;
_ = try state.apply(&next, &event);
const scroll = event.cycle_id;
event.data.scroll.phase = c.UHDK_SCROLL_UPDATE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(scroll, event.cycle_id);
event.type = c.UHDK_EVENT_TEXT_PREEDIT;
_ = try state.apply(&next, &event);
const composition = event.cycle_id;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(composition, event.cycle_id);
event.type = c.UHDK_EVENT_TEXT_COMMIT;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(composition, event.cycle_id);
try std.testing.expect(pointer != scroll and scroll != composition);
event.type = c.UHDK_EVENT_WINDOW_METRICS;
event.data.metrics = std.mem.zeroes(c.uhdk_window_metrics);
const ended = try state.apply(&next, &event);
try std.testing.expectEqual(@as(usize, 3), ended.len);
try std.testing.expectEqualSlices(u64, &.{ pointer, scroll, composition }, &ended.ids);
try std.testing.expectEqual(@as(usize, 0), (try state.apply(&next, &event)).len);
event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_DISCRETE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(@as(u64, 0), event.cycle_id);
}
test "interleaved gestures finish independently and a chord ends on its last release" {
var state: Cycles = .{};
var next: u64 = 1;
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event);
const pointer = event.cycle_id;
event.data.pointer.button = c.UHDK_BUTTON_SECONDARY;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(pointer, event.cycle_id);
event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_BEGIN;
_ = try state.apply(&next, &event);
const scroll = event.cycle_id;
event.type = c.UHDK_EVENT_TEXT_PREEDIT;
_ = try state.apply(&next, &event);
const composition = event.cycle_id;
event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_END;
const scroll_end = try state.apply(&next, &event);
try std.testing.expectEqual(scroll, event.cycle_id);
try std.testing.expectEqual(scroll, scroll_end.ids[0]);
event.type = c.UHDK_EVENT_TEXT_COMPOSITION_END;
const ime_end = try state.apply(&next, &event);
try std.testing.expectEqual(composition, event.cycle_id);
try std.testing.expectEqual(composition, ime_end.ids[0]);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer = std.mem.zeroes(c.uhdk_pointer_event);
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
try std.testing.expectEqual(@as(usize, 0), (try state.apply(&next, &event)).len);
try std.testing.expectEqual(pointer, event.cycle_id);
event.data.pointer.button = c.UHDK_BUTTON_SECONDARY;
const pointer_end = try state.apply(&next, &event);
try std.testing.expectEqual(pointer, pointer_end.ids[0]);
try std.testing.expectEqual(@as(usize, 0), state.endAll(c.UHDK_CYCLE_SHUTDOWN).len);
}
test "cycle reasons distinguish release loss cancellation replacement and shutdown" {
var state: Cycles = .{};
var next: u64 = 1;
var event = std.mem.zeroes(c.z_event);
for ([_]c.uhdk_cycle_end_reason{ c.UHDK_CYCLE_CAPTURE_RELEASED, c.UHDK_CYCLE_CAPTURE_LOST, c.UHDK_CYCLE_FOCUS_LOST }) |reason| {
event.type = c.UHDK_EVENT_POINTER_MODE_CHANGED;
event.data.pointer_mode = c.UHDK_POINTER_CAPTURE;
_ = try state.apply(&next, &event);
event.data.pointer_mode = c.UHDK_POINTER_NORMAL;
event.cycle_end_reason = reason;
const ended = try state.apply(&next, &event);
try std.testing.expectEqual(@as(usize, 1), ended.len);
try std.testing.expectEqual(reason, ended.reasons[0]);
}
event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_BEGIN;
_ = try state.apply(&next, &event);
const superseded = try state.apply(&next, &event);
try std.testing.expectEqual(@as(u32, c.UHDK_CYCLE_SUPERSEDED), superseded.reasons[0]);
event.data.scroll.phase = c.UHDK_SCROLL_CANCEL;
try std.testing.expectEqual(@as(u32, c.UHDK_CYCLE_CANCELLED), (try state.apply(&next, &event)).reasons[0]);
for ([_]bool{ false, true }) |commit| {
event.type = c.UHDK_EVENT_TEXT_PREEDIT;
_ = try state.apply(&next, &event);
if (commit) {
event.type = c.UHDK_EVENT_TEXT_COMMIT;
_ = try state.apply(&next, &event);
}
event.type = c.UHDK_EVENT_TEXT_COMPOSITION_END;
try std.testing.expectEqual(@as(u32, if (commit) c.UHDK_CYCLE_COMPLETED else c.UHDK_CYCLE_CANCELLED), (try state.apply(&next, &event)).reasons[0]);
}
for ([_]bool{ false, true }) |hidden| {
event.type = c.UHDK_EVENT_TEXT_PREEDIT;
_ = try state.apply(&next, &event);
event.type = c.UHDK_EVENT_WINDOW_METRICS;
event.data.metrics = std.mem.zeroes(c.uhdk_window_metrics);
event.data.metrics.visible = @intFromBool(!hidden);
try std.testing.expectEqual(@as(u32, if (hidden) c.UHDK_CYCLE_HIDDEN else c.UHDK_CYCLE_FOCUS_LOST), (try state.apply(&next, &event)).reasons[0]);
}
event.type = c.UHDK_EVENT_TEXT_PREEDIT;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(@as(u32, c.UHDK_CYCLE_SHUTDOWN), state.endAll(c.UHDK_CYCLE_SHUTDOWN).reasons[0]);
}

View File

@ -25,7 +25,7 @@ fn result(allocator: std.mem.Allocator, source: c.z_request_result) !c.uhdk_requ
c.UHDK_REQUEST_WATCH => try store(c.uhdk_watch_result, allocator, .{ .watch = source.value.watch }),
else => .{},
};
return .{ .id = source.id, .kind = source.kind, .status = source.status, .diagnostic = try abi.copyText(allocator, source.diagnostic), .data = data.ptr, .data_size = data.size };
return .{ .tag = source.tag, .kind = source.kind, .status = source.status, .diagnostic = if (source.status != abi.OK and source.diagnostic.len == 0) abi.statusMessage(source.status) else try abi.copyText(allocator, source.diagnostic), .data = data.ptr, .data_size = data.size };
}
pub fn pack(allocator: std.mem.Allocator, source: c.z_event) !c.uhdk_event {
@ -51,8 +51,9 @@ 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_CYCLE_END => try store(c.uhdk_cycle_end_event, allocator, source.data.cycle_end),
c.UHDK_EVENT_REQUEST_DONE => try store(c.uhdk_request_result, allocator, try result(allocator, source.data.request)),
else => .{},
};
return .{ .struct_size = @sizeOf(c.uhdk_event), .type = source.type, .time_ns = source.time_ns, .input_id = source.input_id, .window = source.window, .data = data.ptr, .data_size = data.size };
return .{ .struct_size = @sizeOf(c.uhdk_event), .type = source.type, .time_ns = source.time_ns, .input_id = source.input_id, .cycle_id = source.cycle_id, .window = source.window, .data = data.ptr, .data_size = data.size };
}

View File

@ -14,7 +14,8 @@ arena: abi.Arena,
gpa: std.mem.Allocator,
data: c.z_command = std.mem.zeroes(c.z_command),
node: *Event,
id: u64 = 0,
id: u64 = 0, // Private monotonically increasing native identity.
tag: u64 = 0,
kind: u32 = 0,
cancelled: bool = false,
native_deferred: bool = false,

View File

@ -33,6 +33,7 @@ pub const Payload = union(Kind) {
};
pub const Window = struct {
cycles: @import("Cycles.zig") = .{},
context: ?*Resource = null,
parent: ?*Resource = null,
metrics: c.uhdk_window_metrics = std.mem.zeroes(c.uhdk_window_metrics),

View File

@ -61,3 +61,21 @@ pub fn finiteSize(s: c.uhdk_size) bool {
pub fn boundary(s: []const u8, offset: u64) bool {
return offset <= s.len and (offset == s.len or (s[@intCast(offset)] & 0xC0) != 0x80);
}
pub fn statusMessage(status: Status) c.uhdk_text {
return textSpan(switch (status) {
c.UHDK_STATUS_OK => "Success",
c.UHDK_STATUS_CANCELLED => "Operation cancelled",
c.UHDK_STATUS_UNSUPPORTED => "Operation not supported",
c.UHDK_STATUS_INVALID_ARGUMENT => "Invalid argument",
c.UHDK_STATUS_OUT_OF_MEMORY => "Out of memory",
c.UHDK_STATUS_PERMISSION_DENIED => "Permission denied",
c.UHDK_STATUS_UNAVAILABLE => "Resource unavailable",
c.UHDK_STATUS_NOT_FOUND => "Not found",
c.UHDK_STATUS_BUSY => "Resource or request tag is busy",
c.UHDK_STATUS_WRONG_THREAD => "Called from the wrong thread",
c.UHDK_STATUS_OS_ERROR => "Operating system error",
c.UHDK_STATUS_BUFFER_TOO_SMALL => "Buffer or requested size limit is too small",
else => "Unknown UHDK status",
});
}

View File

@ -245,14 +245,14 @@ pub export fn uhdk_has_capability(handle: ?*c.uhdk_session, cap: c.uhdk_capabili
};
}
pub export fn uhdk_request_cancel(handle: ?*c.uhdk_session, id: u64) abi.Status {
if (handle == null or id == 0) return abi.INVALID;
pub export fn uhdk_request_cancel(handle: ?*c.uhdk_session, tag: u64) abi.Status {
if (handle == null or tag == 0) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
application.lock();
var cursor = application.requests;
while (cursor) |command| : (cursor = command.next) {
if (command.id == id) {
if (command.completion == .request and command.tag == tag) {
command.cancelled = true;
application.unlock();
c.z_native_wake();
@ -288,3 +288,7 @@ fn releaseStorage(application: *Application) void {
gpa.destroy(application);
singleton = false;
}
pub export fn uhdk_status_message(status: abi.Status) c.uhdk_text {
return abi.statusMessage(status);
}

View File

@ -20,18 +20,18 @@ pub export fn uhdk_clipboard_write_text(
pub export fn uhdk_clipboard_read_text_async(
handle: ?*c.uhdk_session,
limit: u64,
out: [*c]u64,
tag: u64,
) abi.Status {
const command = runtime.createAppCommand(handle, c.Z_CLIP_READ) catch |err| return runtime.applicationError(err);
command.kind = c.UHDK_REQUEST_CLIPBOARD_TEXT;
command.data.limit = limit;
return runtime.submit(runtime.fromAppHandle(handle), command, out);
return runtime.submit(runtime.fromAppHandle(handle), command, tag);
}
pub export fn uhdk_shell_open_url_async(
handle: ?*c.uhdk_session,
text: c.uhdk_text,
out: [*c]u64,
tag: u64,
) abi.Status {
if (!abi.validText(text, true) or text.len == 0) return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_URL) catch |err| return runtime.applicationError(err);
@ -40,7 +40,7 @@ pub export fn uhdk_shell_open_url_async(
runtime.abandon(command);
return abi.OOM;
};
return runtime.submit(runtime.fromAppHandle(handle), command, out);
return runtime.submit(runtime.fromAppHandle(handle), command, tag);
}
pub export fn uhdk_set_icon(

View File

@ -7,7 +7,7 @@ const abi = @import("../abi.zig");
pub export fn uhdk_file_dialog_show_async(
handle: ?*c.uhdk_session,
desc: [*c]const c.uhdk_file_dialog_desc,
out: [*c]u64,
tag: u64,
) abi.Status {
if (handle == null or !abi.validDescriptor(c.uhdk_file_dialog_desc, desc)) return abi.INVALID;
const d = desc.*;
@ -27,7 +27,7 @@ pub export fn uhdk_file_dialog_show_async(
runtime.abandon(command);
return if (err == error.OutOfMemory) abi.OOM else abi.INVALID;
};
return runtime.submit(runtime.fromAppHandle(handle), command, out);
return runtime.submit(runtime.fromAppHandle(handle), command, tag);
}
pub export fn uhdk_file_create_from_native_path(
@ -103,17 +103,17 @@ pub export fn uhdk_file_copy_representation(
return abi.OK;
}
pub export fn uhdk_file_read_all_async(handle: ?*c.uhdk_file, limit: u64, out: [*c]u64) abi.Status {
pub export fn uhdk_file_read_all_async(handle: ?*c.uhdk_file, limit: u64, tag: u64) abi.Status {
const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, abi.IO_READ) catch |err| return runtime.objectError(err);
command.kind = c.UHDK_REQUEST_FILE_READ;
command.data.limit = limit;
return runtime.submit(runtime.fromObjectHandle(handle).app, command, out);
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);
}
pub export fn uhdk_file_write_all_async(
handle: ?*c.uhdk_file,
data: c.uhdk_bytes,
out: [*c]u64,
tag: u64,
) abi.Status {
if (!abi.validSpan(data.ptr, data.len)) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, abi.IO_WRITE) catch |err| return runtime.objectError(err);
@ -122,16 +122,16 @@ pub export fn uhdk_file_write_all_async(
runtime.abandon(command);
return abi.OOM;
};
return runtime.submit(runtime.fromObjectHandle(handle).app, command, out);
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);
}
pub export fn uhdk_file_get_info_async(handle: ?*c.uhdk_file, out: [*c]u64) abi.Status {
pub export fn uhdk_file_get_info_async(handle: ?*c.uhdk_file, tag: u64) abi.Status {
const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, abi.IO_INFO) catch |err| return runtime.objectError(err);
command.kind = c.UHDK_REQUEST_FILE_INFO;
return runtime.submit(runtime.fromObjectHandle(handle).app, command, out);
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);
}
pub export fn uhdk_watch_create_async(handle: ?*c.uhdk_file, out: [*c]u64) abi.Status {
pub export fn uhdk_watch_create_async(handle: ?*c.uhdk_file, tag: u64) abi.Status {
const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, c.Z_WATCH) catch |err| return runtime.objectError(err);
const f = runtime.fromObjectHandle(handle);
const object = runtime.createObject(f.app, c.Z_KIND_WATCH) catch {
@ -142,7 +142,7 @@ pub export fn uhdk_watch_create_async(handle: ?*c.uhdk_file, out: [*c]u64) abi.S
runtime.retain(f);
command.data.other = object;
command.kind = c.UHDK_REQUEST_WATCH;
return runtime.submit(f.app, command, out);
return runtime.submit(f.app, command, tag);
}
pub export fn uhdk_watch_destroy(handle: ?*c.uhdk_watch) void {

View File

@ -92,7 +92,7 @@ pub export fn uhdk_menu_popup_async(
handle: ?*c.uhdk_menu,
window: ?*c.uhdk_window,
point: c.uhdk_point,
out: [*c]u64,
tag: u64,
) abi.Status {
if (handle == null or
window == null or
@ -108,5 +108,5 @@ pub export fn uhdk_menu_popup_async(
};
command.data.point = point;
command.kind = c.UHDK_REQUEST_MENU_POPUP;
return runtime.submit(runtime.fromObjectHandle(handle).app, command, out);
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);
}

View File

@ -58,8 +58,8 @@ test "accepted request gets one terminal result when cancellation wins" {
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));
const request_id: u64 = 42;
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_OK), runtime.submit(application, command, request_id));
try std.testing.expect(request_id != 0);
application.lock();
command.cancelled = true;
@ -70,7 +70,7 @@ test "accepted request gets one terminal result when cancellation wins" {
const event = application.pending_head.?;
try std.testing.expect(event.next == null);
try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_REQUEST_DONE), event.event.type);
try std.testing.expectEqual(request_id, event.event.data.request.id);
try std.testing.expectEqual(request_id, event.event.data.request.tag);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_CANCELLED), event.event.data.request.status);
}
@ -126,7 +126,7 @@ test "poll allocation failure keeps queued terminal completion retryable" {
var bytes = [_]u8{42} ** 20000;
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_REQUEST_DONE;
event.data.request = .{ .id = 123, .kind = c.UHDK_REQUEST_FILE_READ, .status = abi.OK, .diagnostic = .{ .ptr = null, .len = 0 }, .value = .{ .bytes = .{ .ptr = &bytes, .len = bytes.len } } };
event.data.request = .{ .tag = 123, .kind = c.UHDK_REQUEST_FILE_READ, .status = abi.OK, .diagnostic = .{ .ptr = null, .len = 0 }, .value = .{ .bytes = .{ .ptr = &bytes, .len = bytes.len } } };
runtime.emit(handle, &event);
@memset(&bytes, 0);
failing.fail_index = failing.alloc_index;
@ -135,10 +135,12 @@ test "poll allocation failure keeps queued terminal completion retryable" {
try std.testing.expectEqual(@as(u64, 0), batch.len);
try std.testing.expect(application.pending_head != null);
failing.fail_index = std.math.maxInt(usize);
const duplicate = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, duplicate, 123));
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);
try std.testing.expectEqual(@as(u64, 123), result.tag);
const data: *const c.uhdk_bytes = @ptrCast(@alignCast(result.data.?));
try std.testing.expectEqual(@as(u64, bytes.len), data.len);
for (data.ptr[0..@intCast(data.len)]) |b| try std.testing.expectEqual(@as(u8, 42), b);
@ -221,8 +223,8 @@ test "blocked file execution leaves event polling live and cancellation drains o
}
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));
const id: u64 = 42;
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);
@ -248,7 +250,7 @@ test "blocked file execution leaves event polling live and cancellation drains o
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(id, result.tag);
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.poll(handle, 0, &events));
@ -256,7 +258,7 @@ test "blocked file execution leaves event polling live and cancellation drains o
}
}
test "file queue saturation rejects without accepting an ID" {
test "file queue saturation rejects without reserving a tag" {
const application = try Application.create(std.testing.allocator, std.testing.io, "io limit");
defer destroyApplication(application);
application.running = true;
@ -264,15 +266,12 @@ test "file queue saturation rejects without accepting an ID" {
application.main_thread = std.Thread.getCurrentId();
const file = try runtime.createObject(application, c.Z_KIND_FILE);
defer runtime.release(file);
for (0..64) |_| {
for (0..64) |i| {
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));
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, command, i + 1));
}
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);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, excess, 65));
application.stopping = true;
while (application.requests != null) runtime.dispatch(runtime.toAppHandle(application));
try std.testing.expectEqual(@as(usize, 0), application.io_pending);
@ -290,3 +289,97 @@ test "fatal native failure persists and wakes subsequent polls" {
var events: c.uhdk_event_list = undefined;
for (0..2) |_| try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_OS_ERROR), app_api.poll(handle, std.math.maxInt(u64), &events));
}
test "caller tags remain reserved until delivery and isolate late native completions" {
const app_api = @import("api/app.zig");
const application = try Application.create(std.testing.allocator, std.testing.io, "tags");
defer destroyApplication(application);
application.running = true;
application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application);
const tag = std.math.maxInt(u64); // The full nonzero caller range is available.
const zero = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, abi.INVALID), runtime.submit(application, zero, 0));
try std.testing.expect(application.requests == null);
const first = try runtime.createCommand(application, c.Z_CLIP_READ, null);
first.kind = c.UHDK_REQUEST_CLIPBOARD_TEXT;
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, first, tag));
const old_native_id = first.id;
const duplicate = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, duplicate, tag));
try std.testing.expectEqual(@as(u32, abi.OK), app_api.uhdk_request_cancel(handle, tag));
runtime.dispatch(handle);
const queued_duplicate = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, queued_duplicate, tag));
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_NOT_FOUND), app_api.uhdk_request_cancel(handle, tag));
var events: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 1), events.len);
const result: *const c.uhdk_request_result = @ptrCast(@alignCast(events.ptr[0].data.?));
try std.testing.expectEqual(tag, result.tag);
try std.testing.expectEqual(@as(u32, abi.CANCELLED), result.status);
const second = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, second, tag));
try std.testing.expect(second.id != old_native_id);
runtime.complete(handle, old_native_id, abi.OK, null);
try std.testing.expect(application.requests == second);
try std.testing.expect(application.pending_head == null);
try std.testing.expectEqual(@as(u32, abi.OK), app_api.uhdk_request_cancel(handle, tag));
runtime.dispatch(handle);
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 1), events.len);
}
test "error messages and diagnostics need no session and preserve native details" {
const app_api = @import("api/app.zig");
for (0..13) |status| {
const message = app_api.uhdk_status_message(@intCast(status));
try std.testing.expect(message.len > 0);
try std.testing.expect(abi.validText(message, true));
}
try std.testing.expect(app_api.uhdk_status_message(std.math.maxInt(u32)).len > 0);
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_REQUEST_DONE;
event.data.request.status = c.UHDK_STATUS_PERMISSION_DENIED;
const converted = try @import("EventPayload.zig").pack(arena.allocator(), event);
const result: *const c.uhdk_request_result = @ptrCast(@alignCast(converted.data.?));
try std.testing.expectEqualStrings(abi.textBytes(app_api.uhdk_status_message(c.UHDK_STATUS_PERMISSION_DENIED)), abi.textBytes(result.diagnostic));
event.data.request.diagnostic = abi.textSpan("Native context detail");
const detailed = try @import("EventPayload.zig").pack(arena.allocator(), event);
const with_detail: *const c.uhdk_request_result = @ptrCast(@alignCast(detailed.data.?));
try std.testing.expectEqualStrings("Native context detail", abi.textBytes(with_detail.diagnostic));
}
test "cycle end markers survive public event batching" {
const app_api = @import("api/app.zig");
const application = try Application.create(std.testing.allocator, std.testing.io, "cycles");
defer destroyApplication(application);
application.running = true;
application.main_thread = std.Thread.getCurrentId();
const window = try runtime.createObject(application, c.Z_KIND_WINDOW);
defer {
window.arena.deinit();
application.gpa.destroy(window);
}
const handle = runtime.toAppHandle(application);
var event = std.mem.zeroes(c.z_event);
event.window = runtime.castHandle(*c.uhdk_window, window);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1;
runtime.emit(handle, &event);
event.data.pointer.pressed = 0;
runtime.emit(handle, &event);
var batch: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 3), batch.len);
try std.testing.expect(batch.ptr[0].cycle_id != 0);
try std.testing.expectEqual(batch.ptr[0].cycle_id, batch.ptr[1].cycle_id);
try std.testing.expectEqual(batch.ptr[0].cycle_id, batch.ptr[2].cycle_id);
try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_CYCLE_END), batch.ptr[2].type);
try std.testing.expectEqual(@as(u64, @sizeOf(c.uhdk_cycle_end_event)), batch.ptr[2].data_size);
const ending: *const c.uhdk_cycle_end_event = @ptrCast(@alignCast(batch.ptr[2].data.?));
try std.testing.expectEqual(@as(u32, c.UHDK_CYCLE_COMPLETED), ending.reason);
}

View File

@ -329,7 +329,7 @@ fn leaveKeyboard() void {
s.modifiers = 0;
s.serial = 0;
if (s.state != null) _ = c.z_xkb_state_update_mask.?(s.state, 0, 0, 0, 0, 0, 0);
normal();
normal(n.UHDK_CYCLE_FOCUS_LOST);
}
fn pointerEvent(kind: u32, button_: u32, pressed: bool, delta: n.uhdk_point) void {
if (Popup.active()) return;
@ -357,7 +357,7 @@ fn pointerLeave(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, _: ?*c.struct_
fn leavePointer() void {
Popup.pointerLeave();
const s = state();
normal();
normal(n.UHDK_CYCLE_CAPTURE_LOST);
pointerEvent(n.UHDK_EVENT_POINTER_LEAVE, 0, false, .{ .x = 0, .y = 0 });
s.pointer_focus = null;
s.buttons = 0;
@ -413,7 +413,7 @@ fn button(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, _: u32, code: u
s.last_click_position = s.position;
} else s.buttons &= ~mask;
pointerEvent(n.UHDK_EVENT_POINTER_BUTTON, mapped, pressed != 0, .{ .x = 0, .y = 0 });
if (s.buttons == 0) normal();
if (s.buttons == 0) normal(n.UHDK_CYCLE_COMPLETED);
}
fn axis(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, which: u32, value: i32) callconv(.c) void {
const v: f32 = @as(f32, @floatFromInt(value)) / 256;
@ -474,7 +474,7 @@ pub fn capture(w: *native.Window, enabled: bool) u32 {
const s = state();
if (enabled and (s.pointer_focus != w or s.buttons == 0)) return abi.UNAVAILABLE;
if (!enabled) {
normal();
normal(n.UHDK_CYCLE_CAPTURE_RELEASED);
return abi.OK;
}
s.captured = true;
@ -484,7 +484,7 @@ pub fn capture(w: *native.Window, enabled: bool) u32 {
send(w, &e);
return abi.OK;
}
fn normal() void {
fn normal(reason: n.uhdk_cycle_end_reason) void {
const s = state();
if (!s.captured) return;
s.captured = false;
@ -492,6 +492,7 @@ fn normal() void {
var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_POINTER_MODE_CHANGED;
e.data.pointer_mode = n.UHDK_POINTER_NORMAL;
e.cycle_end_reason = reason;
send(w, &e);
}
}
@ -502,7 +503,7 @@ fn popupTrigger(w: ?*native.Window, serial: u32) void {
s.popup_time = runtime.now(b().app.io);
}
pub fn beginPopup() void {
normal();
normal(n.UHDK_CYCLE_CAPTURE_LOST);
state().buttons = 0;
state().scrolling = false;
}

View File

@ -93,7 +93,6 @@ fn done(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, serial: u32) callconv(.
// A cleared serial belongs to a cancelled/disabled input session.
const basis = sent orelse return;
if (t.pending_commit) |bytes| if (!std.unicode.utf8ValidateSlice(bytes)) return;
end(w);
if (t.pending_commit != null or t.before != 0 or t.after != 0) {
var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_TEXT_COMMIT;
@ -111,8 +110,10 @@ fn done(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, serial: u32) callconv(.
}
t.last_edit = event.input_id;
Input.send(w, &event);
end(w);
}
if (t.pending_preedit) |bytes| {
if (bytes.len == 0) end(w);
if (bytes.len != 0 and std.unicode.utf8ValidateSlice(bytes)) {
var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_TEXT_PREEDIT;

View File

@ -51,7 +51,7 @@ static void menus(uhdk_session *app) {
OK(uhdk_window_set_menu(b, override));
uhdk_menu_release(override); // The attachment must keep its model alive.
OK(uhdk_window_set_text_input(a, 1));
OK(uhdk_menu_popup_async(root, a, (uhdk_point){0, 0}, &id));
OK(uhdk_menu_popup_async(root, a, (uhdk_point){0, 0}, (id = 1)));
assert(wait_result(app, id).status == UHDK_STATUS_UNSUPPORTED);
menu_phase(app, a, "menus-ready");
unsigned stage = 0, opens_a = 0, opens_b = 0, copies = 0, quits = 0, overrides_seen = 0,

View File

@ -24,7 +24,7 @@ static void popups(uhdk_session *app) {
};
OK(uhdk_menu_create(app, items, 6, &root));
uhdk_menu_release(child);
OK(uhdk_menu_popup_async(root, w, (uhdk_point){4, 4}, &id));
OK(uhdk_menu_popup_async(root, w, (uhdk_point){4, 4}, (id = 1)));
assert(wait_result(app, id).status == UHDK_STATUS_UNAVAILABLE); // No input action yet.
for (unsigned stage = 0; stage < 12; ++stage) {
uhdk_menu *menu = root;
@ -52,10 +52,10 @@ static void popups(uhdk_session *app) {
assert(p->button == UHDK_BUTTON_SECONDARY);
if (p->pressed) {
assert(popup == 0);
OK(uhdk_menu_popup_async(menu, w, p->position, &popup));
OK(uhdk_menu_popup_async(menu, w, p->position, (popup = 2)));
started = uhdk_get_time_ns(app);
if (stage == 0)
OK(uhdk_menu_popup_async(menu, w, p->position, &busy));
OK(uhdk_menu_popup_async(menu, w, p->position, (busy = 3)));
}
} else if (e->type == UHDK_EVENT_MENU_COMMAND) {
uint64_t command = ((const uhdk_menu_event *)e->data)->command_id;
@ -72,12 +72,12 @@ static void popups(uhdk_session *app) {
++commands;
} else if (e->type == UHDK_EVENT_REQUEST_DONE) {
const uhdk_request_result *r = e->data;
if (r->id == popup && popup) {
if (r->tag == popup && popup) {
int selected = stage <= 2 || stage == 7 || stage == 8 || stage == 10;
assert(r->status == (selected ? UHDK_STATUS_OK : UHDK_STATUS_CANCELLED));
assert(commands == (unsigned)selected); // Ordering and exactly one action.
++complete;
} else if (r->id == busy && busy) {
} else if (r->tag == busy && busy) {
assert(r->status == UHDK_STATUS_BUSY);
++busy_done;
} else

View File

@ -29,7 +29,7 @@ static uhdk_request_result wait_result(uhdk_session *app, uint64_t id) {
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;
if (r->id == id)
if (r->tag == id)
return *r;
}
}
@ -98,7 +98,7 @@ static void watches(uhdk_session *app) {
app, (uhdk_bytes){(const uint8_t *)path, strlen(path)}, &file
));
uint64_t id;
OK(uhdk_watch_create_async(file, &id));
OK(uhdk_watch_create_async(file, (id = 1)));
uhdk_request_result result = wait_result(app, id);
OK(result.status);
uhdk_watch *watch = ((const uhdk_watch_result *)result.data)->watch;
@ -156,7 +156,7 @@ static void portals(uhdk_session *app) {
desc.filters = &filter;
desc.filters_len = 1;
uint64_t id;
OK(uhdk_file_dialog_show_async(app, &desc, &id));
OK(uhdk_file_dialog_show_async(app, &desc, (id = 2)));
uhdk_request_result r = wait_result(app, id);
OK(r.status);
const uhdk_file_list *files = r.data;
@ -180,7 +180,7 @@ static void portals(uhdk_session *app) {
desc.suggested_name = text("book.txt");
desc.accept_label = text("Store");
desc.initial_directory = directory;
OK(uhdk_file_dialog_show_async(app, &desc, &id));
OK(uhdk_file_dialog_show_async(app, &desc, (id = 3)));
r = wait_result(app, id);
OK(r.status);
assert(((const uhdk_file_list *)r.data)->len == 1);
@ -190,30 +190,30 @@ static void portals(uhdk_session *app) {
desc.suggested_name = text("");
desc.accept_label = text("");
desc.title = text("cancel");
OK(uhdk_file_dialog_show_async(app, &desc, &id));
OK(uhdk_file_dialog_show_async(app, &desc, (id = 4)));
// Allow method submission, then cancel while the mock withholds its reply.
uhdk_event_list 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(uhdk_shell_open_url_async(app, text("https://example.org/test"), (id = 5)));
OK(wait_result(app, id).status);
OK(uhdk_get_preferences(app, &prefs));
assert(
prefs.appearance == UHDK_APPEARANCE_LIGHT && !prefs.reduced_motion && !prefs.high_contrast
);
desc.title = text("parent");
OK(uhdk_file_dialog_show_async(app, &desc, &id));
OK(uhdk_file_dialog_show_async(app, &desc, (id = 6)));
uhdk_window_destroy(w);
assert(wait_result(app, id).status == UHDK_STATUS_CANCELLED);
desc.parent = NULL;
desc.title = text("restart");
OK(uhdk_file_dialog_show_async(app, &desc, &id));
OK(uhdk_file_dialog_show_async(app, &desc, (id = 7)));
assert(wait_result(app, id).status == UHDK_STATUS_UNAVAILABLE);
wait_capability(app, UHDK_CAP_FILE_DIALOGS);
desc.title = text("dismiss");
OK(uhdk_file_dialog_show_async(app, &desc, &id));
OK(uhdk_file_dialog_show_async(app, &desc, (id = 8)));
assert(wait_result(app, id).status == UHDK_STATUS_CANCELLED);
puts("portal results/cancellation/parent/restart: PASS");
}
@ -443,21 +443,21 @@ static void input(uhdk_session *app) {
assert(
key && repeat && commit >= 2 && preedit && pointer && scroll && dropped && copy && compose
);
OK(uhdk_clipboard_read_text_async(app, 3, &id));
OK(uhdk_clipboard_read_text_async(app, 3, (id = 9)));
assert(wait_result(app, id).status == UHDK_STATUS_BUFFER_TOO_SMALL);
OK(uhdk_clipboard_read_text_async(app, 100, &id));
OK(uhdk_clipboard_read_text_async(app, 100, (id = 10)));
uhdk_request_result r = wait_result(app, id);
OK(r.status);
const uhdk_text *t = r.data;
assert(t->len == 11 && memcmp(t->ptr, "hello café", 11) == 0);
OK(uhdk_clipboard_read_text_async(app, 100, &id));
OK(uhdk_clipboard_read_text_async(app, 100, (id = 11)));
uhdk_event_list 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));
OK(uhdk_clipboard_read_text_async(app, 100, (id = 12)));
assert(wait_result(app, id).status == UHDK_STATUS_INVALID_ARGUMENT);
OK(uhdk_clipboard_read_text_async(app, 0, &id));
OK(uhdk_clipboard_read_text_async(app, 0, (id = 13)));
r = wait_result(app, id);
OK(r.status);
assert(((const uhdk_text *)r.data)->len == 0);

View File

@ -811,6 +811,7 @@ static uhdk_key logical(NSEvent *e) {
self.view.capture = NO;
z_event e = {.type = UHDK_EVENT_POINTER_MODE_CHANGED, .window = self.handle};
e.data.pointer_mode = UHDK_POINTER_NORMAL;
e.cycle_end_reason = UHDK_CYCLE_FOCUS_LOST;
z_emit(host.app, &e);
}
[host refreshMenus];
@ -1638,6 +1639,7 @@ uhdk_status z_native_execute(
{
z_event e = {.type = UHDK_EVENT_POINTER_MODE_CHANGED, .window = w.handle};
e.data.pointer_mode = (uint32_t)cmd->number;
e.cycle_end_reason = UHDK_CYCLE_CAPTURE_RELEASED;
z_emit(app, &e);
}
break;

View File

@ -24,7 +24,7 @@ typedef struct 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;
uint64_t tag;
uhdk_request_kind kind;
uhdk_status status;
uhdk_text diagnostic; /* Optional; for humans, never parse for logic. */
@ -42,6 +42,8 @@ typedef struct z_event {
uhdk_event_type type;
uint64_t time_ns;
uint64_t input_id; /* Correlates raw key and native edit/text; zero for non-input. */
uint64_t cycle_id; /* Assigned by the shared event pipeline. */
uhdk_cycle_end_reason cycle_end_reason; /* Native cause for capture release/loss. */
uhdk_window *window;
union {
uhdk_bool active;
@ -58,6 +60,7 @@ typedef struct z_event {
uhdk_menu_event menu;
uhdk_watch_event watch;
z_request_result request;
uhdk_cycle_end_event cycle_end;
} data;
} z_event;

View File

@ -19,6 +19,7 @@ test {
std.testing.refAllDecls(@import("FileOperation.zig"));
std.testing.refAllDecls(@import("MinimalIo.zig"));
_ = @import("core_tests.zig");
_ = @import("Cycles.zig");
_ = @import("arenas.zig");
if (@import("builtin").os.tag == .linux) {
_ = @import("linux/Files.zig");
@ -42,7 +43,7 @@ fn checkExports(comptime module: type) void {
comptime {
std.debug.assert(@sizeOf(c.uhdk_bool) == 1);
std.debug.assert(@sizeOf(c.uhdk_status) == 4);
std.debug.assert(@sizeOf(c.uhdk_request_id) == 8);
std.debug.assert(@sizeOf(c.uhdk_request_tag) == 8);
std.debug.assert(@sizeOf(@FieldType(c.uhdk_point, "x")) == 4);
std.debug.assert(@sizeOf(c.uhdk_event) == c.Z_EVENT_SIZE);
std.debug.assert(@alignOf(c.uhdk_event) == c.Z_EVENT_ALIGNMENT);

View File

@ -210,10 +210,11 @@ fn discardCreation(command: *Request) void {
}
}
pub fn submit(application: *Application, command: *Request, out: [*c]u64) abi.Status {
if (out == null or checkThread(application) != abi.OK) {
pub fn submit(application: *Application, command: *Request, tag: u64) abi.Status {
if ((command.completion == .request and tag == 0) or checkThread(application) != abi.OK) {
const status: abi.Status = if (command.completion == .request and tag == 0) abi.INVALID else c.UHDK_STATUS_WRONG_THREAD;
abandon(command);
return if (out == null) abi.INVALID else c.UHDK_STATUS_WRONG_THREAD;
return status;
}
application.lock();
if (application.stopping or application.next_id == std.math.maxInt(u64)) {
@ -221,6 +222,25 @@ pub fn submit(application: *Application, command: *Request, out: [*c]u64) abi.St
abandon(command);
return abi.UNAVAILABLE;
}
if (command.completion == .request) {
var request = application.requests;
while (request) |pending| : (request = pending.next) {
if (pending.completion == .request and pending.tag == tag) {
application.unlock();
abandon(command);
return c.UHDK_STATUS_BUSY;
}
}
// A finished request still owns its tag until its event is delivered.
var event = application.pending_head;
while (event) |pending| : (event = pending.next) {
if (pending.event.type == c.UHDK_EVENT_REQUEST_DONE and pending.event.data.request.tag == tag) {
application.unlock();
abandon(command);
return c.UHDK_STATUS_BUSY;
}
}
}
if ((command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) and application.io_pending >= 64) {
application.unlock();
abandon(command);
@ -229,7 +249,7 @@ pub fn submit(application: *Application, command: *Request, out: [*c]u64) abi.St
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;
command.tag = tag;
command.next = application.requests;
application.requests = command;
if (application.queue_tail) |tail| tail.queued_next = command else application.queue_head = command;
@ -241,14 +261,12 @@ pub fn submit(application: *Application, command: *Request, out: [*c]u64) abi.St
pub fn submitResource(application: *Application, command: *Request) abi.Status {
command.completion = .resource;
var ignored: u64 = 0;
return submit(application, command, &ignored);
return submit(application, command, 0);
}
pub fn submitCommand(application: *Application, command: *Request) abi.Status {
command.completion = .discard;
var ignored: u64 = 0;
return submit(application, command, &ignored);
return submit(application, command, 0);
}
pub fn notifyCommand(object: *Resource, op: u32) void {
@ -299,7 +317,7 @@ pub fn finish(
.request => request: {
node.event.type = c.UHDK_EVENT_REQUEST_DONE;
if (value) |v| node.event.data.request = v.*;
node.event.data.request.id = command.id;
node.event.data.request.tag = command.tag;
node.event.data.request.kind = command.kind;
node.event.data.request.status = status;
copyPayload(node) catch {
@ -623,6 +641,22 @@ pub fn setMenuFlags(object: *Resource, id: u64, flags: u32) bool {
return false;
}
fn publishCycleEnds(application: *Application, window: *c.uhdk_window, ended: @import("Cycles.zig").Ended) void {
for (ended.ids[0..ended.len], ended.reasons[0..ended.len]) |id, reason| {
const node = application.gpa.create(Event) catch {
application.event_error = abi.OOM;
application.notify();
return;
};
node.* = .{ .gpa = application.gpa, .arena = .init(application.gpa) };
node.event.type = c.UHDK_EVENT_CYCLE_END;
node.event.window = window;
node.event.cycle_id = id;
node.event.data.cycle_end.reason = reason;
publishLocked(application, node);
}
}
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 {
@ -661,7 +695,30 @@ pub fn emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void {
}
}
}
publishLocked(application, node);
if (node.event.window) |window| {
const ended = fromObjectHandle(window).payload.window.cycles.apply(&application.next_cycle, &node.event) catch {
application.event_error = abi.UNAVAILABLE;
application.notify();
application.unlock();
destroyEvent(node);
application.lock();
return;
};
publishLocked(application, node);
publishCycleEnds(application, window, ended);
} else {
// Session deactivation and normal shutdown retire every active window cycle.
if ((node.event.type == c.UHDK_EVENT_APP_ACTIVATION and node.event.data.active == 0) or
node.event.type == c.UHDK_EVENT_STOPPED)
{
var cursor = application.objects;
while (cursor) |object| : (cursor = object.next) {
if (object.alive and object.payload == .window)
publishCycleEnds(application, castHandle(*c.uhdk_window, object), object.payload.window.cycles.endAll(if (node.event.type == c.UHDK_EVENT_STOPPED) c.UHDK_CYCLE_SHUTDOWN else c.UHDK_CYCLE_FOCUS_LOST));
}
}
publishLocked(application, node);
}
}
pub fn complete(

View File

@ -51,6 +51,7 @@ typedef struct Graphics {
uint32_t major, minor;
} Graphics;
struct Window {
BOOL releasing_capture;
Window *next;
HWND hwnd;
uhdk_window *handle;
@ -633,6 +634,8 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
e.type = UHDK_EVENT_POINTER_MODE_CHANGED;
e.window = w->handle;
e.data.pointer_mode = UHDK_POINTER_NORMAL;
e.cycle_end_reason =
w->releasing_capture ? UHDK_CYCLE_CAPTURE_RELEASED : UHDK_CYCLE_CAPTURE_LOST;
z_emit(host.app, &e);
return 0;
}
@ -1876,13 +1879,16 @@ uhdk_status z_native_execute(
if (GetCapture() != w->hwnd)
return UHDK_STATUS_OS_ERROR;
} else if (GetCapture() == w->hwnd) {
w->releasing_capture = TRUE;
ReleaseCapture();
w->releasing_capture = FALSE;
break;
}
z_event e = {0};
e.type = UHDK_EVENT_POINTER_MODE_CHANGED;
e.window = w->handle;
e.data.pointer_mode = (uint32_t)cmd->number;
e.cycle_end_reason = UHDK_CYCLE_CAPTURE_RELEASED;
z_emit(host.app, &e);
break;
}