This commit is contained in:
Peterino2 2026-09-21 19:33:44 +00:00
parent b55bcb3050
commit ce76333d32
36 changed files with 1237 additions and 26 deletions

View File

@ -4,12 +4,13 @@ pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{}); const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{}); const optimize = b.standardOptimizeOption(.{});
const use_llvm = b.option(bool, "use_llvm", "Use LLVM for Zig compilation") orelse null;
const shared = b.option(bool, "shared", "Build libuhdk as a shared library instead of static") orelse false; const shared = b.option(bool, "shared", "Build libuhdk as a shared library instead of static") orelse false;
const tracy = b.option(bool, "tracy", "Emit Tracy 0.14.1 on-demand hooks; consumer must link the client") orelse false; const tracy = b.option(bool, "tracy", "Emit Tracy 0.14.1 on-demand hooks; consumer must link the client") orelse false;
if (tracy and shared) @panic("Tracy instrumentation requires static linking"); if (tracy and shared) @panic("Tracy instrumentation requires static linking");
const lib = createLibraryNamed(b, target, optimize, shared, tracy, "uhdk"); const lib = createLibraryNamed(b, target, optimize, use_llvm, shared, tracy, "uhdk");
const module = lib.root_module; const module = lib.root_module;
const install_lib = b.addInstallArtifact(lib, .{}); const install_lib = b.addInstallArtifact(lib, .{});
const install_headers = b.addInstallDirectory(.{ const install_headers = b.addInstallDirectory(.{
@ -55,11 +56,11 @@ pub fn build(b: *std.Build) void {
// Create a library artifact without installing it. Instrumented static builds // Create a library artifact without installing it. Instrumented static builds
// require the consumer to link a matching Tracy client. // require the consumer to link a matching Tracy client.
pub fn createLibrary(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, shared: bool, instrumented: bool) *std.Build.Step.Compile { pub fn createLibrary(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, use_llvm: ?bool, shared: bool, instrumented: bool) *std.Build.Step.Compile {
return createLibraryNamed(b, target, optimize, shared, instrumented, if (instrumented) "uhdk-instrumented" else "uhdk"); return createLibraryNamed(b, target, optimize, use_llvm, shared, instrumented, if (instrumented) "uhdk-instrumented" else "uhdk");
} }
fn createLibraryNamed(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, shared: bool, instrumented: bool, artifact_name: []const u8) *std.Build.Step.Compile { fn createLibraryNamed(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, use_llvm: ?bool, shared: bool, instrumented: bool, artifact_name: []const u8) *std.Build.Step.Compile {
std.debug.assert(!shared or !instrumented); std.debug.assert(!shared or !instrumented);
const module = b.createModule(.{ const module = b.createModule(.{
@ -103,12 +104,14 @@ fn createLibraryNamed(b: *std.Build, target: std.Build.ResolvedTarget, optimize:
module.addCSourceFile(.{ .file = b.path("src/windows/native.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-DUNICODE", "-D_UNICODE" } }); module.addCSourceFile(.{ .file = b.path("src/windows/native.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-DUNICODE", "-D_UNICODE" } });
for ([_][]const u8{ "user32", "gdi32", "opengl32", "shell32", "ole32", "uuid", "imm32", "comctl32", "shlwapi", "advapi32", "api-ms-win-core-synch-l1-2-0" }) |name| module.linkSystemLibrary(name, .{}); for ([_][]const u8{ "user32", "gdi32", "opengl32", "shell32", "ole32", "uuid", "imm32", "comctl32", "shlwapi", "advapi32", "api-ms-win-core-synch-l1-2-0" }) |name| module.linkSystemLibrary(name, .{});
} }
module.addCSourceFile(.{ .file = b.path("src/gl_loader.c"), .flags = &.{ "-std=c99", "-Wall", "-Wextra", "-Werror", "-fvisibility=hidden" } }); module.addCSourceFile(.{ .file = b.path("src/gl_loader.c"), .flags = &.{ "-std=c99", "-Wall", "-Wextra", "-Werror", "-fvisibility=hidden" } });
module.addCSourceFile(.{ .file = b.path("src/platform_io.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } }); module.addCSourceFile(.{ .file = b.path("src/platform_io.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
const lib = b.addLibrary(.{ const lib = b.addLibrary(.{
.name = artifact_name, .name = artifact_name,
.linkage = if (shared) .dynamic else .static, .linkage = if (shared) .dynamic else .static,
.use_llvm = use_llvm,
.root_module = module, .root_module = module,
}); });
if (shared and target.result.os.tag == .linux) if (shared and target.result.os.tag == .linux)
@ -123,6 +126,7 @@ fn createLibraryNamed(b: *std.Build, target: std.Build.ResolvedTarget, optimize:
pub fn createProfileModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, enabled: bool) *std.Build.Module { pub fn createProfileModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, enabled: bool) *std.Build.Module {
const options = b.addOptions(); const options = b.addOptions();
options.addOption(bool, "enabled", enabled); options.addOption(bool, "enabled", enabled);
const profile = b.createModule(.{ const profile = b.createModule(.{
.root_source_file = b.path("src/Profile.zig"), .root_source_file = b.path("src/Profile.zig"),
.target = target, .target = target,

View File

@ -9,15 +9,18 @@ const Resource = @import("Resource.zig");
const arenas = @import("arenas.zig"); const arenas = @import("arenas.zig");
const Application = @This(); const Application = @This();
gpa: std.mem.Allocator, gpa: std.mem.Allocator,
io: std.Io, io: std.Io,
mutex: std.Io.Mutex = .init, mutex: std.Io.Mutex = .init,
in_dispatch: bool = false, in_dispatch: bool = false,
next_cycle: u64 = 1, next_cycle: u64 = 1,
objects: ?*Resource = null, objects: ?*Resource = null,
queue_head: ?*Request = null, queue_head: ?*Request = null,
queue_tail: ?*Request = null, queue_tail: ?*Request = null,
requests: ?*Request = null, requests: ?*Request = null,
io_active: ?*Request = null, io_active: ?*Request = null,
io_completed_head: ?*Request = null, io_completed_head: ?*Request = null,
io_completed_tail: ?*Request = null, io_completed_tail: ?*Request = null,
@ -25,6 +28,7 @@ io_pending: usize = 0,
io_worker: ?std.Thread = null, io_worker: ?std.Thread = null,
io_available: std.Io.Event = .unset, io_available: std.Io.Event = .unset,
io_exit: bool = false, io_exit: bool = false,
// Test-only gate permits deterministic blocked-filesystem scheduling tests. // Test-only gate permits deterministic blocked-filesystem scheduling tests.
io_test_hook: if (@import("builtin").is_test) ?struct { io_test_hook: if (@import("builtin").is_test) ?struct {
context: *anyopaque, context: *anyopaque,
@ -32,15 +36,18 @@ io_test_hook: if (@import("builtin").is_test) ?struct {
} else void = if (@import("builtin").is_test) null else {}, } else void = if (@import("builtin").is_test) null else {},
io_head: ?*Request = null, io_head: ?*Request = null,
io_tail: ?*Request = null, io_tail: ?*Request = null,
pending_head: ?*Event = null, pending_head: ?*Event = null,
pending_tail: ?*Event = null, pending_tail: ?*Event = null,
published: ?*Event = null, published: ?*Event = null,
scratch: arenas.BumpArena, scratch: arenas.BumpArena,
name: []u8, name: []u8,
application_id: []const u8 = "", application_id: []const u8 = "",
epoch: u64, epoch: u64,
deadline: u64 = 0, deadline: u64 = 0,
next_id: u64 = 1, next_id: u64 = 1,
running: bool = false, running: bool = false,
native_started: bool = false, native_started: bool = false,
native_error: abi.Status = abi.OK, native_error: abi.Status = abi.OK,
@ -49,9 +56,11 @@ stopped_sent: bool = false,
stopped_seen: bool = false, stopped_seen: bool = false,
event_error: abi.Status = abi.OK, event_error: abi.Status = abi.OK,
main_thread: ?std.Thread.Id = null, main_thread: ?std.Thread.Id = null,
preferences: c.uhdk_preferences = std.mem.zeroes(c.uhdk_preferences), preferences: c.uhdk_preferences = std.mem.zeroes(c.uhdk_preferences),
stats: c.uhdk_stats = std.mem.zeroes(c.uhdk_stats), stats: c.uhdk_stats = std.mem.zeroes(c.uhdk_stats),
last_frame_time: ?u64 = null, last_frame_time: ?u64 = null,
session_gl: c.uhdk_gl_functions = std.mem.zeroes(c.uhdk_gl_functions), session_gl: c.uhdk_gl_functions = std.mem.zeroes(c.uhdk_gl_functions),
session_window: ?*c.uhdk_window = null, session_window: ?*c.uhdk_window = null,
session_has_gl: bool = false, session_has_gl: bool = false,
@ -65,8 +74,10 @@ startup_timeout_ns: u64 = 10 * std.time.ns_per_s,
pub fn create(gpa: std.mem.Allocator, io: std.Io, name: []const u8) !*Application { pub fn create(gpa: std.mem.Allocator, io: std.Io, name: []const u8) !*Application {
const self = try gpa.create(Application); const self = try gpa.create(Application);
errdefer gpa.destroy(self); errdefer gpa.destroy(self);
const owned_name = try gpa.dupe(u8, name); const owned_name = try gpa.dupe(u8, name);
errdefer gpa.free(owned_name); errdefer gpa.free(owned_name);
const scratch = try arenas.BumpArena.init(gpa, io); const scratch = try arenas.BumpArena.init(gpa, io);
self.* = .{ self.* = .{
.gpa = gpa, .gpa = gpa,
@ -85,6 +96,7 @@ pub fn lock(self: *Application) void {
pub fn unlock(self: *Application) void { pub fn unlock(self: *Application) void {
self.mutex.unlock(self.io); self.mutex.unlock(self.io);
} }
pub fn notify(self: *Application) void { pub fn notify(self: *Application) void {
// Wake native dispatch for events and worker completions. // Wake native dispatch for events and worker completions.
if (self.native_started) c.z_native_wake(); if (self.native_started) c.z_native_wake();

View File

@ -21,12 +21,15 @@ pub const Ended = struct {
id.* = 0; id.* = 0;
} }
}; };
fn begin(id: *u64, next: *u64) !void { fn begin(id: *u64, next: *u64) !void {
if (id.* != 0) return; if (id.* != 0) return;
if (next.* == std.math.maxInt(u64)) return error.Exhausted; if (next.* == std.math.maxInt(u64)) return error.Exhausted;
id.* = next.*; id.* = next.*;
next.* += 1; next.* += 1;
} }
pub fn endAll(self: *Cycles, reason: c.uhdk_cycle_end_reason) Ended { pub fn endAll(self: *Cycles, reason: c.uhdk_cycle_end_reason) Ended {
var ended: Ended = .{}; var ended: Ended = .{};
ended.take(&self.pointer, reason); ended.take(&self.pointer, reason);
@ -37,6 +40,7 @@ pub fn endAll(self: *Cycles, reason: c.uhdk_cycle_end_reason) Ended {
self.composition_committed = false; self.composition_committed = false;
return ended; return ended;
} }
pub fn apply(self: *Cycles, next: *u64, event: *c.z_event) !Ended { pub fn apply(self: *Cycles, next: *u64, event: *c.z_event) !Ended {
var ended: Ended = .{}; var ended: Ended = .{};
event.cycle_id = 0; event.cycle_id = 0;
@ -44,6 +48,7 @@ pub fn apply(self: *Cycles, next: *u64, event: *c.z_event) !Ended {
c.UHDK_EVENT_POINTER_BUTTON => { c.UHDK_EVENT_POINTER_BUTTON => {
const p = event.data.pointer; const p = event.data.pointer;
if (p.button == 0 or p.button >= 32) return ended; if (p.button == 0 or p.button >= 32) return ended;
const bit = @as(u32, 1) << @as(u5, @intCast(p.button)); const bit = @as(u32, 1) << @as(u5, @intCast(p.button));
if (p.pressed != 0) { if (p.pressed != 0) {
try begin(&self.pointer, next); try begin(&self.pointer, next);
@ -93,6 +98,7 @@ pub fn apply(self: *Cycles, next: *u64, event: *c.z_event) !Ended {
}, },
else => {}, else => {},
} }
return ended; return ended;
} }
@ -104,6 +110,7 @@ test "drag and capture share a cycle and late releases cannot revive it" {
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY; event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1; event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
const drag = event.cycle_id; const drag = event.cycle_id;
try std.testing.expect(drag != 0); try std.testing.expect(drag != 0);
event.type = c.UHDK_EVENT_POINTER_MODE_CHANGED; event.type = c.UHDK_EVENT_POINTER_MODE_CHANGED;
@ -119,6 +126,7 @@ test "drag and capture share a cycle and late releases cannot revive it" {
try std.testing.expectEqual(@as(usize, 0), (try state.apply(&next, &event)).len); try std.testing.expectEqual(@as(usize, 0), (try state.apply(&next, &event)).len);
event.type = c.UHDK_EVENT_POINTER_MODE_CHANGED; event.type = c.UHDK_EVENT_POINTER_MODE_CHANGED;
event.data.pointer_mode = c.UHDK_POINTER_NORMAL; event.data.pointer_mode = c.UHDK_POINTER_NORMAL;
const ended = try state.apply(&next, &event); const ended = try state.apply(&next, &event);
try std.testing.expectEqual(@as(usize, 1), ended.len); try std.testing.expectEqual(@as(usize, 1), ended.len);
try std.testing.expectEqual(drag, ended.ids[0]); try std.testing.expectEqual(drag, ended.ids[0]);
@ -144,18 +152,21 @@ test "independent windows and kinds get distinct cycles and focus loss ends all"
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY; event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1; event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
const pointer = event.cycle_id; const pointer = event.cycle_id;
_ = try other.apply(&next, &event); _ = try other.apply(&next, &event);
try std.testing.expect(event.cycle_id != pointer); try std.testing.expect(event.cycle_id != pointer);
event.type = c.UHDK_EVENT_SCROLL; event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_BEGIN; event.data.scroll.phase = c.UHDK_SCROLL_BEGIN;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
const scroll = event.cycle_id; const scroll = event.cycle_id;
event.data.scroll.phase = c.UHDK_SCROLL_UPDATE; event.data.scroll.phase = c.UHDK_SCROLL_UPDATE;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
try std.testing.expectEqual(scroll, event.cycle_id); try std.testing.expectEqual(scroll, event.cycle_id);
event.type = c.UHDK_EVENT_TEXT_PREEDIT; event.type = c.UHDK_EVENT_TEXT_PREEDIT;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
const composition = event.cycle_id; const composition = event.cycle_id;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
try std.testing.expectEqual(composition, event.cycle_id); try std.testing.expectEqual(composition, event.cycle_id);
@ -165,6 +176,7 @@ test "independent windows and kinds get distinct cycles and focus loss ends all"
try std.testing.expect(pointer != scroll and scroll != composition); try std.testing.expect(pointer != scroll and scroll != composition);
event.type = c.UHDK_EVENT_WINDOW_METRICS; event.type = c.UHDK_EVENT_WINDOW_METRICS;
event.data.metrics = std.mem.zeroes(c.uhdk_window_metrics); event.data.metrics = std.mem.zeroes(c.uhdk_window_metrics);
const ended = try state.apply(&next, &event); const ended = try state.apply(&next, &event);
try std.testing.expectEqual(@as(usize, 3), ended.len); try std.testing.expectEqual(@as(usize, 3), ended.len);
try std.testing.expectEqualSlices(u64, &.{ pointer, scroll, composition }, &ended.ids); try std.testing.expectEqualSlices(u64, &.{ pointer, scroll, composition }, &ended.ids);
@ -183,6 +195,7 @@ test "interleaved gestures finish independently and a chord ends on its last rel
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY; event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1; event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
const pointer = event.cycle_id; const pointer = event.cycle_id;
event.data.pointer.button = c.UHDK_BUTTON_SECONDARY; event.data.pointer.button = c.UHDK_BUTTON_SECONDARY;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
@ -190,16 +203,20 @@ test "interleaved gestures finish independently and a chord ends on its last rel
event.type = c.UHDK_EVENT_SCROLL; event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_BEGIN; event.data.scroll.phase = c.UHDK_SCROLL_BEGIN;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
const scroll = event.cycle_id; const scroll = event.cycle_id;
event.type = c.UHDK_EVENT_TEXT_PREEDIT; event.type = c.UHDK_EVENT_TEXT_PREEDIT;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
const composition = event.cycle_id; const composition = event.cycle_id;
event.type = c.UHDK_EVENT_SCROLL; event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_END; event.data.scroll.phase = c.UHDK_SCROLL_END;
const scroll_end = try state.apply(&next, &event); const scroll_end = try state.apply(&next, &event);
try std.testing.expectEqual(scroll, event.cycle_id); try std.testing.expectEqual(scroll, event.cycle_id);
try std.testing.expectEqual(scroll, scroll_end.ids[0]); try std.testing.expectEqual(scroll, scroll_end.ids[0]);
event.type = c.UHDK_EVENT_TEXT_COMPOSITION_END; event.type = c.UHDK_EVENT_TEXT_COMPOSITION_END;
const ime_end = try state.apply(&next, &event); const ime_end = try state.apply(&next, &event);
try std.testing.expectEqual(composition, event.cycle_id); try std.testing.expectEqual(composition, event.cycle_id);
try std.testing.expectEqual(composition, ime_end.ids[0]); try std.testing.expectEqual(composition, ime_end.ids[0]);
@ -209,6 +226,7 @@ test "interleaved gestures finish independently and a chord ends on its last rel
try std.testing.expectEqual(@as(usize, 0), (try state.apply(&next, &event)).len); try std.testing.expectEqual(@as(usize, 0), (try state.apply(&next, &event)).len);
try std.testing.expectEqual(pointer, event.cycle_id); try std.testing.expectEqual(pointer, event.cycle_id);
event.data.pointer.button = c.UHDK_BUTTON_SECONDARY; event.data.pointer.button = c.UHDK_BUTTON_SECONDARY;
const pointer_end = try state.apply(&next, &event); const pointer_end = try state.apply(&next, &event);
try std.testing.expectEqual(pointer, pointer_end.ids[0]); try std.testing.expectEqual(pointer, pointer_end.ids[0]);
try std.testing.expectEqual(@as(usize, 0), state.endAll(c.UHDK_CYCLE_SHUTDOWN).len); try std.testing.expectEqual(@as(usize, 0), state.endAll(c.UHDK_CYCLE_SHUTDOWN).len);
@ -224,13 +242,16 @@ test "cycle reasons distinguish release loss cancellation replacement and shutdo
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
event.data.pointer_mode = c.UHDK_POINTER_NORMAL; event.data.pointer_mode = c.UHDK_POINTER_NORMAL;
event.cycle_end_reason = reason; event.cycle_end_reason = reason;
const ended = try state.apply(&next, &event); const ended = try state.apply(&next, &event);
try std.testing.expectEqual(@as(usize, 1), ended.len); try std.testing.expectEqual(@as(usize, 1), ended.len);
try std.testing.expectEqual(reason, ended.reasons[0]); try std.testing.expectEqual(reason, ended.reasons[0]);
} }
event.type = c.UHDK_EVENT_SCROLL; event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_BEGIN; event.data.scroll.phase = c.UHDK_SCROLL_BEGIN;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
const superseded = 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]); try std.testing.expectEqual(@as(u32, c.UHDK_CYCLE_SUPERSEDED), superseded.reasons[0]);
event.data.scroll.phase = c.UHDK_SCROLL_CANCEL; event.data.scroll.phase = c.UHDK_SCROLL_CANCEL;
@ -242,9 +263,11 @@ test "cycle reasons distinguish release loss cancellation replacement and shutdo
event.type = c.UHDK_EVENT_TEXT_COMMIT; event.type = c.UHDK_EVENT_TEXT_COMMIT;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
} }
event.type = c.UHDK_EVENT_TEXT_COMPOSITION_END; 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]); 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| { for ([_]bool{ false, true }) |hidden| {
event.type = c.UHDK_EVENT_TEXT_PREEDIT; event.type = c.UHDK_EVENT_TEXT_PREEDIT;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
@ -253,6 +276,7 @@ test "cycle reasons distinguish release loss cancellation replacement and shutdo
event.data.metrics.visible = @intFromBool(!hidden); 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]); 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; event.type = c.UHDK_EVENT_TEXT_PREEDIT;
_ = try state.apply(&next, &event); _ = try state.apply(&next, &event);
try std.testing.expectEqual(@as(u32, c.UHDK_CYCLE_SHUTDOWN), state.endAll(c.UHDK_CYCLE_SHUTDOWN).reasons[0]); try std.testing.expectEqual(@as(u32, c.UHDK_CYCLE_SHUTDOWN), state.endAll(c.UHDK_CYCLE_SHUTDOWN).reasons[0]);

View File

@ -15,6 +15,7 @@ fn store(comptime T: type, allocator: std.mem.Allocator, value: T) !Data {
fn files(allocator: std.mem.Allocator, value: c.uhdk_file_list) !c.uhdk_file_list { fn files(allocator: std.mem.Allocator, value: c.uhdk_file_list) !c.uhdk_file_list {
if (value.len == 0) return .{ .ptr = null, .len = 0 }; if (value.len == 0) return .{ .ptr = null, .len = 0 };
const ptr = try allocator.dupe(?*c.uhdk_file, value.ptr[0..@intCast(value.len)]); const ptr = try allocator.dupe(?*c.uhdk_file, value.ptr[0..@intCast(value.len)]);
return .{ .ptr = ptr.ptr, .len = ptr.len }; return .{ .ptr = ptr.ptr, .len = ptr.len };
} }

View File

@ -12,6 +12,7 @@ pub const Info = struct {
modified_ns: i64, modified_ns: i64,
kind: FileKind, kind: FileKind,
}; };
pub const Result = union(enum) { pub const Result = union(enum) {
pending, pending,
bytes: []const u8, bytes: []const u8,
@ -59,6 +60,7 @@ pub fn step(self: *FileOperation) !Result {
if (self.kind == .info) { if (self.kind == .info) {
return .{ .info = try metadata(self.path, true) }; return .{ .info = try metadata(self.path, true) };
} }
if (!self.started) { if (!self.started) {
switch (self.kind) { switch (self.kind) {
.read => { .read => {
@ -67,6 +69,7 @@ pub fn step(self: *FileOperation) !Result {
const stat = try metadata(self.path, false); const stat = try metadata(self.path, false);
if (stat.kind != .file) return error.NotRegularFile; if (stat.kind != .file) return error.NotRegularFile;
if (stat.size > self.limit) return error.StreamTooLong; if (stat.size > self.limit) return error.StreamTooLong;
try statusError(c.z_file_reader_open(pathSpan(self.path), &self.reader)); try statusError(c.z_file_reader_open(pathSpan(self.path), &self.reader));
}, },
.write => { .write => {
@ -74,6 +77,7 @@ pub fn step(self: *FileOperation) !Result {
}, },
.info => unreachable, .info => unreachable,
} }
self.started = true; self.started = true;
return .pending; return .pending;
} }
@ -87,6 +91,7 @@ pub fn step(self: *FileOperation) !Result {
try statusError(c.z_file_reader_read(self.reader.?, self.offset, &chunk, capacity, &count)); try statusError(c.z_file_reader_read(self.reader.?, self.offset, &chunk, capacity, &count));
if (count == 0) return .{ .bytes = self.contents.items }; if (count == 0) return .{ .bytes = self.contents.items };
if (count > remaining) return error.StreamTooLong; if (count > remaining) return error.StreamTooLong;
try self.contents.appendSlice(self.gpa, chunk[0..count]); try self.contents.appendSlice(self.gpa, chunk[0..count]);
self.offset += count; self.offset += count;
return .pending; return .pending;
@ -98,9 +103,11 @@ pub fn step(self: *FileOperation) !Result {
const part = remaining[0..@min(chunk_size, remaining.len)]; const part = remaining[0..@min(chunk_size, remaining.len)];
try statusError(c.z_file_writer_write(self.writer.?, self.offset, part.ptr, part.len, &count)); try statusError(c.z_file_writer_write(self.writer.?, self.offset, part.ptr, part.len, &count));
if (count == 0) return error.WriteFailed; if (count == 0) return error.WriteFailed;
self.offset += count; self.offset += count;
return .pending; return .pending;
} }
try statusError(c.z_file_writer_commit(self.writer.?)); try statusError(c.z_file_writer_commit(self.writer.?));
self.writer = null; self.writer = null;
return .written; return .written;
@ -141,16 +148,20 @@ test "chunked replacement, bounded read, and cancellation before commit" {
const io = std.testing.io; const io = std.testing.io;
var temporary = std.testing.tmpDir(.{}); var temporary = std.testing.tmpDir(.{});
defer temporary.cleanup(); defer temporary.cleanup();
const directory = try temporary.dir.realPathFileAlloc(io, ".", gpa); const directory = try temporary.dir.realPathFileAlloc(io, ".", gpa);
defer gpa.free(directory); defer gpa.free(directory);
const path = try std.fs.path.join(gpa, &.{ directory, "document" }); const path = try std.fs.path.join(gpa, &.{ directory, "document" });
defer gpa.free(path); defer gpa.free(path);
const contents = try gpa.alloc(u8, 600_000); const contents = try gpa.alloc(u8, 600_000);
defer gpa.free(contents); defer gpa.free(contents);
@memset(contents, 0xab); @memset(contents, 0xab);
var write = FileOperation.init(gpa, .write, path, contents, 0); var write = FileOperation.init(gpa, .write, path, contents, 0);
defer write.deinit(); defer write.deinit();
var passes: usize = 0; var passes: usize = 0;
while (try write.step() == .pending) : (passes += 1) {} while (try write.step() == .pending) : (passes += 1) {}
try std.testing.expect(passes >= 4); try std.testing.expect(passes >= 4);
@ -167,6 +178,7 @@ test "chunked replacement, bounded read, and cancellation before commit" {
else => unreachable, else => unreachable,
} }
} }
var limited = FileOperation.init(gpa, .read, path, &.{}, 10); var limited = FileOperation.init(gpa, .read, path, &.{}, 10);
defer limited.deinit(); defer limited.deinit();
try std.testing.expectError(error.StreamTooLong, limited.step()); try std.testing.expectError(error.StreamTooLong, limited.step());
@ -175,6 +187,7 @@ test "chunked replacement, bounded read, and cancellation before commit" {
try std.testing.expect(try cancelled.step() == .pending); try std.testing.expect(try cancelled.step() == .pending);
try std.testing.expect(try cancelled.step() == .pending); try std.testing.expect(try cancelled.step() == .pending);
cancelled.deinit(); cancelled.deinit();
const preserved = try temporary.dir.readFileAlloc(io, "document", gpa, .limited(contents.len + 1)); const preserved = try temporary.dir.readFileAlloc(io, "document", gpa, .limited(contents.len + 1));
defer gpa.free(preserved); defer gpa.free(preserved);
try std.testing.expectEqualSlices(u8, contents, preserved); try std.testing.expectEqualSlices(u8, contents, preserved);

View File

@ -13,11 +13,13 @@ const SourceLocation = extern struct {
line: u32, line: u32,
color: u32 = 0, color: u32 = 0,
}; };
const Token = extern struct { const Token = extern struct {
id: u32 = 0, id: u32 = 0,
active: i32 = 0, active: i32 = 0,
connection: u64 = 0, connection: u64 = 0,
}; };
extern fn ___tracy_emit_zone_begin(source: *const SourceLocation, active: i32) Token; extern fn ___tracy_emit_zone_begin(source: *const SourceLocation, active: i32) Token;
extern fn ___tracy_emit_zone_end(zone: Token) void; extern fn ___tracy_emit_zone_end(zone: Token) void;
extern fn ___tracy_emit_frame_mark(name: ?[*:0]const u8) void; extern fn ___tracy_emit_frame_mark(name: ?[*:0]const u8) void;
@ -36,6 +38,7 @@ pub const Zone = if (enabled) struct {
std.debug.assert(self.depth == stack_depth); std.debug.assert(self.depth == stack_depth);
stack_depth -= 1; stack_depth -= 1;
} }
if (self.token.active != 0) ___tracy_emit_zone_end(self.token); if (self.token.active != 0) ___tracy_emit_zone_end(self.token);
} }
} else struct { } else struct {
@ -58,6 +61,7 @@ fn StaticSource(comptime source: std.builtin.SourceLocation, comptime name: [:0]
pub inline fn begin(comptime source: std.builtin.SourceLocation, comptime name: [:0]const u8) Zone { pub inline fn begin(comptime source: std.builtin.SourceLocation, comptime name: [:0]const u8) Zone {
if (!enabled) return .{}; if (!enabled) return .{};
const Statics = StaticSource(source, name); const Statics = StaticSource(source, name);
const token = ___tracy_emit_zone_begin(&Statics.location, 1); const token = ___tracy_emit_zone_begin(&Statics.location, 1);
if (verify_stack_order) stack_depth += 1; if (verify_stack_order) stack_depth += 1;
@ -102,6 +106,7 @@ pub fn TrackingAllocator(comptime pool: [:0]const u8) type {
.vtable = &.{ .vtable = &.{
.alloc = allocate, .alloc = allocate,
.resize = resize, .resize = resize,
// Let Allocator.realloc use alloc/copy/free. A moving rawRemap // Let Allocator.realloc use alloc/copy/free. A moving rawRemap
// releases the old address before we can report its free, so // releases the old address before we can report its free, so
// another thread could reuse it and emit an out-of-order alloc. // another thread could reuse it and emit an out-of-order alloc.
@ -110,19 +115,23 @@ pub fn TrackingAllocator(comptime pool: [:0]const u8) type {
}, },
}; };
} }
fn allocate(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ret: usize) ?[*]u8 { fn allocate(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ret: usize) ?[*]u8 {
const self: *Self = @ptrCast(@alignCast(ctx)); const self: *Self = @ptrCast(@alignCast(ctx));
const ptr = self.child.rawAlloc(len, alignment, ret) orelse return null; const ptr = self.child.rawAlloc(len, alignment, ret) orelse return null;
alloc(ptr, len, pool); alloc(ptr, len, pool);
return ptr; return ptr;
} }
fn resize(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, len: usize, ret: usize) bool { fn resize(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, len: usize, ret: usize) bool {
const self: *Self = @ptrCast(@alignCast(ctx)); const self: *Self = @ptrCast(@alignCast(ctx));
if (!self.child.rawResize(memory, alignment, len, ret)) return false; if (!self.child.rawResize(memory, alignment, len, ret)) return false;
free(memory.ptr, pool); free(memory.ptr, pool);
alloc(memory.ptr, len, pool); alloc(memory.ptr, len, pool);
return true; return true;
} }
fn release(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ret: usize) void { fn release(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ret: usize) void {
const self: *Self = @ptrCast(@alignCast(ctx)); const self: *Self = @ptrCast(@alignCast(ctx));
free(memory.ptr, pool); free(memory.ptr, pool);

View File

@ -51,6 +51,7 @@ pub fn validDescriptor(comptime T: type, handle: [*c]const T) bool {
pub fn writeOutput(comptime T: type, dest: [*c]T, value: T) Status { pub fn writeOutput(comptime T: type, dest: [*c]T, value: T) Status {
if (dest == null or dest.*.struct_size < @sizeOf(T)) return INVALID; if (dest == null or dest.*.struct_size < @sizeOf(T)) return INVALID;
dest.* = value; dest.* = value;
dest.*.struct_size = @sizeOf(T); dest.*.struct_size = @sizeOf(T);
return OK; return OK;

View File

@ -6,6 +6,7 @@ const backend_kind = switch (@import("builtin").os.tag) {
.linux => c.UHDK_BACKEND_WAYLAND, .linux => c.UHDK_BACKEND_WAYLAND,
else => c.UHDK_BACKEND_MACOS, else => c.UHDK_BACKEND_MACOS,
}; };
const c = @import("native"); const c = @import("native");
const runtime = @import("../runtime.zig"); const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig"); const abi = @import("../abi.zig");
@ -20,6 +21,7 @@ pub fn create(desc: *const c.uhdk_options, out: *?*c.uhdk_session) abi.Status {
if (!abi.validText(desc.title, true) or !abi.validText(desc.application_id, true)) return abi.INVALID; if (!abi.validText(desc.title, true) or !abi.validText(desc.application_id, true)) return abi.INVALID;
if (desc.preferred_backend != c.UHDK_BACKEND_AUTO and desc.preferred_backend != backend_kind) return c.UHDK_STATUS_UNSUPPORTED; if (desc.preferred_backend != c.UHDK_BACKEND_AUTO and desc.preferred_backend != backend_kind) return c.UHDK_STATUS_UNSUPPORTED;
if (singleton) return c.UHDK_STATUS_BUSY; if (singleton) return c.UHDK_STATUS_BUSY;
const gpa = profile.allocator(); const gpa = profile.allocator();
const application = Application.create(gpa, MinimalIo.instance, abi.textBytes(desc.title)) catch return abi.OOM; const application = Application.create(gpa, MinimalIo.instance, abi.textBytes(desc.title)) catch return abi.OOM;
application.application_id = gpa.dupe(u8, abi.textBytes(desc.application_id)) catch { application.application_id = gpa.dupe(u8, abi.textBytes(desc.application_id)) catch {
@ -28,12 +30,14 @@ pub fn create(desc: *const c.uhdk_options, out: *?*c.uhdk_session) abi.Status {
gpa.destroy(application); gpa.destroy(application);
return abi.OOM; return abi.OOM;
}; };
singleton = true; singleton = true;
const status = initialize(application); const status = initialize(application);
if (status != abi.OK) { if (status != abi.OK) {
releaseStorage(application); releaseStorage(application);
return status; return status;
} }
out.* = runtime.toAppHandle(application); out.* = runtime.toAppHandle(application);
return abi.OK; return abi.OK;
} }
@ -41,14 +45,17 @@ pub fn create(desc: *const c.uhdk_options, out: *?*c.uhdk_session) abi.Status {
fn initialize(application: *Application) abi.Status { fn initialize(application: *Application) abi.Status {
const handle = runtime.toAppHandle(application); const handle = runtime.toAppHandle(application);
profile.thread("UHDK platform"); profile.thread("UHDK platform");
const status = c.z_native_start(handle, abi.textSpan(application.name)); const status = c.z_native_start(handle, abi.textSpan(application.name));
if (status != abi.OK) { if (status != abi.OK) {
return status; return status;
} }
application.io_worker = std.Thread.spawn(.{}, runtime.ioMain, .{application}) catch { application.io_worker = std.Thread.spawn(.{}, runtime.ioMain, .{application}) catch {
c.z_native_finish(); c.z_native_finish();
return abi.OOM; return abi.OOM;
}; };
application.native_started = true; application.native_started = true;
application.running = true; application.running = true;
application.main_thread = std.Thread.getCurrentId(); application.main_thread = std.Thread.getCurrentId();
@ -62,21 +69,26 @@ fn shutdown(application: *Application) void {
application.lock(); application.lock();
application.stopping = true; application.stopping = true;
application.unlock(); application.unlock();
// Keep native services alive while cancellation, completion, and destruction drain. // Keep native services alive while cancellation, completion, and destruction drain.
while (true) { while (true) {
runtime.dispatch(handle); runtime.dispatch(handle);
application.lock(); application.lock();
const drained = application.requests == null and application.queue_head == null; const drained = application.requests == null and application.queue_head == null;
application.unlock(); application.unlock();
if (drained) break; if (drained) break;
c.z_native_pump(10 * std.time.ns_per_ms); c.z_native_pump(10 * std.time.ns_per_ms);
} }
application.lock(); application.lock();
application.io_exit = true; application.io_exit = true;
application.io_available.set(application.io); application.io_available.set(application.io);
application.unlock(); application.unlock();
if (application.io_worker) |worker| worker.join(); if (application.io_worker) |worker| worker.join();
application.io_worker = null; application.io_worker = null;
// Native sources stop before any of their Zig records can be released. // Native sources stop before any of their Zig records can be released.
var cursor = application.objects; var cursor = application.objects;
while (cursor) |object| : (cursor = object.next) { while (cursor) |object| : (cursor = object.next) {
@ -85,6 +97,7 @@ fn shutdown(application: *Application) void {
object.native = null; object.native = null;
} }
} }
cursor = application.objects; cursor = application.objects;
while (cursor) |object| : (cursor = object.next) { while (cursor) |object| : (cursor = object.next) {
if (object.kind() == c.Z_KIND_WINDOW and object.native != null) { if (object.kind() == c.Z_KIND_WINDOW and object.native != null) {
@ -92,10 +105,12 @@ fn shutdown(application: *Application) void {
c.z_native_destroy(c.Z_KIND_GL, object.native); c.z_native_destroy(c.Z_KIND_GL, object.native);
object.payload.window.gl_ready = false; object.payload.window.gl_ready = false;
} }
c.z_native_destroy(object.kind(), object.native); c.z_native_destroy(object.kind(), object.native);
object.native = null; object.native = null;
} }
} }
c.z_native_finish(); c.z_native_finish();
application.native_started = false; application.native_started = false;
application.running = false; application.running = false;
@ -108,15 +123,18 @@ pub fn poll(
out: [*c]c.uhdk_event_list, out: [*c]c.uhdk_event_list,
) abi.Status { ) abi.Status {
if (handle == null or out == null) return abi.INVALID; if (handle == null or out == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (runtime.hasFrame(application)) return c.UHDK_STATUS_BUSY; if (runtime.hasFrame(application)) return c.UHDK_STATUS_BUSY;
const poll_zone = profile.begin(@src(), "UHDK poll events (includes wait)"); const poll_zone = profile.begin(@src(), "UHDK poll events (includes wait)");
defer poll_zone.end(); defer poll_zone.end();
runtime.destroyEvents(application.published); runtime.destroyEvents(application.published);
application.published = null; application.published = null;
application.scratch.reset(); application.scratch.reset();
out.* = .{ .ptr = null, .len = 0 }; out.* = .{ .ptr = null, .len = 0 };
const start = runtime.now(application.io); const start = runtime.now(application.io);
const end = start +| timeout; const end = start +| timeout;
runtime.dispatch(handle); runtime.dispatch(handle);
@ -132,6 +150,7 @@ pub fn poll(
runtime.simpleEvent(application, c.UHDK_EVENT_WAKE); runtime.simpleEvent(application, c.UHDK_EVENT_WAKE);
application.lock(); application.lock();
} }
while (application.pending_head == null and application.event_error == abi.OK and application.native_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); const current = runtime.now(application.io);
if (application.deadline != 0 and current - application.epoch >= application.deadline) { if (application.deadline != 0 and current - application.epoch >= application.deadline) {
@ -141,40 +160,49 @@ pub fn poll(
application.lock(); application.lock();
break; break;
} }
if (current >= end) return abi.OK; if (current >= end) return abi.OK;
const wake_time = if (application.deadline == 0) end else @min(end, application.epoch +| application.deadline); const wake_time = if (application.deadline == 0) end else @min(end, application.epoch +| application.deadline);
const ns = wake_time -| current; const ns = wake_time -| current;
application.unlock(); application.unlock();
const wait_zone = profile.begin(@src(), "UHDK wait for events"); const wait_zone = profile.begin(@src(), "UHDK wait for events");
defer wait_zone.end(); defer wait_zone.end();
if (application.native_started) c.z_native_pump(ns); if (application.native_started) c.z_native_pump(ns);
runtime.dispatch(handle); runtime.dispatch(handle);
application.lock(); application.lock();
} }
if (application.native_error != abi.OK) return application.native_error; if (application.native_error != abi.OK) return application.native_error;
if (application.event_error != abi.OK) { if (application.event_error != abi.OK) {
const err = application.event_error; const err = application.event_error;
application.event_error = abi.OK; application.event_error = abi.OK;
return err; return err;
} }
var cursor = application.pending_head; var cursor = application.pending_head;
var count: usize = 0; var count: usize = 0;
while (cursor) |node| : (cursor = node.next) { while (cursor) |node| : (cursor = node.next) {
count += 1; count += 1;
} }
const allocator = application.scratch.allocator(); const allocator = application.scratch.allocator();
const events = allocator.alloc(c.uhdk_event, count) catch return abi.OOM; const events = allocator.alloc(c.uhdk_event, count) catch return abi.OOM;
var len: usize = 0; var len: usize = 0;
cursor = application.pending_head; cursor = application.pending_head;
// Do not consume nodes until the entire batch has been converted. On OOM, // Do not consume nodes until the entire batch has been converted. On OOM,
// the queue (and all terminal request completions) remains retryable. // the queue (and all terminal request completions) remains retryable.
while (cursor) |node| : (cursor = node.next) { while (cursor) |node| : (cursor = node.next) {
const event = node.event; const event = node.event;
if (event.window != null and !runtime.fromObjectHandle(event.window).alive) continue; if (event.window != null and !runtime.fromObjectHandle(event.window).alive) continue;
if (event.type == c.UHDK_EVENT_WATCH and !runtime.fromObjectHandle(event.data.watch.watch).alive) continue; if (event.type == c.UHDK_EVENT_WATCH and !runtime.fromObjectHandle(event.data.watch.watch).alive) continue;
events[len] = @import("../EventPayload.zig").pack(allocator, event) catch return abi.OOM; events[len] = @import("../EventPayload.zig").pack(allocator, event) catch return abi.OOM;
len += 1; len += 1;
} }
application.published = application.pending_head; application.published = application.pending_head;
application.pending_head = null; application.pending_head = null;
application.pending_tail = null; application.pending_tail = null;
@ -185,6 +213,7 @@ pub fn poll(
_ = node.arena.reset(.free_all); _ = node.arena.reset(.free_all);
if (node.event.type == c.UHDK_EVENT_STOPPED) application.stopped_seen = true; if (node.event.type == c.UHDK_EVENT_STOPPED) application.stopped_seen = true;
} }
out.* = .{ .ptr = if (len == 0) null else events.ptr, .len = len }; out.* = .{ .ptr = if (len == 0) null else events.ptr, .len = len };
application.stats.event_count +|= out.*.len; application.stats.event_count +|= out.*.len;
return abi.OK; return abi.OK;
@ -192,6 +221,7 @@ pub fn poll(
pub export fn uhdk_get_stats(handle: ?*c.uhdk_session, out: [*c]c.uhdk_stats) abi.Status { pub export fn uhdk_get_stats(handle: ?*c.uhdk_session, out: [*c]c.uhdk_stats) abi.Status {
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
return abi.writeOutput(c.uhdk_stats, out, application.stats); return abi.writeOutput(c.uhdk_stats, out, application.stats);
@ -199,6 +229,7 @@ pub export fn uhdk_get_stats(handle: ?*c.uhdk_session, out: [*c]c.uhdk_stats) ab
pub export fn uhdk_quit(handle: ?*c.uhdk_session) void { pub export fn uhdk_quit(handle: ?*c.uhdk_session) void {
if (handle == null) return; if (handle == null) return;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
application.lock(); application.lock();
application.stopping = true; application.stopping = true;
@ -220,8 +251,10 @@ pub export fn uhdk_get_time_ns(handle: ?*c.uhdk_session) u64 {
pub export fn uhdk_set_wake_deadline(handle: ?*c.uhdk_session, deadline: u64) abi.Status { pub export fn uhdk_set_wake_deadline(handle: ?*c.uhdk_session, deadline: u64) abi.Status {
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
application.lock(); application.lock();
application.deadline = deadline; application.deadline = deadline;
application.notify(); application.notify();
@ -244,8 +277,10 @@ pub export fn uhdk_has_capability(handle: ?*c.uhdk_session, cap: c.uhdk_capabili
pub export fn uhdk_request_cancel(handle: ?*c.uhdk_session, tag: u64) abi.Status { pub export fn uhdk_request_cancel(handle: ?*c.uhdk_session, tag: u64) abi.Status {
if (handle == null or tag == 0) return abi.INVALID; if (handle == null or tag == 0) return abi.INVALID;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
application.lock(); application.lock();
var cursor = application.requests; var cursor = application.requests;
while (cursor) |command| : (cursor = command.next) { while (cursor) |command| : (cursor = command.next) {
@ -256,12 +291,14 @@ pub export fn uhdk_request_cancel(handle: ?*c.uhdk_session, tag: u64) abi.Status
return abi.OK; return abi.OK;
} }
} }
application.unlock(); application.unlock();
return c.UHDK_STATUS_NOT_FOUND; return c.UHDK_STATUS_NOT_FOUND;
} }
pub fn destroy(handle: ?*c.uhdk_session) void { pub fn destroy(handle: ?*c.uhdk_session) void {
if (handle == null) return; if (handle == null) return;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
std.debug.assert(c.z_native_is_main_thread() != 0); std.debug.assert(c.z_native_is_main_thread() != 0);
shutdown(application); shutdown(application);
@ -272,6 +309,7 @@ fn releaseStorage(application: *Application) void {
runtime.destroyEvents(application.published); runtime.destroyEvents(application.published);
runtime.destroyEvents(application.pending_head); runtime.destroyEvents(application.pending_head);
application.scratch.deinit(); application.scratch.deinit();
var cursor = application.objects; var cursor = application.objects;
while (cursor) |object| { while (cursor) |object| {
cursor = object.next; cursor = object.next;
@ -279,6 +317,7 @@ fn releaseStorage(application: *Application) void {
object.arena.deinit(); object.arena.deinit();
application.gpa.destroy(object); application.gpa.destroy(object);
} }
const gpa = application.gpa; const gpa = application.gpa;
gpa.free(application.name); gpa.free(application.name);
gpa.free(application.application_id); gpa.free(application.application_id);

View File

@ -8,6 +8,7 @@ pub export fn uhdk_clipboard_write_text(
text: c.uhdk_text, text: c.uhdk_text,
) abi.Status { ) abi.Status {
if (!abi.validText(text, false)) return abi.INVALID; if (!abi.validText(text, false)) return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_CLIP_WRITE) catch |err| return runtime.applicationError(err); const command = runtime.createAppCommand(handle, c.Z_CLIP_WRITE) catch |err| return runtime.applicationError(err);
command.data.text = abi.copyText(command.arena.allocator(), text) catch { command.data.text = abi.copyText(command.arena.allocator(), text) catch {
runtime.abandon(command); runtime.abandon(command);
@ -33,6 +34,7 @@ pub export fn uhdk_shell_open_url_async(
tag: u64, tag: u64,
) abi.Status { ) abi.Status {
if (!abi.validText(text, true) or text.len == 0) return abi.INVALID; 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); const command = runtime.createAppCommand(handle, c.Z_URL) catch |err| return runtime.applicationError(err);
command.kind = c.UHDK_REQUEST_SHELL; command.kind = c.UHDK_REQUEST_SHELL;
command.data.text = abi.copyText(command.arena.allocator(), text) catch { command.data.text = abi.copyText(command.arena.allocator(), text) catch {
@ -47,6 +49,7 @@ pub export fn uhdk_set_icon(
image: [*c]const c.uhdk_image, image: [*c]const c.uhdk_image,
) abi.Status { ) abi.Status {
if (!abi.validDescriptor(c.uhdk_image, image)) return abi.INVALID; if (!abi.validDescriptor(c.uhdk_image, image)) return abi.INVALID;
const i = image.*; const i = image.*;
if (i.reserved != 0 or if (i.reserved != 0 or
i.width == 0 or i.width == 0 or
@ -69,8 +72,10 @@ pub export fn uhdk_get_preferences(
out: [*c]c.uhdk_preferences, out: [*c]c.uhdk_preferences,
) abi.Status { ) abi.Status {
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
application.lock(); application.lock();
defer application.unlock(); defer application.unlock();
return abi.writeOutput(c.uhdk_preferences, out, application.preferences); return abi.writeOutput(c.uhdk_preferences, out, application.preferences);

View File

@ -10,6 +10,7 @@ pub export fn uhdk_file_dialog_show_async(
tag: u64, tag: u64,
) abi.Status { ) abi.Status {
if (handle == null or !abi.validDescriptor(c.uhdk_file_dialog_desc, desc)) return abi.INVALID; if (handle == null or !abi.validDescriptor(c.uhdk_file_dialog_desc, desc)) return abi.INVALID;
const d = desc.*; const d = desc.*;
if (d.kind > c.UHDK_DIALOG_SAVE_FILE or if (d.kind > c.UHDK_DIALOG_SAVE_FILE or
!abi.validText(d.title, true) or !abi.validText(d.title, true) or
@ -20,6 +21,7 @@ pub export fn uhdk_file_dialog_show_async(
if (d.parent != null and (runtime.fromObjectHandle(d.parent).app != runtime.fromAppHandle(handle) or if (d.parent != null and (runtime.fromObjectHandle(d.parent).app != runtime.fromAppHandle(handle) or
!runtime.fromObjectHandle(d.parent).alive)) return abi.INVALID; !runtime.fromObjectHandle(d.parent).alive)) return abi.INVALID;
if (d.initial_directory != null and runtime.fromObjectHandle(d.initial_directory).app != runtime.fromAppHandle(handle)) return abi.INVALID; if (d.initial_directory != null and runtime.fromObjectHandle(d.initial_directory).app != runtime.fromAppHandle(handle)) return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_DIALOG) catch |err| return runtime.applicationError(err); const command = runtime.createAppCommand(handle, c.Z_DIALOG) catch |err| return runtime.applicationError(err);
command.kind = c.UHDK_REQUEST_FILE_DIALOG; command.kind = c.UHDK_REQUEST_FILE_DIALOG;
command.data.dialog = d; command.data.dialog = d;
@ -42,12 +44,14 @@ pub export fn uhdk_file_create_from_native_path(
if (@import("builtin").os.tag != .windows and if (@import("builtin").os.tag != .windows and
(abi.bytes(path)[0] != '/' or std.mem.findScalar(u8, abi.bytes(path), 0) != null)) return abi.INVALID; (abi.bytes(path)[0] != '/' or std.mem.findScalar(u8, abi.bytes(path), 0) != null)) return abi.INVALID;
if (runtime.validateMainThreadSessionReady(runtime.fromAppHandle(handle)) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (runtime.validateMainThreadSessionReady(runtime.fromAppHandle(handle)) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
const object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_FILE) catch return abi.OOM; const object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_FILE) catch return abi.OOM;
const status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), path, .{ .ptr = null, .len = 0 }, null); const status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), path, .{ .ptr = null, .len = 0 }, null);
if (status != abi.OK) { if (status != abi.OK) {
runtime.release(object); runtime.release(object);
return status; return status;
} }
out.* = runtime.castHandle(*c.uhdk_file, object); out.* = runtime.castHandle(*c.uhdk_file, object);
return abi.OK; return abi.OK;
} }
@ -59,12 +63,14 @@ pub export fn uhdk_file_create_from_uri(
) abi.Status { ) abi.Status {
if (handle == null or out == null or !abi.validText(uri, true)) return abi.INVALID; if (handle == null or out == null or !abi.validText(uri, true)) return abi.INVALID;
if (runtime.validateMainThreadSessionReady(runtime.fromAppHandle(handle)) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (runtime.validateMainThreadSessionReady(runtime.fromAppHandle(handle)) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
const object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_FILE) catch return abi.OOM; const object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_FILE) catch return abi.OOM;
const status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), .{ .ptr = null, .len = 0 }, uri, null); const status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), .{ .ptr = null, .len = 0 }, uri, null);
if (status != abi.OK) { if (status != abi.OK) {
runtime.release(object); runtime.release(object);
return status; return status;
} }
out.* = runtime.castHandle(*c.uhdk_file, object); out.* = runtime.castHandle(*c.uhdk_file, object);
return abi.OK; return abi.OK;
} }
@ -85,15 +91,18 @@ pub export fn uhdk_file_copy_representation(
out: [*c]u64, out: [*c]u64,
) abi.Status { ) abi.Status {
if (handle == null or out == null or !abi.validSpan(buffer, capacity)) return abi.INVALID; if (handle == null or out == null or !abi.validSpan(buffer, capacity)) return abi.INVALID;
const object = runtime.fromObjectHandle(handle); const object = runtime.fromObjectHandle(handle);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_FILE); const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_FILE);
if (status != abi.OK) return status; if (status != abi.OK) return status;
const data = switch (form) { const data = switch (form) {
c.UHDK_FILE_DISPLAY_NAME => object.payload.file.display, c.UHDK_FILE_DISPLAY_NAME => object.payload.file.display,
c.UHDK_FILE_URI => object.payload.file.uri, c.UHDK_FILE_URI => object.payload.file.uri,
c.UHDK_FILE_NATIVE_PATH => object.payload.file.native_path, c.UHDK_FILE_NATIVE_PATH => object.payload.file.native_path,
else => return abi.INVALID, else => return abi.INVALID,
}; };
if (@import("builtin").os.tag == .windows and form == c.UHDK_FILE_URI and data.len == 0) if (@import("builtin").os.tag == .windows and form == c.UHDK_FILE_URI and data.len == 0)
return c.UHDK_STATUS_UNSUPPORTED; return c.UHDK_STATUS_UNSUPPORTED;
out.* = data.len; out.* = data.len;
@ -116,6 +125,7 @@ pub export fn uhdk_file_write_all_async(
tag: u64, tag: u64,
) abi.Status { ) abi.Status {
if (!abi.validSpan(data.ptr, data.len)) return abi.INVALID; 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); const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, abi.IO_WRITE) catch |err| return runtime.objectError(err);
command.kind = c.UHDK_REQUEST_FILE_WRITE; command.kind = c.UHDK_REQUEST_FILE_WRITE;
command.data.bytes = abi.copyBytes(command.arena.allocator(), data) catch { command.data.bytes = abi.copyBytes(command.arena.allocator(), data) catch {
@ -138,6 +148,7 @@ pub export fn uhdk_watch_create_async(handle: ?*c.uhdk_file, tag: u64) abi.Statu
runtime.abandon(command); runtime.abandon(command);
return abi.OOM; return abi.OOM;
}; };
object.payload.watch.owner = f; object.payload.watch.owner = f;
runtime.retain(f); runtime.retain(f);
command.data.other = object; command.data.other = object;

View File

@ -12,6 +12,7 @@ pub fn create(handle: ?*c.uhdk_window) abi.Status {
runtime.abandon(command); runtime.abandon(command);
return c.UHDK_STATUS_BUSY; return c.UHDK_STATUS_BUSY;
} }
w.payload.window.gl_requested = true; w.payload.window.gl_requested = true;
return runtime.submitResource(w.app, command); return runtime.submitResource(w.app, command);
} }
@ -20,8 +21,10 @@ pub fn acquire(handle: ?*c.uhdk_window) abi.Status {
const zone = profile.begin(@src(), "UHDK acquire GL context"); const zone = profile.begin(@src(), "UHDK acquire GL context");
defer zone.end(); defer zone.end();
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle); const object = runtime.fromObjectHandle(handle);
if (object.payload.window.bracket) return c.UHDK_STATUS_BUSY; if (object.payload.window.bracket) return c.UHDK_STATUS_BUSY;
const status = runtime.glCall(handle, 1, null); const status = runtime.glCall(handle, 1, null);
if (status == abi.OK) { if (status == abi.OK) {
object.payload.window.bracket = true; object.payload.window.bracket = true;
@ -29,6 +32,7 @@ pub fn acquire(handle: ?*c.uhdk_window) abi.Status {
object.payload.window.swap_cpu_time = 0; object.payload.window.swap_cpu_time = 0;
object.payload.window.presented = false; object.payload.window.presented = false;
} }
return status; return status;
} }
@ -42,14 +46,17 @@ pub fn release(handle: ?*c.uhdk_window) abi.Status {
const elapsed = runtime.threadCpuTime(object.app.io) -| object.payload.window.frame_cpu_start; const elapsed = runtime.threadCpuTime(object.app.io) -| object.payload.window.frame_cpu_start;
stats.render_time_ns = elapsed -| object.payload.window.swap_cpu_time; stats.render_time_ns = elapsed -| object.payload.window.swap_cpu_time;
stats.frame_count +|= 1; stats.frame_count +|= 1;
const now = runtime.now(object.app.io); const now = runtime.now(object.app.io);
if (object.app.last_frame_time) |previous| { if (object.app.last_frame_time) |previous| {
const interval = now -| previous; const interval = now -| previous;
stats.frames_per_second = if (interval == 0) 0 else @as(f32, std.time.ns_per_s) / @as(f32, @floatFromInt(interval)); stats.frames_per_second = if (interval == 0) 0 else @as(f32, std.time.ns_per_s) / @as(f32, @floatFromInt(interval));
} }
object.app.last_frame_time = now; object.app.last_frame_time = now;
} }
} }
return status; return status;
} }
@ -57,10 +64,12 @@ pub fn present(handle: ?*c.uhdk_window) abi.Status {
const zone = profile.begin(@src(), "UHDK present (includes vsync)"); const zone = profile.begin(@src(), "UHDK present (includes vsync)");
defer zone.end(); defer zone.end();
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle); const object = runtime.fromObjectHandle(handle);
const valid = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW); const valid = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (valid != abi.OK) return valid; if (valid != abi.OK) return valid;
if (!object.payload.window.bracket) return c.UHDK_STATUS_BUSY; if (!object.payload.window.bracket) return c.UHDK_STATUS_BUSY;
// Exclude even driver CPU work/spinning inside presentation, not just sleep. // Exclude even driver CPU work/spinning inside presentation, not just sleep.
const start = runtime.threadCpuTime(object.app.io); const start = runtime.threadCpuTime(object.app.io);
const status = runtime.glCall(handle, 6, null); const status = runtime.glCall(handle, 6, null);
@ -74,6 +83,7 @@ pub fn setSwapInterval(
interval: i32, interval: i32,
) abi.Status { ) abi.Status {
if (interval != 0 and interval != 1) return abi.INVALID; if (interval != 0 and interval != 1) return abi.INVALID;
var value = interval; var value = interval;
return runtime.glCall(handle, 7, &value); return runtime.glCall(handle, 7, &value);
} }

View File

@ -46,6 +46,7 @@ pub export fn uhdk_window_set_text_state(
runtime.abandon(command); runtime.abandon(command);
return abi.OOM; return abi.OOM;
}; };
const application = runtime.fromObjectHandle(handle).app; const application = runtime.fromObjectHandle(handle).app;
application.lock(); application.lock();
if (application.queue_tail) |tail| tail.queued_next = command else application.queue_head = command; if (application.queue_tail) |tail| tail.queued_next = command else application.queue_head = command;

View File

@ -11,13 +11,16 @@ pub export fn uhdk_menu_create(
out: [*c]?*c.uhdk_menu, out: [*c]?*c.uhdk_menu,
) abi.Status { ) abi.Status {
if (handle == null or out == null or !abi.validSpan(items, len) or len > 4096) return abi.INVALID; if (handle == null or out == null or !abi.validSpan(items, len) or len > 4096) return abi.INVALID;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
const object = runtime.createObject(application, c.Z_KIND_MENU) catch return abi.OOM; const object = runtime.createObject(application, c.Z_KIND_MENU) catch return abi.OOM;
object.payload.menu.items = object.arena.allocator().alloc(c.uhdk_menu_item, @intCast(len)) catch { object.payload.menu.items = object.arena.allocator().alloc(c.uhdk_menu_item, @intCast(len)) catch {
runtime.release(object); runtime.release(object);
return abi.OOM; return abi.OOM;
}; };
for (object.payload.menu.items, 0..) |*item, i| { for (object.payload.menu.items, 0..) |*item, i| {
item.* = items[i]; item.* = items[i];
if (!abi.validText(item.label, true) or if (!abi.validText(item.label, true) or
@ -28,26 +31,31 @@ pub export fn uhdk_menu_create(
runtime.release(object); runtime.release(object);
return abi.INVALID; return abi.INVALID;
} }
if (item.submenu != null and (runtime.fromObjectHandle(item.submenu).app != application or if (item.submenu != null and (runtime.fromObjectHandle(item.submenu).app != application or
!runtime.fromObjectHandle(item.submenu).alive)) !runtime.fromObjectHandle(item.submenu).alive))
{ {
runtime.release(object); runtime.release(object);
return abi.INVALID; return abi.INVALID;
} }
item.label = abi.copyText(object.arena.allocator(), item.label) catch { item.label = abi.copyText(object.arena.allocator(), item.label) catch {
runtime.release(object); runtime.release(object);
return abi.OOM; return abi.OOM;
}; };
} }
var ids: std.AutoHashMap(u64, void) = .init(application.gpa); var ids: std.AutoHashMap(u64, void) = .init(application.gpa);
defer ids.deinit(); defer ids.deinit();
runtime.validateMenu(object, &ids, 0) catch |err| { runtime.validateMenu(object, &ids, 0) catch |err| {
runtime.release(object); runtime.release(object);
return if (err == error.OutOfMemory) abi.OOM else abi.INVALID; return if (err == error.OutOfMemory) abi.OOM else abi.INVALID;
}; };
for (object.payload.menu.items) |item| if (item.submenu) |sub| { for (object.payload.menu.items) |item| if (item.submenu) |sub| {
runtime.retain(runtime.fromObjectHandle(sub)); runtime.retain(runtime.fromObjectHandle(sub));
}; };
object.payload.menu.owns_submenus = true; object.payload.menu.owns_submenus = true;
out.* = runtime.castHandle(*c.uhdk_menu, object); out.* = runtime.castHandle(*c.uhdk_menu, object);
return abi.OK; return abi.OK;
@ -82,6 +90,7 @@ pub export fn uhdk_menu_set_item_flags(
flags: u32, flags: u32,
) abi.Status { ) abi.Status {
if (id == 0 or flags & ~@as(u32, 3) != 0) return abi.INVALID; if (id == 0 or flags & ~@as(u32, 3) != 0) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_MENU, c.Z_MENU_FLAGS) catch |err| return runtime.objectError(err); const command = runtime.createObjectCommand(handle, c.Z_KIND_MENU, c.Z_MENU_FLAGS) catch |err| return runtime.objectError(err);
command.data.number = id; command.data.number = id;
command.data.limit = flags; command.data.limit = flags;
@ -106,6 +115,7 @@ pub export fn uhdk_menu_popup_async(
runtime.abandon(command); runtime.abandon(command);
return abi.OOM; return abi.OOM;
}; };
command.data.point = point; command.data.point = point;
command.kind = c.UHDK_REQUEST_MENU_POPUP; command.kind = c.UHDK_REQUEST_MENU_POPUP;
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag); return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);

View File

@ -11,113 +11,156 @@ const graphics = @import("graphics.zig");
fn state(session: *c.uhdk_session) *Application { fn state(session: *c.uhdk_session) *Application {
return @ptrCast(@alignCast(session)); return @ptrCast(@alignCast(session));
} }
fn handle(a: *Application) *c.uhdk_session { fn handle(a: *Application) *c.uhdk_session {
return runtime.toAppHandle(a); return runtime.toAppHandle(a);
} }
pub fn acquire(a: *Application) abi.Status { pub fn acquire(a: *Application) abi.Status {
if (!a.session_has_gl) return abi.OK; if (!a.session_has_gl) return abi.OK;
const window = runtime.fromObjectHandle(a.session_window); const window = runtime.fromObjectHandle(a.session_window);
if (window.payload.window.bracket) return abi.OK; if (window.payload.window.bracket) return abi.OK;
return graphics.acquire(a.session_window); return graphics.acquire(a.session_window);
} }
pub fn release(a: *Application) abi.Status { pub fn release(a: *Application) abi.Status {
if (!a.session_has_gl) return abi.OK; if (!a.session_has_gl) return abi.OK;
const window = runtime.fromObjectHandle(a.session_window); const window = runtime.fromObjectHandle(a.session_window);
if (!window.payload.window.bracket) return abi.OK; if (!window.payload.window.bracket) return abi.OK;
return graphics.release(a.session_window); return graphics.release(a.session_window);
} }
pub fn ready(a: *Application, resource: anytype, deadline: u64) abi.Status { pub fn ready(a: *Application, resource: anytype, deadline: u64) abi.Status {
const object = runtime.fromObjectHandle(resource); const object = runtime.fromObjectHandle(resource);
while (!object.ready) { while (!object.ready) {
if (!object.alive) return if (object.creation_status == abi.OK) abi.UNAVAILABLE else object.creation_status; if (!object.alive) return if (object.creation_status == abi.OK) abi.UNAVAILABLE else object.creation_status;
if (a.native_error != abi.OK) return a.native_error; if (a.native_error != abi.OK) return a.native_error;
if (a.event_error != abi.OK) return a.event_error; if (a.event_error != abi.OK) return a.event_error;
const now = runtime.now(a.io); const now = runtime.now(a.io);
if (now >= deadline) return abi.UNAVAILABLE; if (now >= deadline) return abi.UNAVAILABLE;
runtime.dispatch(handle(a)); runtime.dispatch(handle(a));
c.z_native_pump(@min(deadline - now, 10 * std.time.ns_per_ms)); c.z_native_pump(@min(deadline - now, 10 * std.time.ns_per_ms));
} }
return abi.OK; return abi.OK;
} }
fn readyGl(a: *Application, deadline: u64) abi.Status { fn readyGl(a: *Application, deadline: u64) abi.Status {
const window = runtime.fromObjectHandle(a.session_window); const window = runtime.fromObjectHandle(a.session_window);
while (!window.payload.window.gl_ready) { while (!window.payload.window.gl_ready) {
if (!window.alive) return abi.UNAVAILABLE; if (!window.alive) return abi.UNAVAILABLE;
if (a.native_error != abi.OK) return a.native_error; if (a.native_error != abi.OK) return a.native_error;
if (a.event_error != abi.OK) return a.event_error; if (a.event_error != abi.OK) return a.event_error;
const now = runtime.now(a.io); const now = runtime.now(a.io);
if (now >= deadline) return abi.UNAVAILABLE; if (now >= deadline) return abi.UNAVAILABLE;
runtime.dispatch(handle(a)); runtime.dispatch(handle(a));
c.z_native_pump(@min(deadline - now, 10 * std.time.ns_per_ms)); c.z_native_pump(@min(deadline - now, 10 * std.time.ns_per_ms));
} }
return window.payload.window.gl_status; return window.payload.window.gl_status;
} }
pub export fn uhdk_open(options: [*c]const c.uhdk_options, out: [*c]?*c.uhdk_session) abi.Status { pub export fn uhdk_open(options: [*c]const c.uhdk_options, out: [*c]?*c.uhdk_session) abi.Status {
if (out == null) return abi.INVALID; if (out == null) return abi.INVALID;
out.* = null; out.* = null;
if (c.z_native_is_main_thread() == 0) return c.UHDK_STATUS_WRONG_THREAD; if (c.z_native_is_main_thread() == 0) return c.UHDK_STATUS_WRONG_THREAD;
var opts = std.mem.zeroes(c.uhdk_options); var opts = std.mem.zeroes(c.uhdk_options);
if (options != null) { if (options != null) {
if (!abi.validDescriptor(c.uhdk_options, options)) return abi.INVALID; if (!abi.validDescriptor(c.uhdk_options, options)) return abi.INVALID;
opts = options.*; opts = options.*;
} }
if (opts.render_mode > c.UHDK_RENDER_ON_DEMAND or
(opts.undecorated != 0 and opts.undecorated != 1) or if (opts.render_mode > c.UHDK_RENDER_ON_DEMAND) return abi.INVALID;
(opts.fixed_size != 0 and opts.fixed_size != 1) or if (opts.undecorated != 0 and opts.undecorated != 1) return abi.INVALID;
(opts.disable_vsync != 0 and opts.disable_vsync != 1) or if (opts.fixed_size != 0 and opts.fixed_size != 1) return abi.INVALID;
(opts.request_focus != 0 and opts.request_focus != 1) or if (opts.disable_vsync != 0 and opts.disable_vsync != 1) return abi.INVALID;
(opts.no_opengl != 0 and opts.no_opengl != 1)) return abi.INVALID; if (opts.request_focus != 0 and opts.request_focus != 1) return abi.INVALID;
if (opts.no_opengl != 0 and opts.no_opengl != 1) return abi.INVALID;
if (opts.title.len == 0) opts.title = abi.textSpan("UHDK"); if (opts.title.len == 0) opts.title = abi.textSpan("UHDK");
var application: ?*c.uhdk_session = null; var application: ?*c.uhdk_session = null;
var status = app.create(&opts, &application); var status = app.create(&opts, &application);
if (status != abi.OK) return status; if (status != abi.OK) return status;
const a = runtime.fromAppHandle(application); const a = runtime.fromAppHandle(application);
var success = false; var success = false;
defer if (!success) { defer if (!success) {
_ = release(a); _ = release(a);
app.destroy(application); app.destroy(application);
}; };
a.session_on_demand = opts.render_mode == c.UHDK_RENDER_ON_DEMAND; a.session_on_demand = opts.render_mode == c.UHDK_RENDER_ON_DEMAND;
var window = std.mem.zeroes(c.z_window_desc); var window = std.mem.zeroes(c.z_window_desc);
window.struct_size = @sizeOf(c.z_window_desc); window.struct_size = @sizeOf(c.z_window_desc);
window.title = opts.title; window.title = opts.title;
window.flags = if (opts.no_opengl == 0) c.Z_WINDOW_OPENGL else 0; window.flags = if (opts.no_opengl == 0) c.Z_WINDOW_OPENGL else 0;
window.style = .{ .struct_size = @sizeOf(c.uhdk_window_style), .decorated = 1 - opts.undecorated, .resizable = 1 - opts.fixed_size, .reserved = 0 }; window.style = .{
.struct_size = @sizeOf(c.uhdk_window_style),
.decorated = 1 - opts.undecorated,
.resizable = 1 - opts.fixed_size,
.reserved = 0,
};
window.content_size = opts.content_size; window.content_size = opts.content_size;
if (window.content_size.width == 0) window.content_size.width = 800; if (window.content_size.width == 0) window.content_size.width = 800;
if (window.content_size.height == 0) window.content_size.height = 600; if (window.content_size.height == 0) window.content_size.height = 600;
window.min_size = opts.min_size; window.min_size = opts.min_size;
window.max_size = opts.max_size; window.max_size = opts.max_size;
if (opts.startup_timeout_ns != 0) a.startup_timeout_ns = opts.startup_timeout_ns; if (opts.startup_timeout_ns != 0) a.startup_timeout_ns = opts.startup_timeout_ns;
const deadline = runtime.now(a.io) +| a.startup_timeout_ns; const deadline = runtime.now(a.io) +| a.startup_timeout_ns;
status = windows.queueCreate(application, &window, &a.session_window); status = windows.queueCreate(application, &window, &a.session_window);
if (status != abi.OK) return status; if (status != abi.OK) return status;
status = ready(a, a.session_window, deadline); status = ready(a, a.session_window, deadline);
if (status != abi.OK) return status; if (status != abi.OK) return status;
if (opts.no_opengl == 0) { if (opts.no_opengl == 0) {
status = graphics.create(a.session_window); status = graphics.create(a.session_window);
if (status != abi.OK) return status; if (status != abi.OK) return status;
status = readyGl(a, deadline); status = readyGl(a, deadline);
if (status != abi.OK) return status; if (status != abi.OK) return status;
a.session_has_gl = true; a.session_has_gl = true;
} }
status = windows.uhdk_window_set_visible(a.session_window, 1); status = windows.uhdk_window_set_visible(a.session_window, 1);
if (status != abi.OK) return status; if (status != abi.OK) return status;
if (opts.request_focus != 0) { if (opts.request_focus != 0) {
status = windows.uhdk_window_request_focus(a.session_window); status = windows.uhdk_window_request_focus(a.session_window);
if (status != abi.OK) return status; if (status != abi.OK) return status;
} }
runtime.dispatch(application); runtime.dispatch(application);
c.z_native_pump(0); c.z_native_pump(0);
if (a.native_error != abi.OK) return a.native_error; if (a.native_error != abi.OK) return a.native_error;
status = acquire(a); status = acquire(a);
if (status != abi.OK) return status; if (status != abi.OK) return status;
if (opts.no_opengl == 0) { if (opts.no_opengl == 0) {
status = graphics.setSwapInterval(a.session_window, 1 - @as(i32, opts.disable_vsync)); status = graphics.setSwapInterval(a.session_window, 1 - @as(i32, opts.disable_vsync));
if (status != abi.OK and status != c.UHDK_STATUS_UNSUPPORTED) return status; if (status != abi.OK and status != c.UHDK_STATUS_UNSUPPORTED) return status;
if (c.z_gl_load(runtime.fromObjectHandle(a.session_window).native, &a.session_gl) == 0) return c.UHDK_STATUS_UNSUPPORTED; if (c.z_gl_load(runtime.fromObjectHandle(a.session_window).native, &a.session_gl) == 0) {
return c.UHDK_STATUS_UNSUPPORTED;
} }
}
out.* = @ptrCast(a); out.* = @ptrCast(a);
success = true; success = true;
return abi.OK; return abi.OK;
@ -126,25 +169,32 @@ pub export fn uhdk_open(options: [*c]const c.uhdk_options, out: [*c]?*c.uhdk_ses
pub export fn uhdk_next_frame(session: ?*c.uhdk_session, out: [*c]c.uhdk_frame) c.uhdk_bool { pub export fn uhdk_next_frame(session: ?*c.uhdk_session, out: [*c]c.uhdk_frame) c.uhdk_bool {
const a = state(session orelse return 0); const a = state(session orelse return 0);
if (runtime.validateMainThreadSessionReady(a) != abi.OK) return 0; if (runtime.validateMainThreadSessionReady(a) != abi.OK) return 0;
if (out == null or a.session_active) { if (out == null or a.session_active) {
a.session_status = if (out == null) abi.INVALID else c.UHDK_STATUS_BUSY; a.session_status = if (out == null) abi.INVALID else c.UHDK_STATUS_BUSY;
return 0; return 0;
} }
out.* = std.mem.zeroes(c.uhdk_frame); out.* = std.mem.zeroes(c.uhdk_frame);
if (a.session_status != abi.OK or a.stopped_seen) return 0; if (a.session_status != abi.OK or a.stopped_seen) return 0;
var metrics = std.mem.zeroes(c.uhdk_window_metrics); var metrics = std.mem.zeroes(c.uhdk_window_metrics);
metrics.struct_size = @sizeOf(c.uhdk_window_metrics); metrics.struct_size = @sizeOf(c.uhdk_window_metrics);
_ = windows.uhdk_window_get_metrics(a.session_window, &metrics); _ = windows.uhdk_window_get_metrics(a.session_window, &metrics);
const wait = !a.session_first and (a.session_on_demand or !drawable(metrics)); const wait = !a.session_first and (a.session_on_demand or !drawable(metrics));
a.session_status = release(a); a.session_status = release(a);
if (a.session_status != abi.OK) return 0; if (a.session_status != abi.OK) return 0;
const poll_status = app.poll(handle(a), if (wait) std.math.maxInt(u64) else 0, &out.*.events); const poll_status = app.poll(handle(a), if (wait) std.math.maxInt(u64) else 0, &out.*.events);
// Restore GL ownership even after polling fails so cleanup can delete resources. // Restore GL ownership even after polling fails so cleanup can delete resources.
const acquire_status = acquire(a); const acquire_status = acquire(a);
a.session_status = if (poll_status != abi.OK) poll_status else acquire_status; a.session_status = if (poll_status != abi.OK) poll_status else acquire_status;
if (a.session_status != abi.OK) return 0; if (a.session_status != abi.OK) return 0;
a.session_status = windows.uhdk_window_get_metrics(a.session_window, &metrics); a.session_status = windows.uhdk_window_get_metrics(a.session_window, &metrics);
if (a.session_status != abi.OK) return 0; if (a.session_status != abi.OK) return 0;
out.*.gl = if (a.session_has_gl) &a.session_gl else null; out.*.gl = if (a.session_has_gl) &a.session_gl else null;
out.*.metrics = metrics; out.*.metrics = metrics;
a.session_drawable = !a.stopping and drawable(metrics); a.session_drawable = !a.stopping and drawable(metrics);
@ -160,17 +210,18 @@ fn drawable(metrics: c.uhdk_window_metrics) bool {
else else
metrics.state == c.UHDK_WINDOW_MINIMIZED; metrics.state == c.UHDK_WINDOW_MINIMIZED;
const suspended = metrics.observations & c.UHDK_WINDOW_OBSERVE_SUSPENDED != 0 and metrics.suspended != 0; const suspended = metrics.observations & c.UHDK_WINDOW_OBSERVE_SUSPENDED != 0 and metrics.suspended != 0;
return metrics.visible != 0 and metrics.framebuffer_width != 0 and metrics.framebuffer_height != 0 and return metrics.visible != 0 and metrics.framebuffer_width != 0 and metrics.framebuffer_height != 0 and !minimized and !suspended;
!minimized and !suspended;
} }
pub export fn uhdk_end_frame(session: ?*c.uhdk_session) abi.Status { pub export fn uhdk_end_frame(session: ?*c.uhdk_session) abi.Status {
const a = state(session orelse return abi.INVALID); const a = state(session orelse return abi.INVALID);
if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (!a.session_active) return c.UHDK_STATUS_BUSY; if (!a.session_active) return c.UHDK_STATUS_BUSY;
a.session_active = false; a.session_active = false;
var status: abi.Status = abi.OK; var status: abi.Status = abi.OK;
if (a.session_drawable and !a.stopping and a.session_has_gl) status = graphics.present(a.session_window); if (a.session_drawable and !a.stopping and a.session_has_gl) status = graphics.present(a.session_window);
const end_status = release(a); const end_status = release(a);
const begin_status = if (end_status == abi.OK) acquire(a) else end_status; const begin_status = if (end_status == abi.OK) acquire(a) else end_status;
a.session_status = if (status != abi.OK) status else begin_status; a.session_status = if (status != abi.OK) status else begin_status;
@ -182,13 +233,16 @@ pub export fn uhdk_get_status(session: ?*c.uhdk_session) abi.Status {
if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
return a.session_status; return a.session_status;
} }
pub export fn uhdk_get_gl(session: ?*c.uhdk_session) [*c]const c.uhdk_gl_functions { pub export fn uhdk_get_gl(session: ?*c.uhdk_session) [*c]const c.uhdk_gl_functions {
const a = state(session orelse return null); const a = state(session orelse return null);
return if (a.session_has_gl) &a.session_gl else null; return if (a.session_has_gl) &a.session_gl else null;
} }
pub export fn uhdk_get_window(session: ?*c.uhdk_session) ?*c.uhdk_window { pub export fn uhdk_get_window(session: ?*c.uhdk_session) ?*c.uhdk_window {
return state(session orelse return null).session_window; return state(session orelse return null).session_window;
} }
pub export fn uhdk_close(session: ?*c.uhdk_session) void { pub export fn uhdk_close(session: ?*c.uhdk_session) void {
const a = state(session orelse return); const a = state(session orelse return);
std.debug.assert(runtime.validateMainThreadSessionReady(a) == abi.OK); std.debug.assert(runtime.validateMainThreadSessionReady(a) == abi.OK);
@ -201,6 +255,7 @@ pub export fn uhdk_get_gl_proc(session: ?*c.uhdk_session, name: c.uhdk_text, out
if (!a.session_has_gl) return c.UHDK_STATUS_UNSUPPORTED; if (!a.session_has_gl) return c.UHDK_STATUS_UNSUPPORTED;
return graphics.getProc(a.session_window, name, out); return graphics.getProc(a.session_window, name, out);
} }
pub export fn uhdk_set_vsync(session: ?*c.uhdk_session, enabled: c.uhdk_bool) abi.Status { pub export fn uhdk_set_vsync(session: ?*c.uhdk_session, enabled: c.uhdk_bool) abi.Status {
const a = state(session orelse return abi.INVALID); const a = state(session orelse return abi.INVALID);
if (enabled != 0 and enabled != 1) return abi.INVALID; if (enabled != 0 and enabled != 1) return abi.INVALID;

View File

@ -11,6 +11,7 @@ pub fn queueCreate(
) abi.Status { ) abi.Status {
if (handle == null or !abi.validDescriptor(c.z_window_desc, desc)) return abi.INVALID; if (handle == null or !abi.validDescriptor(c.z_window_desc, desc)) return abi.INVALID;
if (out == null) return abi.INVALID; if (out == null) return abi.INVALID;
const d = desc.*; const d = desc.*;
if (!validStyle(&d.style) if (!validStyle(&d.style)
or !abi.validText(d.title, true) or !abi.validText(d.title, true)
@ -32,6 +33,7 @@ pub fn queueCreate(
runtime.abandon(command); runtime.abandon(command);
return abi.OOM; return abi.OOM;
}; };
object.payload.window.parent = if (d.parent) |parent| runtime.fromObjectHandle(parent) else null; object.payload.window.parent = if (d.parent) |parent| runtime.fromObjectHandle(parent) else null;
command.data.target = object; command.data.target = object;
command.data.window = d; command.data.window = d;
@ -40,6 +42,7 @@ pub fn queueCreate(
object.alive = false; object.alive = false;
return abi.OOM; return abi.OOM;
}; };
const status = runtime.submitResource(runtime.fromAppHandle(handle), command); const status = runtime.submitResource(runtime.fromAppHandle(handle), command);
if (status != abi.OK) object.alive = false; if (status != abi.OK) object.alive = false;
if (status == abi.OK) out.* = runtime.castHandle(*c.uhdk_window, object); if (status == abi.OK) out.* = runtime.castHandle(*c.uhdk_window, object);
@ -59,6 +62,7 @@ pub export fn uhdk_window_set_title(handle: ?*c.uhdk_window, title: c.uhdk_text)
pub export fn uhdk_window_set_size(handle: ?*c.uhdk_window, size: c.uhdk_size) abi.Status { pub export fn uhdk_window_set_size(handle: ?*c.uhdk_window, size: c.uhdk_size) abi.Status {
if (!abi.finiteSize(size) or size.width == 0 or size.height == 0) return abi.INVALID; if (!abi.finiteSize(size) or size.width == 0 or size.height == 0) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_SIZE) catch |err| return runtime.objectError(err); const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_SIZE) catch |err| return runtime.objectError(err);
command.data.size = size; command.data.size = size;
return runtime.submitCommand(runtime.fromObjectHandle(handle).app, command); return runtime.submitCommand(runtime.fromObjectHandle(handle).app, command);
@ -79,6 +83,7 @@ pub export fn uhdk_window_set_style(
style: [*c]const c.uhdk_window_style, style: [*c]const c.uhdk_window_style,
) abi.Status { ) abi.Status {
if (!validStyle(style)) return abi.INVALID; if (!validStyle(style)) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_STYLE) catch |err| return runtime.objectError(err); const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_STYLE) catch |err| return runtime.objectError(err);
command.data.style = style.*; command.data.style = style.*;
return runtime.submitCommand(runtime.fromObjectHandle(handle).app, command); return runtime.submitCommand(runtime.fromObjectHandle(handle).app, command);
@ -93,9 +98,11 @@ pub export fn uhdk_window_get_metrics(
out: [*c]c.uhdk_window_metrics, out: [*c]c.uhdk_window_metrics,
) abi.Status { ) abi.Status {
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle); const object = runtime.fromObjectHandle(handle);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW); const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status; if (status != abi.OK) return status;
object.app.lock(); object.app.lock();
defer object.app.unlock(); defer object.app.unlock();
return abi.writeOutput(c.uhdk_window_metrics, out, object.payload.window.metrics); return abi.writeOutput(c.uhdk_window_metrics, out, object.payload.window.metrics);
@ -110,20 +117,25 @@ pub export fn uhdk_window_get_native(
out: [*c]c.uhdk_native_window, out: [*c]c.uhdk_native_window,
) abi.Status { ) abi.Status {
if (handle == null or out == null or out.*.struct_size < @sizeOf(c.uhdk_native_window)) return abi.INVALID; if (handle == null or out == null or out.*.struct_size < @sizeOf(c.uhdk_native_window)) return abi.INVALID;
const object = runtime.fromObjectHandle(handle); const object = runtime.fromObjectHandle(handle);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW); const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status; if (status != abi.OK) return status;
c.z_native_handles(object.native, out); c.z_native_handles(object.native, out);
return abi.OK; return abi.OK;
} }
pub export fn uhdk_window_create(handle: ?*c.uhdk_session, desc: [*c]const c.uhdk_window_desc, out: [*c]?*c.uhdk_window) abi.Status { pub export fn uhdk_window_create(handle: ?*c.uhdk_session, desc: [*c]const c.uhdk_window_desc, out: [*c]?*c.uhdk_window) abi.Status {
if (out == null) return abi.INVALID; if (out == null) return abi.INVALID;
out.* = null; out.* = null;
if (handle == null or !abi.validDescriptor(c.uhdk_window_desc, desc) or desc.*.reserved != 0) return abi.INVALID; if (handle == null or !abi.validDescriptor(c.uhdk_window_desc, desc) or desc.*.reserved != 0) return abi.INVALID;
const a = runtime.fromAppHandle(handle); const a = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (a.session_active) return c.UHDK_STATUS_BUSY; if (a.session_active) return c.UHDK_STATUS_BUSY;
const session = @import("session.zig"); const session = @import("session.zig");
const d: c.z_window_desc = .{ const d: c.z_window_desc = .{
.struct_size = @sizeOf(c.z_window_desc), .struct_size = @sizeOf(c.z_window_desc),
@ -135,28 +147,34 @@ pub export fn uhdk_window_create(handle: ?*c.uhdk_session, desc: [*c]const c.uhd
.max_size = desc.*.max_size, .max_size = desc.*.max_size,
.parent = desc.*.parent, .parent = desc.*.parent,
}; };
var status = session.release(a); var status = session.release(a);
if (status != abi.OK) return status; if (status != abi.OK) return status;
var window: ?*c.uhdk_window = null; var window: ?*c.uhdk_window = null;
status = queueCreate(handle, &d, &window); status = queueCreate(handle, &d, &window);
if (status == abi.OK) status = session.ready(a, window, runtime.now(a.io) +| a.startup_timeout_ns); if (status == abi.OK) status = session.ready(a, window, runtime.now(a.io) +| a.startup_timeout_ns);
if (status != abi.OK and window != null) runtime.destroyObject(runtime.fromObjectHandle(window)); if (status != abi.OK and window != null) runtime.destroyObject(runtime.fromObjectHandle(window));
const restored = session.acquire(a); const restored = session.acquire(a);
if (restored != abi.OK) { if (restored != abi.OK) {
a.session_status = restored; a.session_status = restored;
if (status == abi.OK) runtime.destroyObject(runtime.fromObjectHandle(window)); if (status == abi.OK) runtime.destroyObject(runtime.fromObjectHandle(window));
return restored; return restored;
} }
if (status == abi.OK) out.* = window; if (status == abi.OK) out.* = window;
return status; return status;
} }
pub export fn uhdk_window_destroy(window: ?*c.uhdk_window) abi.Status { pub export fn uhdk_window_destroy(window: ?*c.uhdk_window) abi.Status {
if (window == null) return abi.OK; if (window == null) return abi.OK;
const object = runtime.fromObjectHandle(window); const object = runtime.fromObjectHandle(window);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW); const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status; if (status != abi.OK) return status;
if (object.app.session_window == window) return abi.INVALID; if (object.app.session_window == window) return abi.INVALID;
runtime.destroyObject(object); runtime.destroyObject(object);
return abi.OK; return abi.OK;
} }

View File

@ -89,10 +89,12 @@ pub const BumpArena = struct {
self.pageIndex += 1; self.pageIndex += 1;
offset = 0; offset = 0;
} }
const memory = self.small.getMutable(self.pageIndex)[offset .. offset + len]; const memory = self.small.getMutable(self.pageIndex)[offset .. offset + len];
self.smallBumpOffset = offset + len; self.smallBumpOffset = offset + len;
break :result memory.ptr; break :result memory.ptr;
}; };
self.allocatedBytes += len; self.allocatedBytes += len;
self.allocCount += 1; self.allocCount += 1;
return result; return result;
@ -251,6 +253,7 @@ pub fn PagedVectorAdvanced(comptime T: type, comptime growth: usize) type {
pub fn append(self: *@This(), allocator: std.mem.Allocator, value: T) !void { pub fn append(self: *@This(), allocator: std.mem.Allocator, value: T) !void {
if (self.currentPage().len == growth) try self.maybeExpand(allocator); if (self.currentPage().len == growth) try self.maybeExpand(allocator);
const page = self.currentPage(); const page = self.currentPage();
self.head = &page.data[page.len]; self.head = &page.data[page.len];
self.head.* = value; self.head.* = value;
@ -433,6 +436,7 @@ test "simple loading multiple pages." {
for (0..1024) |_| { for (0..1024) |_| {
vector.swapRemove(0); vector.swapRemove(0);
} }
std.debug.assert(vector.len() == 128 + 1024 * 5 - 4 - 1024); std.debug.assert(vector.len() == 128 + 1024 * 5 - 4 - 1024);
} }
@ -472,26 +476,31 @@ test "reset retains pages and clears length" {
fn exercise(gpa: std.mem.Allocator) !void { fn exercise(gpa: std.mem.Allocator) !void {
var arena = try BumpArena.init(gpa, std.testing.io); var arena = try BumpArena.init(gpa, std.testing.io);
defer arena.deinit(); defer arena.deinit();
const a = arena.allocator(); const a = arena.allocator();
const first = try a.alloc(u8, 4096); const first = try a.alloc(u8, 4096);
@memset(first, 17); @memset(first, 17);
_ = try a.alloc(u8, 4096); _ = try a.alloc(u8, 4096);
_ = try a.alloc(u8, 4096); _ = try a.alloc(u8, 4096);
_ = try a.alloc(u8, 4093); _ = try a.alloc(u8, 4093);
// Alignment rounding takes this allocation across the first page boundary. // Alignment rounding takes this allocation across the first page boundary.
const aligned = try a.create(u64); const aligned = try a.create(u64);
aligned.* = 0x12345678; aligned.* = 0x12345678;
try std.testing.expectEqual(@as(usize, 0), @intFromPtr(aligned) % @alignOf(u64)); try std.testing.expectEqual(@as(usize, 0), @intFromPtr(aligned) % @alignOf(u64));
const OverAligned = struct { value: u8 align(256) }; const OverAligned = struct { value: u8 align(256) };
const over = try a.create(OverAligned); const over = try a.create(OverAligned);
over.* = .{ .value = 42 }; over.* = .{ .value = 42 };
try std.testing.expectEqual(@as(usize, 0), @intFromPtr(over) % 256); try std.testing.expectEqual(@as(usize, 0), @intFromPtr(over) % 256);
const large = try a.alloc(u8, 20000); const large = try a.alloc(u8, 20000);
@memset(large, 29); @memset(large, 29);
for (first) |v| try std.testing.expectEqual(@as(u8, 17), v); for (first) |v| try std.testing.expectEqual(@as(u8, 17), v);
try std.testing.expectEqual(@as(u64, 0x12345678), aligned.*); try std.testing.expectEqual(@as(u64, 0x12345678), aligned.*);
arena.reset(); arena.reset();
try std.testing.expectEqual(@as(usize, 0), arena.usage()); try std.testing.expectEqual(@as(usize, 0), arena.usage());
const reused = try a.alloc(u8, 4096); const reused = try a.alloc(u8, 4096);
try std.testing.expectEqual(@intFromPtr(first.ptr), @intFromPtr(reused.ptr)); try std.testing.expectEqual(@intFromPtr(first.ptr), @intFromPtr(reused.ptr));
for (0..12) |_| _ = try a.alloc(u8, 4096); for (0..12) |_| _ = try a.alloc(u8, 4096);
@ -507,13 +516,16 @@ test "bump arena failed page allocation can be retried" {
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{});
var arena = try BumpArena.init(failing.allocator(), std.testing.io); var arena = try BumpArena.init(failing.allocator(), std.testing.io);
defer arena.deinit(); defer arena.deinit();
const a = arena.allocator(); const a = arena.allocator();
for (0..4) |_| _ = try a.alloc(u8, 4096); for (0..4) |_| _ = try a.alloc(u8, 4096);
const before = arena.usage(); const before = arena.usage();
failing.fail_index = failing.alloc_index; failing.fail_index = failing.alloc_index;
try std.testing.expectError(error.OutOfMemory, a.alloc(u8, 4096)); try std.testing.expectError(error.OutOfMemory, a.alloc(u8, 4096));
try std.testing.expectEqual(before, arena.usage()); try std.testing.expectEqual(before, arena.usage());
failing.fail_index = std.math.maxInt(usize); failing.fail_index = std.math.maxInt(usize);
const memory = try a.alloc(u8, 4096); const memory = try a.alloc(u8, 4096);
@memset(memory, 7); @memset(memory, 7);
try std.testing.expectEqual(before + 4096, arena.usage()); try std.testing.expectEqual(before + 4096, arena.usage());

View File

@ -38,6 +38,7 @@ export fn z_metrics(handle: ?*c.uhdk_window, value: [*c]const c.uhdk_window_metr
object.app.lock(); object.app.lock();
object.payload.window.metrics = value.*; object.payload.window.metrics = value.*;
object.app.unlock(); object.app.unlock();
var event = std.mem.zeroes(c.z_event); var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_WINDOW_METRICS; event.type = c.UHDK_EVENT_WINDOW_METRICS;
event.window = handle; event.window = handle;
@ -50,6 +51,7 @@ export fn z_preferences(handle: ?*c.uhdk_session, value: [*c]const c.uhdk_prefer
application.lock(); application.lock();
application.preferences = value.*; application.preferences = value.*;
application.unlock(); application.unlock();
var event = std.mem.zeroes(c.z_event); var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_PREFERENCES_CHANGED; event.type = c.UHDK_EVENT_PREFERENCES_CHANGED;
event.data.preferences = value.*; event.data.preferences = value.*;
@ -68,12 +70,14 @@ export fn z_file_init(
object.payload.file.native_path = arena.dupe(u8, abi.bytes(path)) catch return abi.OOM; object.payload.file.native_path = arena.dupe(u8, abi.bytes(path)) catch return abi.OOM;
if (@import("builtin").os.tag == .windows) { if (@import("builtin").os.tag == .windows) {
if (path.len % 2 != 0) return abi.INVALID; if (path.len % 2 != 0) return abi.INVALID;
const wide = arena.alloc(u16, @intCast(path.len / 2)) catch return abi.OOM; const wide = arena.alloc(u16, @intCast(path.len / 2)) catch return abi.OOM;
@memcpy(std.mem.sliceAsBytes(wide), abi.bytes(path)); @memcpy(std.mem.sliceAsBytes(wide), abi.bytes(path));
object.payload.file.path = std.unicode.wtf16LeToWtf8AllocZ(arena, wide) catch return abi.OOM; object.payload.file.path = std.unicode.wtf16LeToWtf8AllocZ(arena, wide) catch return abi.OOM;
} else { } else {
object.payload.file.path = arena.dupeZ(u8, abi.bytes(path)) catch return abi.OOM; object.payload.file.path = arena.dupeZ(u8, abi.bytes(path)) catch return abi.OOM;
} }
object.payload.file.uri = arena.dupe(u8, abi.textBytes(uri)) catch return abi.OOM; object.payload.file.uri = arena.dupe(u8, abi.textBytes(uri)) catch return abi.OOM;
object.payload.file.display = arena.dupe(u8, abi.textBytes(display)) catch return abi.OOM; object.payload.file.display = arena.dupe(u8, abi.textBytes(display)) catch return abi.OOM;
object.native = grant; object.native = grant;
@ -90,6 +94,7 @@ export fn z_file_from_url(
object.alive = false; object.alive = false;
return null; return null;
} }
return runtime.castHandle(*c.uhdk_file, object); return runtime.castHandle(*c.uhdk_file, object);
} }

View File

@ -8,6 +8,7 @@ fn destroyApplication(application: *Application) void {
runtime.destroyEvents(application.pending_head); runtime.destroyEvents(application.pending_head);
runtime.destroyEvents(application.published); runtime.destroyEvents(application.published);
application.scratch.deinit(); application.scratch.deinit();
const gpa = application.gpa; const gpa = application.gpa;
gpa.free(application.name); gpa.free(application.name);
application.* = undefined; application.* = undefined;
@ -17,8 +18,10 @@ fn destroyApplication(application: *Application) void {
fn allocationLifecycle(gpa: std.mem.Allocator) !void { fn allocationLifecycle(gpa: std.mem.Allocator) !void {
const application = try Application.create(gpa, std.testing.io, "test"); const application = try Application.create(gpa, std.testing.io, "test");
defer destroyApplication(application); defer destroyApplication(application);
const file = try runtime.createObject(application, c.Z_KIND_FILE); const file = try runtime.createObject(application, c.Z_KIND_FILE);
defer runtime.release(file); defer runtime.release(file);
const command = try runtime.createCommand(application, c.Z_CLIP_WRITE, file); const command = try runtime.createCommand(application, c.Z_CLIP_WRITE, file);
defer runtime.abandon(command); defer runtime.abandon(command);
command.data.text = try abi.copyText(command.arena.allocator(), .{ command.data.text = try abi.copyText(command.arena.allocator(), .{
@ -36,12 +39,14 @@ test "all request construction failures release partial ownership" {
test "publication copies text and preserves batches across ordinary calls" { test "publication copies text and preserves batches across ordinary calls" {
const application = try Application.create(std.testing.allocator, std.testing.io, "events"); const application = try Application.create(std.testing.allocator, std.testing.io, "events");
defer destroyApplication(application); defer destroyApplication(application);
var source = [_]u8{ 'h', 'i' }; var source = [_]u8{ 'h', 'i' };
var event = std.mem.zeroes(c.z_event); var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_TEXT_COMMIT; event.type = c.UHDK_EVENT_TEXT_COMMIT;
event.data.text.text = .{ .ptr = &source, .len = source.len }; event.data.text.text = .{ .ptr = &source, .len = source.len };
runtime.emit(runtime.toAppHandle(application), &event); runtime.emit(runtime.toAppHandle(application), &event);
@memset(&source, '?'); @memset(&source, '?');
const published = application.pending_head.?; const published = application.pending_head.?;
try std.testing.expectEqualStrings("hi", abi.textBytes(published.event.data.text.text)); try std.testing.expectEqualStrings("hi", abi.textBytes(published.event.data.text.text));
runtime.simpleEvent(application, c.UHDK_EVENT_WAKE); runtime.simpleEvent(application, c.UHDK_EVENT_WAKE);
@ -67,6 +72,7 @@ test "accepted request gets one terminal result when cancellation wins" {
runtime.dispatch(runtime.toAppHandle(application)); runtime.dispatch(runtime.toAppHandle(application));
try std.testing.expect(application.requests == null); try std.testing.expect(application.requests == null);
try std.testing.expect(application.queue_head == null); try std.testing.expect(application.queue_head == null);
const event = application.pending_head.?; const event = application.pending_head.?;
try std.testing.expect(event.next == null); 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(@as(u32, c.UHDK_EVENT_REQUEST_DONE), event.event.type);
@ -92,19 +98,23 @@ test "public payload scratch lifetime empty polls and resource pins" {
const handle = runtime.toAppHandle(application); const handle = runtime.toAppHandle(application);
const file = try runtime.createObject(application, c.Z_KIND_FILE); const file = try runtime.createObject(application, c.Z_KIND_FILE);
defer runtime.release(file); defer runtime.release(file);
var handles = [_]?*c.uhdk_file{@ptrCast(file)}; var handles = [_]?*c.uhdk_file{@ptrCast(file)};
var event = std.mem.zeroes(c.z_event); var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_OPEN_FILES; event.type = c.UHDK_EVENT_OPEN_FILES;
event.data.files = .{ .ptr = &handles, .len = 1 }; event.data.files = .{ .ptr = &handles, .len = 1 };
runtime.emit(handle, &event); runtime.emit(handle, &event);
try std.testing.expectEqual(@as(usize, 2), file.refs); try std.testing.expectEqual(@as(usize, 2), file.refs);
var batch: c.uhdk_event_list = undefined; var batch: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch)); try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 1), batch.len); try std.testing.expectEqual(@as(u64, 1), batch.len);
try std.testing.expectEqual(@as(u64, @sizeOf(c.uhdk_file_list)), batch.ptr[0].data_size); try std.testing.expectEqual(@as(u64, @sizeOf(c.uhdk_file_list)), batch.ptr[0].data_size);
const payload: *const c.uhdk_file_list = @ptrCast(@alignCast(batch.ptr[0].data.?)); const payload: *const c.uhdk_file_list = @ptrCast(@alignCast(batch.ptr[0].data.?));
try std.testing.expectEqual(@intFromPtr(file), @intFromPtr(payload.ptr[0].?)); try std.testing.expectEqual(@intFromPtr(file), @intFromPtr(payload.ptr[0].?));
try std.testing.expectEqual(@as(usize, 2), file.refs); try std.testing.expectEqual(@as(usize, 2), file.refs);
// Invalid calls must not reset a borrow. Valid empty polls must release it. // Invalid calls must not reset a borrow. Valid empty polls must release it.
try std.testing.expectEqual(@as(abi.Status, abi.INVALID), app_api.poll(handle, 0, null)); try std.testing.expectEqual(@as(abi.Status, abi.INVALID), app_api.poll(handle, 0, null));
try std.testing.expectEqual(@as(u64, 1), payload.len); try std.testing.expectEqual(@as(u64, 1), payload.len);
@ -130,21 +140,26 @@ test "poll allocation failure keeps queued terminal completion retryable" {
runtime.emit(handle, &event); runtime.emit(handle, &event);
@memset(&bytes, 0); @memset(&bytes, 0);
failing.fail_index = failing.alloc_index; failing.fail_index = failing.alloc_index;
var batch: c.uhdk_event_list = undefined; var batch: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(abi.Status, abi.OOM), app_api.poll(handle, 0, &batch)); try std.testing.expectEqual(@as(abi.Status, abi.OOM), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 0), batch.len); try std.testing.expectEqual(@as(u64, 0), batch.len);
try std.testing.expect(application.pending_head != null); try std.testing.expect(application.pending_head != null);
failing.fail_index = std.math.maxInt(usize); failing.fail_index = std.math.maxInt(usize);
const duplicate = try runtime.createCommand(application, c.Z_CLIP_READ, null); 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(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(abi.Status, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 1), batch.len); try std.testing.expectEqual(@as(u64, 1), batch.len);
const result: *const c.uhdk_request_result = @ptrCast(@alignCast(batch.ptr[0].data.?)); const result: *const c.uhdk_request_result = @ptrCast(@alignCast(batch.ptr[0].data.?));
try std.testing.expectEqual(@as(u64, 123), result.tag); try std.testing.expectEqual(@as(u64, 123), result.tag);
const data: *const c.uhdk_bytes = @ptrCast(@alignCast(result.data.?)); const data: *const c.uhdk_bytes = @ptrCast(@alignCast(result.data.?));
try std.testing.expectEqual(@as(u64, bytes.len), data.len); 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); for (data.ptr[0..@intCast(data.len)]) |b| try std.testing.expectEqual(@as(u8, 42), b);
try std.testing.expect(application.pending_head == null); try std.testing.expect(application.pending_head == null);
// Producer payload storage has been freed; the public copy is in scratch. // Producer payload storage has been freed; the public copy is in scratch.
try std.testing.expectEqual(@as(usize, 0), application.published.?.arena.queryCapacity()); try std.testing.expectEqual(@as(usize, 0), application.published.?.arena.queryCapacity());
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch)); try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch));
@ -177,11 +192,13 @@ test "desktop edit defaults preserve modifiers and selection intent" {
.{ c.UHDK_KEY_PAGE_DOWN, ctrl, 0 }, .{ c.UHDK_KEY_PAGE_DOWN, ctrl, 0 },
.{ 'v', ctrl | shift, 0 }, .{ 'v', ctrl | shift, 0 },
}; };
for (cases) |item| { for (cases) |item| {
try std.testing.expectEqual(item[2], c.z_edit_key(item[0], item[1])); try std.testing.expectEqual(item[2], c.z_edit_key(item[0], item[1]));
try std.testing.expectEqual(@as(u32, 0), c.z_edit_key(item[0], item[1] | c.UHDK_MOD_ALT)); try std.testing.expectEqual(@as(u32, 0), c.z_edit_key(item[0], item[1] | c.UHDK_MOD_ALT));
try std.testing.expectEqual(@as(u32, 0), c.z_edit_key(item[0], item[1] | c.UHDK_MOD_SUPER)); try std.testing.expectEqual(@as(u32, 0), c.z_edit_key(item[0], item[1] | c.UHDK_MOD_SUPER));
} }
try std.testing.expect(c.z_edit_extends_selection(c.UHDK_EDIT_WORD_LEFT, shift) != 0); try std.testing.expect(c.z_edit_extends_selection(c.UHDK_EDIT_WORD_LEFT, shift) != 0);
try std.testing.expect(c.z_edit_extends_selection(c.UHDK_EDIT_PAGE_DOWN, shift) != 0); try std.testing.expect(c.z_edit_extends_selection(c.UHDK_EDIT_PAGE_DOWN, shift) != 0);
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| 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|
@ -210,8 +227,10 @@ test "blocked file execution leaves event polling live and cancellation drains o
const handle = runtime.toAppHandle(application); const handle = runtime.toAppHandle(application);
var gate: IoGate = .{ .io = application.io }; var gate: IoGate = .{ .io = application.io };
application.io_test_hook = .{ .context = &gate, .before = IoGate.block }; application.io_test_hook = .{ .context = &gate, .before = IoGate.block };
const file = try runtime.createObject(application, c.Z_KIND_FILE); const file = try runtime.createObject(application, c.Z_KIND_FILE);
defer runtime.release(file); defer runtime.release(file);
const worker = try std.Thread.spawn(.{}, runtime.ioMain, .{application}); const worker = try std.Thread.spawn(.{}, runtime.ioMain, .{application});
defer { defer {
gate.release.set(application.io); gate.release.set(application.io);
@ -221,34 +240,43 @@ test "blocked file execution leaves event polling live and cancellation drains o
application.unlock(); application.unlock();
worker.join(); worker.join();
} }
const command = try runtime.createCommand(application, abi.IO_INFO, file); const command = try runtime.createCommand(application, abi.IO_INFO, file);
command.kind = c.UHDK_REQUEST_FILE_INFO; command.kind = c.UHDK_REQUEST_FILE_INFO;
const id: u64 = 42; const id: u64 = 42;
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, id));
runtime.dispatch(handle); runtime.dispatch(handle);
try gate.entered.waitTimeout(application.io, .{ .duration = .{ .raw = .fromSeconds(5), .clock = .awake } }); try gate.entered.waitTimeout(application.io, .{ .duration = .{ .raw = .fromSeconds(5), .clock = .awake } });
runtime.simpleEvent(application, c.UHDK_EVENT_WAKE); runtime.simpleEvent(application, c.UHDK_EVENT_WAKE);
var events: c.uhdk_event_list = undefined; 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(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 1), events.len); try std.testing.expectEqual(@as(u64, 1), events.len);
try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_WAKE), events.ptr[0].type); try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_WAKE), events.ptr[0].type);
// Shutdown is requested while the OS operation is still blocked. // Shutdown is requested while the OS operation is still blocked.
app_api.uhdk_quit(handle); app_api.uhdk_quit(handle);
runtime.dispatch(handle); runtime.dispatch(handle);
try std.testing.expect(!application.stopped_sent); try std.testing.expect(!application.stopped_sent);
gate.release.set(application.io); gate.release.set(application.io);
const deadline = runtime.now(application.io) + 5 * std.time.ns_per_s; const deadline = runtime.now(application.io) + 5 * std.time.ns_per_s;
while (true) { while (true) {
runtime.dispatch(handle); runtime.dispatch(handle);
application.lock(); application.lock();
const done = application.requests == null; const done = application.requests == null;
application.unlock(); application.unlock();
if (done) break; if (done) break;
try std.testing.expect(runtime.now(application.io) < deadline); try std.testing.expect(runtime.now(application.io) < deadline);
try (std.Io.Clock.Duration{ .raw = .fromMilliseconds(1), .clock = .awake }).sleep(application.io); try (std.Io.Clock.Duration{ .raw = .fromMilliseconds(1), .clock = .awake }).sleep(application.io);
} }
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events)); try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 2), events.len); try std.testing.expectEqual(@as(u64, 2), events.len);
const result: *const c.uhdk_request_result = @ptrCast(@alignCast(events.ptr[0].data.?)); const result: *const c.uhdk_request_result = @ptrCast(@alignCast(events.ptr[0].data.?));
try std.testing.expectEqual(id, result.tag); try std.testing.expectEqual(id, result.tag);
try std.testing.expectEqual(@as(u32, abi.CANCELLED), result.status); try std.testing.expectEqual(@as(u32, abi.CANCELLED), result.status);
@ -270,6 +298,7 @@ test "file queue saturation rejects without reserving a tag" {
const command = try runtime.createCommand(application, abi.IO_INFO, file); const command = try runtime.createCommand(application, abi.IO_INFO, file);
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, command, i + 1)); try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, command, i + 1));
} }
const excess = try runtime.createCommand(application, abi.IO_INFO, file); const excess = try runtime.createCommand(application, abi.IO_INFO, file);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, excess, 65)); try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, excess, 65));
application.stopping = true; application.stopping = true;
@ -286,6 +315,7 @@ test "fatal native failure persists and wakes subsequent polls" {
application.main_thread = std.Thread.getCurrentId(); application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application); const handle = runtime.toAppHandle(application);
c.z_native_failed(handle, c.UHDK_STATUS_OS_ERROR); c.z_native_failed(handle, c.UHDK_STATUS_OS_ERROR);
var events: c.uhdk_event_list = undefined; 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)); for (0..2) |_| try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_OS_ERROR), app_api.poll(handle, std.math.maxInt(u64), &events));
} }
@ -296,28 +326,35 @@ test "caller tags remain reserved until delivery and isolate late native complet
defer destroyApplication(application); defer destroyApplication(application);
application.running = true; application.running = true;
application.main_thread = std.Thread.getCurrentId(); application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application); const handle = runtime.toAppHandle(application);
const tag = std.math.maxInt(u64); // The full nonzero caller range is available. const tag = std.math.maxInt(u64); // The full nonzero caller range is available.
const zero = try runtime.createCommand(application, c.Z_CLIP_READ, null); 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.expectEqual(@as(u32, abi.INVALID), runtime.submit(application, zero, 0));
try std.testing.expect(application.requests == null); try std.testing.expect(application.requests == null);
const first = try runtime.createCommand(application, c.Z_CLIP_READ, null); const first = try runtime.createCommand(application, c.Z_CLIP_READ, null);
first.kind = c.UHDK_REQUEST_CLIPBOARD_TEXT; first.kind = c.UHDK_REQUEST_CLIPBOARD_TEXT;
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, first, tag)); try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, first, tag));
const old_native_id = first.id; const old_native_id = first.id;
const duplicate = try runtime.createCommand(application, c.Z_CLIP_READ, null); 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, c.UHDK_STATUS_BUSY), runtime.submit(application, duplicate, tag));
try std.testing.expectEqual(@as(u32, abi.OK), app_api.uhdk_request_cancel(handle, tag)); try std.testing.expectEqual(@as(u32, abi.OK), app_api.uhdk_request_cancel(handle, tag));
runtime.dispatch(handle); runtime.dispatch(handle);
const queued_duplicate = try runtime.createCommand(application, c.Z_CLIP_READ, null); 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_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)); 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; 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(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 1), events.len); try std.testing.expectEqual(@as(u64, 1), events.len);
const result: *const c.uhdk_request_result = @ptrCast(@alignCast(events.ptr[0].data.?)); const result: *const c.uhdk_request_result = @ptrCast(@alignCast(events.ptr[0].data.?));
try std.testing.expectEqual(tag, result.tag); try std.testing.expectEqual(tag, result.tag);
try std.testing.expectEqual(@as(u32, abi.CANCELLED), result.status); try std.testing.expectEqual(@as(u32, abi.CANCELLED), result.status);
const second = try runtime.createCommand(application, c.Z_CLIP_READ, null); 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.expectEqual(@as(u32, abi.OK), runtime.submit(application, second, tag));
try std.testing.expect(second.id != old_native_id); try std.testing.expect(second.id != old_native_id);
@ -337,16 +374,20 @@ test "error messages and diagnostics need no session and preserve native details
try std.testing.expect(message.len > 0); try std.testing.expect(message.len > 0);
try std.testing.expect(abi.validText(message, true)); try std.testing.expect(abi.validText(message, true));
} }
try std.testing.expect(app_api.uhdk_status_message(std.math.maxInt(u32)).len > 0); try std.testing.expect(app_api.uhdk_status_message(std.math.maxInt(u32)).len > 0);
var arena = std.heap.ArenaAllocator.init(std.testing.allocator); var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit(); defer arena.deinit();
var event = std.mem.zeroes(c.z_event); var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_REQUEST_DONE; event.type = c.UHDK_EVENT_REQUEST_DONE;
event.data.request.status = c.UHDK_STATUS_PERMISSION_DENIED; event.data.request.status = c.UHDK_STATUS_PERMISSION_DENIED;
const converted = try @import("EventPayload.zig").pack(arena.allocator(), event); const converted = try @import("EventPayload.zig").pack(arena.allocator(), event);
const result: *const c.uhdk_request_result = @ptrCast(@alignCast(converted.data.?)); 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)); 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"); event.data.request.diagnostic = abi.textSpan("Native context detail");
const detailed = try @import("EventPayload.zig").pack(arena.allocator(), event); const detailed = try @import("EventPayload.zig").pack(arena.allocator(), event);
const with_detail: *const c.uhdk_request_result = @ptrCast(@alignCast(detailed.data.?)); const with_detail: *const c.uhdk_request_result = @ptrCast(@alignCast(detailed.data.?));
try std.testing.expectEqualStrings("Native context detail", abi.textBytes(with_detail.diagnostic)); try std.testing.expectEqualStrings("Native context detail", abi.textBytes(with_detail.diagnostic));
@ -358,11 +399,13 @@ test "cycle end markers survive public event batching" {
defer destroyApplication(application); defer destroyApplication(application);
application.running = true; application.running = true;
application.main_thread = std.Thread.getCurrentId(); application.main_thread = std.Thread.getCurrentId();
const window = try runtime.createObject(application, c.Z_KIND_WINDOW); const window = try runtime.createObject(application, c.Z_KIND_WINDOW);
defer { defer {
window.arena.deinit(); window.arena.deinit();
application.gpa.destroy(window); application.gpa.destroy(window);
} }
const handle = runtime.toAppHandle(application); const handle = runtime.toAppHandle(application);
var event = std.mem.zeroes(c.z_event); var event = std.mem.zeroes(c.z_event);
event.window = runtime.castHandle(*c.uhdk_window, window); event.window = runtime.castHandle(*c.uhdk_window, window);
@ -372,6 +415,7 @@ test "cycle end markers survive public event batching" {
runtime.emit(handle, &event); runtime.emit(handle, &event);
event.data.pointer.pressed = 0; event.data.pointer.pressed = 0;
runtime.emit(handle, &event); runtime.emit(handle, &event);
var batch: c.uhdk_event_list = undefined; 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(u32, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 3), batch.len); try std.testing.expectEqual(@as(u64, 3), batch.len);
@ -380,6 +424,7 @@ test "cycle end markers survive public event batching" {
try std.testing.expectEqual(batch.ptr[0].cycle_id, batch.ptr[2].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(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); 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.?)); 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); try std.testing.expectEqual(@as(u32, c.UHDK_CYCLE_COMPLETED), ending.reason);
} }

View File

@ -5,6 +5,7 @@ const data = @embedFile("font/roboto-16.fontatlas");
fn word(offset: usize) u16 { fn word(offset: usize) u16 {
return std.mem.readInt(u16, data[offset..][0..2], .little); return std.mem.readInt(u16, data[offset..][0..2], .little);
} }
const count = word(4); const count = word(4);
const fallback = word(6); const fallback = word(6);
const Glyph = struct { const Glyph = struct {
@ -16,6 +17,7 @@ const Glyph = struct {
y: i8, y: i8,
advance: u8, advance: u8,
}; };
fn record(index: usize) Glyph { fn record(index: usize) Glyph {
const offset = 8 + index * 12; const offset = 8 + index * 12;
return .{ return .{
@ -28,6 +30,7 @@ fn record(index: usize) Glyph {
.advance = data[offset + 10], .advance = data[offset + 10],
}; };
} }
fn glyph(codepoint: u21) Glyph { fn glyph(codepoint: u21) Glyph {
var lo: usize = 0; var lo: usize = 0;
var hi: usize = count; var hi: usize = count;
@ -37,10 +40,13 @@ fn glyph(codepoint: u21) Glyph {
const key = word(8 + mid * 12); const key = word(8 + mid * 12);
if (key < codepoint) lo = mid + 1 else hi = mid; if (key < codepoint) lo = mid + 1 else hi = mid;
} }
if (lo < count and word(8 + lo * 12) == codepoint) return record(lo); if (lo < count and word(8 + lo * 12) == codepoint) return record(lo);
} }
return record(fallback); return record(fallback);
} }
pub fn width(text: []const u8) i32 { pub fn width(text: []const u8) i32 {
var it = std.unicode.Utf8View.initUnchecked(text).iterator(); var it = std.unicode.Utf8View.initUnchecked(text).iterator();
var result: i32 = 0; var result: i32 = 0;
@ -48,8 +54,10 @@ pub fn width(text: []const u8) i32 {
result += glyph(cp).advance; result += glyph(cp).advance;
if (result >= 1024) break; // Menus constrain/ellipsize long labels. if (result >= 1024) break; // Menus constrain/ellipsize long labels.
} }
return result; return result;
} }
pub const Canvas = struct { pub const Canvas = struct {
pixels: []u32, pixels: []u32,
width: i32, width: i32,
@ -61,24 +69,30 @@ pub const Canvas = struct {
const x1 = std.math.clamp(x + w, 0, self.width) * self.scale; const x1 = std.math.clamp(x + w, 0, self.width) * self.scale;
const y1 = std.math.clamp(y + h, 0, self.height) * self.scale; const y1 = std.math.clamp(y + h, 0, self.height) * self.scale;
if (x1 <= x0 or y1 <= y0) return; if (x1 <= x0 or y1 <= y0) return;
var row = y0; var row = y0;
while (row < y1) : (row += 1) { while (row < y1) : (row += 1) {
const offset: usize = @intCast(row * self.width * self.scale); const offset: usize = @intCast(row * self.width * self.scale);
@memset(self.pixels[offset + @as(usize, @intCast(x0)) .. offset + @as(usize, @intCast(x1))], color | 0xff000000); @memset(self.pixels[offset + @as(usize, @intCast(x0)) .. offset + @as(usize, @intCast(x1))], color | 0xff000000);
} }
} }
fn pixel(self: Canvas, x: i32, y: i32, color: u32, alpha: u32) void { fn pixel(self: Canvas, x: i32, y: i32, color: u32, alpha: u32) void {
if (x < 0 or y < 0 or x >= self.width or y >= self.height or alpha == 0) return; if (x < 0 or y < 0 or x >= self.width or y >= self.height or alpha == 0) return;
const index: usize = @intCast((y * self.width * self.scale + x) * self.scale); const index: usize = @intCast((y * self.width * self.scale + x) * self.scale);
const background = self.pixels[index]; const background = self.pixels[index];
var blended: u32 = 0xff000000; var blended: u32 = 0xff000000;
inline for (.{ 0, 8, 16 }) |shift| { inline for (.{ 0, 8, 16 }) |shift| {
blended |= ((((color >> shift) & 255) * alpha + ((background >> shift) & 255) * (255 - alpha) + 127) / 255) << shift; blended |= ((((color >> shift) & 255) * alpha + ((background >> shift) & 255) * (255 - alpha) + 127) / 255) << shift;
} }
self.rect(x, y, 1, 1, blended); self.rect(x, y, 1, 1, blended);
} }
fn drawGlyph(self: Canvas, value: Glyph, x: i32, baseline: i32, color: u32) void { fn drawGlyph(self: Canvas, value: Glyph, x: i32, baseline: i32, color: u32) void {
if (value.width == 0) return; if (value.width == 0) return;
const encoded = data[value.offset..][0..value.packed_size]; const encoded = data[value.offset..][0..value.packed_size];
const pixel_count: usize = @as(usize, value.width) * value.height; const pixel_count: usize = @as(usize, value.width) * value.height;
var byte_index: usize = 0; var byte_index: usize = 0;
@ -86,11 +100,13 @@ pub const Canvas = struct {
while (byte_index < encoded.len and pixel_index < pixel_count) { while (byte_index < encoded.len and pixel_index < pixel_count) {
const control = encoded[byte_index]; const control = encoded[byte_index];
byte_index += 1; byte_index += 1;
const run: usize = @as(usize, control & 0x7f) + 1; const run: usize = @as(usize, control & 0x7f) + 1;
if (control & 0x80 != 0) { if (control & 0x80 != 0) {
pixel_index += run * 2; pixel_index += run * 2;
continue; continue;
} }
for (encoded[byte_index..][0..run]) |pair| { for (encoded[byte_index..][0..run]) |pair| {
inline for (.{ pair & 0x0f, pair >> 4 }) |coverage| { inline for (.{ pair & 0x0f, pair >> 4 }) |coverage| {
if (pixel_index < pixel_count and coverage != 0) { if (pixel_index < pixel_count and coverage != 0) {
@ -98,12 +114,15 @@ pub const Canvas = struct {
const row = pixel_index / value.width; const row = pixel_index / value.width;
self.pixel(x + value.x + @as(i32, @intCast(column)), baseline + value.y + @as(i32, @intCast(row)), color, @as(u32, coverage) * 17); self.pixel(x + value.x + @as(i32, @intCast(column)), baseline + value.y + @as(i32, @intCast(row)), color, @as(u32, coverage) * 17);
} }
pixel_index += 1; pixel_index += 1;
} }
} }
byte_index += run; byte_index += run;
} }
} }
pub fn text(self: Canvas, value: []const u8, x: i32, baseline: i32, limit: i32, color: u32) void { pub fn text(self: Canvas, value: []const u8, x: i32, baseline: i32, limit: i32, color: u32) void {
var it = std.unicode.Utf8View.initUnchecked(value).iterator(); var it = std.unicode.Utf8View.initUnchecked(value).iterator();
var cursor = x; var cursor = x;
@ -115,35 +134,44 @@ pub const Canvas = struct {
if (limit >= ellipsis.advance) self.drawGlyph(ellipsis, cursor, baseline, color); if (limit >= ellipsis.advance) self.drawGlyph(ellipsis, cursor, baseline, color);
return; return;
} }
self.drawGlyph(g, cursor, baseline, color); self.drawGlyph(g, cursor, baseline, color);
cursor += g.advance; cursor += g.advance;
} }
} }
}; };
test "bitmap bounds, coverage and clipping" { test "bitmap bounds, coverage and clipping" {
try std.testing.expectEqualStrings("FAP1", data[0..4]); try std.testing.expectEqualStrings("FAP1", data[0..4]);
try std.testing.expect(fallback < count); try std.testing.expect(fallback < count);
var previous: u16 = 0; var previous: u16 = 0;
for (0..count) |i| { for (0..count) |i| {
const cp = word(8 + i * 12); const cp = word(8 + i * 12);
try std.testing.expect(cp > previous); try std.testing.expect(cp > previous);
previous = cp; previous = cp;
const g = glyph(@intCast(cp)); const g = glyph(@intCast(cp));
try std.testing.expect(g.offset + g.packed_size <= data.len); try std.testing.expect(g.offset + g.packed_size <= data.len);
var input: usize = 0; var input: usize = 0;
var decoded_bytes: usize = 0; var decoded_bytes: usize = 0;
while (input < g.packed_size) { while (input < g.packed_size) {
const control = data[g.offset + input]; const control = data[g.offset + input];
input += 1; input += 1;
const run: usize = @as(usize, control & 0x7f) + 1; const run: usize = @as(usize, control & 0x7f) + 1;
decoded_bytes += run; decoded_bytes += run;
if (control & 0x80 == 0) input += run; if (control & 0x80 == 0) input += run;
try std.testing.expect(input <= g.packed_size); try std.testing.expect(input <= g.packed_size);
} }
try std.testing.expectEqual((@as(usize, g.width) * g.height + 1) / 2, decoded_bytes); try std.testing.expectEqual((@as(usize, g.width) * g.height + 1) / 2, decoded_bytes);
} }
try std.testing.expectEqual(@as(u16, '~'), previous); try std.testing.expectEqual(@as(u16, '~'), previous);
try std.testing.expectEqual(width("?"), width("漢")); try std.testing.expectEqual(width("?"), width("漢"));
var pixels: [64 * 32]u32 = @splat(0xff000000); var pixels: [64 * 32]u32 = @splat(0xff000000);
const canvas: Canvas = .{ .pixels = &pixels, .width = 64, .height = 32, .scale = 1 }; const canvas: Canvas = .{ .pixels = &pixels, .width = 64, .height = 32, .scale = 1 };
canvas.text("Roboto café", -2, 17, 60, 0xffffff); canvas.text("Roboto café", -2, 17, 60, 0xffffff);

View File

@ -8,69 +8,87 @@ pub const Message = c.DBusMessage;
pub fn method(destination: [*:0]const u8, path: [*:0]const u8, interface: [*:0]const u8, member: [*:0]const u8) Error!*Message { pub fn method(destination: [*:0]const u8, path: [*:0]const u8, interface: [*:0]const u8, member: [*:0]const u8) Error!*Message {
return c.z_dbus_message_new_method_call.?(destination, path, interface, member) orelse error.OutOfMemory; return c.z_dbus_message_new_method_call.?(destination, path, interface, member) orelse error.OutOfMemory;
} }
pub fn append(message: *Message) Iter { pub fn append(message: *Message) Iter {
var i: Iter = undefined; var i: Iter = undefined;
c.z_dbus_message_iter_init_append.?(message, &i); c.z_dbus_message_iter_init_append.?(message, &i);
return i; return i;
} }
pub fn parse(message: *Message) Iter { pub fn parse(message: *Message) Iter {
var i: Iter = std.mem.zeroes(Iter); var i: Iter = std.mem.zeroes(Iter);
_ = c.z_dbus_message_iter_init.?(message, &i); _ = c.z_dbus_message_iter_init.?(message, &i);
return i; return i;
} }
pub fn basic(i: *Iter, type_: c_int, value: anytype) Error!void { pub fn basic(i: *Iter, type_: c_int, value: anytype) Error!void {
var v = value; var v = value;
if (c.z_dbus_message_iter_append_basic.?(i, type_, @ptrCast(&v)) == 0) return error.OutOfMemory; if (c.z_dbus_message_iter_append_basic.?(i, type_, @ptrCast(&v)) == 0) return error.OutOfMemory;
} }
pub fn string(i: *Iter, value: [*:0]const u8) Error!void { pub fn string(i: *Iter, value: [*:0]const u8) Error!void {
try basic(i, c.DBUS_TYPE_STRING, value); try basic(i, c.DBUS_TYPE_STRING, value);
} }
pub fn open(i: *Iter, type_: c_int, signature: ?[*:0]const u8) Error!Iter { pub fn open(i: *Iter, type_: c_int, signature: ?[*:0]const u8) Error!Iter {
var nested: Iter = std.mem.zeroes(Iter); var nested: Iter = std.mem.zeroes(Iter);
if (c.z_dbus_message_iter_open_container.?(i, type_, signature, &nested) == 0) return error.OutOfMemory; if (c.z_dbus_message_iter_open_container.?(i, type_, signature, &nested) == 0) return error.OutOfMemory;
return nested; return nested;
} }
pub fn close(i: *Iter, nested: *Iter) Error!void { pub fn close(i: *Iter, nested: *Iter) Error!void {
if (c.z_dbus_message_iter_close_container.?(i, nested) == 0) return error.OutOfMemory; if (c.z_dbus_message_iter_close_container.?(i, nested) == 0) return error.OutOfMemory;
} }
pub fn option(i: *Iter, key: [*:0]const u8, comptime signature: [:0]const u8, value: anytype) Error!void { pub fn option(i: *Iter, key: [*:0]const u8, comptime signature: [:0]const u8, value: anytype) Error!void {
var pair = try open(i, c.DBUS_TYPE_DICT_ENTRY, null); var pair = try open(i, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(i, &pair); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(i, &pair);
try string(&pair, key); try string(&pair, key);
var payload = try open(&pair, c.DBUS_TYPE_VARIANT, signature); var payload = try open(&pair, c.DBUS_TYPE_VARIANT, signature);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&pair, &payload); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&pair, &payload);
try basic(&payload, signature[0], value); try basic(&payload, signature[0], value);
try close(&pair, &payload); try close(&pair, &payload);
try close(i, &pair); try close(i, &pair);
} }
pub fn kind(i: *Iter) c_int { pub fn kind(i: *Iter) c_int {
return c.z_dbus_message_iter_get_arg_type.?(i); return c.z_dbus_message_iter_get_arg_type.?(i);
} }
pub fn next(i: *Iter) bool { pub fn next(i: *Iter) bool {
return c.z_dbus_message_iter_next.?(i) != 0; return c.z_dbus_message_iter_next.?(i) != 0;
} }
pub fn child(i: *Iter) Iter { pub fn child(i: *Iter) Iter {
var result: Iter = std.mem.zeroes(Iter); var result: Iter = std.mem.zeroes(Iter);
c.z_dbus_message_iter_recurse.?(i, &result); c.z_dbus_message_iter_recurse.?(i, &result);
return result; return result;
} }
pub fn str(i: *Iter) ?[]const u8 { pub fn str(i: *Iter) ?[]const u8 {
if (kind(i) != c.DBUS_TYPE_STRING and kind(i) != c.DBUS_TYPE_OBJECT_PATH) return null; if (kind(i) != c.DBUS_TYPE_STRING and kind(i) != c.DBUS_TYPE_OBJECT_PATH) return null;
var value: [*c]const u8 = null; var value: [*c]const u8 = null;
c.z_dbus_message_iter_get_basic.?(i, @ptrCast(&value)); c.z_dbus_message_iter_get_basic.?(i, @ptrCast(&value));
return if (value == null) null else std.mem.span(value); return if (value == null) null else std.mem.span(value);
} }
pub fn uint(i: *Iter) ?u32 { pub fn uint(i: *Iter) ?u32 {
if (kind(i) != c.DBUS_TYPE_UINT32) return null; if (kind(i) != c.DBUS_TYPE_UINT32) return null;
var value: u32 = 0; var value: u32 = 0;
c.z_dbus_message_iter_get_basic.?(i, @ptrCast(&value)); c.z_dbus_message_iter_get_basic.?(i, @ptrCast(&value));
return value; return value;
} }
pub fn variant(i: *Iter) ?Iter { pub fn variant(i: *Iter) ?Iter {
return if (kind(i) == c.DBUS_TYPE_VARIANT) child(i) else null; return if (kind(i) == c.DBUS_TYPE_VARIANT) child(i) else null;
} }
pub fn entry(i: *Iter, key: []const u8) ?Iter { pub fn entry(i: *Iter, key: []const u8) ?Iter {
if (kind(i) != c.DBUS_TYPE_ARRAY) return null; if (kind(i) != c.DBUS_TYPE_ARRAY) return null;
var entries = child(i); var entries = child(i);
while (kind(&entries) == c.DBUS_TYPE_DICT_ENTRY) { while (kind(&entries) == c.DBUS_TYPE_DICT_ENTRY) {
var pair = child(&entries); var pair = child(&entries);
@ -79,8 +97,10 @@ pub fn entry(i: *Iter, key: []const u8) ?Iter {
if (std.mem.eql(u8, name, key)) return pair; if (std.mem.eql(u8, name, key)) return pair;
if (!next(&entries)) break; if (!next(&entries)) break;
} }
return null; return null;
} }
comptime { comptime {
std.debug.assert(@sizeOf(c.dbus_uint32_t) == 4); std.debug.assert(@sizeOf(c.dbus_uint32_t) == 4);
std.debug.assert(@sizeOf(c.dbus_uint64_t) == 8); std.debug.assert(@sizeOf(c.dbus_uint64_t) == 8);
@ -89,6 +109,7 @@ comptime {
pub fn int(i: *Iter) ?i32 { pub fn int(i: *Iter) ?i32 {
if (kind(i) != c.DBUS_TYPE_INT32) return null; if (kind(i) != c.DBUS_TYPE_INT32) return null;
var value: i32 = 0; var value: i32 = 0;
c.z_dbus_message_iter_get_basic.?(i, @ptrCast(&value)); c.z_dbus_message_iter_get_basic.?(i, @ptrCast(&value));
return value; return value;

View File

@ -17,12 +17,14 @@ const Offer = struct {
actions: u32 = 0, actions: u32 = 0,
action: u32 = 0, action: u32 = 0,
}; };
const Source = struct { const Source = struct {
next: ?*Source = null, next: ?*Source = null,
proxy: ?*c.struct_wl_data_source, proxy: ?*c.struct_wl_data_source,
bytes: []u8, bytes: []u8,
refs: usize = 1, refs: usize = 1,
}; };
const Transfer = struct { const Transfer = struct {
next: ?*Transfer = null, next: ?*Transfer = null,
fd: c_int, fd: c_int,
@ -36,6 +38,7 @@ const Transfer = struct {
limit: u64 = 0, limit: u64 = 0,
deadline: u64, deadline: u64,
}; };
pub const State = struct { pub const State = struct {
manager: ?*c.struct_wl_data_device_manager = null, manager: ?*c.struct_wl_data_device_manager = null,
device: ?*c.struct_wl_data_device = null, device: ?*c.struct_wl_data_device = null,
@ -48,67 +51,83 @@ pub const State = struct {
position: n.uhdk_point = .{ .x = 0, .y = 0 }, position: n.uhdk_point = .{ .x = 0, .y = 0 },
transfers: ?*Transfer = null, transfers: ?*Transfer = null,
}; };
fn backend() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
fn dataState() *State { fn dataState() *State {
return &backend().data; return &backend().data;
} }
fn data(comptime T: type, raw: ?*anyopaque) *T { fn data(comptime T: type, raw: ?*anyopaque) *T {
return @ptrCast(@alignCast(raw.?)); return @ptrCast(@alignCast(raw.?));
} }
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void { pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void {
if (std.mem.eql(u8, interface, "wl_data_device_manager") and version >= 3) if (std.mem.eql(u8, interface, "wl_data_device_manager") and version >= 3)
dataState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wl_data_device_manager_interface, 3)); dataState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wl_data_device_manager_interface, 3));
} }
pub fn setup() void { pub fn setup() void {
if (dataState().manager != null and Input.state().seat != null and dataState().device == null) { if (dataState().manager != null and Input.state().seat != null and dataState().device == null) {
dataState().device = c.wl_data_device_manager_get_data_device(dataState().manager, Input.state().seat); dataState().device = c.wl_data_device_manager_get_data_device(dataState().manager, Input.state().seat);
if (dataState().device != null) _ = c.wl_data_device_add_listener(dataState().device, &device_listener, null); if (dataState().device != null) _ = c.wl_data_device_add_listener(dataState().device, &device_listener, null);
} }
native.setCapability(n.UHDK_CAP_CLIPBOARD, dataState().device != null); native.setCapability(n.UHDK_CAP_CLIPBOARD, dataState().device != null);
native.setCapability(n.UHDK_CAP_DROP_FILES, dataState().device != null); native.setCapability(n.UHDK_CAP_DROP_FILES, dataState().device != null);
} }
fn unref(o: *Offer) void { fn unref(o: *Offer) void {
o.refs -= 1; o.refs -= 1;
if (o.refs != 0) return; if (o.refs != 0) return;
var link = &dataState().offers; var link = &dataState().offers;
while (link.* != o) link = &link.*.?.next; while (link.* != o) link = &link.*.?.next;
link.* = o.next; link.* = o.next;
c.wl_data_offer_destroy(o.proxy); c.wl_data_offer_destroy(o.proxy);
backend().app.gpa.destroy(o); backend().app.gpa.destroy(o);
} }
fn offer(_: ?*anyopaque, _: ?*c.struct_wl_data_device, proxy: ?*c.struct_wl_data_offer) callconv(.c) void { fn offer(_: ?*anyopaque, _: ?*c.struct_wl_data_device, proxy: ?*c.struct_wl_data_offer) callconv(.c) void {
const o = backend().app.gpa.create(Offer) catch { const o = backend().app.gpa.create(Offer) catch {
c.wl_data_offer_destroy(proxy); c.wl_data_offer_destroy(proxy);
return; return;
}; };
o.* = .{ .next = dataState().offers, .proxy = proxy }; o.* = .{ .next = dataState().offers, .proxy = proxy };
dataState().offers = o; dataState().offers = o;
_ = c.wl_data_offer_add_listener(proxy, &offer_listener, o); _ = c.wl_data_offer_add_listener(proxy, &offer_listener, o);
} }
fn mime(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, name: [*c]const u8) callconv(.c) void { fn mime(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, name: [*c]const u8) callconv(.c) void {
const o = data(Offer, raw); const o = data(Offer, raw);
const str = std.mem.span(name); const str = std.mem.span(name);
if (std.mem.eql(u8, str, "text/plain;charset=utf-8")) o.text = "text/plain;charset=utf-8" else if (std.mem.eql(u8, str, "text/plain") and o.text == null) o.text = "text/plain"; if (std.mem.eql(u8, str, "text/plain;charset=utf-8")) o.text = "text/plain;charset=utf-8" else if (std.mem.eql(u8, str, "text/plain") and o.text == null) o.text = "text/plain";
if (std.mem.eql(u8, str, "text/uri-list")) o.uris = true; if (std.mem.eql(u8, str, "text/uri-list")) o.uris = true;
} }
fn actions(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, value: u32) callconv(.c) void { fn actions(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, value: u32) callconv(.c) void {
data(Offer, raw).actions = value; data(Offer, raw).actions = value;
} }
fn action(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, value: u32) callconv(.c) void { fn action(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, value: u32) callconv(.c) void {
data(Offer, raw).action = value; data(Offer, raw).action = value;
} }
const offer_listener: c.struct_wl_data_offer_listener = .{ .offer = mime, .source_actions = actions, .action = action }; const offer_listener: c.struct_wl_data_offer_listener = .{ .offer = mime, .source_actions = actions, .action = action };
fn lookup(proxy: ?*c.struct_wl_data_offer) ?*Offer { fn lookup(proxy: ?*c.struct_wl_data_offer) ?*Offer {
var o = dataState().offers; var o = dataState().offers;
while (o) |item| : (o = item.next) if (item.proxy == proxy) return item; while (o) |item| : (o = item.next) if (item.proxy == proxy) return item;
return null; return null;
} }
fn selection(_: ?*anyopaque, _: ?*c.struct_wl_data_device, proxy: ?*c.struct_wl_data_offer) callconv(.c) void { fn selection(_: ?*anyopaque, _: ?*c.struct_wl_data_device, proxy: ?*c.struct_wl_data_offer) callconv(.c) void {
if (dataState().selection) |old| unref(old); if (dataState().selection) |old| unref(old);
dataState().selection = lookup(proxy); // Takes the initial offer reference. dataState().selection = lookup(proxy); // Takes the initial offer reference.
} }
fn enter(_: ?*anyopaque, _: ?*c.struct_wl_data_device, serial: u32, surface: ?*c.struct_wl_surface, x: i32, y: i32, proxy: ?*c.struct_wl_data_offer) callconv(.c) void { fn enter(_: ?*anyopaque, _: ?*c.struct_wl_data_device, serial: u32, surface: ?*c.struct_wl_surface, x: i32, y: i32, proxy: ?*c.struct_wl_data_offer) callconv(.c) void {
leave(null, null); leave(null, null);
dataState().drag = lookup(proxy); dataState().drag = lookup(proxy);
@ -117,45 +136,56 @@ fn enter(_: ?*anyopaque, _: ?*c.struct_wl_data_device, serial: u32, surface: ?*c
dataState().position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 }; dataState().position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 };
negotiate(); negotiate();
} }
fn negotiate() void { fn negotiate() void {
const o = dataState().drag orelse return; const o = dataState().drag orelse return;
const accepted = o.uris and dataState().drag_window != null and dataState().drag_window.?.drop_enabled; const accepted = o.uris and dataState().drag_window != null and dataState().drag_window.?.drop_enabled;
c.wl_data_offer_accept(o.proxy, dataState().drag_serial, if (accepted) "text/uri-list" else null); c.wl_data_offer_accept(o.proxy, dataState().drag_serial, if (accepted) "text/uri-list" else null);
c.wl_data_offer_set_actions(o.proxy, if (accepted) c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY else 0, if (accepted) c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY else 0); c.wl_data_offer_set_actions(o.proxy, if (accepted) c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY else 0, if (accepted) c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY else 0);
} }
fn leave(_: ?*anyopaque, _: ?*c.struct_wl_data_device) callconv(.c) void { fn leave(_: ?*anyopaque, _: ?*c.struct_wl_data_device) callconv(.c) void {
if (dataState().drag) |o| unref(o); if (dataState().drag) |o| unref(o);
dataState().drag = null; dataState().drag = null;
dataState().drag_window = null; dataState().drag_window = null;
} }
fn motion(_: ?*anyopaque, _: ?*c.struct_wl_data_device, _: u32, x: i32, y: i32) callconv(.c) void { fn motion(_: ?*anyopaque, _: ?*c.struct_wl_data_device, _: u32, x: i32, y: i32) callconv(.c) void {
dataState().position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 }; dataState().position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 };
} }
fn drop(_: ?*anyopaque, _: ?*c.struct_wl_data_device) callconv(.c) void { fn drop(_: ?*anyopaque, _: ?*c.struct_wl_data_device) callconv(.c) void {
const o = dataState().drag orelse return; const o = dataState().drag orelse return;
const w = dataState().drag_window orelse return; const w = dataState().drag_window orelse return;
if (!w.drop_enabled or !o.uris or o.action != c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY) return; if (!w.drop_enabled or !o.uris or o.action != c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY) return;
_ = receive(o, "text/uri-list", 0, 16 * 1024 * 1024, w); _ = receive(o, "text/uri-list", 0, 16 * 1024 * 1024, w);
// drop ends the drag session; no leave is required after a successful drop. // drop ends the drag session; no leave is required after a successful drop.
leave(null, null); leave(null, null);
} }
const device_listener: c.struct_wl_data_device_listener = .{ .data_offer = offer, .enter = enter, .leave = leave, .motion = motion, .drop = drop, .selection = selection }; const device_listener: c.struct_wl_data_device_listener = .{ .data_offer = offer, .enter = enter, .leave = leave, .motion = motion, .drop = drop, .selection = selection };
pub fn enable(w: *native.Window, enabled: bool) u32 { pub fn enable(w: *native.Window, enabled: bool) u32 {
if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED; if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED;
w.drop_enabled = enabled; w.drop_enabled = enabled;
if (dataState().drag_window == w) negotiate(); if (dataState().drag_window == w) negotiate();
return abi.OK; return abi.OK;
} }
fn sourceUnref(source: *Source) void { fn sourceUnref(source: *Source) void {
source.refs -= 1; source.refs -= 1;
if (source.refs != 0) return; if (source.refs != 0) return;
var link = &dataState().sources; var link = &dataState().sources;
while (link.* != source) link = &link.*.?.next; while (link.* != source) link = &link.*.?.next;
link.* = source.next; link.* = source.next;
backend().app.gpa.free(source.bytes); backend().app.gpa.free(source.bytes);
backend().app.gpa.destroy(source); backend().app.gpa.destroy(source);
} }
fn target(_: ?*anyopaque, _: ?*c.struct_wl_data_source, _: [*c]const u8) callconv(.c) void {} fn target(_: ?*anyopaque, _: ?*c.struct_wl_data_source, _: [*c]const u8) callconv(.c) void {}
fn send(raw: ?*anyopaque, _: ?*c.struct_wl_data_source, name: [*c]const u8, fd: i32) callconv(.c) void { fn send(raw: ?*anyopaque, _: ?*c.struct_wl_data_source, name: [*c]const u8, fd: i32) callconv(.c) void {
const source = data(Source, raw); const source = data(Source, raw);
const str = std.mem.span(name); const str = std.mem.span(name);
@ -163,39 +193,48 @@ fn send(raw: ?*anyopaque, _: ?*c.struct_wl_data_source, name: [*c]const u8, fd:
_ = c.close(fd); _ = c.close(fd);
return; return;
} }
const transfer = backend().app.gpa.create(Transfer) catch { const transfer = backend().app.gpa.create(Transfer) catch {
_ = c.close(fd); _ = c.close(fd);
return; return;
}; };
source.refs += 1; source.refs += 1;
transfer.* = .{ .next = dataState().transfers, .fd = fd, .source = source, .deadline = runtime.now(backend().app.io) + 10 * std.time.ns_per_s }; transfer.* = .{ .next = dataState().transfers, .fd = fd, .source = source, .deadline = runtime.now(backend().app.io) + 10 * std.time.ns_per_s };
dataState().transfers = transfer; dataState().transfers = transfer;
} }
fn cancelled(raw: ?*anyopaque, proxy: ?*c.struct_wl_data_source) callconv(.c) void { fn cancelled(raw: ?*anyopaque, proxy: ?*c.struct_wl_data_source) callconv(.c) void {
const source = data(Source, raw); const source = data(Source, raw);
c.wl_data_source_destroy(proxy); c.wl_data_source_destroy(proxy);
source.proxy = null; source.proxy = null;
sourceUnref(source); sourceUnref(source);
} }
fn unused(_: ?*anyopaque, _: ?*c.struct_wl_data_source) callconv(.c) void {} fn unused(_: ?*anyopaque, _: ?*c.struct_wl_data_source) callconv(.c) void {}
fn unusedAction(_: ?*anyopaque, _: ?*c.struct_wl_data_source, _: u32) callconv(.c) void {} fn unusedAction(_: ?*anyopaque, _: ?*c.struct_wl_data_source, _: u32) callconv(.c) void {}
const source_listener: c.struct_wl_data_source_listener = .{ .target = target, .send = send, .cancelled = cancelled, .dnd_drop_performed = unused, .dnd_finished = unused, .action = unusedAction }; const source_listener: c.struct_wl_data_source_listener = .{ .target = target, .send = send, .cancelled = cancelled, .dnd_drop_performed = unused, .dnd_finished = unused, .action = unusedAction };
pub fn write(text: n.uhdk_text) u32 { pub fn write(text: n.uhdk_text) u32 {
if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED; if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED;
const input = Input.state(); const input = Input.state();
// Selection changes require an actual input serial. Never queue a write to // Selection changes require an actual input serial. Never queue a write to
// hijack an unrelated future keystroke when the app has no input focus. // hijack an unrelated future keystroke when the app has no input focus.
if (input.key_focus == null or input.serial == 0) return abi.UNAVAILABLE; if (input.key_focus == null or input.serial == 0) return abi.UNAVAILABLE;
const source = backend().app.gpa.create(Source) catch return abi.OOM; const source = backend().app.gpa.create(Source) catch return abi.OOM;
const bytes = backend().app.gpa.dupe(u8, abi.textBytes(text)) catch { const bytes = backend().app.gpa.dupe(u8, abi.textBytes(text)) catch {
backend().app.gpa.destroy(source); backend().app.gpa.destroy(source);
return abi.OOM; return abi.OOM;
}; };
const proxy = c.wl_data_device_manager_create_data_source(dataState().manager) orelse { const proxy = c.wl_data_device_manager_create_data_source(dataState().manager) orelse {
backend().app.gpa.free(bytes); backend().app.gpa.free(bytes);
backend().app.gpa.destroy(source); backend().app.gpa.destroy(source);
return abi.OOM; return abi.OOM;
}; };
source.* = .{ .next = dataState().sources, .proxy = proxy, .bytes = bytes }; source.* = .{ .next = dataState().sources, .proxy = proxy, .bytes = bytes };
dataState().sources = source; dataState().sources = source;
_ = c.wl_data_source_add_listener(proxy, &source_listener, source); _ = c.wl_data_source_add_listener(proxy, &source_listener, source);
@ -204,21 +243,26 @@ pub fn write(text: n.uhdk_text) u32 {
c.wl_data_device_set_selection(dataState().device, proxy, input.serial); c.wl_data_device_set_selection(dataState().device, proxy, input.serial);
return abi.OK; return abi.OK;
} }
pub fn read(id: u64, limit: u64) u32 { pub fn read(id: u64, limit: u64) u32 {
if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED; if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED;
if (Input.state().key_focus == null) return abi.UNAVAILABLE; if (Input.state().key_focus == null) return abi.UNAVAILABLE;
const o = dataState().selection orelse return n.UHDK_STATUS_NOT_FOUND; const o = dataState().selection orelse return n.UHDK_STATUS_NOT_FOUND;
const format = o.text orelse return n.UHDK_STATUS_NOT_FOUND; const format = o.text orelse return n.UHDK_STATUS_NOT_FOUND;
return receive(o, format, id, limit, null); return receive(o, format, id, limit, null);
} }
fn receive(o: *Offer, format: [*:0]const u8, id: u64, limit: u64, w: ?*native.Window) u32 { fn receive(o: *Offer, format: [*:0]const u8, id: u64, limit: u64, w: ?*native.Window) u32 {
var fds: [2]c_int = undefined; var fds: [2]c_int = undefined;
if (c.z_linux_pipe(&fds) != 0) return n.UHDK_STATUS_OS_ERROR; if (c.z_linux_pipe(&fds) != 0) return n.UHDK_STATUS_OS_ERROR;
const transfer = backend().app.gpa.create(Transfer) catch { const transfer = backend().app.gpa.create(Transfer) catch {
_ = c.close(fds[0]); _ = c.close(fds[0]);
_ = c.close(fds[1]); _ = c.close(fds[1]);
return abi.OOM; return abi.OOM;
}; };
o.refs += 1; o.refs += 1;
transfer.* = .{ .next = dataState().transfers, .fd = fds[0], .request = id, .offer = o, .window = w, .position = dataState().position, .limit = limit, .deadline = runtime.now(backend().app.io) + 10 * std.time.ns_per_s }; transfer.* = .{ .next = dataState().transfers, .fd = fds[0], .request = id, .offer = o, .window = w, .position = dataState().position, .limit = limit, .deadline = runtime.now(backend().app.io) + 10 * std.time.ns_per_s };
dataState().transfers = transfer; dataState().transfers = transfer;
@ -226,10 +270,12 @@ fn receive(o: *Offer, format: [*:0]const u8, id: u64, limit: u64, w: ?*native.Wi
_ = c.close(fds[1]); _ = c.close(fds[1]);
return n.Z_DEFERRED; return n.Z_DEFERRED;
} }
pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void { pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
var t = dataState().transfers; var t = dataState().transfers;
while (t) |item| : (t = item.next) try fds.append(backend().app.gpa, .{ .fd = item.fd, .events = if (item.source != null) c.POLLOUT else c.POLLIN, .revents = 0 }); while (t) |item| : (t = item.next) try fds.append(backend().app.gpa, .{ .fd = item.fd, .events = if (item.source != null) c.POLLOUT else c.POLLIN, .revents = 0 });
} }
pub fn tick() i32 { pub fn tick() i32 {
var t = dataState().transfers; var t = dataState().transfers;
while (t) |item| { while (t) |item| {
@ -238,12 +284,14 @@ pub fn tick() i32 {
finish(item, abi.UNAVAILABLE); finish(item, abi.UNAVAILABLE);
continue; continue;
} }
if (item.source) |source| { if (item.source) |source| {
const bytes = source.bytes[item.offset..]; const bytes = source.bytes[item.offset..];
if (bytes.len == 0) { if (bytes.len == 0) {
finish(item, abi.OK); finish(item, abi.OK);
continue; continue;
} }
const amount = c.z_linux_pipe_write(item.fd, bytes.ptr, @min(bytes.len, 65536)); const amount = c.z_linux_pipe_write(item.fd, bytes.ptr, @min(bytes.len, 65536));
if (amount > 0) item.offset += @intCast(amount) else if (amount < 0 and c.z_linux_errno() != c.EAGAIN and c.z_linux_errno() != c.EINTR) finish(item, abi.UNAVAILABLE); if (amount > 0) item.offset += @intCast(amount) else if (amount < 0 and c.z_linux_errno() != c.EAGAIN and c.z_linux_errno() != c.EINTR) finish(item, abi.UNAVAILABLE);
} else { } else {
@ -255,6 +303,7 @@ pub fn tick() i32 {
finish(item, n.UHDK_STATUS_BUFFER_TOO_SMALL); finish(item, n.UHDK_STATUS_BUFFER_TOO_SMALL);
continue; continue;
} }
item.bytes.appendSlice(backend().app.gpa, buffer[0..length]) catch { item.bytes.appendSlice(backend().app.gpa, buffer[0..length]) catch {
finish(item, abi.OOM); finish(item, abi.OOM);
continue; continue;
@ -262,8 +311,10 @@ pub fn tick() i32 {
} else if (c.z_linux_errno() != c.EAGAIN and c.z_linux_errno() != c.EINTR) finish(item, abi.UNAVAILABLE); } else if (c.z_linux_errno() != c.EAGAIN and c.z_linux_errno() != c.EINTR) finish(item, abi.UNAVAILABLE);
} }
} }
return if (dataState().transfers != null) 100 else -1; return if (dataState().transfers != null) 100 else -1;
} }
fn finish(t: *Transfer, status: u32) void { fn finish(t: *Transfer, status: u32) void {
if (t.request != 0) { if (t.request != 0) {
var result = std.mem.zeroes(n.z_request_result); var result = std.mem.zeroes(n.z_request_result);
@ -272,6 +323,7 @@ fn finish(t: *Transfer, status: u32) void {
} else if (t.window) |w| { } else if (t.window) |w| {
if (status == abi.OK and w.drop_enabled and emitDrop(w, t.bytes.items, t.position)) c.wl_data_offer_finish(t.offer.?.proxy); if (status == abi.OK and w.drop_enabled and emitDrop(w, t.bytes.items, t.position)) c.wl_data_offer_finish(t.offer.?.proxy);
} }
var link = &dataState().transfers; var link = &dataState().transfers;
while (link.* != t) link = &link.*.?.next; while (link.* != t) link = &link.*.?.next;
link.* = t.next; link.* = t.next;
@ -281,31 +333,38 @@ fn finish(t: *Transfer, status: u32) void {
t.bytes.deinit(backend().app.gpa); t.bytes.deinit(backend().app.gpa);
backend().app.gpa.destroy(t); backend().app.gpa.destroy(t);
} }
fn emitDrop(w: *native.Window, bytes: []const u8, position: n.uhdk_point) bool { fn emitDrop(w: *native.Window, bytes: []const u8, position: n.uhdk_point) bool {
var files: std.ArrayList(?*n.uhdk_file) = .empty; var files: std.ArrayList(?*n.uhdk_file) = .empty;
defer { defer {
for (files.items) |file| n.uhdk_file_release(file); for (files.items) |file| n.uhdk_file_release(file);
files.deinit(backend().app.gpa); files.deinit(backend().app.gpa);
} }
var lines = std.mem.splitScalar(u8, bytes, '\n'); var lines = std.mem.splitScalar(u8, bytes, '\n');
while (lines.next()) |line| { while (lines.next()) |line| {
const uri = std.mem.trim(u8, line, "\r"); const uri = std.mem.trim(u8, line, "\r");
if (uri.len == 0 or uri[0] == '#') continue; if (uri.len == 0 or uri[0] == '#') continue;
const path = Files.decode(backend().app.gpa, uri) catch return false; const path = Files.decode(backend().app.gpa, uri) catch return false;
defer backend().app.gpa.free(path); defer backend().app.gpa.free(path);
const file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = path.ptr, .len = path.len }, null) orelse return false; const file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = path.ptr, .len = path.len }, null) orelse return false;
files.append(backend().app.gpa, file) catch { files.append(backend().app.gpa, file) catch {
n.uhdk_file_release(file); n.uhdk_file_release(file);
return false; return false;
}; };
} }
if (files.items.len == 0) return false; if (files.items.len == 0) return false;
var event = std.mem.zeroes(n.z_event); var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_DROP_FILES; event.type = n.UHDK_EVENT_DROP_FILES;
event.data.drop_files = .{ .files = .{ .ptr = files.items.ptr, .len = files.items.len }, .position = position }; event.data.drop_files = .{ .files = .{ .ptr = files.items.ptr, .len = files.items.len }, .position = position };
Input.send(w, &event); Input.send(w, &event);
return true; return true;
} }
pub fn cancel(id: u64) bool { pub fn cancel(id: u64) bool {
var t = dataState().transfers; var t = dataState().transfers;
while (t) |item| : (t = item.next) if (item.request == id) { while (t) |item| : (t = item.next) if (item.request == id) {
@ -314,11 +373,13 @@ pub fn cancel(id: u64) bool {
}; };
return false; return false;
} }
pub fn forget(w: *native.Window) void { pub fn forget(w: *native.Window) void {
if (dataState().drag_window == w) { if (dataState().drag_window == w) {
dataState().drag_window = null; dataState().drag_window = null;
negotiate(); negotiate();
} }
var t = dataState().transfers; var t = dataState().transfers;
while (t) |item| { while (t) |item| {
t = item.next; t = item.next;
@ -328,6 +389,7 @@ pub fn forget(w: *native.Window) void {
} }
} }
} }
pub fn releaseSeat() void { pub fn releaseSeat() void {
while (dataState().transfers) |t| finish(t, abi.CANCELLED); while (dataState().transfers) |t| finish(t, abi.CANCELLED);
dataState().selection = null; dataState().selection = null;
@ -338,11 +400,13 @@ pub fn releaseSeat() void {
if (source.proxy != null) c.wl_data_source_destroy(source.proxy); if (source.proxy != null) c.wl_data_source_destroy(source.proxy);
sourceUnref(source); sourceUnref(source);
} }
if (dataState().device != null) c.wl_data_device_release(dataState().device); if (dataState().device != null) c.wl_data_device_release(dataState().device);
dataState().device = null; dataState().device = null;
native.setCapability(n.UHDK_CAP_CLIPBOARD, false); native.setCapability(n.UHDK_CAP_CLIPBOARD, false);
native.setCapability(n.UHDK_CAP_DROP_FILES, false); native.setCapability(n.UHDK_CAP_DROP_FILES, false);
} }
pub fn deinit() void { pub fn deinit() void {
releaseSeat(); releaseSeat();
if (dataState().manager != null) c.wl_data_device_manager_destroy(dataState().manager); if (dataState().manager != null) c.wl_data_device_manager_destroy(dataState().manager);

View File

@ -14,12 +14,14 @@ const Activation = struct {
token: ?*c.struct_xdg_activation_token_v1, token: ?*c.struct_xdg_activation_token_v1,
deadline: u64, deadline: u64,
}; };
const Icon = struct { const Icon = struct {
proxy: ?*c.struct_xdg_toplevel_icon_v1, proxy: ?*c.struct_xdg_toplevel_icon_v1,
buffer: ?*c.struct_wl_buffer, buffer: ?*c.struct_wl_buffer,
mapping: *anyopaque, mapping: *anyopaque,
size: usize, size: usize,
}; };
pub const State = struct { pub const State = struct {
activation: ?*c.struct_xdg_activation_v1 = null, activation: ?*c.struct_xdg_activation_v1 = null,
manager: ?*c.struct_xdg_toplevel_icon_manager_v1 = null, manager: ?*c.struct_xdg_toplevel_icon_manager_v1 = null,
@ -28,12 +30,15 @@ pub const State = struct {
pending: ?*Activation = null, pending: ?*Activation = null,
launch: ?[:0]u8 = null, launch: ?[:0]u8 = null,
}; };
fn backend() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
fn desktopState() *State { fn desktopState() *State {
return &backend().desktop; return &backend().desktop;
} }
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void { pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void {
if (std.mem.eql(u8, interface, "xdg_activation_v1")) desktopState().activation = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_activation_v1_interface, 1)) else if (std.mem.eql(u8, interface, "xdg_toplevel_icon_manager_v1")) { if (std.mem.eql(u8, interface, "xdg_activation_v1")) desktopState().activation = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_activation_v1_interface, 1)) else if (std.mem.eql(u8, interface, "xdg_toplevel_icon_manager_v1")) {
desktopState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_toplevel_icon_manager_v1_interface, 1)); desktopState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_toplevel_icon_manager_v1_interface, 1));
@ -42,9 +47,12 @@ pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8
desktopState().shm = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wl_shm_interface, 1)); desktopState().shm = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wl_shm_interface, 1));
if (desktopState().shm != null) _ = c.wl_shm_add_listener(desktopState().shm, &shm_listener, null); if (desktopState().shm != null) _ = c.wl_shm_add_listener(desktopState().shm, &shm_listener, null);
} }
native.setCapability(n.UHDK_CAP_APP_ICON, desktopState().manager != null and desktopState().shm != null); native.setCapability(n.UHDK_CAP_APP_ICON, desktopState().manager != null and desktopState().shm != null);
} }
fn iconSize(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel_icon_manager_v1, _: i32) callconv(.c) void {} fn iconSize(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel_icon_manager_v1, _: i32) callconv(.c) void {}
fn iconDone(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel_icon_manager_v1) callconv(.c) void {} fn iconDone(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel_icon_manager_v1) callconv(.c) void {}
const icon_listener: c.struct_xdg_toplevel_icon_manager_v1_listener = .{ .icon_size = iconSize, .done = iconDone }; const icon_listener: c.struct_xdg_toplevel_icon_manager_v1_listener = .{ .icon_size = iconSize, .done = iconDone };
fn format(_: ?*anyopaque, _: ?*c.struct_wl_shm, _: u32) callconv(.c) void {} fn format(_: ?*anyopaque, _: ?*c.struct_wl_shm, _: u32) callconv(.c) void {}
@ -56,6 +64,7 @@ pub fn initialize() void {
_ = c.unsetenv("XDG_ACTIVATION_TOKEN"); _ = c.unsetenv("XDG_ACTIVATION_TOKEN");
} }
} }
pub fn focus(w: *native.Window, id: u64) u32 { pub fn focus(w: *native.Window, id: u64) u32 {
if (desktopState().activation == null) return n.UHDK_STATUS_UNSUPPORTED; if (desktopState().activation == null) return n.UHDK_STATUS_UNSUPPORTED;
if (desktopState().launch) |token| { if (desktopState().launch) |token| {
@ -64,6 +73,7 @@ pub fn focus(w: *native.Window, id: u64) u32 {
desktopState().launch = null; desktopState().launch = null;
return abi.OK; return abi.OK;
} }
const input = Input.state(); const input = Input.state();
if (input.serial == 0 or input.key_focus == null or if (input.serial == 0 or input.key_focus == null or
runtime.now(backend().app.io) -| input.serial_time > 5 * std.time.ns_per_s) runtime.now(backend().app.io) -| input.serial_time > 5 * std.time.ns_per_s)
@ -73,6 +83,7 @@ pub fn focus(w: *native.Window, id: u64) u32 {
backend().app.gpa.destroy(p); backend().app.gpa.destroy(p);
return abi.OOM; return abi.OOM;
}; };
p.* = .{ p.* = .{
.next = desktopState().pending, .next = desktopState().pending,
.id = id, .id = id,
@ -80,10 +91,12 @@ pub fn focus(w: *native.Window, id: u64) u32 {
.token = token, .token = token,
.deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s, .deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s,
}; };
desktopState().pending = p; desktopState().pending = p;
_ = c.xdg_activation_token_v1_add_listener(token, &activation_listener, p); _ = c.xdg_activation_token_v1_add_listener(token, &activation_listener, p);
c.xdg_activation_token_v1_set_serial(token, input.serial, input.seat); c.xdg_activation_token_v1_set_serial(token, input.serial, input.seat);
c.xdg_activation_token_v1_set_surface(token, input.key_focus.?.surface); c.xdg_activation_token_v1_set_surface(token, input.key_focus.?.surface);
const app_id = backend().app.gpa.dupeZ(u8, backend().app.application_id) catch { const app_id = backend().app.gpa.dupeZ(u8, backend().app.application_id) catch {
finish(p, abi.OOM); finish(p, abi.OOM);
return n.Z_DEFERRED; return n.Z_DEFERRED;
@ -93,11 +106,13 @@ pub fn focus(w: *native.Window, id: u64) u32 {
c.xdg_activation_token_v1_commit(token); c.xdg_activation_token_v1_commit(token);
return n.Z_DEFERRED; return n.Z_DEFERRED;
} }
fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c]const u8) callconv(.c) void { fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c]const u8) callconv(.c) void {
const p: *Activation = @ptrCast(@alignCast(raw.?)); const p: *Activation = @ptrCast(@alignCast(raw.?));
c.xdg_activation_v1_activate(desktopState().activation, token, p.window.surface); c.xdg_activation_v1_activate(desktopState().activation, token, p.window.surface);
finish(p, abi.OK); finish(p, abi.OK);
} }
const activation_listener: c.struct_xdg_activation_token_v1_listener = .{ .done = activated }; const activation_listener: c.struct_xdg_activation_token_v1_listener = .{ .done = activated };
fn finish(p: *Activation, status: u32) void { fn finish(p: *Activation, status: u32) void {
var link = &desktopState().pending; var link = &desktopState().pending;
@ -107,14 +122,17 @@ fn finish(p: *Activation, status: u32) void {
n.z_complete(runtime.toAppHandle(backend().app), p.id, status, null); n.z_complete(runtime.toAppHandle(backend().app), p.id, status, null);
backend().app.gpa.destroy(p); backend().app.gpa.destroy(p);
} }
pub fn tick() i32 { pub fn tick() i32 {
var cursor = desktopState().pending; var cursor = desktopState().pending;
while (cursor) |p| { while (cursor) |p| {
cursor = p.next; cursor = p.next;
if (runtime.now(backend().app.io) >= p.deadline) finish(p, abi.UNAVAILABLE); if (runtime.now(backend().app.io) >= p.deadline) finish(p, abi.UNAVAILABLE);
} }
return if (desktopState().pending != null) 100 else -1; return if (desktopState().pending != null) 100 else -1;
} }
pub fn cancel(id: u64) bool { pub fn cancel(id: u64) bool {
var cursor = desktopState().pending; var cursor = desktopState().pending;
while (cursor) |p| : (cursor = p.next) if (p.id == id) { while (cursor) |p| : (cursor = p.next) if (p.id == id) {
@ -123,6 +141,7 @@ pub fn cancel(id: u64) bool {
}; };
return false; return false;
} }
pub fn forget(w: *native.Window) void { pub fn forget(w: *native.Window) void {
var cursor = desktopState().pending; var cursor = desktopState().pending;
while (cursor) |p| { while (cursor) |p| {
@ -130,14 +149,17 @@ pub fn forget(w: *native.Window) void {
if (p.window == w) finish(p, abi.CANCELLED); if (p.window == w) finish(p, abi.CANCELLED);
} }
} }
pub fn applyIcon(w: *native.Window) void { pub fn applyIcon(w: *native.Window) void {
if (desktopState().icon) |icon| if (desktopState().icon) |icon|
c.xdg_toplevel_icon_manager_v1_set_icon(desktopState().manager, w.top, icon.proxy); c.xdg_toplevel_icon_manager_v1_set_icon(desktopState().manager, w.top, icon.proxy);
} }
/// Public pixels are straight RGBA; wl_shm ARGB8888 uses native-endian, /// Public pixels are straight RGBA; wl_shm ARGB8888 uses native-endian,
/// premultiplied channels. Pad rectangular images to a transparent square. /// premultiplied channels. Pad rectangular images to a transparent square.
pub fn pixels(destination: []u32, side: usize, image: n.uhdk_image) void { pub fn pixels(destination: []u32, side: usize, image: n.uhdk_image) void {
@memset(destination, 0); @memset(destination, 0);
const source = abi.bytes(image.pixels); const source = abi.bytes(image.pixels);
const x0 = (side - image.width) / 2; const x0 = (side - image.width) / 2;
const y0 = (side - image.height) / 2; const y0 = (side - image.height) / 2;
@ -150,24 +172,31 @@ pub fn pixels(destination: []u32, side: usize, image: n.uhdk_image) void {
destination[(y + y0) * side + x + x0] = a << 24 | r << 16 | g << 8 | blue; destination[(y + y0) * side + x + x0] = a << 24 | r << 16 | g << 8 | blue;
}; };
} }
pub fn setIcon(image: n.uhdk_image) u32 { pub fn setIcon(image: n.uhdk_image) u32 {
if (desktopState().manager == null or desktopState().shm == null) return n.UHDK_STATUS_UNSUPPORTED; if (desktopState().manager == null or desktopState().shm == null) return n.UHDK_STATUS_UNSUPPORTED;
const side = @max(image.width, image.height); const side = @max(image.width, image.height);
const size: usize = @as(usize, side) * side * 4; const size: usize = @as(usize, side) * side * 4;
const fd = c.memfd_create("uhdk-icon", c.MFD_CLOEXEC); const fd = c.memfd_create("uhdk-icon", c.MFD_CLOEXEC);
if (fd < 0) return n.UHDK_STATUS_OS_ERROR; if (fd < 0) return n.UHDK_STATUS_OS_ERROR;
defer _ = c.close(fd); defer _ = c.close(fd);
if (c.ftruncate(fd, @intCast(size)) != 0) return n.UHDK_STATUS_OS_ERROR; if (c.ftruncate(fd, @intCast(size)) != 0) return n.UHDK_STATUS_OS_ERROR;
const mapping = c.mmap(null, size, c.PROT_READ | c.PROT_WRITE, c.MAP_SHARED, fd, 0); const mapping = c.mmap(null, size, c.PROT_READ | c.PROT_WRITE, c.MAP_SHARED, fd, 0);
if (mapping == c.MAP_FAILED) return n.UHDK_STATUS_OS_ERROR; if (mapping == c.MAP_FAILED) return n.UHDK_STATUS_OS_ERROR;
var retained = false; var retained = false;
defer if (!retained) { defer if (!retained) {
_ = c.munmap(mapping, size); _ = c.munmap(mapping, size);
}; };
const words: [*]u32 = @ptrCast(@alignCast(mapping.?)); const words: [*]u32 = @ptrCast(@alignCast(mapping.?));
pixels(words[0 .. size / 4], side, image); pixels(words[0 .. size / 4], side, image);
const pool = c.wl_shm_create_pool(desktopState().shm, fd, @intCast(size)) orelse return abi.OOM; const pool = c.wl_shm_create_pool(desktopState().shm, fd, @intCast(size)) orelse return abi.OOM;
defer c.wl_shm_pool_destroy(pool); defer c.wl_shm_pool_destroy(pool);
const buffer = c.wl_shm_pool_create_buffer( const buffer = c.wl_shm_pool_create_buffer(
pool, pool,
0, 0,
@ -176,24 +205,29 @@ pub fn setIcon(image: n.uhdk_image) u32 {
@intCast(side * 4), @intCast(side * 4),
c.WL_SHM_FORMAT_ARGB8888, c.WL_SHM_FORMAT_ARGB8888,
) orelse return abi.OOM; ) orelse return abi.OOM;
const proxy = c.xdg_toplevel_icon_manager_v1_create_icon(desktopState().manager) orelse { const proxy = c.xdg_toplevel_icon_manager_v1_create_icon(desktopState().manager) orelse {
c.wl_buffer_destroy(buffer); c.wl_buffer_destroy(buffer);
return abi.OOM; return abi.OOM;
}; };
c.xdg_toplevel_icon_v1_add_buffer(proxy, buffer, 1); c.xdg_toplevel_icon_v1_add_buffer(proxy, buffer, 1);
const old = desktopState().icon; const old = desktopState().icon;
desktopState().icon = .{ .proxy = proxy, .buffer = buffer, .mapping = mapping.?, .size = size }; desktopState().icon = .{ .proxy = proxy, .buffer = buffer, .mapping = mapping.?, .size = size };
retained = true; retained = true;
var cursor = backend().windows; var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) applyIcon(w); while (cursor) |w| : (cursor = w.next) applyIcon(w);
if (old) |icon| destroyIcon(icon); if (old) |icon| destroyIcon(icon);
return abi.OK; return abi.OK;
} }
fn destroyIcon(icon: Icon) void { fn destroyIcon(icon: Icon) void {
c.xdg_toplevel_icon_v1_destroy(icon.proxy); c.xdg_toplevel_icon_v1_destroy(icon.proxy);
c.wl_buffer_destroy(icon.buffer); c.wl_buffer_destroy(icon.buffer);
_ = c.munmap(icon.mapping, icon.size); _ = c.munmap(icon.mapping, icon.size);
} }
pub fn deinit() void { pub fn deinit() void {
while (desktopState().pending) |p| finish(p, abi.CANCELLED); while (desktopState().pending) |p| finish(p, abi.CANCELLED);
if (desktopState().icon) |icon| destroyIcon(icon); if (desktopState().icon) |icon| destroyIcon(icon);
@ -202,12 +236,14 @@ pub fn deinit() void {
if (desktopState().shm != null) c.wl_shm_destroy(desktopState().shm); if (desktopState().shm != null) c.wl_shm_destroy(desktopState().shm);
if (desktopState().activation != null) c.xdg_activation_v1_destroy(desktopState().activation); if (desktopState().activation != null) c.xdg_activation_v1_destroy(desktopState().activation);
} }
test "icons premultiply RGBA and pad rectangular images" { test "icons premultiply RGBA and pad rectangular images" {
const rgba = [_]u8{ 255, 128, 0, 128, 0, 255, 0, 255 }; const rgba = [_]u8{ 255, 128, 0, 128, 0, 255, 0, 255 };
var image = std.mem.zeroes(n.uhdk_image); var image = std.mem.zeroes(n.uhdk_image);
image.width = 2; image.width = 2;
image.height = 1; image.height = 1;
image.pixels = .{ .ptr = &rgba, .len = rgba.len }; image.pixels = .{ .ptr = &rgba, .len = rgba.len };
var result: [4]u32 = undefined; var result: [4]u32 = undefined;
pixels(&result, 2, image); pixels(&result, 2, image);
try std.testing.expectEqualSlices(u32, &.{ 0x80804000, 0xff00ff00, 0, 0 }, &result); try std.testing.expectEqualSlices(u32, &.{ 0x80804000, 0xff00ff00, 0, 0 }, &result);

View File

@ -12,12 +12,15 @@ pub const Context = struct {
surface: c.EGLSurface, surface: c.EGLSurface,
context: c.EGLContext, context: c.EGLContext,
}; };
threadlocal var frame: ?*Context = null; threadlocal var frame: ?*Context = null;
pub fn initialize(b: *native.Backend) void { pub fn initialize(b: *native.Backend) void {
if (c.z_linux_egl_available() == 0) return; if (c.z_linux_egl_available() == 0) return;
const display = c.z_eglGetPlatformDisplay.?(c.EGL_PLATFORM_WAYLAND_KHR, b.display, null); const display = c.z_eglGetPlatformDisplay.?(c.EGL_PLATFORM_WAYLAND_KHR, b.display, null);
if (display == null) return; if (display == null) return;
var major: c.EGLint = 0; var major: c.EGLint = 0;
var minor: c.EGLint = 0; var minor: c.EGLint = 0;
if (c.z_eglInitialize.?(display, &major, &minor) == c.EGL_FALSE) return; if (c.z_eglInitialize.?(display, &major, &minor) == c.EGL_FALSE) return;
@ -25,6 +28,7 @@ pub fn initialize(b: *native.Backend) void {
_ = c.z_eglTerminate.?(display); _ = c.z_eglTerminate.?(display);
return; return;
} }
const attributes = [_]c.EGLint{ c.EGL_SURFACE_TYPE, c.EGL_WINDOW_BIT, c.EGL_RENDERABLE_TYPE, c.EGL_OPENGL_BIT, c.EGL_RED_SIZE, 8, c.EGL_GREEN_SIZE, 8, c.EGL_BLUE_SIZE, 8, c.EGL_ALPHA_SIZE, 8, c.EGL_NONE }; const attributes = [_]c.EGLint{ c.EGL_SURFACE_TYPE, c.EGL_WINDOW_BIT, c.EGL_RENDERABLE_TYPE, c.EGL_OPENGL_BIT, c.EGL_RED_SIZE, 8, c.EGL_GREEN_SIZE, 8, c.EGL_BLUE_SIZE, 8, c.EGL_ALPHA_SIZE, 8, c.EGL_NONE };
var config: c.EGLConfig = null; var config: c.EGLConfig = null;
var count: c.EGLint = 0; var count: c.EGLint = 0;
@ -32,9 +36,11 @@ pub fn initialize(b: *native.Backend) void {
_ = c.z_eglTerminate.?(display); _ = c.z_eglTerminate.?(display);
return; return;
} }
b.egl_display = display; b.egl_display = display;
b.egl_config = config; b.egl_config = config;
} }
pub fn finish(b: *native.Backend) void { pub fn finish(b: *native.Backend) void {
if (b.egl_display != null) { if (b.egl_display != null) {
_ = c.z_eglTerminate.?(b.egl_display); _ = c.z_eglTerminate.?(b.egl_display);
@ -42,34 +48,41 @@ pub fn finish(b: *native.Backend) void {
b.egl_display = null; b.egl_display = null;
} }
} }
pub fn create(b: *native.Backend, w: *native.Window) u32 { pub fn create(b: *native.Backend, w: *native.Window) u32 {
if (b.egl_display == null or w.flags & n.Z_WINDOW_OPENGL == 0) return n.UHDK_STATUS_UNSUPPORTED; if (b.egl_display == null or w.flags & n.Z_WINDOW_OPENGL == 0) return n.UHDK_STATUS_UNSUPPORTED;
if (w.egl != null) return n.UHDK_STATUS_BUSY; if (w.egl != null) return n.UHDK_STATUS_BUSY;
if (c.z_eglBindAPI.?(c.EGL_OPENGL_API) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR; if (c.z_eglBindAPI.?(c.EGL_OPENGL_API) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR;
const attrs = [_]c.EGLint{ c.EGL_CONTEXT_MAJOR_VERSION, 3, c.EGL_CONTEXT_MINOR_VERSION, 3, c.EGL_CONTEXT_OPENGL_PROFILE_MASK, c.EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, c.EGL_NONE }; const attrs = [_]c.EGLint{ c.EGL_CONTEXT_MAJOR_VERSION, 3, c.EGL_CONTEXT_MINOR_VERSION, 3, c.EGL_CONTEXT_OPENGL_PROFILE_MASK, c.EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, c.EGL_NONE };
const context = c.z_eglCreateContext.?(b.egl_display, b.egl_config, null, &attrs); const context = c.z_eglCreateContext.?(b.egl_display, b.egl_config, null, &attrs);
if (context == null) return n.UHDK_STATUS_UNSUPPORTED; if (context == null) return n.UHDK_STATUS_UNSUPPORTED;
const win = c.z_wl_egl_window_create.?(w.surface, @intCast(w.metrics.framebuffer_width), @intCast(w.metrics.framebuffer_height)); const win = c.z_wl_egl_window_create.?(w.surface, @intCast(w.metrics.framebuffer_width), @intCast(w.metrics.framebuffer_height));
if (win == null) { if (win == null) {
_ = c.z_eglDestroyContext.?(b.egl_display, context); _ = c.z_eglDestroyContext.?(b.egl_display, context);
return abi.OOM; return abi.OOM;
} }
const surface = c.z_eglCreateWindowSurface.?(b.egl_display, b.egl_config, @ptrCast(win), null); const surface = c.z_eglCreateWindowSurface.?(b.egl_display, b.egl_config, @ptrCast(win), null);
if (surface == null) { if (surface == null) {
c.z_wl_egl_window_destroy.?(win); c.z_wl_egl_window_destroy.?(win);
_ = c.z_eglDestroyContext.?(b.egl_display, context); _ = c.z_eglDestroyContext.?(b.egl_display, context);
return n.UHDK_STATUS_OS_ERROR; return n.UHDK_STATUS_OS_ERROR;
} }
const ctx = b.app.gpa.create(Context) catch { const ctx = b.app.gpa.create(Context) catch {
_ = c.z_eglDestroySurface.?(b.egl_display, surface); _ = c.z_eglDestroySurface.?(b.egl_display, surface);
c.z_wl_egl_window_destroy.?(win); c.z_wl_egl_window_destroy.?(win);
_ = c.z_eglDestroyContext.?(b.egl_display, context); _ = c.z_eglDestroyContext.?(b.egl_display, context);
return abi.OOM; return abi.OOM;
}; };
ctx.* = .{ .window = w, .native = win, .surface = surface, .context = context }; ctx.* = .{ .window = w, .native = win, .surface = surface, .context = context };
w.egl = ctx; w.egl = ctx;
return abi.OK; return abi.OK;
} }
pub fn destroy(ctx: *Context) void { pub fn destroy(ctx: *Context) void {
const b = native.instance.?; const b = native.instance.?;
_ = c.z_eglDestroySurface.?(b.egl_display, ctx.surface); _ = c.z_eglDestroySurface.?(b.egl_display, ctx.surface);
@ -78,18 +91,22 @@ pub fn destroy(ctx: *Context) void {
ctx.window.egl = null; ctx.window.egl = null;
b.app.gpa.destroy(ctx); b.app.gpa.destroy(ctx);
} }
pub fn resetSurface(ctx: *Context) void { pub fn resetSurface(ctx: *Context) void {
const b = native.instance.?; const b = native.instance.?;
// An unmapped surface may never receive the driver's outstanding frame // An unmapped surface may never receive the driver's outstanding frame
// callback. Drop its EGL surface before hiding so remapping cannot wait // callback. Drop its EGL surface before hiding so remapping cannot wait
// forever in the next swap; the GL context and application resources survive. // forever in the next swap; the GL context and application resources survive.
if (ctx.surface != null) _ = c.z_eglDestroySurface.?(b.egl_display, ctx.surface); if (ctx.surface != null) _ = c.z_eglDestroySurface.?(b.egl_display, ctx.surface);
ctx.surface = c.z_eglCreateWindowSurface.?(b.egl_display, b.egl_config, ctx.native, null); ctx.surface = c.z_eglCreateWindowSurface.?(b.egl_display, b.egl_config, ctx.native, null);
} }
fn makeCurrent(b: *native.Backend, ctx: *Context) bool { fn makeCurrent(b: *native.Backend, ctx: *Context) bool {
return ctx.surface != null and c.z_eglBindAPI.?(c.EGL_OPENGL_API) != c.EGL_FALSE and return ctx.surface != null and c.z_eglBindAPI.?(c.EGL_OPENGL_API) != c.EGL_FALSE and
c.z_eglMakeCurrent.?(b.egl_display, ctx.surface, ctx.surface, ctx.context) != c.EGL_FALSE; c.z_eglMakeCurrent.?(b.egl_display, ctx.surface, ctx.surface, ctx.context) != c.EGL_FALSE;
} }
pub fn call(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 { pub fn call(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 {
const b = native.instance orelse return abi.UNAVAILABLE; const b = native.instance orelse return abi.UNAVAILABLE;
if (b.egl_display == null) return n.UHDK_STATUS_UNSUPPORTED; if (b.egl_display == null) return n.UHDK_STATUS_UNSUPPORTED;
@ -97,23 +114,29 @@ pub fn call(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 {
if (op == 8 and frame != null) return n.UHDK_STATUS_BUSY; if (op == 8 and frame != null) return n.UHDK_STATUS_BUSY;
return if (c.z_eglMakeCurrent.?(b.egl_display, null, null, null) != c.EGL_FALSE) abi.OK else n.UHDK_STATUS_OS_ERROR; return if (c.z_eglMakeCurrent.?(b.egl_display, null, null, null) != c.EGL_FALSE) abi.OK else n.UHDK_STATUS_OS_ERROR;
} }
const ctx: *Context = @ptrCast(@alignCast(ptr orelse return abi.INVALID)); const ctx: *Context = @ptrCast(@alignCast(ptr orelse return abi.INVALID));
if (op == 1) { if (op == 1) {
if (frame != null) return n.UHDK_STATUS_BUSY; if (frame != null) return n.UHDK_STATUS_BUSY;
if (b.failed.load(.acquire)) return abi.UNAVAILABLE; if (b.failed.load(.acquire)) return abi.UNAVAILABLE;
ctx.window.mutex.lockUncancelable(b.app.io); ctx.window.mutex.lockUncancelable(b.app.io);
if (!makeCurrent(b, ctx)) { if (!makeCurrent(b, ctx)) {
ctx.window.mutex.unlock(b.app.io); ctx.window.mutex.unlock(b.app.io);
return n.UHDK_STATUS_OS_ERROR; return n.UHDK_STATUS_OS_ERROR;
} }
frame = ctx; frame = ctx;
return abi.OK; return abi.OK;
} }
if (frame != ctx) return n.UHDK_STATUS_BUSY; if (frame != ctx) return n.UHDK_STATUS_BUSY;
switch (op) { switch (op) {
2 => { 2 => {
// Keep ownership on failure so a caller cannot destroy a current context. // Keep ownership on failure so a caller cannot destroy a current context.
if (c.z_eglMakeCurrent.?(b.egl_display, null, null, null) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR; if (c.z_eglMakeCurrent.?(b.egl_display, null, null, null) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR;
frame = null; frame = null;
ctx.window.mutex.unlock(b.app.io); ctx.window.mutex.unlock(b.app.io);
n.z_native_wake(); n.z_native_wake();
@ -127,19 +150,24 @@ pub fn call(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 {
}, },
7 => { 7 => {
if (c.z_eglGetCurrentContext.?() != ctx.context) return n.UHDK_STATUS_BUSY; if (c.z_eglGetCurrentContext.?() != ctx.context) return n.UHDK_STATUS_BUSY;
const interval: *const i32 = @ptrCast(@alignCast(out.?)); const interval: *const i32 = @ptrCast(@alignCast(out.?));
if (c.z_eglSwapInterval.?(b.egl_display, interval.*) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR; if (c.z_eglSwapInterval.?(b.egl_display, interval.*) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR;
}, },
else => return abi.INVALID, else => return abi.INVALID,
} }
return abi.OK; return abi.OK;
} }
pub fn proc(ptr: ?*anyopaque, name: n.uhdk_text, out: [*c]n.uhdk_gl_proc) u32 { pub fn proc(ptr: ?*anyopaque, name: n.uhdk_text, out: [*c]n.uhdk_gl_proc) u32 {
const ctx: *Context = @ptrCast(@alignCast(ptr orelse return abi.INVALID)); const ctx: *Context = @ptrCast(@alignCast(ptr orelse return abi.INVALID));
if (frame != ctx or c.z_eglGetCurrentContext.?() != ctx.context) return n.UHDK_STATUS_BUSY; if (frame != ctx or c.z_eglGetCurrentContext.?() != ctx.context) return n.UHDK_STATUS_BUSY;
const allocator = ctx.window.owner.gpa; const allocator = ctx.window.owner.gpa;
const terminated = allocator.dupeZ(u8, abi.textBytes(name)) catch return abi.OOM; const terminated = allocator.dupeZ(u8, abi.textBytes(name)) catch return abi.OOM;
defer allocator.free(terminated); defer allocator.free(terminated);
const address = c.z_eglGetProcAddress.?(terminated) orelse return n.UHDK_STATUS_NOT_FOUND; const address = c.z_eglGetProcAddress.?(terminated) orelse return n.UHDK_STATUS_NOT_FOUND;
out.* = @ptrCast(address); out.* = @ptrCast(address);
return abi.OK; return abi.OK;

View File

@ -8,20 +8,25 @@ pub fn decode(allocator: std.mem.Allocator, uri: []const u8) ![]u8 {
const encoded = if (std.mem.startsWith(u8, uri, "file:///")) uri[7..] else if (std.mem.startsWith(u8, uri, "file://localhost/")) uri[16..] else return error.Invalid; const encoded = if (std.mem.startsWith(u8, uri, "file:///")) uri[7..] else if (std.mem.startsWith(u8, uri, "file://localhost/")) uri[16..] else return error.Invalid;
var result: std.Io.Writer.Allocating = .init(allocator); var result: std.Io.Writer.Allocating = .init(allocator);
errdefer result.deinit(); errdefer result.deinit();
var i: usize = 0; var i: usize = 0;
while (i < encoded.len) : (i += 1) { while (i < encoded.len) : (i += 1) {
var byte = encoded[i]; var byte = encoded[i];
if (byte == '%') { if (byte == '%') {
if (encoded.len - i < 3) return error.Invalid; if (encoded.len - i < 3) return error.Invalid;
if (!std.ascii.isHex(encoded[i + 1]) or !std.ascii.isHex(encoded[i + 2])) return error.Invalid; if (!std.ascii.isHex(encoded[i + 1]) or !std.ascii.isHex(encoded[i + 2])) return error.Invalid;
byte = std.fmt.parseInt(u8, encoded[i + 1 ..][0..2], 16) catch return error.Invalid; byte = std.fmt.parseInt(u8, encoded[i + 1 ..][0..2], 16) catch return error.Invalid;
i += 2; i += 2;
} else if (byte == '?' or byte == '#') return error.Invalid; } else if (byte == '?' or byte == '#') return error.Invalid;
if (byte == 0) return error.Invalid; if (byte == 0) return error.Invalid;
try result.writer.writeByte(byte); try result.writer.writeByte(byte);
} }
return result.toOwnedSlice(); return result.toOwnedSlice();
} }
fn encode(allocator: std.mem.Allocator, path: []const u8) ![]u8 { fn encode(allocator: std.mem.Allocator, path: []const u8) ![]u8 {
var result: std.Io.Writer.Allocating = .init(allocator); var result: std.Io.Writer.Allocating = .init(allocator);
errdefer result.deinit(); errdefer result.deinit();
@ -31,18 +36,24 @@ fn encode(allocator: std.mem.Allocator, path: []const u8) ![]u8 {
try result.writer.writeByte(byte); try result.writer.writeByte(byte);
} else try result.writer.print("%{X:0>2}", .{byte}); } else try result.writer.print("%{X:0>2}", .{byte});
} }
return result.toOwnedSlice(); return result.toOwnedSlice();
} }
pub fn init(file: ?*n.uhdk_file, path: n.uhdk_bytes, uri: n.uhdk_text, grant: ?*anyopaque) u32 { pub fn init(file: ?*n.uhdk_file, path: n.uhdk_bytes, uri: n.uhdk_text, grant: ?*anyopaque) u32 {
if (grant != null) return n.UHDK_STATUS_UNSUPPORTED; if (grant != null) return n.UHDK_STATUS_UNSUPPORTED;
const object = runtime.fromObjectHandle(file); const object = runtime.fromObjectHandle(file);
var arena: std.heap.ArenaAllocator = .init(object.app.gpa); var arena: std.heap.ArenaAllocator = .init(object.app.gpa);
defer arena.deinit(); defer arena.deinit();
const allocator = arena.allocator(); const allocator = arena.allocator();
const bytes = if (path.len != 0) abi.bytes(path) else decode(allocator, abi.textBytes(uri)) catch |err| return if (err == error.Invalid) abi.INVALID else abi.OOM; const bytes = if (path.len != 0) abi.bytes(path) else decode(allocator, abi.textBytes(uri)) catch |err| return if (err == error.Invalid) abi.INVALID else abi.OOM;
if (bytes.len == 0 or bytes[0] != '/' or std.mem.findScalar(u8, bytes, 0) != null) return abi.INVALID; if (bytes.len == 0 or bytes[0] != '/' or std.mem.findScalar(u8, bytes, 0) != null) return abi.INVALID;
const encoded = encode(allocator, bytes) catch return abi.OOM; const encoded = encode(allocator, bytes) catch return abi.OOM;
const basename = std.fs.path.basename(bytes); const basename = std.fs.path.basename(bytes);
// Display text is lossy only when the native byte name isn't UTF-8. // Display text is lossy only when the native byte name isn't UTF-8.
const display = if (std.unicode.utf8ValidateSlice(basename)) basename else "(non-UTF-8 filename)"; const display = if (std.unicode.utf8ValidateSlice(basename)) basename else "(non-UTF-8 filename)";
return n.z_file_init(file, .{ .ptr = bytes.ptr, .len = bytes.len }, abi.textSpan(encoded), abi.textSpan(display), null); return n.z_file_init(file, .{ .ptr = bytes.ptr, .len = bytes.len }, abi.textSpan(encoded), abi.textSpan(display), null);
@ -54,12 +65,14 @@ test "file URI preserves POSIX bytes and rejects remote, NUL, malformed escapes"
const uri = try encode(allocator, original); const uri = try encode(allocator, original);
defer allocator.free(uri); defer allocator.free(uri);
try std.testing.expectEqualStrings("file:///tmp/a%20b%25%23%FF", uri); try std.testing.expectEqualStrings("file:///tmp/a%20b%25%23%FF", uri);
const path = try decode(allocator, uri); const path = try decode(allocator, uri);
defer allocator.free(path); defer allocator.free(path);
try std.testing.expectEqualStrings(original, path); try std.testing.expectEqualStrings(original, path);
for ([_][]const u8{ "https://host/file", "file://host/path", "file:///a%", "file:///a%XX", "file:///a%00", "file:///a%+1", "file:///a#fragment" }) |bad| { for ([_][]const u8{ "https://host/file", "file://host/path", "file:///a%", "file:///a%XX", "file:///a%00", "file:///a%+1", "file:///a#fragment" }) |bad| {
try std.testing.expectError(error.Invalid, decode(allocator, bad)); try std.testing.expectError(error.Invalid, decode(allocator, bad));
} }
const local = try decode(allocator, "file://localhost/tmp/a"); const local = try decode(allocator, "file://localhost/tmp/a");
defer allocator.free(local); defer allocator.free(local);
try std.testing.expectEqualStrings("/tmp/a", local); try std.testing.expectEqualStrings("/tmp/a", local);

View File

@ -20,17 +20,21 @@ const Key = struct {
text: [256]u8 = undefined, text: [256]u8 = undefined,
len: usize = 0, len: usize = 0,
}; };
pub const State = struct { pub const State = struct {
seat: ?*c.struct_wl_seat = null, seat: ?*c.struct_wl_seat = null,
seat_name: u32 = 0, seat_name: u32 = 0,
keyboard: ?*c.struct_wl_keyboard = null, keyboard: ?*c.struct_wl_keyboard = null,
pointer: ?*c.struct_wl_pointer = null, pointer: ?*c.struct_wl_pointer = null,
cursor_manager: ?*c.struct_wp_cursor_shape_manager_v1 = null, cursor_manager: ?*c.struct_wp_cursor_shape_manager_v1 = null,
cursor_device: ?*c.struct_wp_cursor_shape_device_v1 = null, cursor_device: ?*c.struct_wp_cursor_shape_device_v1 = null,
text_manager: ?*c.struct_zwp_text_input_manager_v3 = null, text_manager: ?*c.struct_zwp_text_input_manager_v3 = null,
text_input: ?*c.struct_zwp_text_input_v3 = null, text_input: ?*c.struct_zwp_text_input_v3 = null,
text_focus: ?*native.Window = null, text_focus: ?*native.Window = null,
text_serial: u32 = 0, text_serial: u32 = 0,
key_focus: ?*native.Window = null, key_focus: ?*native.Window = null,
pointer_focus: ?*native.Window = null, pointer_focus: ?*native.Window = null,
context: ?*c.struct_xkb_context = null, context: ?*c.struct_xkb_context = null,
@ -42,6 +46,7 @@ pub const State = struct {
active: bool = false, active: bool = false,
pending_key: ?Key = null, pending_key: ?Key = null,
key_sync: ?*c.struct_wl_callback = null, key_sync: ?*c.struct_wl_callback = null,
serial: u32 = 0, serial: u32 = 0,
serial_time: u64 = 0, serial_time: u64 = 0,
popup_serial: u32 = 0, popup_serial: u32 = 0,
@ -50,48 +55,59 @@ pub const State = struct {
popup_buttons: u32 = 0, popup_buttons: u32 = 0,
pointer_serial: u32 = 0, pointer_serial: u32 = 0,
next_id: u64 = 0, next_id: u64 = 0,
position: n.uhdk_point = .{ .x = 0, .y = 0 }, position: n.uhdk_point = .{ .x = 0, .y = 0 },
buttons: u32 = 0, buttons: u32 = 0,
captured: bool = false, captured: bool = false,
last_click_time: u64 = 0, last_click_time: u64 = 0,
last_click_button: u32 = 0, last_click_button: u32 = 0,
last_click_position: n.uhdk_point = .{ .x = 0, .y = 0 }, last_click_position: n.uhdk_point = .{ .x = 0, .y = 0 },
click_count: u32 = 0, click_count: u32 = 0,
repeat_key: ?u32 = null, repeat_key: ?u32 = null,
repeat_rate: u32 = 0, repeat_rate: u32 = 0,
repeat_delay: u32 = 600, repeat_delay: u32 = 600,
repeat_at: u64 = 0, repeat_at: u64 = 0,
held: [256]bool = @splat(false), held: [256]bool = @splat(false),
menu_keys: [256]bool = @splat(false), menu_keys: [256]bool = @splat(false),
axis: n.uhdk_point = .{ .x = 0, .y = 0 }, axis: n.uhdk_point = .{ .x = 0, .y = 0 },
wheel: n.uhdk_point = .{ .x = 0, .y = 0 }, wheel: n.uhdk_point = .{ .x = 0, .y = 0 },
axis_source: u32 = c.WL_POINTER_AXIS_SOURCE_WHEEL, axis_source: u32 = c.WL_POINTER_AXIS_SOURCE_WHEEL,
axis_stop: bool = false, axis_stop: bool = false,
scrolling: bool = false, scrolling: bool = false,
}; };
fn backend() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
pub fn state() *State { pub fn state() *State {
return &backend().input; return &backend().input;
} }
pub fn find(surface: ?*c.struct_wl_surface) ?*native.Window { pub fn find(surface: ?*c.struct_wl_surface) ?*native.Window {
var item = backend().windows; var item = backend().windows;
while (item) |w| : (item = w.next) if (w.surface == surface) return w; while (item) |w| : (item = w.next) if (w.surface == surface) return w;
return null; return null;
} }
pub fn send(w: *native.Window, event: *n.z_event) void { pub fn send(w: *native.Window, event: *n.z_event) void {
event.window = w.handle; event.window = w.handle;
n.z_emit(runtime.toAppHandle(w.owner), event); n.z_emit(runtime.toAppHandle(w.owner), event);
} }
pub fn id() u64 { pub fn id() u64 {
state().next_id += 1; state().next_id += 1;
return state().next_id; return state().next_id;
} }
pub fn provenance(serial: u32) void { pub fn provenance(serial: u32) void {
state().serial = serial; state().serial = serial;
state().serial_time = runtime.now(backend().app.io); state().serial_time = runtime.now(backend().app.io);
} }
pub fn initialize() void { pub fn initialize() void {
const s = state(); const s = state();
if (c.z_linux_xkb_available() != 0) { if (c.z_linux_xkb_available() != 0) {
@ -106,6 +122,7 @@ pub fn initialize() void {
} }
} }
} }
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void { pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void {
const s = state(); const s = state();
if (std.mem.eql(u8, interface, "wl_seat") and s.seat == null and version >= 5) { if (std.mem.eql(u8, interface, "wl_seat") and s.seat == null and version >= 5) {
@ -118,6 +135,7 @@ pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8
s.text_manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_zwp_text_input_manager_v3_interface, 1)); s.text_manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_zwp_text_input_manager_v3_interface, 1));
} }
} }
pub fn setup() void { pub fn setup() void {
const s = state(); const s = state();
if (s.pointer != null and s.cursor_manager != null and s.cursor_device == null) if (s.pointer != null and s.cursor_manager != null and s.cursor_device == null)
@ -126,11 +144,13 @@ pub fn setup() void {
s.text_input = c.zwp_text_input_manager_v3_get_text_input(s.text_manager, s.seat); s.text_input = c.zwp_text_input_manager_v3_get_text_input(s.text_manager, s.seat);
if (s.text_input != null) Text.listen(s.text_input); if (s.text_input != null) Text.listen(s.text_input);
} }
Data.setup(); Data.setup();
Popup.capability(); Popup.capability();
native.setCapability(n.UHDK_CAP_POINTER_CAPTURE, s.pointer != null); native.setCapability(n.UHDK_CAP_POINTER_CAPTURE, s.pointer != null);
native.setCapability(n.UHDK_CAP_TEXT_INPUT, s.context != null and s.keyboard != null); native.setCapability(n.UHDK_CAP_TEXT_INPUT, s.context != null and s.keyboard != null);
} }
fn seatCapabilities(_: ?*anyopaque, seat: ?*c.struct_wl_seat, caps: u32) callconv(.c) void { fn seatCapabilities(_: ?*anyopaque, seat: ?*c.struct_wl_seat, caps: u32) callconv(.c) void {
const s = state(); const s = state();
if (caps & c.WL_SEAT_CAPABILITY_KEYBOARD != 0 and s.keyboard == null) { if (caps & c.WL_SEAT_CAPABILITY_KEYBOARD != 0 and s.keyboard == null) {
@ -141,6 +161,7 @@ fn seatCapabilities(_: ?*anyopaque, seat: ?*c.struct_wl_seat, caps: u32) callcon
c.wl_keyboard_release(s.keyboard); c.wl_keyboard_release(s.keyboard);
s.keyboard = null; s.keyboard = null;
} }
if (caps & c.WL_SEAT_CAPABILITY_POINTER != 0 and s.pointer == null) { if (caps & c.WL_SEAT_CAPABILITY_POINTER != 0 and s.pointer == null) {
s.pointer = c.wl_seat_get_pointer(seat); s.pointer = c.wl_seat_get_pointer(seat);
if (s.pointer != null) _ = c.wl_pointer_add_listener(s.pointer, &pointer_listener, null); if (s.pointer != null) _ = c.wl_pointer_add_listener(s.pointer, &pointer_listener, null);
@ -151,13 +172,20 @@ fn seatCapabilities(_: ?*anyopaque, seat: ?*c.struct_wl_seat, caps: u32) callcon
c.wl_pointer_release(s.pointer); c.wl_pointer_release(s.pointer);
s.pointer = null; s.pointer = null;
} }
setup(); setup();
} }
fn seatName(_: ?*anyopaque, _: ?*c.struct_wl_seat, _: [*c]const u8) callconv(.c) void {} fn seatName(_: ?*anyopaque, _: ?*c.struct_wl_seat, _: [*c]const u8) callconv(.c) void {}
const seat_listener: c.struct_wl_seat_listener = .{ .capabilities = seatCapabilities, .name = seatName }; const seat_listener: c.struct_wl_seat_listener = .{
.capabilities = seatCapabilities,
.name = seatName,
};
fn keymap(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, format: u32, fd: i32, size: u32) callconv(.c) void { fn keymap(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, format: u32, fd: i32, size: u32) callconv(.c) void {
flushKey(); flushKey();
defer _ = c.close(fd); defer _ = c.close(fd);
const s = state(); const s = state();
s.repeat_key = null; s.repeat_key = null;
if (s.compose != null) c.z_xkb_compose_state_reset.?(s.compose); if (s.compose != null) c.z_xkb_compose_state_reset.?(s.compose);
@ -167,18 +195,23 @@ fn keymap(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, format: u32, fd: i32, size:
s.state = null; s.state = null;
s.keymap = null; s.keymap = null;
if (s.context == null or format != c.WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1 or size == 0 or size > 16 * 1024 * 1024) return; if (s.context == null or format != c.WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1 or size == 0 or size > 16 * 1024 * 1024) return;
const mapped = c.mmap(null, size, c.PROT_READ, c.MAP_PRIVATE, fd, 0); const mapped = c.mmap(null, size, c.PROT_READ, c.MAP_PRIVATE, fd, 0);
if (mapped == c.MAP_FAILED) return; if (mapped == c.MAP_FAILED) return;
defer _ = c.munmap(mapped, size); defer _ = c.munmap(mapped, size);
const bytes: [*]const u8 = @ptrCast(mapped.?); const bytes: [*]const u8 = @ptrCast(mapped.?);
if (bytes[size - 1] != 0) return; if (bytes[size - 1] != 0) return;
s.keymap = c.z_xkb_keymap_new_from_string.?(s.context, @ptrCast(mapped), c.XKB_KEYMAP_FORMAT_TEXT_V1, c.XKB_KEYMAP_COMPILE_NO_FLAGS); s.keymap = c.z_xkb_keymap_new_from_string.?(s.context, @ptrCast(mapped), c.XKB_KEYMAP_FORMAT_TEXT_V1, c.XKB_KEYMAP_COMPILE_NO_FLAGS);
if (s.keymap != null) s.state = c.z_xkb_state_new.?(s.keymap); if (s.keymap != null) s.state = c.z_xkb_state_new.?(s.keymap);
} }
fn keyEnter(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, surface: ?*c.struct_wl_surface, keys: [*c]c.struct_wl_array) callconv(.c) void { fn keyEnter(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, surface: ?*c.struct_wl_surface, keys: [*c]c.struct_wl_array) callconv(.c) void {
leaveKeyboard(); leaveKeyboard();
const s = state(); const s = state();
s.key_focus = Popup.owner(surface) orelse find(surface); s.key_focus = Popup.owner(surface) orelse find(surface);
const suppressed = s.menu_keys; const suppressed = s.menu_keys;
s.menu_keys = @splat(false); s.menu_keys = @splat(false);
if (s.state != null and keys.*.size != 0) { if (s.state != null and keys.*.size != 0) {
@ -191,24 +224,29 @@ fn keyEnter(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, surface: ?*c.stru
} }
} }
} }
fn keyLeave(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, _: ?*c.struct_wl_surface) callconv(.c) void { fn keyLeave(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, _: ?*c.struct_wl_surface) callconv(.c) void {
leaveKeyboard(); leaveKeyboard();
} }
fn updateModifiers() void { fn updateModifiers() void {
const s = state(); const s = state();
s.modifiers = 0; s.modifiers = 0;
if (s.state == null) return; if (s.state == null) return;
const names = [_][*:0]const u8{ "Shift", "Control", "Mod1", "Mod4", "Lock", "Mod2" }; const names = [_][*:0]const u8{ "Shift", "Control", "Mod1", "Mod4", "Lock", "Mod2" };
for (names, 0..) |name, index| if (c.z_xkb_state_mod_name_is_active.?(s.state, name, c.XKB_STATE_MODS_EFFECTIVE) > 0) { for (names, 0..) |name, index| if (c.z_xkb_state_mod_name_is_active.?(s.state, name, c.XKB_STATE_MODS_EFFECTIVE) > 0) {
s.modifiers |= @as(u32, 1) << @intCast(index); s.modifiers |= @as(u32, 1) << @intCast(index);
}; };
} }
fn modifiers(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, depressed: u32, latched: u32, locked: u32, group: u32) callconv(.c) void { fn modifiers(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, depressed: u32, latched: u32, locked: u32, group: u32) callconv(.c) void {
const s = state(); const s = state();
if (s.state != null) _ = c.z_xkb_state_update_mask.?(s.state, depressed, latched, locked, 0, 0, group); if (s.state != null) _ = c.z_xkb_state_update_mask.?(s.state, depressed, latched, locked, 0, 0, group);
updateModifiers(); updateModifiers();
flushKey(); flushKey();
} }
fn key(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, serial: u32, _: u32, code: u32, pressed: u32) callconv(.c) void { fn key(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, serial: u32, _: u32, code: u32, pressed: u32) callconv(.c) void {
const s = state(); const s = state();
flushKey(); flushKey();
@ -216,9 +254,11 @@ fn key(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, serial: u32, _: u32, code: u32
provenance(serial); provenance(serial);
if (pressed != 0 and !Popup.active()) popupTrigger(s.key_focus, serial); if (pressed != 0 and !Popup.active()) popupTrigger(s.key_focus, serial);
if (code < s.held.len) s.held[code] = pressed != 0; if (code < s.held.len) s.held[code] = pressed != 0;
// The compositor supplies the authoritative modifier/group mask. Running // The compositor supplies the authoritative modifier/group mask. Running
// XKB key actions locally as well would apply latch/lock actions twice. // XKB key actions locally as well would apply latch/lock actions twice.
s.pending_key = prepareKey(code, pressed != 0, false); s.pending_key = prepareKey(code, pressed != 0, false);
// wl_keyboard has no frame event. A sync boundary lets the following // wl_keyboard has no frame event. A sync boundary lets the following
// authoritative modifiers event supply the public post-event flags even // authoritative modifiers event supply the public post-event flags even
// when the key and modifier messages arrive in separate socket reads. // when the key and modifier messages arrive in separate socket reads.
@ -226,62 +266,104 @@ fn key(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, serial: u32, _: u32, code: u32
s.key_sync = c.wl_display_sync(backend().display); s.key_sync = c.wl_display_sync(backend().display);
if (s.key_sync != null) _ = c.wl_callback_add_listener(s.key_sync, &key_sync_listener, null) else flushKey(); if (s.key_sync != null) _ = c.wl_callback_add_listener(s.key_sync, &key_sync_listener, null) else flushKey();
} }
if (pressed != 0 and s.repeat_rate > 0 and s.keymap != null and c.z_xkb_keymap_key_repeats.?(s.keymap, code + 8) != 0) { if (pressed != 0 and s.repeat_rate > 0 and s.keymap != null and c.z_xkb_keymap_key_repeats.?(s.keymap, code + 8) != 0) {
s.repeat_key = code; s.repeat_key = code;
s.repeat_at = runtime.now(backend().app.io) + @as(u64, s.repeat_delay) * std.time.ns_per_ms; s.repeat_at = runtime.now(backend().app.io) + @as(u64, s.repeat_delay) * std.time.ns_per_ms;
} else if (s.repeat_key == code) s.repeat_key = null; } else if (s.repeat_key == code) s.repeat_key = null;
} }
fn prepareKey(code: u32, down: bool, repeated: bool) Key { fn prepareKey(code: u32, down: bool, repeated: bool) Key {
const s = state(); const s = state();
var value: Key = .{ .code = code, .down = down, .repeated = repeated, .sym = if (s.state != null) c.z_xkb_state_key_get_one_sym.?(s.state, code + 8) else 0, .modifiers = s.modifiers }; var value: Key = .{
.code = code,
.down = down,
.repeated = repeated,
.sym = if (s.state != null)
c.z_xkb_state_key_get_one_sym.?(s.state, code + 8)
else
0,
.modifiers = s.modifiers,
};
if (down and s.state != null) { if (down and s.state != null) {
const length = c.z_xkb_state_key_get_utf8.?(s.state, code + 8, &value.text, value.text.len); const length = c.z_xkb_state_key_get_utf8.?(s.state, code + 8, &value.text, value.text.len);
if (length > 0 and length < value.text.len) value.len = @intCast(length); if (length > 0 and length < value.text.len) value.len = @intCast(length);
} }
return value; return value;
} }
fn deliverKey(code: u32, down: bool, repeated: bool) void { fn deliverKey(code: u32, down: bool, repeated: bool) void {
emitKey(prepareKey(code, down, repeated)); emitKey(prepareKey(code, down, repeated));
} }
fn emitKey(value: Key) void { fn emitKey(value: Key) void {
const s = state(); const s = state();
const w = s.key_focus orelse return; const w = s.key_focus orelse return;
var event = std.mem.zeroes(n.z_event); var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_KEY; event.type = n.UHDK_EVENT_KEY;
event.input_id = id(); event.input_id = id();
event.data.key = .{ .physical_key = Keyboard.physical(value.code), .logical_key = if (s.state != null) Keyboard.logical(value.sym) else 0, .modifiers = s.modifiers, .pressed = @intFromBool(value.down), .repeat = @intFromBool(value.repeated) }; event.data.key = .{
.physical_key = Keyboard.physical(value.code),
.logical_key = if (s.state != null) Keyboard.logical(value.sym) else 0,
.modifiers = s.modifiers,
.pressed = @intFromBool(value.down),
.repeat = @intFromBool(value.repeated),
};
if (value.code < s.menu_keys.len) { if (value.code < s.menu_keys.len) {
if (s.menu_keys[value.code]) { if (s.menu_keys[value.code]) {
if (!value.down) s.menu_keys[value.code] = false else if (Popup.active()) Popup.key(event.data.key.logical_key, true, s.serial); if (!value.down) s.menu_keys[value.code] = false else if (Popup.active()) Popup.key(event.data.key.logical_key, true, s.serial);
return; // Consume the release/repeats even after flags or focus change. return; // Consume the release/repeats even after flags or focus change.
} }
if (Popup.active()) { if (Popup.active()) {
s.menu_keys[value.code] = value.down; s.menu_keys[value.code] = value.down;
Popup.key(event.data.key.logical_key, value.down, s.serial); Popup.key(event.data.key.logical_key, value.down, s.serial);
return; return;
} }
if (value.down and !value.repeated and !w.text.composing and KdeAppMenu.shortcut(w, event.data.key.logical_key, value.modifiers, event.input_id)) {
if (value.down and
!value.repeated and
!w.text.composing and
KdeAppMenu.shortcut(w, event.data.key.logical_key, value.modifiers, event.input_id))
{
s.menu_keys[value.code] = true; s.menu_keys[value.code] = true;
return; return;
} }
} }
if (Popup.active()) return; if (Popup.active()) return;
send(w, &event); send(w, &event);
// Resolve symbols/text before consuming a latched modifier, while reporting // Resolve symbols/text before consuming a latched modifier, while reporting
// the compositor's post-event flags in the observational raw event. // the compositor's post-event flags in the observational raw event.
if (value.down and w.text.enabled) Text.key(w, value.sym, event.data.key.logical_key, event.input_id, value.modifiers, value.text[0..value.len]); if (value.down and w.text.enabled) {
Text.key(
w,
value.sym,
event.data.key.logical_key,
event.input_id,
value.modifiers,
value.text[0..value.len],
);
}
} }
pub fn flushKey() void { pub fn flushKey() void {
if (state().pending_key) |value| { if (state().pending_key) |value| {
state().pending_key = null; state().pending_key = null;
emitKey(value); emitKey(value);
} }
} }
fn keySynced(_: ?*anyopaque, callback: ?*c.struct_wl_callback, _: u32) callconv(.c) void { fn keySynced(_: ?*anyopaque, callback: ?*c.struct_wl_callback, _: u32) callconv(.c) void {
c.wl_callback_destroy(callback); c.wl_callback_destroy(callback);
state().key_sync = null; state().key_sync = null;
flushKey(); flushKey();
} }
const key_sync_listener: c.struct_wl_callback_listener = .{ .done = keySynced }; const key_sync_listener: c.struct_wl_callback_listener = .{ .done = keySynced };
fn repeatInfo(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, rate: i32, delay: i32) callconv(.c) void { fn repeatInfo(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, rate: i32, delay: i32) callconv(.c) void {
@ -289,17 +371,28 @@ fn repeatInfo(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, rate: i32, delay: i32)
state().repeat_delay = @intCast(@max(0, delay)); state().repeat_delay = @intCast(@max(0, delay));
if (rate <= 0) state().repeat_key = null; if (rate <= 0) state().repeat_key = null;
} }
const keyboard_listener: c.struct_wl_keyboard_listener = .{ .keymap = keymap, .enter = keyEnter, .leave = keyLeave, .key = key, .modifiers = modifiers, .repeat_info = repeatInfo };
const keyboard_listener: c.struct_wl_keyboard_listener = .{
.keymap = keymap,
.enter = keyEnter,
.leave = keyLeave,
.key = key,
.modifiers = modifiers,
.repeat_info = repeatInfo,
};
pub fn tick() i32 { pub fn tick() i32 {
const s = state(); const s = state();
const active = s.key_focus != null; const active = s.key_focus != null;
if (active != s.active) { if (active != s.active) {
s.active = active; s.active = active;
var event = std.mem.zeroes(n.z_event); var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_APP_ACTIVATION; event.type = n.UHDK_EVENT_APP_ACTIVATION;
event.data.active = @intFromBool(active); event.data.active = @intFromBool(active);
n.z_emit(runtime.toAppHandle(backend().app), &event); n.z_emit(runtime.toAppHandle(backend().app), &event);
} }
if (s.pending_key != null) return -1; if (s.pending_key != null) return -1;
if (s.repeat_key) |code| { if (s.repeat_key) |code| {
const now = runtime.now(backend().app.io); const now = runtime.now(backend().app.io);
@ -307,12 +400,16 @@ pub fn tick() i32 {
deliverKey(code, true, true); deliverKey(code, true, true);
s.repeat_at = now + std.time.ns_per_s / @max(1, s.repeat_rate); s.repeat_at = now + std.time.ns_per_s / @max(1, s.repeat_rate);
} }
return @intCast(@min(1000, (s.repeat_at -| now) / std.time.ns_per_ms + 1)); return @intCast(@min(1000, (s.repeat_at -| now) / std.time.ns_per_ms + 1));
} }
return -1; return -1;
} }
fn leaveKeyboard() void { fn leaveKeyboard() void {
flushKey(); flushKey();
const s = state(); const s = state();
s.modifiers = 0; s.modifiers = 0;
s.repeat_key = null; s.repeat_key = null;
@ -322,8 +419,10 @@ fn leaveKeyboard() void {
held.* = false; held.* = false;
if (!s.menu_keys[code]) deliverKey(@intCast(code), false, false); if (!s.menu_keys[code]) deliverKey(@intCast(code), false, false);
}; };
Text.cancel(w); Text.cancel(w);
} }
s.key_focus = null; s.key_focus = null;
// Preserve consumed held keys until the next enter supplies its held-key set. // Preserve consumed held keys until the next enter supplies its held-key set.
s.modifiers = 0; s.modifiers = 0;
@ -331,18 +430,30 @@ fn leaveKeyboard() void {
if (s.state != null) _ = c.z_xkb_state_update_mask.?(s.state, 0, 0, 0, 0, 0, 0); if (s.state != null) _ = c.z_xkb_state_update_mask.?(s.state, 0, 0, 0, 0, 0, 0);
normal(n.UHDK_CYCLE_FOCUS_LOST); normal(n.UHDK_CYCLE_FOCUS_LOST);
} }
fn pointerEvent(kind: u32, button_: u32, pressed: bool, delta: n.uhdk_point) void { fn pointerEvent(kind: u32, button_: u32, pressed: bool, delta: n.uhdk_point) void {
if (Popup.active()) return; if (Popup.active()) return;
const s = state(); const s = state();
const w = s.pointer_focus orelse return; const w = s.pointer_focus orelse return;
var e = std.mem.zeroes(n.z_event); var e = std.mem.zeroes(n.z_event);
e.type = kind; e.type = kind;
e.input_id = id(); e.input_id = id();
e.data.pointer = .{ .position = s.position, .delta = delta, .button = button_, .pressed = @intFromBool(pressed), .modifiers = s.modifiers, .click_count = if (pressed) s.click_count else 0 }; e.data.pointer = .{
.position = s.position,
.delta = delta,
.button = button_,
.pressed = @intFromBool(pressed),
.modifiers = s.modifiers,
.click_count = if (pressed) s.click_count else 0,
};
send(w, &e); send(w, &e);
} }
fn pointerEnter(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, surface: ?*c.struct_wl_surface, x: i32, y: i32) callconv(.c) void { fn pointerEnter(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, surface: ?*c.struct_wl_surface, x: i32, y: i32) callconv(.c) void {
leavePointer(); leavePointer();
const s = state(); const s = state();
s.pointer_focus = find(surface); s.pointer_focus = find(surface);
s.pointer_serial = serial; s.pointer_serial = serial;
@ -351,11 +462,14 @@ fn pointerEnter(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, surface:
pointerEvent(n.UHDK_EVENT_POINTER_ENTER, 0, false, .{ .x = 0, .y = 0 }); pointerEvent(n.UHDK_EVENT_POINTER_ENTER, 0, false, .{ .x = 0, .y = 0 });
if (s.pointer_focus) |w| _ = cursor(w, w.cursor); if (s.pointer_focus) |w| _ = cursor(w, w.cursor);
} }
fn pointerLeave(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, _: ?*c.struct_wl_surface) callconv(.c) void { fn pointerLeave(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, _: ?*c.struct_wl_surface) callconv(.c) void {
leavePointer(); leavePointer();
} }
fn leavePointer() void { fn leavePointer() void {
Popup.pointerLeave(); Popup.pointerLeave();
const s = state(); const s = state();
normal(n.UHDK_CYCLE_CAPTURE_LOST); normal(n.UHDK_CYCLE_CAPTURE_LOST);
pointerEvent(n.UHDK_EVENT_POINTER_LEAVE, 0, false, .{ .x = 0, .y = 0 }); pointerEvent(n.UHDK_EVENT_POINTER_LEAVE, 0, false, .{ .x = 0, .y = 0 });
@ -368,6 +482,7 @@ fn leavePointer() void {
s.axis_stop = false; s.axis_stop = false;
s.last_click_button = 0; s.last_click_button = 0;
} }
fn motion(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, x: i32, y: i32) callconv(.c) void { fn motion(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, x: i32, y: i32) callconv(.c) void {
const s = state(); const s = state();
const previous = s.position; const previous = s.position;
@ -376,11 +491,14 @@ fn motion(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, x: i32, y: i32) call
Popup.motion(s.position.x, s.position.y); Popup.motion(s.position.x, s.position.y);
return; return;
} }
pointerEvent(n.UHDK_EVENT_POINTER_MOVE, 0, false, .{ .x = s.position.x - previous.x, .y = s.position.y - previous.y }); pointerEvent(n.UHDK_EVENT_POINTER_MOVE, 0, false, .{ .x = s.position.x - previous.x, .y = s.position.y - previous.y });
} }
fn button(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, _: u32, code: u32, pressed: u32) callconv(.c) void { fn button(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, _: u32, code: u32, pressed: u32) callconv(.c) void {
const s = state(); const s = state();
provenance(serial); provenance(serial);
const mapped: u32 = switch (code) { const mapped: u32 = switch (code) {
0x110 => n.UHDK_BUTTON_PRIMARY, 0x110 => n.UHDK_BUTTON_PRIMARY,
0x111 => n.UHDK_BUTTON_SECONDARY, 0x111 => n.UHDK_BUTTON_SECONDARY,
@ -389,6 +507,7 @@ fn button(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, _: u32, code: u
0x114, 0x115 => n.UHDK_BUTTON_FORWARD, 0x114, 0x115 => n.UHDK_BUTTON_FORWARD,
else => 0, else => 0,
}; };
if (mapped == 0) return; if (mapped == 0) return;
const mask = @as(u32, 1) << @intCast(mapped); const mask = @as(u32, 1) << @intCast(mapped);
if (Popup.active()) { if (Popup.active()) {
@ -396,18 +515,24 @@ fn button(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, _: u32, code: u
Popup.button(code, pressed != 0, serial); Popup.button(code, pressed != 0, serial);
return; return;
} }
if (pressed == 0 and s.popup_buttons & mask != 0) { if (pressed == 0 and s.popup_buttons & mask != 0) {
s.popup_buttons &= ~mask; s.popup_buttons &= ~mask;
return; return;
} }
if (pressed != 0) popupTrigger(s.pointer_focus, serial); if (pressed != 0) popupTrigger(s.pointer_focus, serial);
if (pressed != 0) { if (pressed != 0) {
s.buttons |= mask; s.buttons |= mask;
const now = runtime.now(backend().app.io); const now = runtime.now(backend().app.io);
const dx = s.position.x - s.last_click_position.x; const dx = s.position.x - s.last_click_position.x;
const dy = s.position.y - s.last_click_position.y; const dy = s.position.y - s.last_click_position.y;
s.click_count = if (s.last_click_button == mapped and now -| s.last_click_time <= 500 * std.time.ns_per_ms and dx * dx + dy * dy <= 25) @min(3, s.click_count + 1) else 1; const repeated_click = s.last_click_button == mapped and
now -| s.last_click_time <= 500 * std.time.ns_per_ms and
dx * dx + dy * dy <= 25;
s.click_count = if (repeated_click) @min(3, s.click_count + 1) else 1;
s.last_click_time = now; s.last_click_time = now;
s.last_click_button = mapped; s.last_click_button = mapped;
s.last_click_position = s.position; s.last_click_position = s.position;
@ -415,23 +540,34 @@ fn button(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, _: u32, code: u
pointerEvent(n.UHDK_EVENT_POINTER_BUTTON, mapped, pressed != 0, .{ .x = 0, .y = 0 }); pointerEvent(n.UHDK_EVENT_POINTER_BUTTON, mapped, pressed != 0, .{ .x = 0, .y = 0 });
if (s.buttons == 0) normal(n.UHDK_CYCLE_COMPLETED); if (s.buttons == 0) normal(n.UHDK_CYCLE_COMPLETED);
} }
fn axis(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, which: u32, value: i32) callconv(.c) void { fn axis(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, which: u32, value: i32) callconv(.c) void {
const v: f32 = @as(f32, @floatFromInt(value)) / 256; const v: f32 = @as(f32, @floatFromInt(value)) / 256;
if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) state().axis.y += v else state().axis.x += v; if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) state().axis.y += v else state().axis.x += v;
} }
fn axisSource(_: ?*anyopaque, _: ?*c.struct_wl_pointer, source: u32) callconv(.c) void { fn axisSource(_: ?*anyopaque, _: ?*c.struct_wl_pointer, source: u32) callconv(.c) void {
state().axis_source = source; state().axis_source = source;
} }
fn axisStop(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, _: u32) callconv(.c) void { fn axisStop(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, _: u32) callconv(.c) void {
state().axis_stop = true; state().axis_stop = true;
} }
fn axisDiscrete(_: ?*anyopaque, _: ?*c.struct_wl_pointer, which: u32, value: i32) callconv(.c) void { fn axisDiscrete(_: ?*anyopaque, _: ?*c.struct_wl_pointer, which: u32, value: i32) callconv(.c) void {
if (c.wl_pointer_get_version(state().pointer) >= 8) return; if (c.wl_pointer_get_version(state().pointer) >= 8) return;
if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) state().wheel.y += @floatFromInt(value) else state().wheel.x += @floatFromInt(value); if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) state().wheel.y += @floatFromInt(value) else state().wheel.x += @floatFromInt(value);
} }
fn axis120(_: ?*anyopaque, _: ?*c.struct_wl_pointer, which: u32, value: i32) callconv(.c) void { fn axis120(_: ?*anyopaque, _: ?*c.struct_wl_pointer, which: u32, value: i32) callconv(.c) void {
if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) state().wheel.y += @as(f32, @floatFromInt(value)) / 120 else state().wheel.x += @as(f32, @floatFromInt(value)) / 120; const amount = @as(f32, @floatFromInt(value)) / 120;
if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) {
state().wheel.y += amount;
} else {
state().wheel.x += amount;
}
} }
fn frame(_: ?*anyopaque, _: ?*c.struct_wl_pointer) callconv(.c) void { fn frame(_: ?*anyopaque, _: ?*c.struct_wl_pointer) callconv(.c) void {
const s = state(); const s = state();
defer { defer {
@ -439,25 +575,58 @@ fn frame(_: ?*anyopaque, _: ?*c.struct_wl_pointer) callconv(.c) void {
s.wheel = .{ .x = 0, .y = 0 }; s.wheel = .{ .x = 0, .y = 0 };
s.axis_stop = false; s.axis_stop = false;
} }
if (Popup.active()) { if (Popup.active()) {
const delta = if (s.wheel.y != 0) s.wheel.y * 26 else s.axis.y; const delta = if (s.wheel.y != 0) s.wheel.y * 26 else s.axis.y;
if (delta != 0) Popup.scroll(delta); if (delta != 0) Popup.scroll(delta);
return; return;
} }
const w = s.pointer_focus orelse return; const w = s.pointer_focus orelse return;
const discrete = s.axis_source == c.WL_POINTER_AXIS_SOURCE_WHEEL or s.axis_source == c.WL_POINTER_AXIS_SOURCE_WHEEL_TILT; const discrete = s.axis_source == c.WL_POINTER_AXIS_SOURCE_WHEEL or s.axis_source == c.WL_POINTER_AXIS_SOURCE_WHEEL_TILT;
const has_wheel = s.wheel.x != 0 or s.wheel.y != 0; const has_wheel = s.wheel.x != 0 or s.wheel.y != 0;
if (s.axis.x == 0 and s.axis.y == 0 and !has_wheel and !s.axis_stop) return; if (s.axis.x == 0 and s.axis.y == 0 and !has_wheel and !s.axis_stop) return;
var e = std.mem.zeroes(n.z_event); var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_SCROLL; e.type = n.UHDK_EVENT_SCROLL;
e.input_id = id(); e.input_id = id();
e.data.scroll = .{ .position = s.position, .delta = if (has_wheel) s.wheel else s.axis, .unit = if (has_wheel) n.UHDK_SCROLL_LINES else n.UHDK_SCROLL_LOGICAL_PIXELS, .phase = if (discrete) n.UHDK_SCROLL_DISCRETE else if (s.axis_stop) n.UHDK_SCROLL_END else if (!s.scrolling) n.UHDK_SCROLL_BEGIN else n.UHDK_SCROLL_UPDATE, .modifiers = s.modifiers, .momentum = 0 }; e.data.scroll = .{
.position = s.position,
.delta = if (has_wheel) s.wheel else s.axis,
.unit = if (has_wheel) n.UHDK_SCROLL_LINES else n.UHDK_SCROLL_LOGICAL_PIXELS,
.phase = if (discrete)
n.UHDK_SCROLL_DISCRETE
else if (s.axis_stop)
n.UHDK_SCROLL_END
else if (!s.scrolling)
n.UHDK_SCROLL_BEGIN
else
n.UHDK_SCROLL_UPDATE,
.modifiers = s.modifiers,
.momentum = 0,
};
s.scrolling = !discrete and !s.axis_stop; s.scrolling = !discrete and !s.axis_stop;
send(w, &e); send(w, &e);
} }
const pointer_listener: c.struct_wl_pointer_listener = .{ .enter = pointerEnter, .leave = pointerLeave, .motion = motion, .button = button, .axis = axis, .frame = frame, .axis_source = axisSource, .axis_stop = axisStop, .axis_discrete = axisDiscrete, .axis_value120 = axis120, .axis_relative_direction = null };
const pointer_listener: c.struct_wl_pointer_listener = .{
.enter = pointerEnter,
.leave = pointerLeave,
.motion = motion,
.button = button,
.axis = axis,
.frame = frame,
.axis_source = axisSource,
.axis_stop = axisStop,
.axis_discrete = axisDiscrete,
.axis_value120 = axis120,
.axis_relative_direction = null,
};
pub fn cursor(w: *native.Window, shape: u32) u32 { pub fn cursor(w: *native.Window, shape: u32) u32 {
w.cursor = shape; w.cursor = shape;
const s = state(); const s = state();
if (shape != n.UHDK_CURSOR_HIDDEN and s.cursor_device == null) return n.UHDK_STATUS_UNSUPPORTED; if (shape != n.UHDK_CURSOR_HIDDEN and s.cursor_device == null) return n.UHDK_STATUS_UNSUPPORTED;
if (s.pointer_focus != w) return abi.OK; if (s.pointer_focus != w) return abi.OK;
@ -465,11 +634,27 @@ pub fn cursor(w: *native.Window, shape: u32) u32 {
c.wl_pointer_set_cursor(s.pointer, s.pointer_serial, null, 0, 0); c.wl_pointer_set_cursor(s.pointer, s.pointer_serial, null, 0, 0);
return abi.OK; return abi.OK;
} }
if (s.cursor_device == null) return n.UHDK_STATUS_UNSUPPORTED; if (s.cursor_device == null) return n.UHDK_STATUS_UNSUPPORTED;
const shapes = [_]u32{ c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CROSSHAIR, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_EW_RESIZE, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NS_RESIZE, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NWSE_RESIZE, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_MOVE, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_WAIT };
const shapes = [_]u32{
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CROSSHAIR,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_EW_RESIZE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NS_RESIZE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NWSE_RESIZE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_MOVE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_WAIT,
};
c.wp_cursor_shape_device_v1_set_shape(s.cursor_device, s.pointer_serial, shapes[shape]); c.wp_cursor_shape_device_v1_set_shape(s.cursor_device, s.pointer_serial, shapes[shape]);
return abi.OK; return abi.OK;
} }
pub fn capture(w: *native.Window, enabled: bool) u32 { pub fn capture(w: *native.Window, enabled: bool) u32 {
const s = state(); const s = state();
if (enabled and (s.pointer_focus != w or s.buttons == 0)) return abi.UNAVAILABLE; if (enabled and (s.pointer_focus != w or s.buttons == 0)) return abi.UNAVAILABLE;
@ -477,6 +662,7 @@ pub fn capture(w: *native.Window, enabled: bool) u32 {
normal(n.UHDK_CYCLE_CAPTURE_RELEASED); normal(n.UHDK_CYCLE_CAPTURE_RELEASED);
return abi.OK; return abi.OK;
} }
s.captured = true; s.captured = true;
var e = std.mem.zeroes(n.z_event); var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_POINTER_MODE_CHANGED; e.type = n.UHDK_EVENT_POINTER_MODE_CHANGED;
@ -484,6 +670,7 @@ pub fn capture(w: *native.Window, enabled: bool) u32 {
send(w, &e); send(w, &e);
return abi.OK; return abi.OK;
} }
fn normal(reason: n.uhdk_cycle_end_reason) void { fn normal(reason: n.uhdk_cycle_end_reason) void {
const s = state(); const s = state();
if (!s.captured) return; if (!s.captured) return;
@ -496,37 +683,44 @@ fn normal(reason: n.uhdk_cycle_end_reason) void {
send(w, &e); send(w, &e);
} }
} }
fn popupTrigger(w: ?*native.Window, serial: u32) void { fn popupTrigger(w: ?*native.Window, serial: u32) void {
const s = state(); const s = state();
s.popup_window = w; s.popup_window = w;
s.popup_serial = serial; s.popup_serial = serial;
s.popup_time = runtime.now(backend().app.io); s.popup_time = runtime.now(backend().app.io);
} }
pub fn beginPopup() void { pub fn beginPopup() void {
normal(n.UHDK_CYCLE_CAPTURE_LOST); normal(n.UHDK_CYCLE_CAPTURE_LOST);
state().buttons = 0; state().buttons = 0;
state().scrolling = false; state().scrolling = false;
} }
pub fn clearPopupTrigger(w: *native.Window) void { pub fn clearPopupTrigger(w: *native.Window) void {
if (state().popup_window == w) { if (state().popup_window == w) {
state().popup_window = null; state().popup_window = null;
state().popup_serial = 0; state().popup_serial = 0;
} }
} }
pub fn forget(w: *native.Window) void { pub fn forget(w: *native.Window) void {
clearPopupTrigger(w); clearPopupTrigger(w);
if (state().key_focus == w) leaveKeyboard(); if (state().key_focus == w) leaveKeyboard();
if (state().pointer_focus == w) leavePointer(); if (state().pointer_focus == w) leavePointer();
Text.forget(w); Text.forget(w);
} }
pub fn remove(name: u32) void { pub fn remove(name: u32) void {
if (name == state().seat_name) releaseSeat(); if (name == state().seat_name) releaseSeat();
} }
fn releaseSeat() void { fn releaseSeat() void {
Popup.deinit(); Popup.deinit();
state().popup_serial = 0; state().popup_serial = 0;
state().popup_window = null; state().popup_window = null;
Data.releaseSeat(); Data.releaseSeat();
const s = state(); const s = state();
if (s.key_sync != null) c.wl_callback_destroy(s.key_sync); if (s.key_sync != null) c.wl_callback_destroy(s.key_sync);
s.key_sync = null; s.key_sync = null;
@ -545,6 +739,7 @@ fn releaseSeat() void {
s.seat = null; s.seat = null;
setup(); setup();
} }
pub fn deinit() void { pub fn deinit() void {
const s = state(); const s = state();
releaseSeat(); releaseSeat();

View File

@ -23,6 +23,7 @@ const Node = struct {
label: [:0]const u8 = "", label: [:0]const u8 = "",
flags: u32 = 0, flags: u32 = 0,
}; };
pub const Export = struct { pub const Export = struct {
next: ?*Export = null, // Temporary transaction list, never an object registry. next: ?*Export = null, // Temporary transaction list, never an object registry.
window: *native.Window, window: *native.Window,
@ -32,18 +33,22 @@ pub const Export = struct {
path: [:0]const u8, path: [:0]const u8,
proxy: ?*c.struct_org_kde_kwin_appmenu = null, proxy: ?*c.struct_org_kde_kwin_appmenu = null,
}; };
pub const State = struct { pub const State = struct {
manager: ?*c.struct_org_kde_kwin_appmenu_manager = null, manager: ?*c.struct_org_kde_kwin_appmenu_manager = null,
global_name: u32 = 0, global_name: u32 = 0,
sequence: u64 = 0, sequence: u64 = 0,
app_menu: ?*Resource = null, app_menu: ?*Resource = null,
}; };
fn backend() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
fn menuState() *State { fn menuState() *State {
return &backend().menus; return &backend().menus;
} }
fn same(a: []const u8, z: []const u8) bool { fn same(a: []const u8, z: []const u8) bool {
return std.mem.eql(u8, a, z); return std.mem.eql(u8, a, z);
} }
@ -54,57 +59,72 @@ pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8
menuState().global_name = name; menuState().global_name = name;
ready(); ready();
} }
pub fn remove(name: u32) void { pub fn remove(name: u32) void {
if (name != menuState().global_name) return; if (name != menuState().global_name) return;
disconnected(); disconnected();
destroyManager(); destroyManager();
} }
fn destroyManager() void { fn destroyManager() void {
if (menuState().manager) |manager| { if (menuState().manager) |manager| {
if (c.org_kde_kwin_appmenu_manager_get_version(manager) >= 2) c.org_kde_kwin_appmenu_manager_release(manager) else c.org_kde_kwin_appmenu_manager_destroy(manager); if (c.org_kde_kwin_appmenu_manager_get_version(manager) >= 2) c.org_kde_kwin_appmenu_manager_release(manager) else c.org_kde_kwin_appmenu_manager_destroy(manager);
} }
menuState().manager = null; menuState().manager = null;
menuState().global_name = 0; menuState().global_name = 0;
} }
pub fn ready() void { pub fn ready() void {
native.setCapability(n.UHDK_CAP_APP_MENU, menuState().manager != null and backend().portal.ready); native.setCapability(n.UHDK_CAP_APP_MENU, menuState().manager != null and backend().portal.ready);
var cursor = backend().windows; var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| associate(e); while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| associate(e);
} }
fn associate(e: *Export) void { fn associate(e: *Export) void {
if (e.proxy != null or menuState().manager == null or !backend().portal.ready) return; if (e.proxy != null or menuState().manager == null or !backend().portal.ready) return;
// The export is already reachable by process() before advertising it. // The export is already reachable by process() before advertising it.
e.proxy = c.org_kde_kwin_appmenu_manager_create(menuState().manager, e.window.surface) orelse return; e.proxy = c.org_kde_kwin_appmenu_manager_create(menuState().manager, e.window.surface) orelse return;
c.org_kde_kwin_appmenu_set_address(e.proxy, backend().portal.unique.?.ptr, e.path.ptr); c.org_kde_kwin_appmenu_set_address(e.proxy, backend().portal.unique.?.ptr, e.path.ptr);
} }
pub fn disconnected() void { pub fn disconnected() void {
native.setCapability(n.UHDK_CAP_APP_MENU, false); native.setCapability(n.UHDK_CAP_APP_MENU, false);
var cursor = backend().windows; var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| unassociate(e); while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| unassociate(e);
} }
fn unassociate(e: *Export) void { fn unassociate(e: *Export) void {
if (e.proxy != null) c.org_kde_kwin_appmenu_release(e.proxy); if (e.proxy != null) c.org_kde_kwin_appmenu_release(e.proxy);
e.proxy = null; e.proxy = null;
} }
fn destroy(e: *Export) void { fn destroy(e: *Export) void {
unassociate(e); unassociate(e);
runtime.release(e.root); runtime.release(e.root);
e.arena.deinit(); e.arena.deinit();
backend().app.gpa.destroy(e); backend().app.gpa.destroy(e);
} }
fn add(e: *Export, menu: *Resource, parent: usize) !void { fn add(e: *Export, menu: *Resource, parent: usize) !void {
var previous: usize = 0; var previous: usize = 0;
for (menu.payload.menu.items) |*item| { for (menu.payload.menu.items) |*item| {
// Bound work and D-Bus message size even for repeatedly shared subtrees. // Bound work and D-Bus message size even for repeatedly shared subtrees.
if (e.nodes.items.len >= 65536) return error.OutOfMemory; if (e.nodes.items.len >= 65536) return error.OutOfMemory;
const index = e.nodes.items.len; const index = e.nodes.items.len;
const allocator = e.arena.allocator(); const allocator = e.arena.allocator();
// D-BusMenu uses '_' as a mnemonic marker; UHDK labels are literal text. // D-BusMenu uses '_' as a mnemonic marker; UHDK labels are literal text.
var label: std.ArrayList(u8) = .empty; var label: std.ArrayList(u8) = .empty;
for (abi.textBytes(item.label)) |byte| { for (abi.textBytes(item.label)) |byte| {
try label.append(allocator, byte); try label.append(allocator, byte);
if (byte == '_') try label.append(allocator, '_'); if (byte == '_') try label.append(allocator, '_');
} }
try label.append(allocator, 0); try label.append(allocator, 0);
try e.nodes.append(allocator, .{ .item = item, .parent = parent, .label = label.items[0 .. label.items.len - 1 :0], .flags = item.flags }); try e.nodes.append(allocator, .{ .item = item, .parent = parent, .label = label.items[0 .. label.items.len - 1 :0], .flags = item.flags });
if (previous == 0) e.nodes.items[parent].first = index else e.nodes.items[previous].next = index; if (previous == 0) e.nodes.items[parent].first = index else e.nodes.items[previous].next = index;
@ -112,6 +132,7 @@ fn add(e: *Export, menu: *Resource, parent: usize) !void {
if (item.submenu) |child| try add(e, @ptrCast(@alignCast(child)), index); if (item.submenu) |child| try add(e, @ptrCast(@alignCast(child)), index);
} }
} }
fn create(w: *native.Window, root: *Resource) !*Export { fn create(w: *native.Window, root: *Resource) !*Export {
const e = try backend().app.gpa.create(Export); const e = try backend().app.gpa.create(Export);
errdefer backend().app.gpa.destroy(e); errdefer backend().app.gpa.destroy(e);
@ -124,21 +145,25 @@ fn create(w: *native.Window, root: *Resource) !*Export {
runtime.retain(root); runtime.retain(root);
return e; return e;
} }
fn replace(w: *native.Window, e: ?*Export) void { fn replace(w: *native.Window, e: ?*Export) void {
const old = w.menu_export; const old = w.menu_export;
w.menu_export = e; w.menu_export = e;
if (old) |value| destroy(value); if (old) |value| destroy(value);
if (e) |value| associate(value); if (e) |value| associate(value);
} }
pub fn inherit(w: *native.Window) !void { pub fn inherit(w: *native.Window) !void {
if (menuState().app_menu) |root| replace(w, try create(w, root)); if (menuState().app_menu) |root| replace(w, try create(w, root));
} }
pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 { pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 {
const root: ?*Resource = if (menu) |p| @ptrCast(@alignCast(p)) else null; const root: ?*Resource = if (menu) |p| @ptrCast(@alignCast(p)) else null;
if (root != null) { if (root != null) {
if (menuState().manager == null) return n.UHDK_STATUS_UNSUPPORTED; if (menuState().manager == null) return n.UHDK_STATUS_UNSUPPORTED;
if (backend().portal.connection == null) return abi.UNAVAILABLE; if (backend().portal.connection == null) return abi.UNAVAILABLE;
} }
if (w) |window| { if (w) |window| {
const effective = root orelse menuState().app_menu; const effective = root orelse menuState().app_menu;
const e = if (effective) |r| create(window, r) catch return abi.OOM else null; const e = if (effective) |r| create(window, r) catch return abi.OOM else null;
@ -153,6 +178,7 @@ pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 {
pending = e.next; pending = e.next;
destroy(e); destroy(e);
}; };
if (root) |r| { if (root) |r| {
var cursor = backend().windows; var cursor = backend().windows;
while (cursor) |window| : (cursor = window.next) if (window.menu_override == null) { while (cursor) |window| : (cursor = window.next) if (window.menu_override == null) {
@ -160,8 +186,10 @@ pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 {
e.next = pending; e.next = pending;
pending = e; pending = e;
}; };
runtime.retain(r); runtime.retain(r);
} }
if (menuState().app_menu) |r| runtime.release(r); if (menuState().app_menu) |r| runtime.release(r);
menuState().app_menu = root; menuState().app_menu = root;
if (root == null) { if (root == null) {
@ -170,40 +198,49 @@ pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 {
replace(window, null); replace(window, null);
}; };
} }
while (pending) |e| { while (pending) |e| {
pending = e.next; pending = e.next;
e.next = null; e.next = null;
replace(e.window, e); replace(e.window, e);
} }
} }
return abi.OK; return abi.OK;
} }
pub fn forget(w: *native.Window) void { pub fn forget(w: *native.Window) void {
replace(w, null); replace(w, null);
if (w.menu_override) |root| runtime.release(root); if (w.menu_override) |root| runtime.release(root);
w.menu_override = null; w.menu_override = null;
} }
pub fn deinit() void { pub fn deinit() void {
if (menuState().app_menu) |root| runtime.release(root); if (menuState().app_menu) |root| runtime.release(root);
menuState().app_menu = null; menuState().app_menu = null;
destroyManager(); destroyManager();
} }
fn enabled(e: *Export, index: usize) bool { fn enabled(e: *Export, index: usize) bool {
var i = index; var i = index;
while (i != 0) : (i = e.nodes.items[i].parent) if (e.nodes.items[i].item.?.flags & n.UHDK_MENU_DISABLED != 0) return false; while (i != 0) : (i = e.nodes.items[i].parent) if (e.nodes.items[i].item.?.flags & n.UHDK_MENU_DISABLED != 0) return false;
return true; return true;
} }
fn activate(e: *Export, index: usize, input_id: u64) void { fn activate(e: *Export, index: usize, input_id: u64) void {
const item = e.nodes.items[index].item orelse return; const item = e.nodes.items[index].item orelse return;
if (!enabled(e, index) or item.flags & n.UHDK_MENU_SEPARATOR != 0 or item.submenu != null) return; if (!enabled(e, index) or item.flags & n.UHDK_MENU_SEPARATOR != 0 or item.submenu != null) return;
Menu.activate(e.window, item, input_id); Menu.activate(e.window, item, input_id);
} }
fn folded(key: u32) u32 { fn folded(key: u32) u32 {
return if (key >= 'A' and key <= 'Z') key + ('a' - 'A') else key; return if (key >= 'A' and key <= 'Z') key + ('a' - 'A') else key;
} }
pub fn shortcut(w: *native.Window, key: u32, mods: u32, input_id: u64) bool { pub fn shortcut(w: *native.Window, key: u32, mods: u32, input_id: u64) bool {
const e = w.menu_export orelse return false; const e = w.menu_export orelse return false;
if (key == 0) return false; if (key == 0) return false;
const mask: u32 = n.UHDK_MOD_SHIFT | n.UHDK_MOD_CONTROL | n.UHDK_MOD_ALT | n.UHDK_MOD_SUPER; const mask: u32 = n.UHDK_MOD_SHIFT | n.UHDK_MOD_CONTROL | n.UHDK_MOD_ALT | n.UHDK_MOD_SUPER;
for (e.nodes.items[1..], 1..) |node, i| { for (e.nodes.items[1..], 1..) |node, i| {
const item = node.item.?; const item = node.item.?;
@ -213,17 +250,21 @@ pub fn shortcut(w: *native.Window, key: u32, mods: u32, input_id: u64) bool {
return true; return true;
} }
} }
return false; return false;
} }
fn nodeId(e: *Export, value: i32) ?usize { fn nodeId(e: *Export, value: i32) ?usize {
return if (value >= 0 and value < e.nodes.items.len) @intCast(value) else null; return if (value >= 0 and value < e.nodes.items.len) @intCast(value) else null;
} }
fn variant(i: *Bus.Iter, comptime sig: [:0]const u8, value: anytype) !void { fn variant(i: *Bus.Iter, comptime sig: [:0]const u8, value: anytype) !void {
var v = try Bus.open(i, c.DBUS_TYPE_VARIANT, sig); var v = try Bus.open(i, c.DBUS_TYPE_VARIANT, sig);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(i, &v); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(i, &v);
try Bus.basic(&v, sig[0], value); try Bus.basic(&v, sig[0], value);
try Bus.close(i, &v); try Bus.close(i, &v);
} }
fn property(e: *Export, index: usize, name: []const u8, out: *Bus.Iter) !bool { fn property(e: *Export, index: usize, name: []const u8, out: *Bus.Iter) !bool {
const node = e.nodes.items[index]; const node = e.nodes.items[index];
const item = node.item; const item = node.item;
@ -231,8 +272,10 @@ fn property(e: *Export, index: usize, name: []const u8, out: *Bus.Iter) !bool {
if (same(name, "type")) try variant(out, "s", @as([*:0]const u8, if (flags & n.UHDK_MENU_SEPARATOR != 0) "separator" else "standard")) else if (same(name, "label")) try variant(out, "s", node.label.ptr) else if (same(name, "enabled")) try variant(out, "b", @as(u32, @intFromBool(enabled(e, index)))) else if (same(name, "visible")) try variant(out, "b", @as(u32, 1)) else if (same(name, "children-display")) try variant(out, "s", @as([*:0]const u8, if (index == 0 or (item != null and item.?.submenu != null)) "submenu" else "")) else if (same(name, "toggle-type")) try variant(out, "s", @as([*:0]const u8, if (flags & n.UHDK_MENU_CHECKED != 0) "checkmark" else "")) else if (same(name, "toggle-state")) try variant(out, "i", @as(i32, if (flags & n.UHDK_MENU_CHECKED != 0) 1 else 0)) else if (same(name, "shortcut")) { if (same(name, "type")) try variant(out, "s", @as([*:0]const u8, if (flags & n.UHDK_MENU_SEPARATOR != 0) "separator" else "standard")) else if (same(name, "label")) try variant(out, "s", node.label.ptr) else if (same(name, "enabled")) try variant(out, "b", @as(u32, @intFromBool(enabled(e, index)))) else if (same(name, "visible")) try variant(out, "b", @as(u32, 1)) else if (same(name, "children-display")) try variant(out, "s", @as([*:0]const u8, if (index == 0 or (item != null and item.?.submenu != null)) "submenu" else "")) else if (same(name, "toggle-type")) try variant(out, "s", @as([*:0]const u8, if (flags & n.UHDK_MENU_CHECKED != 0) "checkmark" else "")) else if (same(name, "toggle-state")) try variant(out, "i", @as(i32, if (flags & n.UHDK_MENU_CHECKED != 0) 1 else 0)) else if (same(name, "shortcut")) {
var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, "aas"); var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, "aas");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v);
var arrays = try Bus.open(&v, c.DBUS_TYPE_ARRAY, "as"); var arrays = try Bus.open(&v, c.DBUS_TYPE_ARRAY, "as");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&v, &arrays); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&v, &arrays);
var buffer: [32]u8 = undefined; var buffer: [32]u8 = undefined;
if (item) |value| if (Menu.keyName(value.shortcut_key, &buffer)) |key_name| { if (item) |value| if (Menu.keyName(value.shortcut_key, &buffer)) |key_name| {
var keys = try Bus.open(&arrays, c.DBUS_TYPE_ARRAY, "s"); var keys = try Bus.open(&arrays, c.DBUS_TYPE_ARRAY, "s");
@ -240,23 +283,29 @@ fn property(e: *Export, index: usize, name: []const u8, out: *Bus.Iter) !bool {
inline for (.{ .{ n.UHDK_MOD_CONTROL, "Control" }, .{ n.UHDK_MOD_ALT, "Alt" }, .{ n.UHDK_MOD_SHIFT, "Shift" }, .{ n.UHDK_MOD_SUPER, "Super" } }) |mod| { inline for (.{ .{ n.UHDK_MOD_CONTROL, "Control" }, .{ n.UHDK_MOD_ALT, "Alt" }, .{ n.UHDK_MOD_SHIFT, "Shift" }, .{ n.UHDK_MOD_SUPER, "Super" } }) |mod| {
if (value.shortcut_modifiers & mod[0] != 0) try Bus.string(&keys, mod[1]); if (value.shortcut_modifiers & mod[0] != 0) try Bus.string(&keys, mod[1]);
} }
try Bus.string(&keys, key_name.ptr); try Bus.string(&keys, key_name.ptr);
try Bus.close(&arrays, &keys); try Bus.close(&arrays, &keys);
}; };
try Bus.close(&v, &arrays); try Bus.close(&v, &arrays);
try Bus.close(out, &v); try Bus.close(out, &v);
} else return false; } else return false;
return true; return true;
} }
fn wanted(filter: ?Bus.Iter, name: []const u8) bool { fn wanted(filter: ?Bus.Iter, name: []const u8) bool {
var iter = filter orelse return true; var iter = filter orelse return true;
if (Bus.kind(&iter) == c.DBUS_TYPE_INVALID) return true; if (Bus.kind(&iter) == c.DBUS_TYPE_INVALID) return true;
while (Bus.str(&iter)) |value| { while (Bus.str(&iter)) |value| {
if (same(value, name)) return true; if (same(value, name)) return true;
if (!Bus.next(&iter)) break; if (!Bus.next(&iter)) break;
} }
return false; return false;
} }
fn props(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void { fn props(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void {
var dict = try Bus.open(out, c.DBUS_TYPE_ARRAY, "{sv}"); var dict = try Bus.open(out, c.DBUS_TYPE_ARRAY, "{sv}");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &dict); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &dict);
@ -267,13 +316,16 @@ fn props(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void {
_ = try property(e, index, name, &pair); _ = try property(e, index, name, &pair);
try Bus.close(&dict, &pair); try Bus.close(&dict, &pair);
}; };
try Bus.close(out, &dict); try Bus.close(out, &dict);
} }
fn layout(e: *Export, index: usize, depth: i32, filter: Bus.Iter, out: *Bus.Iter) Bus.Error!void { fn layout(e: *Export, index: usize, depth: i32, filter: Bus.Iter, out: *Bus.Iter) Bus.Error!void {
var tuple = try Bus.open(out, c.DBUS_TYPE_STRUCT, null); var tuple = try Bus.open(out, c.DBUS_TYPE_STRUCT, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &tuple); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &tuple);
try Bus.basic(&tuple, c.DBUS_TYPE_INT32, @as(i32, @intCast(index))); try Bus.basic(&tuple, c.DBUS_TYPE_INT32, @as(i32, @intCast(index)));
try props(e, index, filter, &tuple); try props(e, index, filter, &tuple);
var children = try Bus.open(&tuple, c.DBUS_TYPE_ARRAY, "v"); var children = try Bus.open(&tuple, c.DBUS_TYPE_ARRAY, "v");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&tuple, &children); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&tuple, &children);
if (depth != 0) { if (depth != 0) {
@ -285,9 +337,11 @@ fn layout(e: *Export, index: usize, depth: i32, filter: Bus.Iter, out: *Bus.Iter
try Bus.close(&children, &v); try Bus.close(&children, &v);
} }
} }
try Bus.close(&tuple, &children); try Bus.close(&tuple, &children);
try Bus.close(out, &tuple); try Bus.close(out, &tuple);
} }
fn groupItem(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void { fn groupItem(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void {
var tuple = try Bus.open(out, c.DBUS_TYPE_STRUCT, null); var tuple = try Bus.open(out, c.DBUS_TYPE_STRUCT, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &tuple); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &tuple);
@ -295,6 +349,7 @@ fn groupItem(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void
try props(e, index, filter, &tuple); try props(e, index, filter, &tuple);
try Bus.close(out, &tuple); try Bus.close(out, &tuple);
} }
pub fn updateFlags() u32 { pub fn updateFlags() u32 {
var cursor = backend().windows; var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| { while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| {
@ -302,34 +357,43 @@ pub fn updateFlags() u32 {
}; };
return abi.OK; return abi.OK;
} }
fn changed(e: *Export) !void { fn changed(e: *Export) !void {
var dirty = false; var dirty = false;
for (e.nodes.items[1..]) |node| if (node.flags != node.item.?.flags) { for (e.nodes.items[1..]) |node| if (node.flags != node.item.?.flags) {
dirty = true; dirty = true;
break; break;
}; };
if (!dirty) return; if (!dirty) return;
if (backend().portal.ready and e.proxy != null) { if (backend().portal.ready and e.proxy != null) {
const message = c.z_dbus_message_new_signal.?(e.path.ptr, iface, "ItemsPropertiesUpdated") orelse return error.OutOfMemory; const message = c.z_dbus_message_new_signal.?(e.path.ptr, iface, "ItemsPropertiesUpdated") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(message); defer c.z_dbus_message_unref.?(message);
var out = Bus.append(message); var out = Bus.append(message);
var updates = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ia{sv})"); var updates = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ia{sv})");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &updates); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &updates);
// Include descendants: a disabled ancestor also disables their activation. // Include descendants: a disabled ancestor also disables their activation.
for (e.nodes.items[1..], 1..) |_, i| try groupItem(e, i, null, &updates); for (e.nodes.items[1..], 1..) |_, i| try groupItem(e, i, null, &updates);
try Bus.close(&out, &updates); try Bus.close(&out, &updates);
var removed = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ias)"); var removed = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ias)");
try Bus.close(&out, &removed); try Bus.close(&out, &removed);
_ = try Portal.send(message); _ = try Portal.send(message);
} }
for (e.nodes.items[1..]) |*node| node.flags = node.item.?.flags; for (e.nodes.items[1..]) |*node| node.flags = node.item.?.flags;
} }
fn fail(message: *Bus.Message, name: [*:0]const u8) !void { fn fail(message: *Bus.Message, name: [*:0]const u8) !void {
if (c.z_dbus_message_get_no_reply.?(message) != 0) return; if (c.z_dbus_message_get_no_reply.?(message) != 0) return;
const reply = c.z_dbus_message_new_error.?(message, name, "Menu request could not be handled") orelse return error.OutOfMemory; const reply = c.z_dbus_message_new_error.?(message, name, "Menu request could not be handled") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(reply); defer c.z_dbus_message_unref.?(reply);
_ = try Portal.send(reply); _ = try Portal.send(reply);
} }
const invalid = "org.freedesktop.DBus.Error.InvalidArgs"; const invalid = "org.freedesktop.DBus.Error.InvalidArgs";
const missing = "com.canonical.dbusmenu.Error.InvalidMenuItem"; const missing = "com.canonical.dbusmenu.Error.InvalidMenuItem";
fn callIs(message: *Bus.Message, interface: []const u8, member: []const u8) bool { fn callIs(message: *Bus.Message, interface: []const u8, member: []const u8) bool {
@ -337,23 +401,29 @@ fn callIs(message: *Bus.Message, interface: []const u8, member: []const u8) bool
const z = c.z_dbus_message_get_member.?(message); const z = c.z_dbus_message_get_member.?(message);
return a != null and z != null and same(std.mem.span(a), interface) and same(std.mem.span(z), member); return a != null and z != null and same(std.mem.span(a), interface) and same(std.mem.span(z), member);
} }
fn signature(message: *Bus.Message, sig: [*:0]const u8) bool { fn signature(message: *Bus.Message, sig: [*:0]const u8) bool {
return c.z_dbus_message_has_signature.?(message, sig) != 0; return c.z_dbus_message_has_signature.?(message, sig) != 0;
} }
fn globalProperty(name: []const u8, out: *Bus.Iter) !bool { fn globalProperty(name: []const u8, out: *Bus.Iter) !bool {
if (same(name, "Version")) try variant(out, "u", @as(u32, 3)) else if (same(name, "TextDirection")) try variant(out, "s", @as([*:0]const u8, "ltr")) else if (same(name, "Status")) try variant(out, "s", @as([*:0]const u8, "normal")) else if (same(name, "IconThemePath")) { if (same(name, "Version")) try variant(out, "u", @as(u32, 3)) else if (same(name, "TextDirection")) try variant(out, "s", @as([*:0]const u8, "ltr")) else if (same(name, "Status")) try variant(out, "s", @as([*:0]const u8, "normal")) else if (same(name, "IconThemePath")) {
var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, "as"); var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, "as");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v);
var paths = try Bus.open(&v, c.DBUS_TYPE_ARRAY, "s"); var paths = try Bus.open(&v, c.DBUS_TYPE_ARRAY, "s");
try Bus.close(&v, &paths); try Bus.close(&v, &paths);
try Bus.close(out, &v); try Bus.close(out, &v);
} else return false; } else return false;
return true; return true;
} }
pub fn process(message: *Bus.Message) !bool { pub fn process(message: *Bus.Message) !bool {
if (c.z_dbus_message_get_type.?(message) != c.DBUS_MESSAGE_TYPE_METHOD_CALL) return false; if (c.z_dbus_message_get_type.?(message) != c.DBUS_MESSAGE_TYPE_METHOD_CALL) return false;
const path = c.z_dbus_message_get_path.?(message); const path = c.z_dbus_message_get_path.?(message);
if (path == null or !std.mem.startsWith(u8, std.mem.span(path), prefix)) return false; if (path == null or !std.mem.startsWith(u8, std.mem.span(path), prefix)) return false;
var found: ?*Export = null; var found: ?*Export = null;
var cursor = backend().windows; var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| { while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| {
@ -362,16 +432,20 @@ pub fn process(message: *Bus.Message) !bool {
break; break;
} }
}; };
if (found) |e| try dispatch(e, message) else try fail(message, "org.freedesktop.DBus.Error.UnknownObject"); if (found) |e| try dispatch(e, message) else try fail(message, "org.freedesktop.DBus.Error.UnknownObject");
return true; return true;
} }
fn dispatch(e: *Export, message: *Bus.Message) !void { fn dispatch(e: *Export, message: *Bus.Message) !void {
const reply = c.z_dbus_message_new_method_return.?(message) orelse return error.OutOfMemory; const reply = c.z_dbus_message_new_method_return.?(message) orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(reply); defer c.z_dbus_message_unref.?(reply);
var out = Bus.append(reply); var out = Bus.append(reply);
var args = Bus.parse(message); var args = Bus.parse(message);
if (callIs(message, "org.freedesktop.DBus.Introspectable", "Introspect")) { if (callIs(message, "org.freedesktop.DBus.Introspectable", "Introspect")) {
if (!signature(message, "")) return fail(message, invalid); if (!signature(message, "")) return fail(message, invalid);
try Bus.string(&out, @embedFile("dbusmenu.xml")); try Bus.string(&out, @embedFile("dbusmenu.xml"));
} else if (callIs(message, "org.freedesktop.DBus.Peer", "Ping")) { } else if (callIs(message, "org.freedesktop.DBus.Peer", "Ping")) {
if (!signature(message, "")) return fail(message, invalid); if (!signature(message, "")) return fail(message, invalid);
@ -392,21 +466,27 @@ fn dispatch(e: *Export, message: *Bus.Message) !void {
_ = try globalProperty(name, &pair); _ = try globalProperty(name, &pair);
try Bus.close(&dict, &pair); try Bus.close(&dict, &pair);
} }
try Bus.close(&out, &dict); try Bus.close(&out, &dict);
} }
} else if (callIs(message, iface, "GetLayout")) { } else if (callIs(message, iface, "GetLayout")) {
if (!signature(message, "iias")) return fail(message, invalid); if (!signature(message, "iias")) return fail(message, invalid);
const index = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing); const index = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing);
_ = Bus.next(&args); _ = Bus.next(&args);
const depth = Bus.int(&args).?; const depth = Bus.int(&args).?;
if (depth < -1) return fail(message, invalid); if (depth < -1) return fail(message, invalid);
_ = Bus.next(&args); _ = Bus.next(&args);
try Bus.basic(&out, c.DBUS_TYPE_UINT32, @as(u32, 1)); try Bus.basic(&out, c.DBUS_TYPE_UINT32, @as(u32, 1));
try layout(e, index, depth, Bus.child(&args), &out); try layout(e, index, depth, Bus.child(&args), &out);
} else if (callIs(message, iface, "GetGroupProperties")) { } else if (callIs(message, iface, "GetGroupProperties")) {
if (!signature(message, "aias")) return fail(message, invalid); if (!signature(message, "aias")) return fail(message, invalid);
var ids = Bus.child(&args); var ids = Bus.child(&args);
_ = Bus.next(&args); _ = Bus.next(&args);
const filter = Bus.child(&args); const filter = Bus.child(&args);
var items = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ia{sv})"); var items = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ia{sv})");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &items); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &items);
@ -416,31 +496,38 @@ fn dispatch(e: *Export, message: *Bus.Message) !void {
if (nodeId(e, value)) |i| try groupItem(e, i, filter, &items); if (nodeId(e, value)) |i| try groupItem(e, i, filter, &items);
if (!Bus.next(&ids)) break; if (!Bus.next(&ids)) break;
} }
try Bus.close(&out, &items); try Bus.close(&out, &items);
} else if (callIs(message, iface, "GetProperty")) { } else if (callIs(message, iface, "GetProperty")) {
if (!signature(message, "is")) return fail(message, invalid); if (!signature(message, "is")) return fail(message, invalid);
const index = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing); const index = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing);
_ = Bus.next(&args); _ = Bus.next(&args);
if (!try property(e, index, Bus.str(&args).?, &out)) return fail(message, "org.freedesktop.DBus.Error.UnknownProperty"); if (!try property(e, index, Bus.str(&args).?, &out)) return fail(message, "org.freedesktop.DBus.Error.UnknownProperty");
} else if (callIs(message, iface, "Event")) { } else if (callIs(message, iface, "Event")) {
if (!signature(message, "isvu")) return fail(message, invalid); if (!signature(message, "isvu")) return fail(message, invalid);
const index = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing); const index = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing);
_ = Bus.next(&args); _ = Bus.next(&args);
if (same(Bus.str(&args).?, "clicked")) activate(e, index, Input.id()); if (same(Bus.str(&args).?, "clicked")) activate(e, index, Input.id());
} else if (callIs(message, iface, "AboutToShow")) { } else if (callIs(message, iface, "AboutToShow")) {
if (!signature(message, "i")) return fail(message, invalid); if (!signature(message, "i")) return fail(message, invalid);
_ = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing); _ = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing);
try Bus.basic(&out, c.DBUS_TYPE_BOOLEAN, @as(u32, 0)); try Bus.basic(&out, c.DBUS_TYPE_BOOLEAN, @as(u32, 0));
} else if (callIs(message, iface, "EventGroup") or callIs(message, iface, "AboutToShowGroup")) { } else if (callIs(message, iface, "EventGroup") or callIs(message, iface, "AboutToShowGroup")) {
const events = callIs(message, iface, "EventGroup"); const events = callIs(message, iface, "EventGroup");
if (!signature(message, if (events) "a(isvu)" else "ai")) return fail(message, invalid); if (!signature(message, if (events) "a(isvu)" else "ai")) return fail(message, invalid);
var ids = Bus.child(&args); var ids = Bus.child(&args);
if (!events) { if (!events) {
var empty = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "i"); var empty = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "i");
try Bus.close(&out, &empty); try Bus.close(&out, &empty);
} }
var errors = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "i"); var errors = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "i");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &errors); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &errors);
var valid_count: usize = 0; var valid_count: usize = 0;
var error_count: usize = 0; var error_count: usize = 0;
while (Bus.kind(&ids) != c.DBUS_TYPE_INVALID) { while (Bus.kind(&ids) != c.DBUS_TYPE_INVALID) {
@ -456,8 +543,10 @@ fn dispatch(e: *Export, message: *Bus.Message) !void {
error_count += 1; error_count += 1;
try Bus.basic(&errors, c.DBUS_TYPE_INT32, number); try Bus.basic(&errors, c.DBUS_TYPE_INT32, number);
} }
if (!Bus.next(&ids)) break; if (!Bus.next(&ids)) break;
} }
try Bus.close(&out, &errors); try Bus.close(&out, &errors);
if (valid_count == 0 and error_count != 0) return fail(message, missing); if (valid_count == 0 and error_count != 0) return fail(message, missing);
} else return fail(message, "org.freedesktop.DBus.Error.UnknownMethod"); } else return fail(message, "org.freedesktop.DBus.Error.UnknownMethod");

View File

@ -16,6 +16,7 @@ pub fn physical(code: u32) u32 {
.{ 102, 74 }, .{ 103, 82 }, .{ 104, 75 }, .{ 105, 80 }, .{ 106, 79 }, .{ 107, 77 }, .{ 108, 81 }, .{ 109, 78 }, .{ 110, 73 }, .{ 102, 74 }, .{ 103, 82 }, .{ 104, 75 }, .{ 105, 80 }, .{ 106, 79 }, .{ 107, 77 }, .{ 108, 81 }, .{ 109, 78 }, .{ 110, 73 },
.{ 111, 76 }, .{ 119, 72 }, .{ 125, 227 }, .{ 126, 231 }, .{ 127, 101 }, .{ 111, 76 }, .{ 119, 72 }, .{ 125, 227 }, .{ 126, 231 }, .{ 127, 101 },
}; };
for (pairs) |p| t[p[0]] = p[1]; for (pairs) |p| t[p[0]] = p[1];
for (0..10) |i| t[2 + i] = 30 + i; for (0..10) |i| t[2 + i] = 30 + i;
for (0..10) |i| t[59 + i] = 58 + i; for (0..10) |i| t[59 + i] = 58 + i;
@ -27,6 +28,7 @@ pub fn physical(code: u32) u32 {
}; };
return if (code < map.len) map[code] else 0; return if (code < map.len) map[code] else 0;
} }
pub fn logical(sym: u32) u32 { pub fn logical(sym: u32) u32 {
return switch (sym) { return switch (sym) {
c.XKB_KEY_Escape => n.UHDK_KEY_ESCAPE, c.XKB_KEY_Escape => n.UHDK_KEY_ESCAPE,
@ -47,6 +49,7 @@ pub fn logical(sym: u32) u32 {
else => c.z_xkb_keysym_to_utf32.?(sym), else => c.z_xkb_keysym_to_utf32.?(sym),
}; };
} }
pub fn edit(key: u32, mods: u32) u32 { pub fn edit(key: u32, mods: u32) u32 {
return n.z_edit_key(key, mods); return n.z_edit_key(key, mods);
} }

View File

@ -18,8 +18,10 @@ pub fn activate(window: *native.Window, item: *const n.uhdk_menu_item, input_id:
Input.send(window, &event); Input.send(window, &event);
} }
} }
pub fn keyName(key: u32, buffer: *[32]u8) ?[:0]const u8 { pub fn keyName(key: u32, buffer: *[32]u8) ?[:0]const u8 {
if (key >= n.UHDK_KEY_F1 and key < n.UHDK_KEY_F1 + 24) return std.fmt.bufPrintZ(buffer, "F{d}", .{key - n.UHDK_KEY_F1 + 1}) catch unreachable; if (key >= n.UHDK_KEY_F1 and key < n.UHDK_KEY_F1 + 24) return std.fmt.bufPrintZ(buffer, "F{d}", .{key - n.UHDK_KEY_F1 + 1}) catch unreachable;
switch (key) { switch (key) {
n.UHDK_KEY_ESCAPE => return "Escape", n.UHDK_KEY_ESCAPE => return "Escape",
n.UHDK_KEY_ENTER => return "Return", n.UHDK_KEY_ENTER => return "Return",
@ -38,7 +40,9 @@ pub fn keyName(key: u32, buffer: *[32]u8) ?[:0]const u8 {
' ' => return "space", ' ' => return "space",
else => {}, else => {},
} }
if (key < 0x21 or key > 0x10ffff) return null; if (key < 0x21 or key > 0x10ffff) return null;
const k = if (key >= 'a' and key <= 'z') key - ('a' - 'A') else key; const k = if (key >= 'a' and key <= 'z') key - ('a' - 'A') else key;
const len = std.unicode.utf8Encode(@intCast(k), buffer) catch return null; const len = std.unicode.utf8Encode(@intCast(k), buffer) catch return null;
buffer[len] = 0; buffer[len] = 0;
@ -55,6 +59,7 @@ pub fn shortcut(item: n.uhdk_menu_item, buffer: *[96]u8) []const u8 {
end += mod[1].len; end += mod[1].len;
} }
} }
@memcpy(buffer[end..][0..key.len], key); @memcpy(buffer[end..][0..key.len], key);
end += key.len; end += key.len;
return buffer[0..end]; return buffer[0..end];

View File

@ -16,6 +16,7 @@ const Buffer = struct {
size: usize = 0, size: usize = 0,
busy: bool = false, busy: bool = false,
}; };
const Panel = struct { const Panel = struct {
parent: ?*Panel, parent: ?*Panel,
menu: *Resource, menu: *Resource,
@ -36,6 +37,7 @@ const Panel = struct {
dirty: bool = true, dirty: bool = true,
deadline: u64 = 0, deadline: u64 = 0,
}; };
pub const State = struct { pub const State = struct {
window: ?*native.Window = null, window: ?*native.Window = null,
root: ?*Resource = null, root: ?*Resource = null,
@ -45,45 +47,57 @@ pub const State = struct {
serial: u32 = 0, serial: u32 = 0,
hover_at: u64 = 0, hover_at: u64 = 0,
}; };
fn backend() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
fn popupState() *State { fn popupState() *State {
return &backend().popup; return &backend().popup;
} }
pub fn active() bool { pub fn active() bool {
return popupState().request != 0; return popupState().request != 0;
} }
pub fn capability() void { pub fn capability() void {
native.setCapability(n.UHDK_CAP_CONTEXT_MENU, backend().desktop.shm != null and Input.state().seat != null); native.setCapability(n.UHDK_CAP_CONTEXT_MENU, backend().desktop.shm != null and Input.state().seat != null);
} }
fn panel(raw: ?*anyopaque) *Panel { fn panel(raw: ?*anyopaque) *Panel {
return @ptrCast(@alignCast(raw.?)); return @ptrCast(@alignCast(raw.?));
} }
fn rowHeight(item: n.uhdk_menu_item) i32 { fn rowHeight(item: n.uhdk_menu_item) i32 {
return if (item.flags & n.UHDK_MENU_SEPARATOR != 0) 9 else 26; return if (item.flags & n.UHDK_MENU_SEPARATOR != 0) 9 else 26;
} }
fn usable(item: n.uhdk_menu_item) bool { fn usable(item: n.uhdk_menu_item) bool {
return item.flags & (n.UHDK_MENU_DISABLED | n.UHDK_MENU_SEPARATOR) == 0; return item.flags & (n.UHDK_MENU_DISABLED | n.UHDK_MENU_SEPARATOR) == 0;
} }
fn rowY(p: *Panel, index: usize) i32 { fn rowY(p: *Panel, index: usize) i32 {
var y: i32 = 4; var y: i32 = 4;
for (p.menu.payload.menu.items[0..index]) |item| y += rowHeight(item); for (p.menu.payload.menu.items[0..index]) |item| y += rowHeight(item);
return y - p.scroll; return y - p.scroll;
} }
fn lookup(surface: ?*c.struct_wl_surface) ?*Panel { fn lookup(surface: ?*c.struct_wl_surface) ?*Panel {
var cursor = popupState().top; var cursor = popupState().top;
while (cursor) |p| : (cursor = p.parent) if (p.surface == surface) return p; while (cursor) |p| : (cursor = p.parent) if (p.surface == surface) return p;
return null; return null;
} }
pub fn owner(surface: ?*c.struct_wl_surface) ?*native.Window { pub fn owner(surface: ?*c.struct_wl_surface) ?*native.Window {
return if (lookup(surface) != null) popupState().window else null; return if (lookup(surface) != null) popupState().window else null;
} }
fn freeBuffer(buf: *Buffer) void { fn freeBuffer(buf: *Buffer) void {
if (buf.proxy != null) c.wl_buffer_destroy(buf.proxy); if (buf.proxy != null) c.wl_buffer_destroy(buf.proxy);
if (buf.mapping) |mapping| _ = c.munmap(mapping, buf.size); if (buf.mapping) |mapping| _ = c.munmap(mapping, buf.size);
buf.* = .{}; buf.* = .{};
} }
fn destroy(p: *Panel) void { fn destroy(p: *Panel) void {
if (popupState().pointer == p) popupState().pointer = null; if (popupState().pointer == p) popupState().pointer = null;
if (p.popup != null) c.xdg_popup_destroy(p.popup); if (p.popup != null) c.xdg_popup_destroy(p.popup);
@ -92,6 +106,7 @@ fn destroy(p: *Panel) void {
for (&p.buffers) |*buf| freeBuffer(buf); for (&p.buffers) |*buf| freeBuffer(buf);
backend().app.gpa.destroy(p); backend().app.gpa.destroy(p);
} }
fn closeChildren(p: *Panel) void { fn closeChildren(p: *Panel) void {
while (popupState().top != p) { while (popupState().top != p) {
const top = popupState().top orelse return; const top = popupState().top orelse return;
@ -99,53 +114,67 @@ fn closeChildren(p: *Panel) void {
destroy(top); destroy(top);
} }
} }
fn finish(status: u32) void { fn finish(status: u32) void {
if (!active()) return; if (!active()) return;
const request_id = popupState().request; const request_id = popupState().request;
while (popupState().top) |top| { while (popupState().top) |top| {
popupState().top = top.parent; popupState().top = top.parent;
destroy(top); destroy(top);
} }
const root = popupState().root.?; const root = popupState().root.?;
popupState().* = .{}; popupState().* = .{};
runtime.release(root); runtime.release(root);
n.z_complete(runtime.toAppHandle(backend().app), request_id, status, null); n.z_complete(runtime.toAppHandle(backend().app), request_id, status, null);
} }
pub fn forget(w: *native.Window) void { pub fn forget(w: *native.Window) void {
if (popupState().window == w) finish(abi.CANCELLED); if (popupState().window == w) finish(abi.CANCELLED);
} }
pub fn cancel(id: u64) bool { pub fn cancel(id: u64) bool {
if (popupState().request != id or !active()) return false; if (popupState().request != id or !active()) return false;
finish(abi.CANCELLED); finish(abi.CANCELLED);
return true; return true;
} }
pub fn deinit() void { pub fn deinit() void {
finish(abi.CANCELLED); finish(abi.CANCELLED);
} }
pub fn request(cmd: *const n.z_command, id: u64) u32 { pub fn request(cmd: *const n.z_command, id: u64) u32 {
if (active()) return n.UHDK_STATUS_BUSY; if (active()) return n.UHDK_STATUS_BUSY;
if (backend().desktop.shm == null or Input.state().seat == null) return n.UHDK_STATUS_UNSUPPORTED; if (backend().desktop.shm == null or Input.state().seat == null) return n.UHDK_STATUS_UNSUPPORTED;
const w: *native.Window = @ptrCast(@alignCast(n.z_object_native(cmd.other) orelse return abi.UNAVAILABLE)); const w: *native.Window = @ptrCast(@alignCast(n.z_object_native(cmd.other) orelse return abi.UNAVAILABLE));
const input = Input.state(); const input = Input.state();
if (!w.visible or !w.configured or input.popup_window != w or input.popup_serial == 0 or runtime.now(backend().app.io) -| input.popup_time > 5 * std.time.ns_per_s) return abi.UNAVAILABLE; if (!w.visible or !w.configured or input.popup_window != w or input.popup_serial == 0 or runtime.now(backend().app.io) -| input.popup_time > 5 * std.time.ns_per_s) return abi.UNAVAILABLE;
const root: *Resource = @ptrCast(@alignCast(cmd.target.?)); const root: *Resource = @ptrCast(@alignCast(cmd.target.?));
if (root.payload.menu.items.len == 0) return abi.CANCELLED; if (root.payload.menu.items.len == 0) return abi.CANCELLED;
popupState().window = w; popupState().window = w;
popupState().root = root; popupState().root = root;
popupState().serial = input.popup_serial; popupState().serial = input.popup_serial;
runtime.retain(root); runtime.retain(root);
const point: n.uhdk_point = .{ .x = std.math.clamp(cmd.point.x, 0, @as(f32, @floatFromInt(@max(0, w.width - 1)))), .y = std.math.clamp(cmd.point.y, 0, @as(f32, @floatFromInt(@max(0, w.height - 1)))) }; const point: n.uhdk_point = .{ .x = std.math.clamp(cmd.point.x, 0, @as(f32, @floatFromInt(@max(0, w.width - 1)))), .y = std.math.clamp(cmd.point.y, 0, @as(f32, @floatFromInt(@max(0, w.height - 1)))) };
const p = create(root, null, @intFromFloat(point.x), @intFromFloat(point.y), 1) catch { const p = create(root, null, @intFromFloat(point.x), @intFromFloat(point.y), 1) catch {
runtime.release(root); runtime.release(root);
popupState().* = .{}; popupState().* = .{};
return abi.OOM; return abi.OOM;
}; };
popupState().top = p; popupState().top = p;
popupState().request = id; popupState().request = id;
Input.beginPopup(); Input.beginPopup();
input.popup_serial = 0; // A root grab consumes its triggering action. input.popup_serial = 0; // A root grab consumes its triggering action.
return n.Z_DEFERRED; return n.Z_DEFERRED;
} }
fn create(menu: *Resource, parent: ?*Panel, x: i32, y: i32, anchor_height: i32) !*Panel { fn create(menu: *Resource, parent: ?*Panel, x: i32, y: i32, anchor_height: i32) !*Panel {
const p = try backend().app.gpa.create(Panel); const p = try backend().app.gpa.create(Panel);
p.* = .{ .parent = parent, .menu = menu, .scale = @intCast(std.math.clamp((popupState().window.?.scale + 119) / 120, 1, 4)), .deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s }; p.* = .{ .parent = parent, .menu = menu, .scale = @intCast(std.math.clamp((popupState().window.?.scale + 119) / 120, 1, 4)), .deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s };
@ -155,14 +184,17 @@ fn create(menu: *Resource, parent: ?*Panel, x: i32, y: i32, anchor_height: i32)
p.width = @max(p.width, 60 + Bitmap.width(abi.textBytes(item.label)) + Bitmap.width(Menu.shortcut(item, &buffer))); p.width = @max(p.width, 60 + Bitmap.width(abi.textBytes(item.label)) + Bitmap.width(Menu.shortcut(item, &buffer)));
p.total += rowHeight(item); p.total += rowHeight(item);
} }
p.width = @min(p.width, 480); p.width = @min(p.width, 480);
p.height = @min(p.total, 480); p.height = @min(p.total, 480);
p.pending_width = p.width; p.pending_width = p.width;
p.pending_height = p.height; p.pending_height = p.height;
p.surface = c.wl_compositor_create_surface(backend().compositor) orelse return error.OutOfMemory; p.surface = c.wl_compositor_create_surface(backend().compositor) orelse return error.OutOfMemory;
if (c.wl_surface_add_listener(p.surface, &surface_listener, p) != 0) return error.OutOfMemory; if (c.wl_surface_add_listener(p.surface, &surface_listener, p) != 0) return error.OutOfMemory;
p.xdg = c.xdg_wm_base_get_xdg_surface(backend().shell, p.surface) orelse return error.OutOfMemory; p.xdg = c.xdg_wm_base_get_xdg_surface(backend().shell, p.surface) orelse return error.OutOfMemory;
if (c.xdg_surface_add_listener(p.xdg, &xdg_listener, p) != 0) return error.OutOfMemory; if (c.xdg_surface_add_listener(p.xdg, &xdg_listener, p) != 0) return error.OutOfMemory;
const pos = c.xdg_wm_base_create_positioner(backend().shell) orelse return error.OutOfMemory; const pos = c.xdg_wm_base_create_positioner(backend().shell) orelse return error.OutOfMemory;
defer c.xdg_positioner_destroy(pos); defer c.xdg_positioner_destroy(pos);
c.xdg_positioner_set_size(pos, p.width, p.height); c.xdg_positioner_set_size(pos, p.width, p.height);
@ -172,16 +204,19 @@ fn create(menu: *Resource, parent: ?*Panel, x: i32, y: i32, anchor_height: i32)
c.xdg_positioner_set_constraint_adjustment(pos, c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_X | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_X | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_Y | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_X | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_Y); c.xdg_positioner_set_constraint_adjustment(pos, c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_X | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_X | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_Y | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_X | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_Y);
p.popup = c.xdg_surface_get_popup(p.xdg, if (parent) |v| v.xdg else popupState().window.?.xdg, pos) orelse return error.OutOfMemory; p.popup = c.xdg_surface_get_popup(p.xdg, if (parent) |v| v.xdg else popupState().window.?.xdg, pos) orelse return error.OutOfMemory;
if (c.xdg_popup_add_listener(p.popup, &popup_listener, p) != 0) return error.OutOfMemory; if (c.xdg_popup_add_listener(p.popup, &popup_listener, p) != 0) return error.OutOfMemory;
c.xdg_popup_grab(p.popup, Input.state().seat, popupState().serial); c.xdg_popup_grab(p.popup, Input.state().seat, popupState().serial);
c.wl_surface_commit(p.surface); c.wl_surface_commit(p.surface);
return p; return p;
} }
fn configure(raw: ?*anyopaque, _: ?*c.struct_xdg_popup, _: i32, _: i32, width: i32, height: i32) callconv(.c) void { fn configure(raw: ?*anyopaque, _: ?*c.struct_xdg_popup, _: i32, _: i32, width: i32, height: i32) callconv(.c) void {
const p = panel(raw); const p = panel(raw);
if (width < 1 or height < 1 or width > 1024 or height > 1024) { if (width < 1 or height < 1 or width > 1024 or height > 1024) {
finish(n.UHDK_STATUS_OS_ERROR); finish(n.UHDK_STATUS_OS_ERROR);
return; return;
} }
// Geometry belongs to the next xdg_surface.configure, which can arrive in // Geometry belongs to the next xdg_surface.configure, which can arrive in
// another socket read. Do not render/commit it before acknowledging that. // another socket read. Do not render/commit it before acknowledging that.
p.pending_width = width; p.pending_width = width;
@ -189,6 +224,7 @@ fn configure(raw: ?*anyopaque, _: ?*c.struct_xdg_popup, _: i32, _: i32, width: i
p.configured = false; p.configured = false;
p.deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s; p.deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s;
} }
fn configured(raw: ?*anyopaque, _: ?*c.struct_xdg_surface, serial: u32) callconv(.c) void { fn configured(raw: ?*anyopaque, _: ?*c.struct_xdg_surface, serial: u32) callconv(.c) void {
const p = panel(raw); const p = panel(raw);
c.xdg_surface_ack_configure(p.xdg, serial); c.xdg_surface_ack_configure(p.xdg, serial);
@ -198,11 +234,13 @@ fn configured(raw: ?*anyopaque, _: ?*c.struct_xdg_surface, serial: u32) callconv
p.height = p.pending_height; p.height = p.pending_height;
p.scroll = std.math.clamp(p.scroll, 0, @max(0, p.total - p.height)); p.scroll = std.math.clamp(p.scroll, 0, @max(0, p.total - p.height));
} }
p.configured = true; p.configured = true;
p.deadline = 0; p.deadline = 0;
p.dirty = true; p.dirty = true;
render(p) catch finish(abi.OOM); render(p) catch finish(abi.OOM);
} }
fn done(raw: ?*anyopaque, _: ?*c.struct_xdg_popup) callconv(.c) void { fn done(raw: ?*anyopaque, _: ?*c.struct_xdg_popup) callconv(.c) void {
const p = panel(raw); const p = panel(raw);
if (p.parent) |parent| { if (p.parent) |parent| {
@ -210,10 +248,12 @@ fn done(raw: ?*anyopaque, _: ?*c.struct_xdg_popup) callconv(.c) void {
popupState().hover_at = 0; popupState().hover_at = 0;
} else finish(abi.CANCELLED); } else finish(abi.CANCELLED);
} }
fn repositioned(_: ?*anyopaque, _: ?*c.struct_xdg_popup, _: u32) callconv(.c) void {} fn repositioned(_: ?*anyopaque, _: ?*c.struct_xdg_popup, _: u32) callconv(.c) void {}
const popup_listener: c.struct_xdg_popup_listener = .{ .configure = configure, .popup_done = done, .repositioned = repositioned }; const popup_listener: c.struct_xdg_popup_listener = .{ .configure = configure, .popup_done = done, .repositioned = repositioned };
const xdg_listener: c.struct_xdg_surface_listener = .{ .configure = configured }; const xdg_listener: c.struct_xdg_surface_listener = .{ .configure = configured };
fn enter(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: ?*c.struct_wl_output) callconv(.c) void {} fn enter(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: ?*c.struct_wl_output) callconv(.c) void {}
fn scale(raw: ?*anyopaque, _: ?*c.struct_wl_surface, value: i32) callconv(.c) void { fn scale(raw: ?*anyopaque, _: ?*c.struct_wl_surface, value: i32) callconv(.c) void {
const p = panel(raw); const p = panel(raw);
const next = std.math.clamp(value, 1, 4); const next = std.math.clamp(value, 1, 4);
@ -222,6 +262,7 @@ fn scale(raw: ?*anyopaque, _: ?*c.struct_wl_surface, value: i32) callconv(.c) vo
for (&p.buffers) |*buf| freeBuffer(buf); for (&p.buffers) |*buf| freeBuffer(buf);
p.dirty = true; p.dirty = true;
} }
fn transform(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: u32) callconv(.c) void {} fn transform(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: u32) callconv(.c) void {}
const surface_listener: c.struct_wl_surface_listener = .{ .enter = enter, .leave = enter, .preferred_buffer_scale = scale, .preferred_buffer_transform = transform }; const surface_listener: c.struct_wl_surface_listener = .{ .enter = enter, .leave = enter, .preferred_buffer_scale = scale, .preferred_buffer_transform = transform };
fn released(raw: ?*anyopaque, proxy: ?*c.struct_wl_buffer) callconv(.c) void { fn released(raw: ?*anyopaque, proxy: ?*c.struct_wl_buffer) callconv(.c) void {
@ -230,6 +271,7 @@ fn released(raw: ?*anyopaque, proxy: ?*c.struct_wl_buffer) callconv(.c) void {
buf.busy = false; buf.busy = false;
}; };
} }
const buffer_listener: c.struct_wl_buffer_listener = .{ .release = released }; const buffer_listener: c.struct_wl_buffer_listener = .{ .release = released };
fn allocateBuffer(p: *Panel, buf: *Buffer) !void { fn allocateBuffer(p: *Panel, buf: *Buffer) !void {
const size: usize = @intCast(p.width * p.height * p.scale * p.scale * 4); const size: usize = @intCast(p.width * p.height * p.scale * p.scale * 4);
@ -237,22 +279,28 @@ fn allocateBuffer(p: *Panel, buf: *Buffer) !void {
if (fd < 0) return error.OutOfMemory; if (fd < 0) return error.OutOfMemory;
defer _ = c.close(fd); defer _ = c.close(fd);
if (c.ftruncate(fd, @intCast(size)) != 0) return error.OutOfMemory; if (c.ftruncate(fd, @intCast(size)) != 0) return error.OutOfMemory;
const mapping = c.mmap(null, size, c.PROT_READ | c.PROT_WRITE, c.MAP_SHARED, fd, 0); const mapping = c.mmap(null, size, c.PROT_READ | c.PROT_WRITE, c.MAP_SHARED, fd, 0);
if (mapping == c.MAP_FAILED) return error.OutOfMemory; if (mapping == c.MAP_FAILED) return error.OutOfMemory;
buf.mapping = mapping; buf.mapping = mapping;
buf.size = size; buf.size = size;
errdefer freeBuffer(buf); errdefer freeBuffer(buf);
const pool = c.wl_shm_create_pool(backend().desktop.shm, fd, @intCast(size)) orelse return error.OutOfMemory; const pool = c.wl_shm_create_pool(backend().desktop.shm, fd, @intCast(size)) orelse return error.OutOfMemory;
defer c.wl_shm_pool_destroy(pool); defer c.wl_shm_pool_destroy(pool);
buf.proxy = c.wl_shm_pool_create_buffer(pool, 0, p.width * p.scale, p.height * p.scale, p.width * p.scale * 4, c.WL_SHM_FORMAT_ARGB8888) orelse return error.OutOfMemory; buf.proxy = c.wl_shm_pool_create_buffer(pool, 0, p.width * p.scale, p.height * p.scale, p.width * p.scale * 4, c.WL_SHM_FORMAT_ARGB8888) orelse return error.OutOfMemory;
if (c.wl_buffer_add_listener(buf.proxy, &buffer_listener, p) != 0) return error.OutOfMemory; if (c.wl_buffer_add_listener(buf.proxy, &buffer_listener, p) != 0) return error.OutOfMemory;
} }
fn render(p: *Panel) !void { fn render(p: *Panel) !void {
if (!p.configured or !p.dirty) return; if (!p.configured or !p.dirty) return;
const buf: *Buffer = for (&p.buffers) |*value| { const buf: *Buffer = for (&p.buffers) |*value| {
if (!value.busy) break value; if (!value.busy) break value;
} else return; } else return;
if (buf.proxy == null) try allocateBuffer(p, buf); if (buf.proxy == null) try allocateBuffer(p, buf);
const words: [*]u32 = @ptrCast(@alignCast(buf.mapping.?)); const words: [*]u32 = @ptrCast(@alignCast(buf.mapping.?));
const canvas: Bitmap.Canvas = .{ .pixels = words[0 .. buf.size / 4], .width = p.width, .height = p.height, .scale = p.scale }; const canvas: Bitmap.Canvas = .{ .pixels = words[0 .. buf.size / 4], .width = p.width, .height = p.height, .scale = p.scale };
paint(canvas, p.menu.payload.menu.items, p.selected, p.scroll, backend().portal.preferences.appearance == n.UHDK_APPEARANCE_LIGHT); paint(canvas, p.menu.payload.menu.items, p.selected, p.scroll, backend().portal.preferences.appearance == n.UHDK_APPEARANCE_LIGHT);
@ -264,11 +312,13 @@ fn render(p: *Panel) !void {
buf.busy = true; buf.busy = true;
p.dirty = false; p.dirty = false;
} }
pub fn paint(canvas: Bitmap.Canvas, items: []const n.uhdk_menu_item, selected: ?usize, scroll_offset: i32, light: bool) void { pub fn paint(canvas: Bitmap.Canvas, items: []const n.uhdk_menu_item, selected: ?usize, scroll_offset: i32, light: bool) void {
const background: u32 = if (light) 0xf6f6f6 else 0x292c30; const background: u32 = if (light) 0xf6f6f6 else 0x292c30;
const foreground: u32 = if (light) 0x202124 else 0xf1f2f3; const foreground: u32 = if (light) 0x202124 else 0xf1f2f3;
const border: u32 = if (light) 0xc4c7ca else 0x53585e; const border: u32 = if (light) 0xc4c7ca else 0x53585e;
canvas.rect(0, 0, canvas.width, canvas.height, background); canvas.rect(0, 0, canvas.width, canvas.height, background);
var y: i32 = 4 - scroll_offset; var y: i32 = 4 - scroll_offset;
for (items, 0..) |item, i| { for (items, 0..) |item, i| {
const height = rowHeight(item); const height = rowHeight(item);
@ -278,12 +328,14 @@ pub fn paint(canvas: Bitmap.Canvas, items: []const n.uhdk_menu_item, selected: ?
canvas.rect(8, y + 4, canvas.width - 16, 1, border); canvas.rect(8, y + 4, canvas.width - 16, 1, border);
continue; continue;
} }
const color: u32 = if (item.flags & n.UHDK_MENU_DISABLED != 0) (if (light) @as(u32, 0x85888c) else 0x8d939a) else if (selected == i) 0xffffff else foreground; const color: u32 = if (item.flags & n.UHDK_MENU_DISABLED != 0) (if (light) @as(u32, 0x85888c) else 0x8d939a) else if (selected == i) 0xffffff else foreground;
if (selected == i and usable(item)) canvas.rect(3, y, canvas.width - 6, height, 0x2969b0); if (selected == i and usable(item)) canvas.rect(3, y, canvas.width - 6, height, 0x2969b0);
if (item.flags & n.UHDK_MENU_CHECKED != 0) { if (item.flags & n.UHDK_MENU_CHECKED != 0) {
for (0..4) |j| canvas.rect(10 + @as(i32, @intCast(j)), y + 12 + @as(i32, @intCast(j)), 2, 2, color); for (0..4) |j| canvas.rect(10 + @as(i32, @intCast(j)), y + 12 + @as(i32, @intCast(j)), 2, 2, color);
for (0..7) |j| canvas.rect(13 + @as(i32, @intCast(j)), y + 15 - @as(i32, @intCast(j)), 2, 2, color); for (0..7) |j| canvas.rect(13 + @as(i32, @intCast(j)), y + 15 - @as(i32, @intCast(j)), 2, 2, color);
} }
var storage: [96]u8 = undefined; var storage: [96]u8 = undefined;
const shortcut = Menu.shortcut(item, &storage); const shortcut = Menu.shortcut(item, &storage);
const shortcut_width = @min(Bitmap.width(shortcut), @max(0, @divTrunc(canvas.width, 2) - 30)); const shortcut_width = @min(Bitmap.width(shortcut), @max(0, @divTrunc(canvas.width, 2) - 30));
@ -295,6 +347,7 @@ pub fn paint(canvas: Bitmap.Canvas, items: []const n.uhdk_menu_item, selected: ?
canvas.rect(canvas.width - 13 + offset, y + 8 + offset, 1, 9 - 2 * offset, color); canvas.rect(canvas.width - 13 + offset, y + 8 + offset, 1, 9 - 2 * offset, color);
}; };
} }
// Padding masks partially scrolled rows and keeps the border intact. // Padding masks partially scrolled rows and keeps the border intact.
canvas.rect(0, 0, canvas.width, 4, background); canvas.rect(0, 0, canvas.width, 4, background);
canvas.rect(0, canvas.height - 4, canvas.width, 4, background); canvas.rect(0, canvas.height - 4, canvas.width, 4, background);
@ -305,6 +358,7 @@ pub fn paint(canvas: Bitmap.Canvas, items: []const n.uhdk_menu_item, selected: ?
if (scroll_offset > 0) canvas.rect(@divTrunc(canvas.width, 2) - 5, 1, 10, 2, foreground); if (scroll_offset > 0) canvas.rect(@divTrunc(canvas.width, 2) - 5, 1, 10, 2, foreground);
if (y > canvas.height - 4) canvas.rect(@divTrunc(canvas.width, 2) - 5, canvas.height - 3, 10, 2, foreground); if (y > canvas.height - 4) canvas.rect(@divTrunc(canvas.width, 2) - 5, canvas.height - 3, 10, 2, foreground);
} }
fn choose(p: *Panel, index: ?usize) void { fn choose(p: *Panel, index: ?usize) void {
if (p.selected == index) return; if (p.selected == index) return;
closeChildren(p); closeChildren(p);
@ -313,55 +367,72 @@ fn choose(p: *Panel, index: ?usize) void {
p.dirty = true; p.dirty = true;
popupState().hover_at = if (index != null and p.menu.payload.menu.items[index.?].submenu != null) runtime.now(backend().app.io) + 200 * std.time.ns_per_ms else 0; popupState().hover_at = if (index != null and p.menu.payload.menu.items[index.?].submenu != null) runtime.now(backend().app.io) + 200 * std.time.ns_per_ms else 0;
} }
fn hit(p: *Panel, x: f32, y: f32) ?usize { fn hit(p: *Panel, x: f32, y: f32) ?usize {
if (x < 3 or x >= @as(f32, @floatFromInt(p.width - 3)) or y < 4 or y >= @as(f32, @floatFromInt(p.height - 4))) return null; if (x < 3 or x >= @as(f32, @floatFromInt(p.width - 3)) or y < 4 or y >= @as(f32, @floatFromInt(p.height - 4))) return null;
var top: i32 = 4 - p.scroll; var top: i32 = 4 - p.scroll;
for (p.menu.payload.menu.items, 0..) |item, i| { for (p.menu.payload.menu.items, 0..) |item, i| {
const bottom = top + rowHeight(item); const bottom = top + rowHeight(item);
if (y >= @as(f32, @floatFromInt(top)) and y < @as(f32, @floatFromInt(bottom))) return if (usable(item)) i else null; if (y >= @as(f32, @floatFromInt(top)) and y < @as(f32, @floatFromInt(bottom))) return if (usable(item)) i else null;
top = bottom; top = bottom;
} }
return null; return null;
} }
pub fn pointerEnter(surface: ?*c.struct_wl_surface, x: f32, y: f32, serial: u32) bool { pub fn pointerEnter(surface: ?*c.struct_wl_surface, x: f32, y: f32, serial: u32) bool {
popupState().pointer = lookup(surface); popupState().pointer = lookup(surface);
const p = popupState().pointer orelse return false; const p = popupState().pointer orelse return false;
const input = Input.state(); const input = Input.state();
if (input.cursor_device != null) c.wp_cursor_shape_device_v1_set_shape(input.cursor_device, serial, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT); if (input.cursor_device != null) c.wp_cursor_shape_device_v1_set_shape(input.cursor_device, serial, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT);
choose(p, hit(p, x, y)); choose(p, hit(p, x, y));
return true; return true;
} }
pub fn pointerLeave() void { pub fn pointerLeave() void {
popupState().pointer = null; popupState().pointer = null;
popupState().hover_at = 0; popupState().hover_at = 0;
} }
pub fn motion(x: f32, y: f32) void { pub fn motion(x: f32, y: f32) void {
if (popupState().pointer) |p| choose(p, hit(p, x, y)); if (popupState().pointer) |p| choose(p, hit(p, x, y));
} }
pub fn button(code: u32, down: bool, serial: u32) void { pub fn button(code: u32, down: bool, serial: u32) void {
if (down) popupState().serial = serial; if (down) popupState().serial = serial;
const p = popupState().pointer orelse { const p = popupState().pointer orelse {
if (down) finish(abi.CANCELLED); if (down) finish(abi.CANCELLED);
return; return;
}; };
if (code != 0x110) return; if (code != 0x110) return;
if (down) p.pressed = p.selected else if (p.pressed != null and p.pressed == p.selected) select(p); if (down) p.pressed = p.selected else if (p.pressed != null and p.pressed == p.selected) select(p);
} }
fn openChild(p: *Panel) void { fn openChild(p: *Panel) void {
popupState().hover_at = 0; popupState().hover_at = 0;
const index = p.selected orelse return; const index = p.selected orelse return;
const item = p.menu.payload.menu.items[index]; const item = p.menu.payload.menu.items[index];
if (!usable(item) or item.submenu == null) return; if (!usable(item) or item.submenu == null) return;
closeChildren(p); closeChildren(p);
const menu: *Resource = @ptrCast(@alignCast(item.submenu.?)); const menu: *Resource = @ptrCast(@alignCast(item.submenu.?));
if (menu.payload.menu.items.len == 0) return; if (menu.payload.menu.items.len == 0) return;
const y = std.math.clamp(rowY(p, index), 0, p.height - 1); const y = std.math.clamp(rowY(p, index), 0, p.height - 1);
const child = create(menu, p, p.width - 1, y, @min(26, p.height - y)) catch { const child = create(menu, p, p.width - 1, y, @min(26, p.height - y)) catch {
finish(abi.OOM); finish(abi.OOM);
return; return;
}; };
popupState().top = child; popupState().top = child;
} }
fn select(p: *Panel) void { fn select(p: *Panel) void {
const index = p.selected orelse return; const index = p.selected orelse return;
const item = &p.menu.payload.menu.items[index]; const item = &p.menu.payload.menu.items[index];
@ -370,9 +441,11 @@ fn select(p: *Panel) void {
openChild(p); openChild(p);
return; return;
} }
Menu.activate(popupState().window.?, item, Input.id()); Menu.activate(popupState().window.?, item, Input.id());
finish(abi.OK); // Command event must precede request completion. finish(abi.OK); // Command event must precede request completion.
} }
fn reveal(p: *Panel) void { fn reveal(p: *Panel) void {
const index = p.selected orelse return; const index = p.selected orelse return;
const y = rowY(p, index); const y = rowY(p, index);
@ -381,9 +454,11 @@ fn reveal(p: *Panel) void {
p.scroll = std.math.clamp(p.scroll, 0, @max(0, p.total - p.height)); p.scroll = std.math.clamp(p.scroll, 0, @max(0, p.total - p.height));
p.dirty = true; p.dirty = true;
} }
fn move(p: *Panel, forward: bool) void { fn move(p: *Panel, forward: bool) void {
const items = p.menu.payload.menu.items; const items = p.menu.payload.menu.items;
if (items.len == 0) return; if (items.len == 0) return;
var index = p.selected orelse (if (forward) items.len - 1 else 0); var index = p.selected orelse (if (forward) items.len - 1 else 0);
for (0..items.len) |_| { for (0..items.len) |_| {
index = if (forward) (index + 1) % items.len else (index + items.len - 1) % items.len; index = if (forward) (index + 1) % items.len else (index + items.len - 1) % items.len;
@ -395,8 +470,10 @@ fn move(p: *Panel, forward: bool) void {
} }
} }
} }
pub fn key(logical: u32, down: bool, serial: u32) void { pub fn key(logical: u32, down: bool, serial: u32) void {
if (!down) return; if (!down) return;
const p = popupState().top orelse return; const p = popupState().top orelse return;
popupState().serial = serial; popupState().serial = serial;
switch (logical) { switch (logical) {
@ -423,6 +500,7 @@ pub fn key(logical: u32, down: bool, serial: u32) void {
else => {}, else => {},
} }
} }
pub fn scroll(delta: f32) void { pub fn scroll(delta: f32) void {
const p = popupState().pointer orelse return; const p = popupState().pointer orelse return;
closeChildren(p); closeChildren(p);
@ -432,6 +510,7 @@ pub fn scroll(delta: f32) void {
p.dirty = true; p.dirty = true;
popupState().hover_at = 0; popupState().hover_at = 0;
} }
pub fn flags() void { pub fn flags() void {
var cursor = popupState().top; var cursor = popupState().top;
while (cursor) |p| : (cursor = p.parent) { while (cursor) |p| : (cursor = p.parent) {
@ -443,13 +522,16 @@ pub fn flags() void {
}; };
} }
} }
pub fn tick() i32 { pub fn tick() i32 {
if (!active()) return -1; if (!active()) return -1;
const now = runtime.now(backend().app.io); const now = runtime.now(backend().app.io);
if (popupState().hover_at != 0 and now >= popupState().hover_at) { if (popupState().hover_at != 0 and now >= popupState().hover_at) {
if (popupState().pointer) |p| openChild(p); if (popupState().pointer) |p| openChild(p);
popupState().hover_at = 0; popupState().hover_at = 0;
} }
var cursor = popupState().top; var cursor = popupState().top;
var timeout: i32 = if (popupState().hover_at != 0) 25 else -1; var timeout: i32 = if (popupState().hover_at != 0) 25 else -1;
while (cursor) |p| : (cursor = p.parent) { while (cursor) |p| : (cursor = p.parent) {
@ -458,12 +540,15 @@ pub fn tick() i32 {
finish(abi.UNAVAILABLE); finish(abi.UNAVAILABLE);
return -1; return -1;
} }
timeout = 100; timeout = 100;
} }
render(p) catch { render(p) catch {
finish(abi.OOM); finish(abi.OOM);
return -1; return -1;
}; };
} }
return timeout; return timeout;
} }

View File

@ -29,6 +29,7 @@ const Pending = struct {
activation: ?*c.struct_xdg_activation_token_v1 = null, activation: ?*c.struct_xdg_activation_token_v1 = null,
deadline: u64, deadline: u64,
}; };
pub const State = struct { pub const State = struct {
connection: ?*c.DBusConnection = null, connection: ?*c.DBusConnection = null,
unique: ?[:0]u8 = null, unique: ?[:0]u8 = null,
@ -44,22 +45,28 @@ pub const State = struct {
exporter: ?*c.struct_zxdg_exporter_v2 = null, exporter: ?*c.struct_zxdg_exporter_v2 = null,
preferences: n.uhdk_preferences = .{ .struct_size = @sizeOf(n.uhdk_preferences), .appearance = n.UHDK_APPEARANCE_UNKNOWN, .reduced_motion = 0, .high_contrast = 0 }, preferences: n.uhdk_preferences = .{ .struct_size = @sizeOf(n.uhdk_preferences), .appearance = n.UHDK_APPEARANCE_UNKNOWN, .reduced_motion = 0, .high_contrast = 0 },
}; };
fn backend() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
fn portalState() *State { fn portalState() *State {
return &backend().portal; return &backend().portal;
} }
pub fn send(message: *Bus.Message) !u32 { pub fn send(message: *Bus.Message) !u32 {
var serial: u32 = 0; var serial: u32 = 0;
if (c.z_dbus_connection_send.?(portalState().connection, message, &serial) == 0) return error.OutOfMemory; if (c.z_dbus_connection_send.?(portalState().connection, message, &serial) == 0) return error.OutOfMemory;
return serial; return serial;
} }
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void { pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void {
if (std.mem.eql(u8, interface, "zxdg_exporter_v2")) portalState().exporter = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_zxdg_exporter_v2_interface, 1)); if (std.mem.eql(u8, interface, "zxdg_exporter_v2")) portalState().exporter = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_zxdg_exporter_v2_interface, 1));
} }
pub fn initialize() void { pub fn initialize() void {
if (c.z_linux_dbus_available() == 0 or c.z_dbus_threads_init_default.?() == 0) return; if (c.z_linux_dbus_available() == 0 or c.z_dbus_threads_init_default.?() == 0) return;
// Avoid libdbus autolaunch/process spawning. Desktop sessions provide this // Avoid libdbus autolaunch/process spawning. Desktop sessions provide this
// address; absence disables portals without affecting windows or input. // address; absence disables portals without affecting windows or input.
const address = c.getenv("DBUS_SESSION_BUS_ADDRESS"); const address = c.getenv("DBUS_SESSION_BUS_ADDRESS");
@ -67,6 +74,7 @@ pub fn initialize() void {
portalState().connection = c.z_dbus_connection_open_private.?(address, null) orelse return; portalState().connection = c.z_dbus_connection_open_private.?(address, null) orelse return;
c.z_dbus_connection_set_exit_on_disconnect.?(portalState().connection, 0); c.z_dbus_connection_set_exit_on_disconnect.?(portalState().connection, 0);
portalState().startup_deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s; portalState().startup_deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s;
const message = Bus.method(dbus, dbus_path, dbus, "Hello") catch { const message = Bus.method(dbus, dbus_path, dbus, "Hello") catch {
disconnect(); disconnect();
return; return;
@ -77,48 +85,58 @@ pub fn initialize() void {
return; return;
}; };
} }
fn addMatches() !void { fn addMatches() !void {
const rules = [_][*:0]const u8{ const rules = [_][*:0]const u8{
"type='signal',sender='org.freedesktop.portal.Desktop',interface='org.freedesktop.portal.Request',member='Response'", "type='signal',sender='org.freedesktop.portal.Desktop',interface='org.freedesktop.portal.Request',member='Response'",
"type='signal',sender='org.freedesktop.portal.Desktop',interface='org.freedesktop.portal.Settings',member='SettingChanged',path='/org/freedesktop/portal/desktop'", "type='signal',sender='org.freedesktop.portal.Desktop',interface='org.freedesktop.portal.Settings',member='SettingChanged',path='/org/freedesktop/portal/desktop'",
"type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.portal.Desktop'", "type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.portal.Desktop'",
}; };
for (rules, 0..) |rule, i| { for (rules, 0..) |rule, i| {
const message = try Bus.method(dbus, dbus_path, dbus, "AddMatch"); const message = try Bus.method(dbus, dbus_path, dbus, "AddMatch");
defer c.z_dbus_message_unref.?(message); defer c.z_dbus_message_unref.?(message);
var args = Bus.append(message); var args = Bus.append(message);
try Bus.string(&args, rule); try Bus.string(&args, rule);
portalState().matches[i] = try send(message); portalState().matches[i] = try send(message);
} }
} }
fn discover() !void { fn discover() !void {
const version = try Bus.method(desktop, path, "org.freedesktop.DBus.Properties", "Get"); const version = try Bus.method(desktop, path, "org.freedesktop.DBus.Properties", "Get");
defer c.z_dbus_message_unref.?(version); defer c.z_dbus_message_unref.?(version);
var args = Bus.append(version); var args = Bus.append(version);
try Bus.string(&args, chooser); try Bus.string(&args, chooser);
try Bus.string(&args, "version"); try Bus.string(&args, "version");
portalState().version_serial = try send(version); portalState().version_serial = try send(version);
const read = try Bus.method(desktop, path, settings, "ReadAll"); const read = try Bus.method(desktop, path, settings, "ReadAll");
defer c.z_dbus_message_unref.?(read); defer c.z_dbus_message_unref.?(read);
args = Bus.append(read); args = Bus.append(read);
var namespaces = try Bus.open(&args, c.DBUS_TYPE_ARRAY, "s"); var namespaces = try Bus.open(&args, c.DBUS_TYPE_ARRAY, "s");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&args, &namespaces); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&args, &namespaces);
try Bus.string(&namespaces, "org.freedesktop.appearance"); try Bus.string(&namespaces, "org.freedesktop.appearance");
try Bus.close(&args, &namespaces); try Bus.close(&args, &namespaces);
portalState().settings_serial = try send(read); portalState().settings_serial = try send(read);
} }
pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void { pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
const connection = portalState().connection orelse return; const connection = portalState().connection orelse return;
var fd: c_int = -1; var fd: c_int = -1;
if (c.z_dbus_connection_get_unix_fd.?(connection, &fd) != 0) if (c.z_dbus_connection_get_unix_fd.?(connection, &fd) != 0)
try fds.append(backend().app.gpa, .{ .fd = fd, .events = @as(c_short, c.POLLIN) | @as(c_short, if (c.z_dbus_connection_has_messages_to_send.?(connection) != 0) c.POLLOUT else 0), .revents = 0 }); try fds.append(backend().app.gpa, .{ .fd = fd, .events = @as(c_short, c.POLLIN) | @as(c_short, if (c.z_dbus_connection_has_messages_to_send.?(connection) != 0) c.POLLOUT else 0), .revents = 0 });
} }
pub fn tick() i32 { pub fn tick() i32 {
const connection = portalState().connection orelse return -1; const connection = portalState().connection orelse return -1;
if (c.z_dbus_connection_read_write.?(connection, 0) == 0) { if (c.z_dbus_connection_read_write.?(connection, 0) == 0) {
disconnect(); disconnect();
return -1; return -1;
} }
// Bound dispatch work so an active bus cannot starve Wayland or app commands. // Bound dispatch work so an active bus cannot starve Wayland or app commands.
for (0..64) |_| { for (0..64) |_| {
const message = c.z_dbus_connection_pop_message.?(connection) orelse break; const message = c.z_dbus_connection_pop_message.?(connection) orelse break;
@ -127,13 +145,16 @@ pub fn tick() i32 {
disconnect(); disconnect();
return -1; return -1;
}; };
if (portalState().connection == null) return -1; if (portalState().connection == null) return -1;
} else return 0; } else return 0;
const now = runtime.now(backend().app.io); const now = runtime.now(backend().app.io);
if (!portalState().ready and now >= portalState().startup_deadline) { if (!portalState().ready and now >= portalState().startup_deadline) {
disconnect(); disconnect();
return -1; return -1;
} }
var cursor = portalState().pending; var cursor = portalState().pending;
while (cursor) |pending| { while (cursor) |pending| {
cursor = pending.next; cursor = pending.next;
@ -143,16 +164,20 @@ pub fn tick() i32 {
destroy(pending); destroy(pending);
} }
} }
return if (portalState().pending != null or !portalState().ready) 100 else -1; return if (portalState().pending != null or !portalState().ready) 100 else -1;
} }
fn setOwner(message: *Bus.Message) !void { fn setOwner(message: *Bus.Message) !void {
const sender = c.z_dbus_message_get_sender.?(message); const sender = c.z_dbus_message_get_sender.?(message);
if (sender == null) return; if (sender == null) return;
if (portalState().owner) |old| backend().app.gpa.free(old); if (portalState().owner) |old| backend().app.gpa.free(old);
portalState().owner = try backend().app.gpa.dupeZ(u8, std.mem.span(sender)); portalState().owner = try backend().app.gpa.dupeZ(u8, std.mem.span(sender));
} }
fn process(message: *Bus.Message) !void { fn process(message: *Bus.Message) !void {
if (try KdeAppMenu.process(message)) return; if (try KdeAppMenu.process(message)) return;
const serial = c.z_dbus_message_get_reply_serial.?(message); const serial = c.z_dbus_message_get_reply_serial.?(message);
const failed = c.z_dbus_message_get_type.?(message) == c.DBUS_MESSAGE_TYPE_ERROR; const failed = c.z_dbus_message_get_type.?(message) == c.DBUS_MESSAGE_TYPE_ERROR;
var args = Bus.parse(message); var args = Bus.parse(message);
@ -162,23 +187,28 @@ fn process(message: *Bus.Message) !void {
disconnect(); disconnect();
return; return;
} }
portalState().unique = try backend().app.gpa.dupeZ(u8, Bus.str(&args).?); portalState().unique = try backend().app.gpa.dupeZ(u8, Bus.str(&args).?);
try addMatches(); try addMatches();
return; return;
} }
for (&portalState().matches) |*match| if (serial != 0 and serial == match.*) { for (&portalState().matches) |*match| if (serial != 0 and serial == match.*) {
if (failed) { if (failed) {
disconnect(); disconnect();
return; return;
} }
match.* = 0; match.* = 0;
if (std.mem.allEqual(u32, &portalState().matches, 0)) { if (std.mem.allEqual(u32, &portalState().matches, 0)) {
portalState().ready = true; portalState().ready = true;
KdeAppMenu.ready(); KdeAppMenu.ready();
try discover(); try discover();
} }
return; return;
}; };
if (serial != 0 and serial == portalState().version_serial) { if (serial != 0 and serial == portalState().version_serial) {
portalState().version_serial = 0; portalState().version_serial = 0;
if (!failed) { if (!failed) {
@ -187,12 +217,15 @@ fn process(message: *Bus.Message) !void {
try setOwner(message); try setOwner(message);
native.setCapability(n.UHDK_CAP_FILE_DIALOGS, portalState().chooser_version >= 3); native.setCapability(n.UHDK_CAP_FILE_DIALOGS, portalState().chooser_version >= 3);
} }
return; return;
} }
if (serial != 0 and serial == portalState().settings_serial) { if (serial != 0 and serial == portalState().settings_serial) {
portalState().settings_serial = 0; portalState().settings_serial = 0;
if (!failed and c.z_dbus_message_has_signature.?(message, "a{sa{sv}}") != 0) { if (!failed and c.z_dbus_message_has_signature.?(message, "a{sa{sv}}") != 0) {
try setOwner(message); try setOwner(message);
var appearance = Bus.entry(&args, "org.freedesktop.appearance") orelse return; var appearance = Bus.entry(&args, "org.freedesktop.appearance") orelse return;
inline for (.{ "color-scheme", "contrast", "reduced-motion" }) |key| { inline for (.{ "color-scheme", "contrast", "reduced-motion" }) |key| {
if (Bus.entry(&appearance, key)) |raw| { if (Bus.entry(&appearance, key)) |raw| {
@ -204,21 +237,26 @@ fn process(message: *Bus.Message) !void {
} }
} }
} }
return; return;
} }
if (c.z_dbus_message_is_signal.?(message, dbus, "NameOwnerChanged") != 0 and c.z_dbus_message_has_signature.?(message, "sss") != 0) { if (c.z_dbus_message_is_signal.?(message, dbus, "NameOwnerChanged") != 0 and c.z_dbus_message_has_signature.?(message, "sss") != 0) {
const sender = c.z_dbus_message_get_sender.?(message); const sender = c.z_dbus_message_get_sender.?(message);
if (sender == null or !std.mem.eql(u8, std.mem.span(sender), dbus)) return; if (sender == null or !std.mem.eql(u8, std.mem.span(sender), dbus)) return;
if (!std.mem.eql(u8, Bus.str(&args).?, desktop)) return; if (!std.mem.eql(u8, Bus.str(&args).?, desktop)) return;
_ = Bus.next(&args); _ = Bus.next(&args);
const old = Bus.str(&args).?; const old = Bus.str(&args).?;
_ = Bus.next(&args); _ = Bus.next(&args);
const new = Bus.str(&args).?; const new = Bus.str(&args).?;
if (old.len != 0) { if (old.len != 0) {
while (portalState().pending) |p| { while (portalState().pending) |p| {
complete(p, abi.UNAVAILABLE, null); complete(p, abi.UNAVAILABLE, null);
destroy(p); destroy(p);
} }
portalState().chooser_version = 0; portalState().chooser_version = 0;
native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false); native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false);
if (portalState().owner) |owner| backend().app.gpa.free(owner); if (portalState().owner) |owner| backend().app.gpa.free(owner);
@ -227,13 +265,16 @@ fn process(message: *Bus.Message) !void {
preference("contrast", 0); preference("contrast", 0);
preference("reduced-motion", 0); preference("reduced-motion", 0);
} }
if (new.len != 0) { if (new.len != 0) {
if (portalState().owner) |owner| backend().app.gpa.free(owner); if (portalState().owner) |owner| backend().app.gpa.free(owner);
portalState().owner = try backend().app.gpa.dupeZ(u8, new); portalState().owner = try backend().app.gpa.dupeZ(u8, new);
try discover(); try discover();
} }
return; return;
} }
var cursor = portalState().pending; var cursor = portalState().pending;
while (cursor) |pending| : (cursor = pending.next) { while (cursor) |pending| : (cursor = pending.next) {
if (serial != 0 and serial == pending.serial) { if (serial != 0 and serial == pending.serial) {
@ -243,11 +284,13 @@ fn process(message: *Bus.Message) !void {
destroy(pending); destroy(pending);
return; return;
} }
if (c.z_dbus_message_has_signature.?(message, "o") == 0) { if (c.z_dbus_message_has_signature.?(message, "o") == 0) {
complete(pending, n.UHDK_STATUS_OS_ERROR, null); complete(pending, n.UHDK_STATUS_OS_ERROR, null);
destroy(pending); destroy(pending);
return; return;
} }
const handle = try backend().app.gpa.dupeZ(u8, Bus.str(&args).?); const handle = try backend().app.gpa.dupeZ(u8, Bus.str(&args).?);
backend().app.gpa.free(pending.handle); backend().app.gpa.free(pending.handle);
pending.handle = handle; pending.handle = handle;
@ -258,6 +301,7 @@ fn process(message: *Bus.Message) !void {
return; return;
} }
} }
// Match rules are installed on the bus, and sender validation also protects // Match rules are installed on the bus, and sender validation also protects
// against unrelated unicast signals sent directly to our private connection. // against unrelated unicast signals sent directly to our private connection.
const sender = c.z_dbus_message_get_sender.?(message); const sender = c.z_dbus_message_get_sender.?(message);
@ -265,8 +309,10 @@ fn process(message: *Bus.Message) !void {
if (c.z_dbus_message_is_signal.?(message, settings, "SettingChanged") != 0 and c.z_dbus_message_has_signature.?(message, "ssv") != 0) { if (c.z_dbus_message_is_signal.?(message, settings, "SettingChanged") != 0 and c.z_dbus_message_has_signature.?(message, "ssv") != 0) {
if (!std.mem.eql(u8, Bus.str(&args).?, "org.freedesktop.appearance")) return; if (!std.mem.eql(u8, Bus.str(&args).?, "org.freedesktop.appearance")) return;
_ = Bus.next(&args); _ = Bus.next(&args);
const key = Bus.str(&args).?; const key = Bus.str(&args).?;
_ = Bus.next(&args); _ = Bus.next(&args);
var value = Bus.variant(&args).?; var value = Bus.variant(&args).?;
preference(key, Bus.uint(&value) orelse 0); preference(key, Bus.uint(&value) orelse 0);
} else if (c.z_dbus_message_is_signal.?(message, "org.freedesktop.portal.Request", "Response") != 0 and c.z_dbus_message_has_signature.?(message, "ua{sv}") != 0) { } else if (c.z_dbus_message_is_signal.?(message, "org.freedesktop.portal.Request", "Response") != 0 and c.z_dbus_message_has_signature.?(message, "ua{sv}") != 0) {
@ -279,16 +325,19 @@ fn process(message: *Bus.Message) !void {
if (pending.id != 0) { if (pending.id != 0) {
if (code != 0) complete(pending, if (code == 1) abi.CANCELLED else n.UHDK_STATUS_OS_ERROR, null) else if (pending.command.?.op == n.Z_URL) complete(pending, abi.OK, null) else responseFiles(pending, &args); if (code != 0) complete(pending, if (code == 1) abi.CANCELLED else n.UHDK_STATUS_OS_ERROR, null) else if (pending.command.?.op == n.Z_URL) complete(pending, abi.OK, null) else responseFiles(pending, &args);
} }
if (pending.replied) destroy(pending); if (pending.replied) destroy(pending);
return; return;
}; };
} }
} }
fn errorStatus(message: *Bus.Message) u32 { fn errorStatus(message: *Bus.Message) u32 {
const name = c.z_dbus_message_get_error_name.?(message); const name = c.z_dbus_message_get_error_name.?(message);
if (name != null and (std.mem.endsWith(u8, std.mem.span(name), ".NotFound") or std.mem.endsWith(u8, std.mem.span(name), ".ServiceUnknown") or std.mem.endsWith(u8, std.mem.span(name), ".UnknownMethod"))) return n.UHDK_STATUS_UNSUPPORTED; if (name != null and (std.mem.endsWith(u8, std.mem.span(name), ".NotFound") or std.mem.endsWith(u8, std.mem.span(name), ".ServiceUnknown") or std.mem.endsWith(u8, std.mem.span(name), ".UnknownMethod"))) return n.UHDK_STATUS_UNSUPPORTED;
return n.UHDK_STATUS_OS_ERROR; return n.UHDK_STATUS_OS_ERROR;
} }
fn preference(key: []const u8, value: u32) void { fn preference(key: []const u8, value: u32) void {
const old = portalState().preferences; const old = portalState().preferences;
if (std.mem.eql(u8, key, "color-scheme")) portalState().preferences.appearance = switch (value) { if (std.mem.eql(u8, key, "color-scheme")) portalState().preferences.appearance = switch (value) {
@ -298,9 +347,11 @@ fn preference(key: []const u8, value: u32) void {
} else if (std.mem.eql(u8, key, "contrast")) portalState().preferences.high_contrast = @intFromBool(value == 1) else if (std.mem.eql(u8, key, "reduced-motion")) portalState().preferences.reduced_motion = @intFromBool(value == 1); } else if (std.mem.eql(u8, key, "contrast")) portalState().preferences.high_contrast = @intFromBool(value == 1) else if (std.mem.eql(u8, key, "reduced-motion")) portalState().preferences.reduced_motion = @intFromBool(value == 1);
if (!std.meta.eql(old, portalState().preferences)) n.z_preferences(runtime.toAppHandle(backend().app), &portalState().preferences); if (!std.meta.eql(old, portalState().preferences)) n.z_preferences(runtime.toAppHandle(backend().app), &portalState().preferences);
} }
pub fn request(cmd: *const n.z_command, id: u64) u32 { pub fn request(cmd: *const n.z_command, id: u64) u32 {
if (!portalState().ready or portalState().connection == null) return abi.UNAVAILABLE; if (!portalState().ready or portalState().connection == null) return abi.UNAVAILABLE;
if (cmd.op == n.Z_DIALOG and portalState().chooser_version < 3) return n.UHDK_STATUS_UNSUPPORTED; if (cmd.op == n.Z_DIALOG and portalState().chooser_version < 3) return n.UHDK_STATUS_UNSUPPORTED;
const p = allocate(cmd, id) catch return abi.OOM; const p = allocate(cmd, id) catch return abi.OOM;
p.next = portalState().pending; p.next = portalState().pending;
portalState().pending = p; portalState().pending = p;
@ -313,6 +364,7 @@ pub fn request(cmd: *const n.z_command, id: u64) u32 {
destroy(p); destroy(p);
return abi.OOM; return abi.OOM;
}; };
_ = c.zxdg_exported_v2_add_listener(p.exported, &export_listener, p); _ = c.zxdg_exported_v2_add_listener(p.exported, &export_listener, p);
} else if (cmd.op == n.Z_URL and backend().desktop.activation != null and Input.state().key_focus != null and } else if (cmd.op == n.Z_URL and backend().desktop.activation != null and Input.state().key_focus != null and
Input.state().serial != 0 and runtime.now(backend().app.io) -| Input.state().serial_time <= 5 * std.time.ns_per_s) Input.state().serial != 0 and runtime.now(backend().app.io) -| Input.state().serial_time <= 5 * std.time.ns_per_s)
@ -321,6 +373,7 @@ pub fn request(cmd: *const n.z_command, id: u64) u32 {
destroy(p); destroy(p);
return abi.OOM; return abi.OOM;
}; };
_ = c.xdg_activation_token_v1_add_listener(p.activation, &activation_listener, p); _ = c.xdg_activation_token_v1_add_listener(p.activation, &activation_listener, p);
c.xdg_activation_token_v1_set_serial(p.activation, Input.state().serial, Input.state().seat); c.xdg_activation_token_v1_set_serial(p.activation, Input.state().serial, Input.state().seat);
c.xdg_activation_token_v1_set_surface(p.activation, Input.state().key_focus.?.surface); c.xdg_activation_token_v1_set_surface(p.activation, Input.state().key_focus.?.surface);
@ -331,12 +384,15 @@ pub fn request(cmd: *const n.z_command, id: u64) u32 {
}; };
return n.Z_DEFERRED; return n.Z_DEFERRED;
} }
fn allocate(cmd: *const n.z_command, id: u64) !*Pending { fn allocate(cmd: *const n.z_command, id: u64) !*Pending {
const gpa = backend().app.gpa; const gpa = backend().app.gpa;
const p = try gpa.create(Pending); const p = try gpa.create(Pending);
errdefer gpa.destroy(p); errdefer gpa.destroy(p);
const token = try std.fmt.allocPrintSentinel(gpa, "uhdk_{x}", .{id}, 0); const token = try std.fmt.allocPrintSentinel(gpa, "uhdk_{x}", .{id}, 0);
errdefer gpa.free(token); errdefer gpa.free(token);
const unique = portalState().unique.?; const unique = portalState().unique.?;
const name = try gpa.dupe(u8, unique[1..]); const name = try gpa.dupe(u8, unique[1..]);
defer gpa.free(name); defer gpa.free(name);
@ -344,6 +400,7 @@ fn allocate(cmd: *const n.z_command, id: u64) !*Pending {
p.* = .{ .id = id, .command = cmd, .token = token, .handle = try std.fmt.allocPrintSentinel(gpa, path ++ "/request/{s}/{s}", .{ name, token }, 0), .deadline = runtime.now(backend().app.io) + 30 * std.time.ns_per_s }; p.* = .{ .id = id, .command = cmd, .token = token, .handle = try std.fmt.allocPrintSentinel(gpa, path ++ "/request/{s}/{s}", .{ name, token }, 0), .deadline = runtime.now(backend().app.io) + 30 * std.time.ns_per_s };
return p; return p;
} }
fn exported(raw: ?*anyopaque, _: ?*c.struct_zxdg_exported_v2, handle: [*c]const u8) callconv(.c) void { fn exported(raw: ?*anyopaque, _: ?*c.struct_zxdg_exported_v2, handle: [*c]const u8) callconv(.c) void {
const p: *Pending = @ptrCast(@alignCast(raw.?)); const p: *Pending = @ptrCast(@alignCast(raw.?));
const parent = std.fmt.allocPrintSentinel(backend().app.gpa, "wayland:{s}", .{std.mem.span(handle)}, 0) catch { const parent = std.fmt.allocPrintSentinel(backend().app.gpa, "wayland:{s}", .{std.mem.span(handle)}, 0) catch {
@ -357,6 +414,7 @@ fn exported(raw: ?*anyopaque, _: ?*c.struct_zxdg_exported_v2, handle: [*c]const
destroy(p); destroy(p);
}; };
} }
const export_listener: c.struct_zxdg_exported_v2_listener = .{ .handle = exported }; const export_listener: c.struct_zxdg_exported_v2_listener = .{ .handle = exported };
fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c]const u8) callconv(.c) void { fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c]const u8) callconv(.c) void {
const p: *Pending = @ptrCast(@alignCast(raw.?)); const p: *Pending = @ptrCast(@alignCast(raw.?));
@ -365,18 +423,22 @@ fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c
destroy(p); destroy(p);
}; };
} }
const activation_listener: c.struct_xdg_activation_token_v1_listener = .{ .done = activated }; const activation_listener: c.struct_xdg_activation_token_v1_listener = .{ .done = activated };
fn submit(p: *Pending, parent: [*:0]const u8, activation_token: ?[*:0]const u8) !void { fn submit(p: *Pending, parent: [*:0]const u8, activation_token: ?[*:0]const u8) !void {
const cmd = p.command.?; const cmd = p.command.?;
const dialog = cmd.op == n.Z_DIALOG; const dialog = cmd.op == n.Z_DIALOG;
const message = try Bus.method(desktop, path, if (dialog) chooser else "org.freedesktop.portal.OpenURI", if (!dialog) "OpenURI" else if (cmd.dialog.kind == n.UHDK_DIALOG_SAVE_FILE) "SaveFile" else "OpenFile"); const message = try Bus.method(desktop, path, if (dialog) chooser else "org.freedesktop.portal.OpenURI", if (!dialog) "OpenURI" else if (cmd.dialog.kind == n.UHDK_DIALOG_SAVE_FILE) "SaveFile" else "OpenFile");
defer c.z_dbus_message_unref.?(message); defer c.z_dbus_message_unref.?(message);
var arena: std.heap.ArenaAllocator = .init(backend().app.gpa); var arena: std.heap.ArenaAllocator = .init(backend().app.gpa);
defer arena.deinit(); defer arena.deinit();
const gpa = arena.allocator(); const gpa = arena.allocator();
var args = Bus.append(message); var args = Bus.append(message);
try Bus.string(&args, parent); try Bus.string(&args, parent);
try Bus.string(&args, try gpa.dupeZ(u8, abi.textBytes(if (dialog) cmd.dialog.title else cmd.text))); try Bus.string(&args, try gpa.dupeZ(u8, abi.textBytes(if (dialog) cmd.dialog.title else cmd.text)));
var options = try Bus.open(&args, c.DBUS_TYPE_ARRAY, "{sv}"); var options = try Bus.open(&args, c.DBUS_TYPE_ARRAY, "{sv}");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&args, &options); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&args, &options);
try Bus.option(&options, "handle_token", "s", p.token.ptr); try Bus.option(&options, "handle_token", "s", p.token.ptr);
@ -387,6 +449,7 @@ fn submit(p: *Pending, parent: [*:0]const u8, activation_token: ?[*:0]const u8)
try Bus.option(&options, "multiple", "b", @as(u32, @intFromBool(cmd.dialog.kind == n.UHDK_DIALOG_OPEN_FILES))); try Bus.option(&options, "multiple", "b", @as(u32, @intFromBool(cmd.dialog.kind == n.UHDK_DIALOG_OPEN_FILES)));
try Bus.option(&options, "directory", "b", @as(u32, @intFromBool(cmd.dialog.kind == n.UHDK_DIALOG_OPEN_DIRECTORY))); try Bus.option(&options, "directory", "b", @as(u32, @intFromBool(cmd.dialog.kind == n.UHDK_DIALOG_OPEN_DIRECTORY)));
} }
if (cmd.dialog.accept_label.len != 0) try Bus.option(&options, "accept_label", "s", (try gpa.dupeZ(u8, abi.textBytes(cmd.dialog.accept_label))).ptr); if (cmd.dialog.accept_label.len != 0) try Bus.option(&options, "accept_label", "s", (try gpa.dupeZ(u8, abi.textBytes(cmd.dialog.accept_label))).ptr);
if (cmd.dialog.suggested_name.len != 0 and cmd.dialog.kind == n.UHDK_DIALOG_SAVE_FILE) try Bus.option(&options, "current_name", "s", (try gpa.dupeZ(u8, abi.textBytes(cmd.dialog.suggested_name))).ptr); if (cmd.dialog.suggested_name.len != 0 and cmd.dialog.kind == n.UHDK_DIALOG_SAVE_FILE) try Bus.option(&options, "current_name", "s", (try gpa.dupeZ(u8, abi.textBytes(cmd.dialog.suggested_name))).ptr);
if (cmd.dialog.initial_directory != null) { if (cmd.dialog.initial_directory != null) {
@ -394,8 +457,10 @@ fn submit(p: *Pending, parent: [*:0]const u8, activation_token: ?[*:0]const u8)
var entry = try Bus.open(&options, c.DBUS_TYPE_DICT_ENTRY, null); var entry = try Bus.open(&options, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&options, &entry); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&options, &entry);
try Bus.string(&entry, "current_folder"); try Bus.string(&entry, "current_folder");
var variant = try Bus.open(&entry, c.DBUS_TYPE_VARIANT, "ay"); var variant = try Bus.open(&entry, c.DBUS_TYPE_VARIANT, "ay");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&entry, &variant); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&entry, &variant);
var bytes = try Bus.open(&variant, c.DBUS_TYPE_ARRAY, "y"); var bytes = try Bus.open(&variant, c.DBUS_TYPE_ARRAY, "y");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&variant, &bytes); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&variant, &bytes);
for (directory) |byte| try Bus.basic(&bytes, c.DBUS_TYPE_BYTE, byte); for (directory) |byte| try Bus.basic(&bytes, c.DBUS_TYPE_BYTE, byte);
@ -404,23 +469,29 @@ fn submit(p: *Pending, parent: [*:0]const u8, activation_token: ?[*:0]const u8)
try Bus.close(&entry, &variant); try Bus.close(&entry, &variant);
try Bus.close(&options, &entry); try Bus.close(&options, &entry);
} }
if (cmd.dialog.filters_len != 0) try filters(&options, cmd.dialog, gpa); if (cmd.dialog.filters_len != 0) try filters(&options, cmd.dialog, gpa);
} }
try Bus.close(&args, &options); try Bus.close(&args, &options);
p.serial = try send(message); p.serial = try send(message);
} }
fn filters(options: *Bus.Iter, desc: n.uhdk_file_dialog_desc, gpa: std.mem.Allocator) !void { fn filters(options: *Bus.Iter, desc: n.uhdk_file_dialog_desc, gpa: std.mem.Allocator) !void {
var entry = try Bus.open(options, c.DBUS_TYPE_DICT_ENTRY, null); var entry = try Bus.open(options, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(options, &entry); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(options, &entry);
try Bus.string(&entry, "filters"); try Bus.string(&entry, "filters");
var variant = try Bus.open(&entry, c.DBUS_TYPE_VARIANT, "a(sa(us))"); var variant = try Bus.open(&entry, c.DBUS_TYPE_VARIANT, "a(sa(us))");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&entry, &variant); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&entry, &variant);
var list = try Bus.open(&variant, c.DBUS_TYPE_ARRAY, "(sa(us))"); var list = try Bus.open(&variant, c.DBUS_TYPE_ARRAY, "(sa(us))");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&variant, &list); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&variant, &list);
for (desc.filters[0..@intCast(desc.filters_len)]) |filter| { for (desc.filters[0..@intCast(desc.filters_len)]) |filter| {
var pair = try Bus.open(&list, c.DBUS_TYPE_STRUCT, null); var pair = try Bus.open(&list, c.DBUS_TYPE_STRUCT, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&list, &pair); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&list, &pair);
try Bus.string(&pair, try gpa.dupeZ(u8, abi.textBytes(filter.label))); try Bus.string(&pair, try gpa.dupeZ(u8, abi.textBytes(filter.label)));
var patterns = try Bus.open(&pair, c.DBUS_TYPE_ARRAY, "(us)"); var patterns = try Bus.open(&pair, c.DBUS_TYPE_ARRAY, "(us)");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&pair, &patterns); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&pair, &patterns);
for (0..@max(1, filter.extensions.len)) |index| { for (0..@max(1, filter.extensions.len)) |index| {
@ -431,37 +502,45 @@ fn filters(options: *Bus.Iter, desc: n.uhdk_file_dialog_desc, gpa: std.mem.Alloc
try Bus.string(&rule, pattern); try Bus.string(&rule, pattern);
try Bus.close(&patterns, &rule); try Bus.close(&patterns, &rule);
} }
try Bus.close(&pair, &patterns); try Bus.close(&pair, &patterns);
try Bus.close(&list, &pair); try Bus.close(&list, &pair);
} }
try Bus.close(&variant, &list); try Bus.close(&variant, &list);
try Bus.close(&entry, &variant); try Bus.close(&entry, &variant);
try Bus.close(options, &entry); try Bus.close(options, &entry);
} }
fn responseFiles(p: *Pending, args: *Bus.Iter) void { fn responseFiles(p: *Pending, args: *Bus.Iter) void {
var raw = Bus.entry(args, "uris") orelse { var raw = Bus.entry(args, "uris") orelse {
complete(p, n.UHDK_STATUS_OS_ERROR, null); complete(p, n.UHDK_STATUS_OS_ERROR, null);
return; return;
}; };
var value = Bus.variant(&raw) orelse { var value = Bus.variant(&raw) orelse {
complete(p, n.UHDK_STATUS_OS_ERROR, null); complete(p, n.UHDK_STATUS_OS_ERROR, null);
return; return;
}; };
if (Bus.kind(&value) != c.DBUS_TYPE_ARRAY) { if (Bus.kind(&value) != c.DBUS_TYPE_ARRAY) {
complete(p, n.UHDK_STATUS_OS_ERROR, null); complete(p, n.UHDK_STATUS_OS_ERROR, null);
return; return;
} }
var strings = Bus.child(&value); var strings = Bus.child(&value);
var files: std.ArrayList(?*n.uhdk_file) = .empty; var files: std.ArrayList(?*n.uhdk_file) = .empty;
defer { defer {
for (files.items) |file| n.uhdk_file_release(file); for (files.items) |file| n.uhdk_file_release(file);
files.deinit(backend().app.gpa); files.deinit(backend().app.gpa);
} }
while (Bus.kind(&strings) != c.DBUS_TYPE_INVALID) { while (Bus.kind(&strings) != c.DBUS_TYPE_INVALID) {
const uri = Bus.str(&strings) orelse { const uri = Bus.str(&strings) orelse {
complete(p, n.UHDK_STATUS_OS_ERROR, null); complete(p, n.UHDK_STATUS_OS_ERROR, null);
return; return;
}; };
const bytes = Files.decode(backend().app.gpa, uri) catch |err| { const bytes = Files.decode(backend().app.gpa, uri) catch |err| {
complete(p, if (err == error.OutOfMemory) abi.OOM else n.UHDK_STATUS_UNSUPPORTED, null); complete(p, if (err == error.OutOfMemory) abi.OOM else n.UHDK_STATUS_UNSUPPORTED, null);
return; return;
@ -471,29 +550,36 @@ fn responseFiles(p: *Pending, args: *Bus.Iter) void {
complete(p, abi.OOM, null); complete(p, abi.OOM, null);
return; return;
}; };
files.append(backend().app.gpa, file) catch { files.append(backend().app.gpa, file) catch {
n.uhdk_file_release(file); n.uhdk_file_release(file);
complete(p, abi.OOM, null); complete(p, abi.OOM, null);
return; return;
}; };
if (!Bus.next(&strings)) break; if (!Bus.next(&strings)) break;
} }
var result = std.mem.zeroes(n.z_request_result); var result = std.mem.zeroes(n.z_request_result);
result.value.files = .{ .ptr = files.items.ptr, .len = files.items.len }; result.value.files = .{ .ptr = files.items.ptr, .len = files.items.len };
complete(p, if (files.items.len == 0) abi.CANCELLED else abi.OK, &result); complete(p, if (files.items.len == 0) abi.CANCELLED else abi.OK, &result);
} }
fn complete(p: *Pending, status: u32, result: ?*n.z_request_result) void { fn complete(p: *Pending, status: u32, result: ?*n.z_request_result) void {
if (p.id != 0) n.z_complete(runtime.toAppHandle(backend().app), p.id, status, result); if (p.id != 0) n.z_complete(runtime.toAppHandle(backend().app), p.id, status, result);
p.id = 0; p.id = 0;
p.command = null; p.command = null;
} }
fn closeRequest(handle: [*:0]const u8) void { fn closeRequest(handle: [*:0]const u8) void {
if (portalState().connection == null) return; if (portalState().connection == null) return;
const message = Bus.method(desktop, handle, "org.freedesktop.portal.Request", "Close") catch return; const message = Bus.method(desktop, handle, "org.freedesktop.portal.Request", "Close") catch return;
defer c.z_dbus_message_unref.?(message); defer c.z_dbus_message_unref.?(message);
c.z_dbus_message_set_no_reply.?(message, 1); c.z_dbus_message_set_no_reply.?(message, 1);
_ = send(message) catch {}; _ = send(message) catch {};
} }
pub fn cancel(id: u64) bool { pub fn cancel(id: u64) bool {
var cursor = portalState().pending; var cursor = portalState().pending;
while (cursor) |p| : (cursor = p.next) if (p.id == id) { while (cursor) |p| : (cursor = p.next) if (p.id == id) {
@ -505,6 +591,7 @@ pub fn cancel(id: u64) bool {
}; };
return false; return false;
} }
fn destroy(p: *Pending) void { fn destroy(p: *Pending) void {
var link = &portalState().pending; var link = &portalState().pending;
while (link.* != p) link = &link.*.?.next; while (link.* != p) link = &link.*.?.next;
@ -515,20 +602,24 @@ fn destroy(p: *Pending) void {
backend().app.gpa.free(p.token); backend().app.gpa.free(p.token);
backend().app.gpa.destroy(p); backend().app.gpa.destroy(p);
} }
fn disconnect() void { fn disconnect() void {
KdeAppMenu.disconnected(); KdeAppMenu.disconnected();
while (portalState().pending) |p| { while (portalState().pending) |p| {
complete(p, abi.UNAVAILABLE, null); complete(p, abi.UNAVAILABLE, null);
destroy(p); destroy(p);
} }
if (portalState().connection) |connection| { if (portalState().connection) |connection| {
c.z_dbus_connection_close.?(connection); c.z_dbus_connection_close.?(connection);
c.z_dbus_connection_unref.?(connection); c.z_dbus_connection_unref.?(connection);
} }
portalState().connection = null; portalState().connection = null;
portalState().ready = false; portalState().ready = false;
native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false); native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false);
} }
pub fn deinit() void { pub fn deinit() void {
var cursor = portalState().pending; var cursor = portalState().pending;
while (cursor) |p| : (cursor = p.next) closeRequest(p.handle); while (cursor) |p| : (cursor = p.next) closeRequest(p.handle);

View File

@ -17,6 +17,7 @@ const Sent = struct {
start: usize, start: usize,
len: usize, len: usize,
}; };
pub const State = struct { pub const State = struct {
enabled: bool = false, enabled: bool = false,
composing: bool = false, composing: bool = false,
@ -34,15 +35,18 @@ pub const State = struct {
before: u32 = 0, before: u32 = 0,
after: u32 = 0, after: u32 = 0,
}; };
pub fn listen(input: ?*c.struct_zwp_text_input_v3) void { pub fn listen(input: ?*c.struct_zwp_text_input_v3) void {
_ = c.zwp_text_input_v3_add_listener(input, &listener, null); _ = c.zwp_text_input_v3_add_listener(input, &listener, null);
} }
fn commit() u32 { fn commit() u32 {
const s = Input.state(); const s = Input.state();
s.text_serial +%= 1; s.text_serial +%= 1;
c.zwp_text_input_v3_commit(s.text_input); c.zwp_text_input_v3_commit(s.text_input);
return s.text_serial; return s.text_serial;
} }
fn enter(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, surface: ?*c.struct_wl_surface) callconv(.c) void { fn enter(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, surface: ?*c.struct_wl_surface) callconv(.c) void {
const s = Input.state(); const s = Input.state();
s.text_focus = Input.find(surface); s.text_focus = Input.find(surface);
@ -51,45 +55,57 @@ fn enter(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, surface: ?*c.struct_wl
_ = publish(w); _ = publish(w);
}; };
} }
fn leave(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, _: ?*c.struct_wl_surface) callconv(.c) void { fn leave(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, _: ?*c.struct_wl_surface) callconv(.c) void {
if (Input.state().text_focus) |w| { if (Input.state().text_focus) |w| {
end(w); end(w);
clearPending(w); clearPending(w);
clearSent(w); clearSent(w);
} }
Input.state().text_focus = null; Input.state().text_focus = null;
} }
fn own(w: *native.Window, destination: *?[]u8, text: [*c]const u8) void { fn own(w: *native.Window, destination: *?[]u8, text: [*c]const u8) void {
if (destination.*) |old| w.owner.gpa.free(old); if (destination.*) |old| w.owner.gpa.free(old);
const bytes = if (text == null) "" else std.mem.span(text); const bytes = if (text == null) "" else std.mem.span(text);
destination.* = w.owner.gpa.dupe(u8, bytes) catch null; destination.* = w.owner.gpa.dupe(u8, bytes) catch null;
} }
fn preedit(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, text: [*c]const u8, first: i32, last: i32) callconv(.c) void { fn preedit(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, text: [*c]const u8, first: i32, last: i32) callconv(.c) void {
const w = Input.state().text_focus orelse return; const w = Input.state().text_focus orelse return;
own(w, &w.text.pending_preedit, text); own(w, &w.text.pending_preedit, text);
w.text.cursor_begin = first; w.text.cursor_begin = first;
w.text.cursor_end = last; w.text.cursor_end = last;
} }
fn committed(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, text: [*c]const u8) callconv(.c) void { fn committed(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, text: [*c]const u8) callconv(.c) void {
const w = Input.state().text_focus orelse return; const w = Input.state().text_focus orelse return;
own(w, &w.text.pending_commit, text); own(w, &w.text.pending_commit, text);
} }
fn deleted(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, before: u32, after: u32) callconv(.c) void { fn deleted(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, before: u32, after: u32) callconv(.c) void {
const w = Input.state().text_focus orelse return; const w = Input.state().text_focus orelse return;
w.text.before = before; w.text.before = before;
w.text.after = after; w.text.after = after;
} }
fn done(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, serial: u32) callconv(.c) void { fn done(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, serial: u32) callconv(.c) void {
Input.flushKey(); Input.flushKey();
const w = Input.state().text_focus orelse return; const w = Input.state().text_focus orelse return;
const t = &w.text; const t = &w.text;
defer clearPending(w); defer clearPending(w);
if (!t.enabled) return; if (!t.enabled) return;
var sent = t.sent; var sent = t.sent;
while (sent) |value| { while (sent) |value| {
if (value.serial == serial) break; if (value.serial == serial) break;
sent = value.next; sent = value.next;
} }
// A cleared serial belongs to a cancelled/disabled input session. // A cleared serial belongs to a cancelled/disabled input session.
const basis = sent orelse return; const basis = sent orelse return;
if (t.pending_commit) |bytes| if (!std.unicode.utf8ValidateSlice(bytes)) return; if (t.pending_commit) |bytes| if (!std.unicode.utf8ValidateSlice(bytes)) return;
@ -101,6 +117,7 @@ fn done(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, serial: u32) callconv(.
event.data.text.revision = basis.revision; event.data.text.revision = basis.revision;
if (t.before != 0 or t.after != 0) { if (t.before != 0 or t.after != 0) {
if (t.before > basis.start or t.after > basis.bytes.len - basis.start - basis.len) return; if (t.before > basis.start or t.after > basis.bytes.len - basis.start - basis.len) return;
const start = basis.start - t.before; const start = basis.start - t.before;
const length = t.before + basis.len + t.after; const length = t.before + basis.len + t.after;
if (!abi.boundary(basis.bytes, start) or !abi.boundary(basis.bytes, start + length)) return; if (!abi.boundary(basis.bytes, start) or !abi.boundary(basis.bytes, start + length)) return;
@ -108,10 +125,12 @@ fn done(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, serial: u32) callconv(.
event.data.text.replacement_start = basis.offset + start; event.data.text.replacement_start = basis.offset + start;
event.data.text.replacement_len = length; event.data.text.replacement_len = length;
} }
t.last_edit = event.input_id; t.last_edit = event.input_id;
Input.send(w, &event); Input.send(w, &event);
end(w); end(w);
} }
if (t.pending_preedit) |bytes| { if (t.pending_preedit) |bytes| {
if (bytes.len == 0) end(w); if (bytes.len == 0) end(w);
if (bytes.len != 0 and std.unicode.utf8ValidateSlice(bytes)) { if (bytes.len != 0 and std.unicode.utf8ValidateSlice(bytes)) {
@ -120,18 +139,21 @@ fn done(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, serial: u32) callconv(.
event.input_id = Input.id(); event.input_id = Input.id();
event.data.text.text = abi.textSpan(bytes); event.data.text.text = abi.textSpan(bytes);
event.data.text.revision = basis.revision; event.data.text.revision = basis.revision;
const lo: usize = @intCast(@max(0, @min(t.cursor_begin, t.cursor_end))); const lo: usize = @intCast(@max(0, @min(t.cursor_begin, t.cursor_end)));
const hi: usize = @intCast(@max(0, @max(t.cursor_begin, t.cursor_end))); const hi: usize = @intCast(@max(0, @max(t.cursor_begin, t.cursor_end)));
if (lo <= hi and hi <= bytes.len and abi.boundary(bytes, lo) and abi.boundary(bytes, hi)) { if (lo <= hi and hi <= bytes.len and abi.boundary(bytes, lo) and abi.boundary(bytes, hi)) {
event.data.text.selection_start = lo; event.data.text.selection_start = lo;
event.data.text.selection_len = hi - lo; event.data.text.selection_len = hi - lo;
} }
t.composing = true; t.composing = true;
t.ime_composing = true; t.ime_composing = true;
t.last_edit = event.input_id; t.last_edit = event.input_id;
Input.send(w, &event); Input.send(w, &event);
} }
} }
// Keep the acknowledged basis: more than one done can share its serial. // Keep the acknowledged basis: more than one done can share its serial.
while (t.sent != basis) { while (t.sent != basis) {
const old = t.sent.?; const old = t.sent.?;
@ -140,10 +162,12 @@ fn done(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, serial: u32) callconv(.
w.owner.gpa.destroy(old); w.owner.gpa.destroy(old);
t.sent_count -= 1; t.sent_count -= 1;
} }
// Never send pending state in response to an older serial. A later matching // Never send pending state in response to an older serial. A later matching
// done or an acknowledged application basis will release the throttle. // done or an acknowledged application basis will release the throttle.
if (serial == Input.state().text_serial and t.dirty and t.snapshot.acknowledged_input_id >= t.last_edit) _ = publish(w); if (serial == Input.state().text_serial and t.dirty and t.snapshot.acknowledged_input_id >= t.last_edit) _ = publish(w);
} }
const listener: c.struct_zwp_text_input_v3_listener = .{ .enter = enter, .leave = leave, .preedit_string = preedit, .commit_string = committed, .delete_surrounding_text = deleted, .done = done }; const listener: c.struct_zwp_text_input_v3_listener = .{ .enter = enter, .leave = leave, .preedit_string = preedit, .commit_string = committed, .delete_surrounding_text = deleted, .done = done };
pub fn crop(bytes: []const u8, start: usize, length: usize) ?struct { pub fn crop(bytes: []const u8, start: usize, length: usize) ?struct {
@ -151,13 +175,16 @@ pub fn crop(bytes: []const u8, start: usize, length: usize) ?struct {
end: usize, end: usize,
} { } {
if (length > 4000 or std.mem.findScalar(u8, bytes, 0) != null) return null; if (length > 4000 or std.mem.findScalar(u8, bytes, 0) != null) return null;
var lo = start -| ((4000 - length) / 2); var lo = start -| ((4000 - length) / 2);
while (lo < start and !abi.boundary(bytes, lo)) lo += 1; while (lo < start and !abi.boundary(bytes, lo)) lo += 1;
var hi = @min(bytes.len, lo + 4000); var hi = @min(bytes.len, lo + 4000);
while (hi > start + length and !abi.boundary(bytes, hi)) hi -= 1; while (hi > start + length and !abi.boundary(bytes, hi)) hi -= 1;
if (hi < start + length) return null; if (hi < start + length) return null;
return .{ .start = lo, .end = hi }; return .{ .start = lo, .end = hi };
} }
fn publish(w: *native.Window) u32 { fn publish(w: *native.Window) u32 {
const s = Input.state(); const s = Input.state();
const t = &w.text; const t = &w.text;
@ -166,25 +193,30 @@ fn publish(w: *native.Window) u32 {
t.dirty = true; t.dirty = true;
return abi.OK; return abi.OK;
} }
// Bound unacknowledged snapshots without discarding snapshots a late IME // Bound unacknowledged snapshots without discarding snapshots a late IME
// batch may still refer to. Keep the newest application state for later. // batch may still refer to. Keep the newest application state for later.
if (t.sent_count >= 32) { if (t.sent_count >= 32) {
t.dirty = true; t.dirty = true;
return abi.OK; return abi.OK;
} }
const range = crop(t.surrounding, @intCast(t.snapshot.selection_start), @intCast(t.snapshot.selection_len)); const range = crop(t.surrounding, @intCast(t.snapshot.selection_start), @intCast(t.snapshot.selection_len));
const sent = w.owner.gpa.create(Sent) catch return abi.OOM; const sent = w.owner.gpa.create(Sent) catch return abi.OOM;
const bytes = w.owner.gpa.dupeZ(u8, if (range) |r| t.surrounding[r.start..r.end] else "") catch { const bytes = w.owner.gpa.dupeZ(u8, if (range) |r| t.surrounding[r.start..r.end] else "") catch {
w.owner.gpa.destroy(sent); w.owner.gpa.destroy(sent);
return abi.OOM; return abi.OOM;
}; };
sent.* = .{ .serial = s.text_serial +% 1, .revision = t.snapshot.revision, .bytes = bytes, .offset = if (range) |r| r.start else 0, .start = if (range) |r| @intCast(t.snapshot.selection_start - r.start) else 0, .len = if (range != null) @intCast(t.snapshot.selection_len) else 0 }; sent.* = .{ .serial = s.text_serial +% 1, .revision = t.snapshot.revision, .bytes = bytes, .offset = if (range) |r| r.start else 0, .start = if (range) |r| @intCast(t.snapshot.selection_start - r.start) else 0, .len = if (range != null) @intCast(t.snapshot.selection_len) else 0 };
c.zwp_text_input_v3_set_surrounding_text(s.text_input, bytes, @intCast(sent.start + sent.len), @intCast(sent.start)); c.zwp_text_input_v3_set_surrounding_text(s.text_input, bytes, @intCast(sent.start + sent.len), @intCast(sent.start));
const caret = t.snapshot.caret; const caret = t.snapshot.caret;
c.zwp_text_input_v3_set_cursor_rectangle(s.text_input, @intFromFloat(std.math.clamp(caret.x, -1000000, 1000000)), @intFromFloat(std.math.clamp(caret.y, -1000000, 1000000)), @intFromFloat(@min(caret.width, 1000000)), @intFromFloat(@min(caret.height, 1000000))); c.zwp_text_input_v3_set_cursor_rectangle(s.text_input, @intFromFloat(std.math.clamp(caret.x, -1000000, 1000000)), @intFromFloat(std.math.clamp(caret.y, -1000000, 1000000)), @intFromFloat(@min(caret.width, 1000000)), @intFromFloat(@min(caret.height, 1000000)));
c.zwp_text_input_v3_set_content_type(s.text_input, c.ZWP_TEXT_INPUT_V3_CONTENT_HINT_MULTILINE, c.ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_NORMAL); c.zwp_text_input_v3_set_content_type(s.text_input, c.ZWP_TEXT_INPUT_V3_CONTENT_HINT_MULTILINE, c.ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_NORMAL);
c.zwp_text_input_v3_set_text_change_cause(s.text_input, if (t.snapshot.acknowledged_input_id == t.last_edit) c.ZWP_TEXT_INPUT_V3_CHANGE_CAUSE_INPUT_METHOD else c.ZWP_TEXT_INPUT_V3_CHANGE_CAUSE_OTHER); c.zwp_text_input_v3_set_text_change_cause(s.text_input, if (t.snapshot.acknowledged_input_id == t.last_edit) c.ZWP_TEXT_INPUT_V3_CHANGE_CAUSE_INPUT_METHOD else c.ZWP_TEXT_INPUT_V3_CHANGE_CAUSE_OTHER);
_ = commit(); _ = commit();
var link = &t.sent; var link = &t.sent;
while (link.*) |item| link = &item.next; while (link.*) |item| link = &item.next;
link.* = sent; link.* = sent;
@ -192,9 +224,11 @@ fn publish(w: *native.Window) u32 {
t.dirty = false; t.dirty = false;
return abi.OK; return abi.OK;
} }
pub fn snapshot(w: *native.Window, value: n.uhdk_text_state) u32 { pub fn snapshot(w: *native.Window, value: n.uhdk_text_state) u32 {
const t = &w.text; const t = &w.text;
if (value.acknowledged_input_id < t.last_edit) return abi.OK; if (value.acknowledged_input_id < t.last_edit) return abi.OK;
const bytes = abi.textBytes(value.surrounding_text); const bytes = abi.textBytes(value.surrounding_text);
const same = t.snapshot.revision == value.revision and t.snapshot.selection_start == value.selection_start and t.snapshot.selection_len == value.selection_len and const same = t.snapshot.revision == value.revision and t.snapshot.selection_start == value.selection_start and t.snapshot.selection_len == value.selection_len and
std.meta.eql(t.snapshot.caret, value.caret) and std.mem.eql(u8, t.surrounding, bytes); std.meta.eql(t.snapshot.caret, value.caret) and std.mem.eql(u8, t.surrounding, bytes);
@ -204,35 +238,44 @@ pub fn snapshot(w: *native.Window, value: n.uhdk_text_state) u32 {
t.snapshot = value; t.snapshot = value;
t.snapshot.surrounding_text = abi.textSpan(copy); t.snapshot.surrounding_text = abi.textSpan(copy);
if (same and !t.dirty) return abi.OK; if (same and !t.dirty) return abi.OK;
t.dirty = true; t.dirty = true;
return publish(w); return publish(w);
} }
pub fn enable(w: *native.Window, enabled: bool) u32 { pub fn enable(w: *native.Window, enabled: bool) u32 {
const t = &w.text; const t = &w.text;
if (enabled and Input.state().context == null) return n.UHDK_STATUS_UNSUPPORTED; if (enabled and Input.state().context == null) return n.UHDK_STATUS_UNSUPPORTED;
if (t.enabled == enabled) return abi.OK; if (t.enabled == enabled) return abi.OK;
end(w); end(w);
clearPending(w); clearPending(w);
clearSent(w); clearSent(w);
if (Input.state().compose != null) c.z_xkb_compose_state_reset.?(Input.state().compose); if (Input.state().compose != null) c.z_xkb_compose_state_reset.?(Input.state().compose);
t.enabled = enabled; t.enabled = enabled;
const s = Input.state(); const s = Input.state();
if (s.text_input != null and s.text_focus == w) { if (s.text_input != null and s.text_focus == w) {
if (enabled) { if (enabled) {
c.zwp_text_input_v3_enable(s.text_input); c.zwp_text_input_v3_enable(s.text_input);
return publish(w); return publish(w);
} }
c.zwp_text_input_v3_disable(s.text_input); c.zwp_text_input_v3_disable(s.text_input);
_ = commit(); _ = commit();
} }
return abi.OK; return abi.OK;
} }
fn end(w: *native.Window) void { fn end(w: *native.Window) void {
if (w.text.composing) endAt(w, Input.id()); if (w.text.composing) endAt(w, Input.id());
} }
fn endAt(w: *native.Window, input_id: u64) void { fn endAt(w: *native.Window, input_id: u64) void {
const t = &w.text; const t = &w.text;
if (!t.composing) return; if (!t.composing) return;
var e = std.mem.zeroes(n.z_event); var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_TEXT_COMPOSITION_END; e.type = n.UHDK_EVENT_TEXT_COMPOSITION_END;
e.input_id = input_id; e.input_id = input_id;
@ -241,6 +284,7 @@ fn endAt(w: *native.Window, input_id: u64) void {
t.composing = false; t.composing = false;
t.ime_composing = false; t.ime_composing = false;
} }
fn clearPending(w: *native.Window) void { fn clearPending(w: *native.Window) void {
const t = &w.text; const t = &w.text;
if (t.pending_preedit) |p| w.owner.gpa.free(p); if (t.pending_preedit) |p| w.owner.gpa.free(p);
@ -250,19 +294,23 @@ fn clearPending(w: *native.Window) void {
t.before = 0; t.before = 0;
t.after = 0; t.after = 0;
} }
fn clearSent(w: *native.Window) void { fn clearSent(w: *native.Window) void {
while (w.text.sent) |item| { while (w.text.sent) |item| {
w.text.sent = item.next; w.text.sent = item.next;
w.owner.gpa.free(item.bytes); w.owner.gpa.free(item.bytes);
w.owner.gpa.destroy(item); w.owner.gpa.destroy(item);
} }
w.text.sent_count = 0; w.text.sent_count = 0;
w.text.dirty = true; w.text.dirty = true;
} }
pub fn cancel(w: *native.Window) void { pub fn cancel(w: *native.Window) void {
end(w); end(w);
clearPending(w); clearPending(w);
clearSent(w); clearSent(w);
const s = Input.state(); const s = Input.state();
if (s.compose != null) c.z_xkb_compose_state_reset.?(s.compose); if (s.compose != null) c.z_xkb_compose_state_reset.?(s.compose);
if (s.text_input != null and s.text_focus == w and w.text.enabled) { if (s.text_input != null and s.text_focus == w and w.text.enabled) {
@ -272,21 +320,26 @@ pub fn cancel(w: *native.Window) void {
_ = publish(w); _ = publish(w);
} }
} }
pub fn forget(w: *native.Window) void { pub fn forget(w: *native.Window) void {
if (Input.state().text_focus == w) { if (Input.state().text_focus == w) {
_ = enable(w, false); _ = enable(w, false);
Input.state().text_focus = null; Input.state().text_focus = null;
} }
end(w); end(w);
clearPending(w); clearPending(w);
clearSent(w); clearSent(w);
} }
pub fn deinit(w: *native.Window) void { pub fn deinit(w: *native.Window) void {
forget(w); forget(w);
w.owner.gpa.free(w.text.surrounding); w.owner.gpa.free(w.text.surrounding);
} }
pub fn editCommand(w: *native.Window, command: u32, modifiers: u32, input_id: u64) void { pub fn editCommand(w: *native.Window, command: u32, modifiers: u32, input_id: u64) void {
if (w.text.ime_composing) return; if (w.text.ime_composing) return;
// A mutation or movement makes old surrounding-text ranges unsafe. Copy // A mutation or movement makes old surrounding-text ranges unsafe. Copy
// leaves the document/selection untouched, so delayed IME batches may retain // leaves the document/selection untouched, so delayed IME batches may retain
// their previously published basis. New state is published only on app ack. // their previously published basis. New state is published only on app ack.
@ -294,6 +347,7 @@ pub fn editCommand(w: *native.Window, command: u32, modifiers: u32, input_id: u6
clearPending(w); clearPending(w);
clearSent(w); clearSent(w);
} }
var event = std.mem.zeroes(n.z_event); var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_EDIT_COMMAND; event.type = n.UHDK_EVENT_EDIT_COMMAND;
event.input_id = input_id; event.input_id = input_id;
@ -301,6 +355,7 @@ pub fn editCommand(w: *native.Window, command: u32, modifiers: u32, input_id: u6
w.text.last_edit = input_id; w.text.last_edit = input_id;
Input.send(w, &event); Input.send(w, &event);
} }
pub fn key(w: *native.Window, sym: u32, logical: u32, input_id: u64, modifiers: u32, plain: []const u8) void { pub fn key(w: *native.Window, sym: u32, logical: u32, input_id: u64, modifiers: u32, plain: []const u8) void {
const s = Input.state(); const s = Input.state();
const t = &w.text; const t = &w.text;
@ -309,6 +364,7 @@ pub fn key(w: *native.Window, sym: u32, logical: u32, input_id: u64, modifiers:
if (Keyboard.edit(logical, modifiers) == n.UHDK_EDIT_CANCEL) cancel(w); if (Keyboard.edit(logical, modifiers) == n.UHDK_EDIT_CANCEL) cancel(w);
return; return;
} }
const edit = Keyboard.edit(logical, modifiers); const edit = Keyboard.edit(logical, modifiers);
if (edit != 0) { if (edit != 0) {
// Escape cancels an XKB compose sequence before becoming an app action. // Escape cancels an XKB compose sequence before becoming an app action.
@ -317,11 +373,13 @@ pub fn key(w: *native.Window, sym: u32, logical: u32, input_id: u64, modifiers:
endAt(w, input_id); endAt(w, input_id);
return; return;
} }
if (s.compose != null) c.z_xkb_compose_state_reset.?(s.compose); if (s.compose != null) c.z_xkb_compose_state_reset.?(s.compose);
endAt(w, input_id); endAt(w, input_id);
editCommand(w, edit, modifiers, input_id); editCommand(w, edit, modifiers, input_id);
return; return;
} }
if (modifiers & (n.UHDK_MOD_CONTROL | n.UHDK_MOD_ALT | n.UHDK_MOD_SUPER) != 0) return; if (modifiers & (n.UHDK_MOD_CONTROL | n.UHDK_MOD_ALT | n.UHDK_MOD_SUPER) != 0) return;
var buffer: [256]u8 = undefined; var buffer: [256]u8 = undefined;
var length: c_int = @intCast(plain.len); var length: c_int = @intCast(plain.len);
@ -346,6 +404,7 @@ pub fn key(w: *native.Window, sym: u32, logical: u32, input_id: u64, modifiers:
else => {}, else => {},
} }
} }
if (length <= 0 or length >= buffer.len or buffer[0] < 32 or buffer[0] == 127) return; if (length <= 0 or length >= buffer.len or buffer[0] < 32 or buffer[0] == 127) return;
var e = std.mem.zeroes(n.z_event); var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_TEXT_COMMIT; e.type = n.UHDK_EVENT_TEXT_COMMIT;
@ -355,12 +414,14 @@ pub fn key(w: *native.Window, sym: u32, logical: u32, input_id: u64, modifiers:
t.last_edit = input_id; t.last_edit = input_id;
Input.send(w, &e); Input.send(w, &e);
} }
test "surrounding crop preserves UTF-8 and complete selections" { test "surrounding crop preserves UTF-8 and complete selections" {
var bytes: [8000]u8 = undefined; var bytes: [8000]u8 = undefined;
for (0..4000) |i| { for (0..4000) |i| {
bytes[i * 2] = 0xc3; bytes[i * 2] = 0xc3;
bytes[i * 2 + 1] = 0xa9; bytes[i * 2 + 1] = 0xa9;
} }
const range = crop(&bytes, 3998, 4).?; const range = crop(&bytes, 3998, 4).?;
try std.testing.expect(range.start % 2 == 0 and range.end % 2 == 0 and range.end - range.start <= 4000); try std.testing.expect(range.start % 2 == 0 and range.end % 2 == 0 and range.end - range.start <= 4000);
try std.testing.expect(range.start <= 3998 and range.end >= 4002); try std.testing.expect(range.start <= 3998 and range.end >= 4002);

View File

@ -14,30 +14,39 @@ pub const Watch = struct {
directory: []u8, directory: []u8,
name: []u8, name: []u8,
}; };
fn backend() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
pub fn prepare(root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, out: *?*anyopaque) u32 { pub fn prepare(root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, out: *?*anyopaque) u32 {
const path = backend().app.gpa.dupeZ(u8, abi.bytes(n.z_file_path(root))) catch return abi.OOM; const path = backend().app.gpa.dupeZ(u8, abi.bytes(n.z_file_path(root))) catch return abi.OOM;
defer backend().app.gpa.free(path); defer backend().app.gpa.free(path);
const kind = c.z_linux_is_directory(path); const kind = c.z_linux_is_directory(path);
if (kind < 0 and c.z_linux_errno() != c.ENOENT) return n.UHDK_STATUS_OS_ERROR; if (kind < 0 and c.z_linux_errno() != c.ENOENT) return n.UHDK_STATUS_OS_ERROR;
const directory = backend().app.gpa.dupeZ(u8, if (kind == 1) path else std.fs.path.dirname(path) orelse "/") catch return abi.OOM; const directory = backend().app.gpa.dupeZ(u8, if (kind == 1) path else std.fs.path.dirname(path) orelse "/") catch return abi.OOM;
defer backend().app.gpa.free(directory); defer backend().app.gpa.free(directory);
const fd = c.inotify_init1(c.IN_NONBLOCK | c.IN_CLOEXEC); const fd = c.inotify_init1(c.IN_NONBLOCK | c.IN_CLOEXEC);
if (fd < 0) return n.UHDK_STATUS_OS_ERROR; if (fd < 0) return n.UHDK_STATUS_OS_ERROR;
const mask = c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_FROM | c.IN_MOVED_TO | c.IN_MODIFY | c.IN_ATTRIB | c.IN_DELETE_SELF | c.IN_MOVE_SELF | c.IN_ONLYDIR; const mask = c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_FROM | c.IN_MOVED_TO | c.IN_MODIFY | c.IN_ATTRIB | c.IN_DELETE_SELF | c.IN_MOVE_SELF | c.IN_ONLYDIR;
if (c.inotify_add_watch(fd, directory, mask) < 0) { if (c.inotify_add_watch(fd, directory, mask) < 0) {
_ = c.close(fd); _ = c.close(fd);
return n.UHDK_STATUS_OS_ERROR; return n.UHDK_STATUS_OS_ERROR;
} }
const w = allocate(fd, root, handle, 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); _ = c.close(fd);
return abi.OOM; return abi.OOM;
}; };
out.* = w; out.* = w;
return abi.OK; return abi.OK;
} }
pub fn commit(handle: ?*n.uhdk_watch, prepared: *anyopaque) void { pub fn commit(handle: ?*n.uhdk_watch, prepared: *anyopaque) void {
const w: *Watch = @ptrCast(@alignCast(prepared)); const w: *Watch = @ptrCast(@alignCast(prepared));
w.next = backend().watches; w.next = backend().watches;
@ -49,15 +58,18 @@ fn allocate(fd: c_int, root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, directory: [
const gpa = backend().app.gpa; const gpa = backend().app.gpa;
const w = try gpa.create(Watch); const w = try gpa.create(Watch);
errdefer gpa.destroy(w); errdefer gpa.destroy(w);
const dir = try gpa.dupe(u8, directory); const dir = try gpa.dupe(u8, directory);
errdefer gpa.free(dir); errdefer gpa.free(dir);
w.* = .{ .fd = fd, .root = root, .handle = handle, .directory = dir, .name = try gpa.dupe(u8, name) }; w.* = .{ .fd = fd, .root = root, .handle = handle, .directory = dir, .name = try gpa.dupe(u8, name) };
return w; return w;
} }
pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void { pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
var w = backend().watches; var w = backend().watches;
while (w) |item| : (w = item.next) if (item.fd >= 0) try fds.append(backend().app.gpa, .{ .fd = item.fd, .events = c.POLLIN, .revents = 0 }); while (w) |item| : (w = item.next) if (item.fd >= 0) try fds.append(backend().app.gpa, .{ .fd = item.fd, .events = c.POLLIN, .revents = 0 });
} }
pub fn flags(mask: u32) u32 { pub fn flags(mask: u32) u32 {
var value: u32 = 0; var value: u32 = 0;
if (mask & (c.IN_CREATE | c.IN_MOVED_TO) != 0) value |= n.UHDK_CHANGE_CREATED; if (mask & (c.IN_CREATE | c.IN_MOVED_TO) != 0) value |= n.UHDK_CHANGE_CREATED;
@ -69,6 +81,7 @@ pub fn flags(mask: u32) u32 {
if (mask & (c.IN_DELETE_SELF | c.IN_MOVE_SELF | c.IN_IGNORED | c.IN_UNMOUNT) != 0) value |= n.UHDK_CHANGE_ROOT_INVALIDATED; if (mask & (c.IN_DELETE_SELF | c.IN_MOVE_SELF | c.IN_IGNORED | c.IN_UNMOUNT) != 0) value |= n.UHDK_CHANGE_ROOT_INVALIDATED;
return value; return value;
} }
fn emit(w: *Watch, changes: u32, name: []const u8, status: u32) void { fn emit(w: *Watch, changes: u32, name: []const u8, status: u32) void {
var file = w.root; var file = w.root;
if (w.name.len == 0 and name.len != 0) { if (w.name.len == 0 and name.len != 0) {
@ -78,16 +91,19 @@ fn emit(w: *Watch, changes: u32, name: []const u8, status: u32) void {
file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = p.ptr, .len = p.len }, null); file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = p.ptr, .len = p.len }, null);
} else file = null; } else file = null;
} }
defer if (file != null and file != w.root) n.uhdk_file_release(file); defer if (file != null and file != w.root) n.uhdk_file_release(file);
var event = std.mem.zeroes(n.z_event); var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_WATCH; event.type = n.UHDK_EVENT_WATCH;
event.data.watch = .{ .watch = w.handle, .flags = changes, .status = status, .file = file }; event.data.watch = .{ .watch = w.handle, .flags = changes, .status = status, .file = file };
n.z_emit(runtime.toAppHandle(backend().app), &event); n.z_emit(runtime.toAppHandle(backend().app), &event);
} }
pub fn tick() void { pub fn tick() void {
var cursor = backend().watches; var cursor = backend().watches;
while (cursor) |w| : (cursor = w.next) { while (cursor) |w| : (cursor = w.next) {
if (w.fd < 0) continue; if (w.fd < 0) continue;
var buffer: [65536]u8 align(@alignOf(c.struct_inotify_event)) = undefined; var buffer: [65536]u8 align(@alignOf(c.struct_inotify_event)) = undefined;
const count = c.z_linux_read(w.fd, &buffer, buffer.len); const count = c.z_linux_read(w.fd, &buffer, buffer.len);
if (count < 0) { if (count < 0) {
@ -96,14 +112,17 @@ pub fn tick() void {
_ = c.close(w.fd); _ = c.close(w.fd);
w.fd = -1; w.fd = -1;
} }
continue; continue;
} }
var offset: usize = 0; var offset: usize = 0;
while (offset + @sizeOf(c.struct_inotify_event) <= @as(usize, @intCast(count))) { while (offset + @sizeOf(c.struct_inotify_event) <= @as(usize, @intCast(count))) {
const event: *const c.struct_inotify_event = @ptrCast(@alignCast(&buffer[offset])); const event: *const c.struct_inotify_event = @ptrCast(@alignCast(&buffer[offset]));
const start = offset + @sizeOf(c.struct_inotify_event); const start = offset + @sizeOf(c.struct_inotify_event);
offset = start + event.len; offset = start + event.len;
if (offset > @as(usize, @intCast(count))) break; if (offset > @as(usize, @intCast(count))) break;
const bytes = buffer[start..offset]; const bytes = buffer[start..offset];
const name = bytes[0 .. std.mem.findScalar(u8, bytes, 0) orelse bytes.len]; const name = bytes[0 .. std.mem.findScalar(u8, bytes, 0) orelse bytes.len];
const changes = flags(event.mask); const changes = flags(event.mask);
@ -117,6 +136,7 @@ pub fn tick() void {
} }
} }
} }
pub fn destroy(w: *Watch) void { pub fn destroy(w: *Watch) void {
var link = &backend().watches; var link = &backend().watches;
while (link.* != w) link = &link.*.?.next; while (link.* != w) link = &link.*.?.next;
@ -126,6 +146,7 @@ pub fn destroy(w: *Watch) void {
backend().app.gpa.free(w.name); backend().app.gpa.free(w.name);
backend().app.gpa.destroy(w); backend().app.gpa.destroy(w);
} }
test "watch replacement is remove/create, overflow and invalidation stay distinct" { test "watch replacement is remove/create, overflow and invalidation stay distinct" {
try std.testing.expectEqual(@as(u32, n.UHDK_CHANGE_CREATED | n.UHDK_CHANGE_RENAMED), flags(c.IN_MOVED_TO)); try std.testing.expectEqual(@as(u32, n.UHDK_CHANGE_CREATED | n.UHDK_CHANGE_RENAMED), flags(c.IN_MOVED_TO));
try std.testing.expectEqual(@as(u32, n.UHDK_CHANGE_RESCAN_REQUIRED), flags(c.IN_Q_OVERFLOW)); try std.testing.expectEqual(@as(u32, n.UHDK_CHANGE_RESCAN_REQUIRED), flags(c.IN_Q_OVERFLOW));

View File

@ -10,6 +10,7 @@ pub const Observation = struct {
suspended: bool = false, suspended: bool = false,
known: u32 = n.UHDK_WINDOW_OBSERVE_RESIZING, known: u32 = n.UHDK_WINDOW_OBSERVE_RESIZING,
}; };
pub fn observe(version: u32, states: []const u32) Observation { pub fn observe(version: u32, states: []const u32) Observation {
var result: Observation = .{}; var result: Observation = .{};
if (version >= 6) result.known |= n.UHDK_WINDOW_OBSERVE_SUSPENDED; if (version >= 6) result.known |= n.UHDK_WINDOW_OBSERVE_SUSPENDED;
@ -25,6 +26,7 @@ pub fn observe(version: u32, states: []const u32) Observation {
}; };
return result; return result;
} }
pub const Capabilities = struct { pub const Capabilities = struct {
// Before v5 there is no advertisement; preserve best-effort requests. // Before v5 there is no advertisement; preserve best-effort requests.
minimize: bool = true, minimize: bool = true,
@ -42,18 +44,22 @@ pub const Capabilities = struct {
return result; return result;
} }
}; };
test "Wayland observations do not invent minimization or occlusion" { test "Wayland observations do not invent minimization or occlusion" {
const old = observe(5, &.{ 1, 2, 3, 4, 9, 999 }); const old = observe(5, &.{ 1, 2, 3, 4, 9, 999 });
try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_FULLSCREEN), old.geometry); try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_FULLSCREEN), old.geometry);
try std.testing.expect(old.focused and old.resizing and !old.suspended); try std.testing.expect(old.focused and old.resizing and !old.suspended);
try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_OBSERVE_RESIZING), old.known); try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_OBSERVE_RESIZING), old.known);
const modern = observe(6, &.{ 9, 2, 1 }); const modern = observe(6, &.{ 9, 2, 1 });
try std.testing.expect(modern.suspended and !modern.resizing); try std.testing.expect(modern.suspended and !modern.resizing);
try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_FULLSCREEN), modern.geometry); try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_FULLSCREEN), modern.geometry);
try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_OBSERVE_RESIZING | n.UHDK_WINDOW_OBSERVE_SUSPENDED), modern.known); try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_OBSERVE_RESIZING | n.UHDK_WINDOW_OBSERVE_SUSPENDED), modern.known);
const resumed = observe(6, &.{}); const resumed = observe(6, &.{});
try std.testing.expect(!resumed.suspended and !resumed.focused and !resumed.resizing); try std.testing.expect(!resumed.suspended and !resumed.focused and !resumed.resizing);
try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_NORMAL), resumed.geometry); try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_NORMAL), resumed.geometry);
const caps = Capabilities.announced(&.{ 2, 999 }); const caps = Capabilities.announced(&.{ 2, 999 });
try std.testing.expect(caps.maximize and !caps.minimize and !caps.fullscreen); try std.testing.expect(caps.maximize and !caps.minimize and !caps.fullscreen);
try std.testing.expect(!Capabilities.announced(&.{}).maximize); try std.testing.expect(!Capabilities.announced(&.{}).maximize);

View File

@ -10,6 +10,7 @@ pub fn configure(b: *std.Build, module: *std.Build.Module, target: std.Build.Res
bindings.addIncludePath(b.path(path)); bindings.addIncludePath(b.path(path));
module.addIncludePath(b.path(path)); module.addIncludePath(b.path(path));
} }
module.addImport("linux_c", bindings.createModule()); module.addImport("linux_c", bindings.createModule());
module.addCSourceFile(.{ .file = b.path("src/linux/libraries.c"), .flags = &.{ "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-fvisibility=hidden" } }); module.addCSourceFile(.{ .file = b.path("src/linux/libraries.c"), .flags = &.{ "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-fvisibility=hidden" } });
for ([_][]const u8{ "wayland", "xdg-shell", "xdg-decoration-unstable-v1", "viewporter", "fractional-scale-v1", "cursor-shape-v1", "tablet-v2", "text-input-unstable-v3", "xdg-activation-v1", "xdg-foreign-unstable-v2", "xdg-toplevel-icon-v1", "appmenu" }) |name| { for ([_][]const u8{ "wayland", "xdg-shell", "xdg-decoration-unstable-v1", "viewporter", "fractional-scale-v1", "cursor-shape-v1", "tablet-v2", "text-input-unstable-v3", "xdg-activation-v1", "xdg-foreign-unstable-v2", "xdg-toplevel-icon-v1", "appmenu" }) |name| {
@ -18,5 +19,6 @@ pub fn configure(b: *std.Build, module: *std.Build.Module, target: std.Build.Res
.flags = &.{ "-std=c99", "-fdata-sections", "-include", b.path("src/linux/protocols/generated/private-symbols.h").getPath(b) }, .flags = &.{ "-std=c99", "-fdata-sections", "-include", b.path("src/linux/protocols/generated/private-symbols.h").getPath(b) },
}); });
} }
module.linkSystemLibrary("dl", .{}); module.linkSystemLibrary("dl", .{});
} }

View File

@ -80,16 +80,20 @@ pub const Backend = struct {
running: bool = true, running: bool = true,
failed: std.atomic.Value(bool) = .init(false), failed: std.atomic.Value(bool) = .init(false),
}; };
pub var instance: ?*Backend = null; pub var instance: ?*Backend = null;
var wake_fd: std.atomic.Value(c_int) = .init(-1); var wake_fd: std.atomic.Value(c_int) = .init(-1);
pub fn backend(handle: ?*n.uhdk_session) u32 { pub fn backend(handle: ?*n.uhdk_session) u32 {
if (handle == null) return n.UHDK_BACKEND_AUTO; if (handle == null) return n.UHDK_BACKEND_AUTO;
const app = runtime.fromAppHandle(handle); const app = runtime.fromAppHandle(handle);
return if (app.native_started) n.UHDK_BACKEND_WAYLAND else n.UHDK_BACKEND_AUTO; return if (app.native_started) n.UHDK_BACKEND_WAYLAND else n.UHDK_BACKEND_AUTO;
} }
pub fn capability(handle: ?*n.uhdk_session, cap: u32) n.uhdk_bool { pub fn capability(handle: ?*n.uhdk_session, cap: u32) n.uhdk_bool {
if (handle == null) return 0; if (handle == null) return 0;
const b = instance orelse return 0; const b = instance orelse return 0;
if (b.app != runtime.fromAppHandle(handle) or !b.app.running or b.failed.load(.acquire)) return 0; if (b.app != runtime.fromAppHandle(handle) or !b.app.running or b.failed.load(.acquire)) return 0;
return @intFromBool(cap < 32 and b.capabilities.load(.acquire) & (@as(u32, 1) << @intCast(cap)) != 0); return @intFromBool(cap < 32 and b.capabilities.load(.acquire) & (@as(u32, 1) << @intCast(cap)) != 0);
@ -105,66 +109,81 @@ export fn z_native_is_main_thread() c_int {
// initial thread. The first session records and enforces its owner thread. // initial thread. The first session records and enforces its owner thread.
return 1; return 1;
} }
export fn z_native_start(handle: ?*n.uhdk_session, _: n.uhdk_text) u32 { export fn z_native_start(handle: ?*n.uhdk_session, _: n.uhdk_text) u32 {
const app = runtime.fromAppHandle(handle); const app = runtime.fromAppHandle(handle);
if (c.z_linux_libraries_open() == 0) return abi.UNAVAILABLE; if (c.z_linux_libraries_open() == 0) return abi.UNAVAILABLE;
const b = app.gpa.create(Backend) catch { const b = app.gpa.create(Backend) catch {
c.z_linux_libraries_close(); c.z_linux_libraries_close();
return abi.OOM; return abi.OOM;
}; };
b.* = .{ .app = app }; b.* = .{ .app = app };
instance = b; instance = b;
Input.initialize(); Input.initialize();
const fd = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK); const fd = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK);
if (fd < 0) { if (fd < 0) {
z_native_finish(); z_native_finish();
return n.UHDK_STATUS_OS_ERROR; return n.UHDK_STATUS_OS_ERROR;
} }
wake_fd.store(fd, .release); wake_fd.store(fd, .release);
b.display = c.z_wl_display_connect.?(null); b.display = c.z_wl_display_connect.?(null);
if (b.display == null) { if (b.display == null) {
z_native_finish(); z_native_finish();
return abi.UNAVAILABLE; return abi.UNAVAILABLE;
} }
b.registry = c.wl_display_get_registry(b.display); b.registry = c.wl_display_get_registry(b.display);
if (b.registry == null) { if (b.registry == null) {
z_native_finish(); z_native_finish();
return abi.OOM; return abi.OOM;
} }
if (c.wl_registry_add_listener(b.registry, &registry_listener, b) != 0 or !initialRegistry(b)) { if (c.wl_registry_add_listener(b.registry, &registry_listener, b) != 0 or !initialRegistry(b)) {
z_native_finish(); z_native_finish();
return n.UHDK_STATUS_OS_ERROR; return n.UHDK_STATUS_OS_ERROR;
} }
if (b.compositor == null or b.shell == null) { if (b.compositor == null or b.shell == null) {
z_native_finish(); z_native_finish();
return n.UHDK_STATUS_UNSUPPORTED; return n.UHDK_STATUS_UNSUPPORTED;
} }
Input.setup(); Input.setup();
if (!initialRegistry(b)) { if (!initialRegistry(b)) {
z_native_finish(); z_native_finish();
return n.UHDK_STATUS_OS_ERROR; return n.UHDK_STATUS_OS_ERROR;
} }
Desktop.initialize(); Desktop.initialize();
Portal.initialize(); Portal.initialize();
Egl.initialize(b); Egl.initialize(b);
setCapability(n.UHDK_CAP_OPENGL, b.egl_display != null); setCapability(n.UHDK_CAP_OPENGL, b.egl_display != null);
return abi.OK; return abi.OK;
} }
// Startup also uses a bounded read/flush/poll handshake: an unresponsive // Startup also uses a bounded read/flush/poll handshake: an unresponsive
// compositor must not trap uhdk_open before returning a session. // compositor must not trap uhdk_open before returning a session.
fn initialRegistry(b: *Backend) bool { fn initialRegistry(b: *Backend) bool {
var done = false; var done = false;
const callback = c.wl_display_sync(b.display) orelse return false; const callback = c.wl_display_sync(b.display) orelse return false;
defer c.wl_callback_destroy(callback); defer c.wl_callback_destroy(callback);
const listener: c.struct_wl_callback_listener = .{ .done = registryDone }; const listener: c.struct_wl_callback_listener = .{ .done = registryDone };
if (c.wl_callback_add_listener(callback, &listener, &done) != 0) return false; if (c.wl_callback_add_listener(callback, &listener, &done) != 0) return false;
const deadline = runtime.now(b.app.io) + 5 * std.time.ns_per_s; const deadline = runtime.now(b.app.io) + 5 * std.time.ns_per_s;
while (!done) { while (!done) {
if (c.z_wl_display_dispatch_pending.?(b.display) < 0) return false; if (c.z_wl_display_dispatch_pending.?(b.display) < 0) return false;
if (done) return true; if (done) return true;
const now = runtime.now(b.app.io); const now = runtime.now(b.app.io);
if (now >= deadline) return false; if (now >= deadline) return false;
if (c.z_wl_display_prepare_read.?(b.display) != 0) continue; if (c.z_wl_display_prepare_read.?(b.display) != 0) continue;
var events: c_short = c.POLLIN; var events: c_short = c.POLLIN;
if (c.z_wl_display_flush.?(b.display) < 0) { if (c.z_wl_display_flush.?(b.display) < 0) {
if (c.z_linux_errno() == c.EAGAIN) events |= c.POLLOUT else { if (c.z_linux_errno() == c.EAGAIN) events |= c.POLLOUT else {
@ -172,6 +191,7 @@ fn initialRegistry(b: *Backend) bool {
return false; return false;
} }
} }
var fd: c.struct_pollfd = .{ .fd = c.z_wl_display_get_fd.?(b.display), .events = events, .revents = 0 }; var fd: c.struct_pollfd = .{ .fd = c.z_wl_display_get_fd.?(b.display), .events = events, .revents = 0 };
const ready = c.z_linux_poll(&fd, 1, @intCast(@min(5000, (deadline - now + std.time.ns_per_ms - 1) / std.time.ns_per_ms))); const ready = c.z_linux_poll(&fd, 1, @intCast(@min(5000, (deadline - now + std.time.ns_per_ms - 1) / std.time.ns_per_ms)));
if (ready > 0 and fd.revents & c.POLLIN != 0) { if (ready > 0 and fd.revents & c.POLLIN != 0) {
@ -180,12 +200,15 @@ fn initialRegistry(b: *Backend) bool {
if (ready < 0 and c.z_linux_errno() != c.EINTR) return false; if (ready < 0 and c.z_linux_errno() != c.EINTR) return false;
if (fd.revents & (c.POLLHUP | c.POLLERR | c.POLLNVAL) != 0) return false; if (fd.revents & (c.POLLHUP | c.POLLERR | c.POLLNVAL) != 0) return false;
} }
return true; return true;
} }
fn registryDone(data: ?*anyopaque, _: ?*c.struct_wl_callback, _: u32) callconv(.c) void { fn registryDone(data: ?*anyopaque, _: ?*c.struct_wl_callback, _: u32) callconv(.c) void {
const done: *bool = @ptrCast(@alignCast(data.?)); const done: *bool = @ptrCast(@alignCast(data.?));
done.* = true; done.* = true;
} }
export fn z_native_finish() void { export fn z_native_finish() void {
const b = instance orelse return; const b = instance orelse return;
std.debug.assert(b.windows == null); std.debug.assert(b.windows == null);
@ -204,24 +227,30 @@ export fn z_native_finish() void {
if (b.compositor != null) c.wl_compositor_destroy(b.compositor); if (b.compositor != null) c.wl_compositor_destroy(b.compositor);
if (b.registry != null) c.wl_registry_destroy(b.registry); if (b.registry != null) c.wl_registry_destroy(b.registry);
if (b.display != null) c.z_wl_display_disconnect.?(b.display); if (b.display != null) c.z_wl_display_disconnect.?(b.display);
const fd = wake_fd.swap(-1, .acq_rel); const fd = wake_fd.swap(-1, .acq_rel);
if (fd >= 0) _ = c.close(fd); if (fd >= 0) _ = c.close(fd);
const gpa = b.app.gpa; const gpa = b.app.gpa;
instance = null; instance = null;
gpa.destroy(b); gpa.destroy(b);
c.z_linux_libraries_close(); c.z_linux_libraries_close();
} }
export fn z_native_wake() void { export fn z_native_wake() void {
const fd = wake_fd.load(.acquire); const fd = wake_fd.load(.acquire);
if (fd < 0) return; if (fd < 0) return;
const one: u64 = 1; const one: u64 = 1;
while (c.z_linux_write(fd, &one, @sizeOf(u64)) < 0) { while (c.z_linux_write(fd, &one, @sizeOf(u64)) < 0) {
if (c.z_linux_errno() != c.EINTR) break; // EAGAIN already means readable. if (c.z_linux_errno() != c.EINTR) break; // EAGAIN already means readable.
} }
} }
export fn z_native_again() void { export fn z_native_again() void {
z_native_wake(); z_native_wake();
} }
fn fail(b: *Backend) void { fn fail(b: *Backend) void {
if (b.failed.swap(true, .acq_rel)) return; if (b.failed.swap(true, .acq_rel)) return;
b.app.lock(); b.app.lock();
@ -232,6 +261,7 @@ fn fail(b: *Backend) void {
Popup.deinit(); Popup.deinit();
runtime.simpleEvent(b.app, n.UHDK_EVENT_QUIT_REQUESTED); runtime.simpleEvent(b.app, n.UHDK_EVENT_QUIT_REQUESTED);
} }
export fn z_native_pump(timeout_ns: u64) void { export fn z_native_pump(timeout_ns: u64) void {
const b = instance orelse return; const b = instance orelse return;
var fds: std.ArrayList(c.struct_pollfd) = .empty; var fds: std.ArrayList(c.struct_pollfd) = .empty;
@ -239,15 +269,20 @@ export fn z_native_pump(timeout_ns: u64) void {
pump: { pump: {
if (!b.failed.load(.acquire) and c.z_wl_display_dispatch_pending.?(b.display) < 0) fail(b); if (!b.failed.load(.acquire) and c.z_wl_display_dispatch_pending.?(b.display) < 0) fail(b);
n.z_dispatch(runtime.toAppHandle(b.app)); n.z_dispatch(runtime.toAppHandle(b.app));
var cursor = b.windows; var cursor = b.windows;
var timeout: c_int = Input.tick(); var timeout: c_int = Input.tick();
Watch.tick(); Watch.tick();
const popup_timeout = Popup.tick(); const popup_timeout = Popup.tick();
if (popup_timeout >= 0) timeout = if (timeout < 0) popup_timeout else @min(timeout, popup_timeout); if (popup_timeout >= 0) timeout = if (timeout < 0) popup_timeout else @min(timeout, popup_timeout);
const desktop_timeout = Desktop.tick(); const desktop_timeout = Desktop.tick();
if (desktop_timeout >= 0) timeout = if (timeout < 0) desktop_timeout else @min(timeout, desktop_timeout); if (desktop_timeout >= 0) timeout = if (timeout < 0) desktop_timeout else @min(timeout, desktop_timeout);
const portal_timeout = Portal.tick(); const portal_timeout = Portal.tick();
if (portal_timeout >= 0) timeout = if (timeout < 0) portal_timeout else @min(timeout, portal_timeout); if (portal_timeout >= 0) timeout = if (timeout < 0) portal_timeout else @min(timeout, portal_timeout);
const data_timeout = Data.tick(); const data_timeout = Data.tick();
if (data_timeout >= 0) timeout = if (timeout < 0) data_timeout else @min(timeout, data_timeout); if (data_timeout >= 0) timeout = if (timeout < 0) data_timeout else @min(timeout, data_timeout);
while (cursor) |w| { while (cursor) |w| {
@ -259,13 +294,16 @@ export fn z_native_pump(timeout_ns: u64) void {
continue; continue;
} }
} }
if (!b.failed.load(.acquire)) apply(w); if (!b.failed.load(.acquire)) apply(w);
} }
if (!b.running) return; if (!b.running) return;
var reading = false; var reading = false;
var display_events: c_short = c.POLLIN; var display_events: c_short = c.POLLIN;
if (!b.failed.load(.acquire)) { if (!b.failed.load(.acquire)) {
if (c.z_wl_display_prepare_read.?(b.display) != 0) break :pump; if (c.z_wl_display_prepare_read.?(b.display) != 0) break :pump;
reading = true; reading = true;
if (c.z_wl_display_flush.?(b.display) < 0) { if (c.z_wl_display_flush.?(b.display) < 0) {
if (c.z_linux_errno() == c.EAGAIN) display_events |= c.POLLOUT else { if (c.z_linux_errno() == c.EAGAIN) display_events |= c.POLLOUT else {
@ -275,6 +313,7 @@ export fn z_native_pump(timeout_ns: u64) void {
} }
} }
} }
fds.clearRetainingCapacity(); fds.clearRetainingCapacity();
fds.appendSlice(b.app.gpa, &.{ fds.appendSlice(b.app.gpa, &.{
.{ .fd = if (reading) c.z_wl_display_get_fd.?(b.display) else -1, .events = display_events, .revents = 0 }, .{ .fd = if (reading) c.z_wl_display_get_fd.?(b.display) else -1, .events = display_events, .revents = 0 },
@ -284,27 +323,33 @@ export fn z_native_pump(timeout_ns: u64) void {
fail(b); fail(b);
break :pump; break :pump;
}; };
Data.poll(&fds) catch { Data.poll(&fds) catch {
if (reading) c.z_wl_display_cancel_read.?(b.display); if (reading) c.z_wl_display_cancel_read.?(b.display);
fail(b); fail(b);
break :pump; break :pump;
}; };
Watch.poll(&fds) catch { Watch.poll(&fds) catch {
if (reading) c.z_wl_display_cancel_read.?(b.display); if (reading) c.z_wl_display_cancel_read.?(b.display);
fail(b); fail(b);
break :pump; break :pump;
}; };
Portal.poll(&fds) catch { Portal.poll(&fds) catch {
if (reading) c.z_wl_display_cancel_read.?(b.display); if (reading) c.z_wl_display_cancel_read.?(b.display);
fail(b); fail(b);
break :pump; break :pump;
}; };
b.app.lock(); b.app.lock();
const queued = (b.app.pending_head != null or b.app.native_error != abi.OK); const queued = (b.app.pending_head != null or b.app.native_error != abi.OK);
b.app.unlock(); b.app.unlock();
const wait_ns: u64 = if (queued) 0 else timeout_ns; 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))); 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); 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); const ready = c.z_linux_poll(fds.items.ptr, fds.items.len, timeout);
if (reading) { if (reading) {
if (ready > 0 and fds.items[0].revents & c.POLLIN != 0) { if (ready > 0 and fds.items[0].revents & c.POLLIN != 0) {
@ -312,6 +357,7 @@ export fn z_native_pump(timeout_ns: u64) void {
c.z_wl_display_dispatch_pending.?(b.display) < 0) fail(b); c.z_wl_display_dispatch_pending.?(b.display) < 0) fail(b);
} else c.z_wl_display_cancel_read.?(b.display); } else c.z_wl_display_cancel_read.?(b.display);
} }
if (ready < 0 and c.z_linux_errno() != c.EINTR) fail(b); if (ready < 0 and c.z_linux_errno() != c.EINTR) fail(b);
if (fds.items[0].revents & (c.POLLERR | c.POLLHUP | c.POLLNVAL) != 0) fail(b); if (fds.items[0].revents & (c.POLLERR | c.POLLHUP | c.POLLNVAL) != 0) fail(b);
if (fds.items[1].revents & c.POLLIN != 0) { if (fds.items[1].revents & c.POLLIN != 0) {
@ -343,54 +389,67 @@ fn registryGlobal(data: ?*anyopaque, registry: ?*c.struct_wl_registry, name: u32
b.fractional = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wp_fractional_scale_manager_v1_interface, 1)); b.fractional = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wp_fractional_scale_manager_v1_interface, 1));
} }
} }
fn registryRemove(_: ?*anyopaque, _: ?*c.struct_wl_registry, name: u32) callconv(.c) void { fn registryRemove(_: ?*anyopaque, _: ?*c.struct_wl_registry, name: u32) callconv(.c) void {
Input.remove(name); Input.remove(name);
KdeAppMenu.remove(name); KdeAppMenu.remove(name);
} }
const registry_listener: c.struct_wl_registry_listener = .{ .global = registryGlobal, .global_remove = registryRemove }; const registry_listener: c.struct_wl_registry_listener = .{ .global = registryGlobal, .global_remove = registryRemove };
fn ping(_: ?*anyopaque, shell: ?*c.struct_xdg_wm_base, serial: u32) callconv(.c) void { fn ping(_: ?*anyopaque, shell: ?*c.struct_xdg_wm_base, serial: u32) callconv(.c) void {
c.xdg_wm_base_pong(shell, serial); c.xdg_wm_base_pong(shell, serial);
} }
const shell_listener: c.struct_xdg_wm_base_listener = .{ .ping = ping }; const shell_listener: c.struct_xdg_wm_base_listener = .{ .ping = ping };
fn window(data: ?*anyopaque) *Window { fn window(data: ?*anyopaque) *Window {
return @ptrCast(@alignCast(data.?)); return @ptrCast(@alignCast(data.?));
} }
fn configure(data: ?*anyopaque, _: ?*c.struct_xdg_surface, serial: u32) callconv(.c) void { fn configure(data: ?*anyopaque, _: ?*c.struct_xdg_surface, serial: u32) callconv(.c) void {
const w = window(data); const w = window(data);
w.serial = serial; w.serial = serial;
w.dirty = true; w.dirty = true;
} }
const surface_listener: c.struct_xdg_surface_listener = .{ .configure = configure }; const surface_listener: c.struct_xdg_surface_listener = .{ .configure = configure };
fn topConfigure(data: ?*anyopaque, _: ?*c.struct_xdg_toplevel, width: i32, height: i32, states: [*c]c.struct_wl_array) callconv(.c) void { fn topConfigure(data: ?*anyopaque, _: ?*c.struct_xdg_toplevel, width: i32, height: i32, states: [*c]c.struct_wl_array) callconv(.c) void {
const w = window(data); const w = window(data);
if (width > 0) w.width = width; if (width > 0) w.width = width;
if (height > 0) w.height = height; if (height > 0) w.height = height;
const values: []const u32 = if (states.*.size == 0) &.{} else @as([*]const u32, @ptrCast(@alignCast(states.*.data)))[0 .. states.*.size / @sizeOf(u32)]; const values: []const u32 = if (states.*.size == 0) &.{} else @as([*]const u32, @ptrCast(@alignCast(states.*.data)))[0 .. states.*.size / @sizeOf(u32)];
w.observation = WindowState.observe(c.xdg_toplevel_get_version(w.top), values); w.observation = WindowState.observe(c.xdg_toplevel_get_version(w.top), values);
w.focused = w.observation.focused; w.focused = w.observation.focused;
w.state = w.observation.geometry; w.state = w.observation.geometry;
} }
fn emit(w: *Window, kind: u32) void { fn emit(w: *Window, kind: u32) void {
var event = std.mem.zeroes(n.z_event); var event = std.mem.zeroes(n.z_event);
event.type = kind; event.type = kind;
event.window = w.handle; event.window = w.handle;
n.z_emit(runtime.toAppHandle(w.owner), &event); n.z_emit(runtime.toAppHandle(w.owner), &event);
} }
fn topClose(data: ?*anyopaque, _: ?*c.struct_xdg_toplevel) callconv(.c) void { fn topClose(data: ?*anyopaque, _: ?*c.struct_xdg_toplevel) callconv(.c) void {
emit(window(data), n.UHDK_EVENT_WINDOW_CLOSE_REQUESTED); emit(window(data), n.UHDK_EVENT_WINDOW_CLOSE_REQUESTED);
} }
fn bounds(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel, _: i32, _: i32) callconv(.c) void {} fn bounds(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel, _: i32, _: i32) callconv(.c) void {}
fn wmCaps(data: ?*anyopaque, _: ?*c.struct_xdg_toplevel, caps: [*c]c.struct_wl_array) callconv(.c) void { fn wmCaps(data: ?*anyopaque, _: ?*c.struct_xdg_toplevel, caps: [*c]c.struct_wl_array) callconv(.c) void {
const values: []const u32 = if (caps.*.size == 0) &.{} else @as([*]const u32, @ptrCast(@alignCast(caps.*.data)))[0 .. caps.*.size / @sizeOf(u32)]; const values: []const u32 = if (caps.*.size == 0) &.{} else @as([*]const u32, @ptrCast(@alignCast(caps.*.data)))[0 .. caps.*.size / @sizeOf(u32)];
window(data).wm_caps = WindowState.Capabilities.announced(values); window(data).wm_caps = WindowState.Capabilities.announced(values);
} }
const top_listener: c.struct_xdg_toplevel_listener = .{ .configure = topConfigure, .close = topClose, .configure_bounds = bounds, .wm_capabilities = wmCaps }; const top_listener: c.struct_xdg_toplevel_listener = .{ .configure = topConfigure, .close = topClose, .configure_bounds = bounds, .wm_capabilities = wmCaps };
fn decorationConfigure(data: ?*anyopaque, _: ?*c.struct_zxdg_toplevel_decoration_v1, mode: u32) callconv(.c) void { fn decorationConfigure(data: ?*anyopaque, _: ?*c.struct_zxdg_toplevel_decoration_v1, mode: u32) callconv(.c) void {
const w = window(data); const w = window(data);
// Until the client-decoration adapter exists, don't silently create a // Until the client-decoration adapter exists, don't silently create a
// decorated window with no title bar on compositors that decline SSD. // decorated window with no title bar on compositors that decline SSD.
if (mode != c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE and w.style.decorated != 0 and w.request != 0) completeCreation(w, n.UHDK_STATUS_UNSUPPORTED); if (mode != c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE and w.style.decorated != 0 and w.request != 0) completeCreation(w, n.UHDK_STATUS_UNSUPPORTED);
} }
const decoration_listener: c.struct_zxdg_toplevel_decoration_v1_listener = .{ .configure = decorationConfigure }; const decoration_listener: c.struct_zxdg_toplevel_decoration_v1_listener = .{ .configure = decorationConfigure };
fn fraction(data: ?*anyopaque, _: ?*c.struct_wp_fractional_scale_v1, scale: u32) callconv(.c) void { fn fraction(data: ?*anyopaque, _: ?*c.struct_wp_fractional_scale_v1, scale: u32) callconv(.c) void {
const w = window(data); const w = window(data);
@ -398,8 +457,10 @@ fn fraction(data: ?*anyopaque, _: ?*c.struct_wp_fractional_scale_v1, scale: u32)
w.scale = scale; w.scale = scale;
w.dirty = true; w.dirty = true;
} }
const fraction_listener: c.struct_wp_fractional_scale_v1_listener = .{ .preferred_scale = fraction }; const fraction_listener: c.struct_wp_fractional_scale_v1_listener = .{ .preferred_scale = fraction };
fn enter(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: ?*c.struct_wl_output) callconv(.c) void {} fn enter(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: ?*c.struct_wl_output) callconv(.c) void {}
fn bufferScale(data: ?*anyopaque, _: ?*c.struct_wl_surface, scale: i32) callconv(.c) void { fn bufferScale(data: ?*anyopaque, _: ?*c.struct_wl_surface, scale: i32) callconv(.c) void {
const w = window(data); const w = window(data);
if (w.fractional == null and scale > 0 and scale <= 16) { if (w.fractional == null and scale > 0 and scale <= 16) {
@ -407,6 +468,7 @@ fn bufferScale(data: ?*anyopaque, _: ?*c.struct_wl_surface, scale: i32) callconv
w.dirty = true; w.dirty = true;
} }
} }
fn bufferTransform(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: u32) callconv(.c) void {} fn bufferTransform(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: u32) callconv(.c) void {}
const wl_surface_listener: c.struct_wl_surface_listener = .{ .enter = enter, .leave = enter, .preferred_buffer_scale = bufferScale, .preferred_buffer_transform = bufferTransform }; const wl_surface_listener: c.struct_wl_surface_listener = .{ .enter = enter, .leave = enter, .preferred_buffer_scale = bufferScale, .preferred_buffer_transform = bufferTransform };
@ -414,16 +476,19 @@ fn completeCreation(w: *Window, status: u32) void {
const id = w.request; const id = w.request;
if (id == 0) return; if (id == 0) return;
w.request = 0; w.request = 0;
const app = runtime.toAppHandle(w.owner); const app = runtime.toAppHandle(w.owner);
if (status != abi.OK) { if (status != abi.OK) {
n.z_object_set_native(w.handle, null); n.z_object_set_native(w.handle, null);
destroyWindow(w); destroyWindow(w);
} }
n.z_complete(app, id, status, null); n.z_complete(app, id, status, null);
} }
fn apply(w: *Window) void { fn apply(w: *Window) void {
if (!w.dirty or !w.mutex.tryLock()) return; if (!w.dirty or !w.mutex.tryLock()) return;
// Never block the display dispatcher behind eglSwapBuffers, which itself // Never block the display dispatcher behind eglSwapBuffers, which itself
// may be waiting for the dispatcher. end_frame wakes us to retry. // may be waiting for the dispatcher. end_frame wakes us to retry.
if (w.serial) |serial| { if (w.serial) |serial| {
@ -431,10 +496,12 @@ fn apply(w: *Window) void {
w.serial = null; w.serial = null;
w.configured = true; w.configured = true;
} }
if (!w.configured) { if (!w.configured) {
w.mutex.unlock(w.owner.io); w.mutex.unlock(w.owner.io);
return; return;
} }
const width = @min(w.width, 65536); const width = @min(w.width, 65536);
const height = @min(w.height, 65536); const height = @min(w.height, 65536);
const pixel_width: u32 = @intCast(@divTrunc(@as(i64, width) * w.scale + 119, 120)); const pixel_width: u32 = @intCast(@divTrunc(@as(i64, width) * w.scale + 119, 120));
@ -451,8 +518,10 @@ fn apply(w: *Window) void {
c.wl_surface_commit(w.surface); c.wl_surface_commit(w.surface);
w.configured = false; w.configured = false;
} }
w.visible = w.want_visible; w.visible = w.want_visible;
w.metrics = .{ .struct_size = @sizeOf(n.uhdk_window_metrics), .framebuffer_width = pixel_width, .framebuffer_height = pixel_height, .logical_size = .{ .width = @floatFromInt(width), .height = @floatFromInt(height) }, .scale = @as(f32, @floatFromInt(w.scale)) / 120, .state = w.state, .focused = @intFromBool(w.focused), .visible = @intFromBool(w.visible), .observations = w.observation.known, .resizing = @intFromBool(w.observation.resizing), .suspended = @intFromBool(w.observation.suspended), .minimized = 0, .occluded = 0 }; w.metrics = .{ .struct_size = @sizeOf(n.uhdk_window_metrics), .framebuffer_width = pixel_width, .framebuffer_height = pixel_height, .logical_size = .{ .width = @floatFromInt(width), .height = @floatFromInt(height) }, .scale = @as(f32, @floatFromInt(w.scale)) / 120, .state = w.state, .focused = @intFromBool(w.focused), .visible = @intFromBool(w.visible), .observations = w.observation.known, .resizing = @intFromBool(w.observation.resizing), .suspended = @intFromBool(w.observation.suspended), .minimized = 0, .occluded = 0 };
const metrics = w.metrics; const metrics = w.metrics;
w.dirty = false; w.dirty = false;
w.mutex.unlock(w.owner.io); w.mutex.unlock(w.owner.io);
@ -464,32 +533,40 @@ fn apply(w: *Window) void {
fn createWindow(b: *Backend, command: *const n.z_command, id: u64) u32 { fn createWindow(b: *Backend, command: *const n.z_command, id: u64) u32 {
const desc = command.window; const desc = command.window;
if (desc.style.decorated != 0 and b.decorations == null) return n.UHDK_STATUS_UNSUPPORTED; if (desc.style.decorated != 0 and b.decorations == null) return n.UHDK_STATUS_UNSUPPORTED;
const w = b.app.gpa.create(Window) catch return abi.OOM; const w = b.app.gpa.create(Window) catch return abi.OOM;
w.* = .{ .owner = b.app, .handle = @ptrCast(command.target), .width = @intFromFloat(@max(1, desc.content_size.width)), .height = @intFromFloat(@max(1, desc.content_size.height)), .min_width = @intFromFloat(desc.min_size.width), .min_height = @intFromFloat(desc.min_size.height), .max_width = @intFromFloat(desc.max_size.width), .max_height = @intFromFloat(desc.max_size.height), .flags = desc.flags, .style = desc.style }; w.* = .{ .owner = b.app, .handle = @ptrCast(command.target), .width = @intFromFloat(@max(1, desc.content_size.width)), .height = @intFromFloat(@max(1, desc.content_size.height)), .min_width = @intFromFloat(desc.min_size.width), .min_height = @intFromFloat(desc.min_size.height), .max_width = @intFromFloat(desc.max_size.width), .max_height = @intFromFloat(desc.max_size.height), .flags = desc.flags, .style = desc.style };
w.next = b.windows; w.next = b.windows;
b.windows = w; b.windows = w;
const status = setupWindow(b, w, desc); const status = setupWindow(b, w, desc);
if (status != abi.OK) { if (status != abi.OK) {
destroyWindow(w); destroyWindow(w);
return status; return status;
} }
n.z_object_set_native(command.target, w); n.z_object_set_native(command.target, w);
w.request = id; w.request = id;
w.deadline = runtime.now(b.app.io) + 5 * std.time.ns_per_s; w.deadline = runtime.now(b.app.io) + 5 * std.time.ns_per_s;
c.wl_surface_commit(w.surface); // Empty initial commit; wait for configure. c.wl_surface_commit(w.surface); // Empty initial commit; wait for configure.
return n.Z_DEFERRED; return n.Z_DEFERRED;
} }
fn setupWindow(b: *Backend, w: *Window, desc: n.z_window_desc) u32 { fn setupWindow(b: *Backend, w: *Window, desc: n.z_window_desc) u32 {
const title = b.app.gpa.dupeZ(u8, abi.textBytes(desc.title)) catch return abi.OOM; const title = b.app.gpa.dupeZ(u8, abi.textBytes(desc.title)) catch return abi.OOM;
defer b.app.gpa.free(title); defer b.app.gpa.free(title);
const app_id = b.app.gpa.dupeZ(u8, b.app.application_id) catch return abi.OOM; const app_id = b.app.gpa.dupeZ(u8, b.app.application_id) catch return abi.OOM;
defer b.app.gpa.free(app_id); defer b.app.gpa.free(app_id);
w.surface = c.wl_compositor_create_surface(b.compositor) orelse return abi.OOM; w.surface = c.wl_compositor_create_surface(b.compositor) orelse return abi.OOM;
if (c.wl_surface_add_listener(w.surface, &wl_surface_listener, w) != 0) return abi.OOM; if (c.wl_surface_add_listener(w.surface, &wl_surface_listener, w) != 0) return abi.OOM;
w.xdg = c.xdg_wm_base_get_xdg_surface(b.shell, w.surface) orelse return abi.OOM; w.xdg = c.xdg_wm_base_get_xdg_surface(b.shell, w.surface) orelse return abi.OOM;
if (c.xdg_surface_add_listener(w.xdg, &surface_listener, w) != 0) return abi.OOM; if (c.xdg_surface_add_listener(w.xdg, &surface_listener, w) != 0) return abi.OOM;
w.top = c.xdg_surface_get_toplevel(w.xdg) orelse return abi.OOM; w.top = c.xdg_surface_get_toplevel(w.xdg) orelse return abi.OOM;
if (c.xdg_toplevel_add_listener(w.top, &top_listener, w) != 0) return abi.OOM; if (c.xdg_toplevel_add_listener(w.top, &top_listener, w) != 0) return abi.OOM;
c.xdg_toplevel_set_title(w.top, title); c.xdg_toplevel_set_title(w.top, title);
c.xdg_toplevel_set_app_id(w.top, app_id); c.xdg_toplevel_set_app_id(w.top, app_id);
Desktop.applyIcon(w); Desktop.applyIcon(w);
@ -498,23 +575,29 @@ fn setupWindow(b: *Backend, w: *Window, desc: n.z_window_desc) u32 {
const p: *Window = @ptrCast(@alignCast(n.z_object_native(parent) orelse return abi.UNAVAILABLE)); const p: *Window = @ptrCast(@alignCast(n.z_object_native(parent) orelse return abi.UNAVAILABLE));
c.xdg_toplevel_set_parent(w.top, p.top); c.xdg_toplevel_set_parent(w.top, p.top);
} }
if (w.style.resizable != 0) { if (w.style.resizable != 0) {
w.width = std.math.clamp(w.width, @max(1, w.min_width), if (w.max_width == 0) 65536 else w.max_width); w.width = std.math.clamp(w.width, @max(1, w.min_width), if (w.max_width == 0) 65536 else w.max_width);
w.height = std.math.clamp(w.height, @max(1, w.min_height), if (w.max_height == 0) 65536 else w.max_height); w.height = std.math.clamp(w.height, @max(1, w.min_height), if (w.max_height == 0) 65536 else w.max_height);
} }
setLimits(w); setLimits(w);
if (w.style.decorated != 0) { if (w.style.decorated != 0) {
w.decoration = c.zxdg_decoration_manager_v1_get_toplevel_decoration(b.decorations, w.top) orelse return abi.OOM; w.decoration = c.zxdg_decoration_manager_v1_get_toplevel_decoration(b.decorations, w.top) orelse return abi.OOM;
if (c.zxdg_toplevel_decoration_v1_add_listener(w.decoration, &decoration_listener, w) != 0) return abi.OOM; if (c.zxdg_toplevel_decoration_v1_add_listener(w.decoration, &decoration_listener, w) != 0) return abi.OOM;
c.zxdg_toplevel_decoration_v1_set_mode(w.decoration, c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE); c.zxdg_toplevel_decoration_v1_set_mode(w.decoration, c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
} }
if (b.fractional != null and b.viewporter != null) { if (b.fractional != null and b.viewporter != null) {
w.viewport = c.wp_viewporter_get_viewport(b.viewporter, w.surface) orelse return abi.OOM; w.viewport = c.wp_viewporter_get_viewport(b.viewporter, w.surface) orelse return abi.OOM;
w.fractional = c.wp_fractional_scale_manager_v1_get_fractional_scale(b.fractional, w.surface) orelse return abi.OOM; w.fractional = c.wp_fractional_scale_manager_v1_get_fractional_scale(b.fractional, w.surface) orelse return abi.OOM;
if (c.wp_fractional_scale_v1_add_listener(w.fractional, &fraction_listener, w) != 0) return abi.OOM; if (c.wp_fractional_scale_v1_add_listener(w.fractional, &fraction_listener, w) != 0) return abi.OOM;
} }
return abi.OK; return abi.OK;
} }
fn setLimits(w: *Window) void { fn setLimits(w: *Window) void {
if (w.style.resizable != 0) { if (w.style.resizable != 0) {
c.xdg_toplevel_set_min_size(w.top, w.min_width, w.min_height); c.xdg_toplevel_set_min_size(w.top, w.min_width, w.min_height);
@ -536,14 +619,17 @@ fn setStyle(b: *Backend, w: *Window, style: n.uhdk_window_style) u32 {
return abi.OOM; return abi.OOM;
} }
} }
c.zxdg_toplevel_decoration_v1_set_mode(w.decoration, c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE); c.zxdg_toplevel_decoration_v1_set_mode(w.decoration, c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
} else if (w.decoration != null) { } else if (w.decoration != null) {
c.zxdg_toplevel_decoration_v1_set_mode(w.decoration, c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE); c.zxdg_toplevel_decoration_v1_set_mode(w.decoration, c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE);
} }
w.style = style; w.style = style;
setLimits(w); setLimits(w);
return abi.OK; return abi.OK;
} }
fn destroyWindow(w: *Window) void { fn destroyWindow(w: *Window) void {
const b = instance.?; const b = instance.?;
std.debug.assert(w.egl == null); std.debug.assert(w.egl == null);
@ -553,14 +639,17 @@ fn destroyWindow(w: *Window) void {
Data.forget(w); Data.forget(w);
Input.forget(w); Input.forget(w);
Text.deinit(w); Text.deinit(w);
var link = &b.windows; var link = &b.windows;
while (link.*) |item| { while (link.*) |item| {
if (item == w) { if (item == w) {
link.* = item.next; link.* = item.next;
break; break;
} }
link = &item.next; link = &item.next;
} }
if (w.fractional != null) c.wp_fractional_scale_v1_destroy(w.fractional); if (w.fractional != null) c.wp_fractional_scale_v1_destroy(w.fractional);
if (w.viewport != null) c.wp_viewport_destroy(w.viewport); if (w.viewport != null) c.wp_viewport_destroy(w.viewport);
if (w.decoration != null) c.zxdg_toplevel_decoration_v1_destroy(w.decoration); if (w.decoration != null) c.zxdg_toplevel_decoration_v1_destroy(w.decoration);
@ -569,6 +658,7 @@ fn destroyWindow(w: *Window) void {
if (w.surface != null) c.wl_surface_destroy(w.surface); if (w.surface != null) c.wl_surface_destroy(w.surface);
w.owner.gpa.destroy(w); w.owner.gpa.destroy(w);
} }
export fn z_native_execute(_: ?*n.uhdk_session, raw: [*c]const n.z_command, id: u64, _: [*c]n.z_request_result) u32 { export fn z_native_execute(_: ?*n.uhdk_session, raw: [*c]const n.z_command, id: u64, _: [*c]n.z_request_result) u32 {
const b = instance.?; const b = instance.?;
const cmd: *const n.z_command = &raw.*; const cmd: *const n.z_command = &raw.*;
@ -577,8 +667,10 @@ export fn z_native_execute(_: ?*n.uhdk_session, raw: [*c]const n.z_command, id:
z_native_destroy(n.z_object_kind(cmd.target), ptr); z_native_destroy(n.z_object_kind(cmd.target), ptr);
n.z_object_set_native(cmd.target, null); n.z_object_set_native(cmd.target, null);
} }
return abi.OK; return abi.OK;
} }
if (b.failed.load(.acquire)) return abi.UNAVAILABLE; if (b.failed.load(.acquire)) return abi.UNAVAILABLE;
if (cmd.op == n.Z_WINDOW) return createWindow(b, cmd, id); if (cmd.op == n.Z_WINDOW) return createWindow(b, cmd, id);
if (cmd.op == n.Z_APP_MENU) return KdeAppMenu.attach(null, cmd.other); if (cmd.op == n.Z_APP_MENU) return KdeAppMenu.attach(null, cmd.other);
@ -586,11 +678,13 @@ export fn z_native_execute(_: ?*n.uhdk_session, raw: [*c]const n.z_command, id:
Popup.flags(); Popup.flags();
return KdeAppMenu.updateFlags(); return KdeAppMenu.updateFlags();
} }
if (cmd.op == n.Z_POPUP) return Popup.request(cmd, id); 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_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_DIALOG or cmd.op == n.Z_URL) return Portal.request(cmd, id);
if (cmd.op == n.Z_CLIP_WRITE) return Data.write(cmd.text); 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); 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; const ptr = if (cmd.target != null) n.z_object_native(cmd.target) else null;
const w: *Window = if (ptr) |p| @ptrCast(@alignCast(p)) else return n.UHDK_STATUS_UNSUPPORTED; const w: *Window = if (ptr) |p| @ptrCast(@alignCast(p)) else return n.UHDK_STATUS_UNSUPPORTED;
switch (cmd.op) { switch (cmd.op) {
@ -602,18 +696,21 @@ export fn z_native_execute(_: ?*n.uhdk_session, raw: [*c]const n.z_command, id:
}, },
n.Z_SIZE => { n.Z_SIZE => {
if (w.state != n.UHDK_WINDOW_NORMAL) return abi.UNAVAILABLE; if (w.state != n.UHDK_WINDOW_NORMAL) return abi.UNAVAILABLE;
w.width = @intFromFloat(@max(1, cmd.size.width)); w.width = @intFromFloat(@max(1, cmd.size.width));
w.height = @intFromFloat(@max(1, cmd.size.height)); w.height = @intFromFloat(@max(1, cmd.size.height));
if (w.style.resizable != 0) { if (w.style.resizable != 0) {
w.width = std.math.clamp(w.width, @max(1, w.min_width), if (w.max_width == 0) 65536 else w.max_width); w.width = std.math.clamp(w.width, @max(1, w.min_width), if (w.max_width == 0) 65536 else w.max_width);
w.height = std.math.clamp(w.height, @max(1, w.min_height), if (w.max_height == 0) 65536 else w.max_height); w.height = std.math.clamp(w.height, @max(1, w.min_height), if (w.max_height == 0) 65536 else w.max_height);
} }
if (w.style.resizable == 0) setLimits(w); if (w.style.resizable == 0) setLimits(w);
w.dirty = true; w.dirty = true;
}, },
n.Z_STATE => switch (cmd.number) { n.Z_STATE => switch (cmd.number) {
n.UHDK_WINDOW_MINIMIZED => { n.UHDK_WINDOW_MINIMIZED => {
if (!w.wm_caps.minimize) return n.UHDK_STATUS_UNSUPPORTED; if (!w.wm_caps.minimize) return n.UHDK_STATUS_UNSUPPORTED;
c.xdg_toplevel_set_minimized(w.top); c.xdg_toplevel_set_minimized(w.top);
}, },
n.UHDK_WINDOW_MAXIMIZED => { n.UHDK_WINDOW_MAXIMIZED => {
@ -623,6 +720,7 @@ export fn z_native_execute(_: ?*n.uhdk_session, raw: [*c]const n.z_command, id:
}, },
n.UHDK_WINDOW_FULLSCREEN => { n.UHDK_WINDOW_FULLSCREEN => {
if (!w.wm_caps.fullscreen) return n.UHDK_STATUS_UNSUPPORTED; if (!w.wm_caps.fullscreen) return n.UHDK_STATUS_UNSUPPORTED;
c.xdg_toplevel_set_fullscreen(w.top, null); c.xdg_toplevel_set_fullscreen(w.top, null);
}, },
else => { else => {
@ -636,6 +734,7 @@ export fn z_native_execute(_: ?*n.uhdk_session, raw: [*c]const n.z_command, id:
Popup.forget(w); Popup.forget(w);
Input.clearPopupTrigger(w); Input.clearPopupTrigger(w);
} }
if (w.want_visible and !w.configured) c.wl_surface_commit(w.surface); if (w.want_visible and !w.configured) c.wl_surface_commit(w.surface);
w.dirty = true; w.dirty = true;
}, },
@ -651,11 +750,14 @@ export fn z_native_execute(_: ?*n.uhdk_session, raw: [*c]const n.z_command, id:
n.Z_GL => return Egl.create(b, w), n.Z_GL => return Egl.create(b, w),
else => return n.UHDK_STATUS_UNSUPPORTED, else => return n.UHDK_STATUS_UNSUPPORTED,
} }
return abi.OK; return abi.OK;
} }
export fn z_native_cancel(id: u64) void { export fn z_native_cancel(id: u64) void {
const b = instance orelse return; const b = instance orelse return;
if (Popup.cancel(id) or Data.cancel(id) or Portal.cancel(id) or Desktop.cancel(id)) return; if (Popup.cancel(id) or Data.cancel(id) or Portal.cancel(id) or Desktop.cancel(id)) return;
var cursor = b.windows; var cursor = b.windows;
while (cursor) |w| : (cursor = w.next) { while (cursor) |w| : (cursor = w.next) {
if (w.request == id) { if (w.request == id) {
@ -664,6 +766,7 @@ export fn z_native_cancel(id: u64) void {
} }
} }
} }
export fn z_native_destroy(kind: u32, ptr: ?*anyopaque) void { export fn z_native_destroy(kind: u32, ptr: ?*anyopaque) void {
const p = ptr orelse return; const p = ptr orelse return;
switch (kind) { switch (kind) {
@ -679,19 +782,24 @@ export fn z_native_destroy(kind: u32, ptr: ?*anyopaque) void {
else => {}, else => {},
} }
} }
export fn z_native_handles(ptr: ?*anyopaque, out: [*c]n.uhdk_native_window) void { export fn z_native_handles(ptr: ?*anyopaque, out: [*c]n.uhdk_native_window) void {
const w: *Window = @ptrCast(@alignCast(ptr.?)); const w: *Window = @ptrCast(@alignCast(ptr.?));
out.* = .{ .struct_size = @sizeOf(n.uhdk_native_window), .backend = n.UHDK_BACKEND_WAYLAND, .primary = instance.?.display, .secondary = w.surface, .value = 0 }; out.* = .{ .struct_size = @sizeOf(n.uhdk_native_window), .backend = n.UHDK_BACKEND_WAYLAND, .primary = instance.?.display, .secondary = w.surface, .value = 0 };
} }
export fn z_native_gl(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 { export fn z_native_gl(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 {
if (op == 4) return Egl.call(null, op, out); if (op == 4) return Egl.call(null, op, out);
const w: *Window = @ptrCast(@alignCast(ptr orelse return abi.INVALID)); const w: *Window = @ptrCast(@alignCast(ptr orelse return abi.INVALID));
return Egl.call(w.egl, op, out); return Egl.call(w.egl, op, out);
} }
export fn z_native_gl_proc(ptr: ?*anyopaque, name: n.uhdk_text, out: [*c]n.uhdk_gl_proc) u32 { export fn z_native_gl_proc(ptr: ?*anyopaque, name: n.uhdk_text, out: [*c]n.uhdk_gl_proc) u32 {
const w: *Window = @ptrCast(@alignCast(ptr orelse return abi.INVALID)); const w: *Window = @ptrCast(@alignCast(ptr orelse return abi.INVALID));
return Egl.proc(w.egl, name, out); return Egl.proc(w.egl, name, out);
} }
export fn z_native_file_init(file: ?*n.uhdk_file, path: n.uhdk_bytes, uri: n.uhdk_text, grant: ?*anyopaque) u32 { 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); return @import("Files.zig").init(file, path, uri, grant);
} }
@ -699,6 +807,7 @@ export fn z_native_file_init(file: ?*n.uhdk_file, path: n.uhdk_bytes, uri: n.uhd
export fn z_native_watch_prepare(root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, out: *?*anyopaque) u32 { export fn z_native_watch_prepare(root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, out: *?*anyopaque) u32 {
return Watch.prepare(root, handle, out); return Watch.prepare(root, handle, out);
} }
export fn z_native_watch_commit(handle: ?*n.uhdk_watch, prepared: *anyopaque) void { export fn z_native_watch_commit(handle: ?*n.uhdk_watch, prepared: *anyopaque) void {
Watch.commit(handle, prepared); Watch.commit(handle, prepared);
} }

View File

@ -72,20 +72,24 @@ pub fn release(object: *Resource) void {
application.unlock(); application.unlock();
return; return;
} }
var link = &application.objects; var link = &application.objects;
while (link.*) |resource| { while (link.*) |resource| {
if (resource == object) { if (resource == object) {
link.* = resource.next; link.* = resource.next;
break; break;
} }
link = &resource.next; link = &resource.next;
} }
application.unlock(); application.unlock();
if (object.payload == .menu and object.payload.menu.owns_submenus) { if (object.payload == .menu and object.payload.menu.owns_submenus) {
for (object.payload.menu.items) |item| { for (object.payload.menu.items) |item| {
if (item.submenu) |submenu| release(fromObjectHandle(submenu)); if (item.submenu) |submenu| release(fromObjectHandle(submenu));
} }
} }
if (object.native) |native| c.z_native_destroy(object.kind(), native); if (object.native) |native| c.z_native_destroy(object.kind(), native);
const gpa = object.gpa; const gpa = object.gpa;
object.arena.deinit(); object.arena.deinit();
@ -128,6 +132,7 @@ pub fn cloneFiles(node: *Event, files: c.uhdk_file_list) !c.uhdk_file_list {
f.* = files.ptr[i]; f.* = files.ptr[i];
try pin(&node.pins, fromObjectHandle(f.*)); try pin(&node.pins, fromObjectHandle(f.*));
} }
return .{ .ptr = out.ptr, .len = out.len }; return .{ .ptr = out.ptr, .len = out.len };
} }
@ -165,6 +170,7 @@ pub fn createCommand(application: *Application, op: u32, target: ?*Resource) !*R
const node = try application.gpa.create(Event); const node = try application.gpa.create(Event);
node.* = .{ .gpa = application.gpa, .arena = .init(application.gpa) }; node.* = .{ .gpa = application.gpa, .arena = .init(application.gpa) };
errdefer destroyEvent(node); errdefer destroyEvent(node);
const command = try application.gpa.create(Request); const command = try application.gpa.create(Request);
command.* = .{ .node = node, .gpa = application.gpa, .arena = .init(application.gpa) }; command.* = .{ .node = node, .gpa = application.gpa, .arena = .init(application.gpa) };
errdefer command.gpa.destroy(command); errdefer command.gpa.destroy(command);
@ -213,12 +219,14 @@ pub fn submit(application: *Application, command: *Request, tag: u64) abi.Status
abandon(command); abandon(command);
return status; return status;
} }
application.lock(); application.lock();
if (application.stopping or application.next_id == std.math.maxInt(u64)) { if (application.stopping or application.next_id == std.math.maxInt(u64)) {
application.unlock(); application.unlock();
abandon(command); abandon(command);
return abi.UNAVAILABLE; return abi.UNAVAILABLE;
} }
if (command.completion == .request) { if (command.completion == .request) {
var request = application.requests; var request = application.requests;
while (request) |pending| : (request = pending.next) { while (request) |pending| : (request = pending.next) {
@ -228,6 +236,7 @@ pub fn submit(application: *Application, command: *Request, tag: u64) abi.Status
return c.UHDK_STATUS_BUSY; return c.UHDK_STATUS_BUSY;
} }
} }
// A finished request still owns its tag until its event is delivered. // A finished request still owns its tag until its event is delivered.
var event = application.pending_head; var event = application.pending_head;
while (event) |pending| : (event = pending.next) { while (event) |pending| : (event = pending.next) {
@ -238,11 +247,13 @@ pub fn submit(application: *Application, command: *Request, tag: u64) abi.Status
} }
} }
} }
if ((command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) and application.io_pending >= 64) { if ((command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) and application.io_pending >= 64) {
application.unlock(); application.unlock();
abandon(command); abandon(command);
return c.UHDK_STATUS_BUSY; return c.UHDK_STATUS_BUSY;
} }
if (command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) application.io_pending += 1; if (command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) application.io_pending += 1;
command.id = application.next_id; command.id = application.next_id;
application.next_id += 1; application.next_id += 1;
@ -274,6 +285,7 @@ pub fn notifyCommand(object: *Resource, op: u32) void {
object.app.unlock(); object.app.unlock();
return; return;
}; };
object.app.lock(); object.app.lock();
if (object.app.queue_tail) |tail| tail.queued_next = command else object.app.queue_head = command; if (object.app.queue_tail) |tail| tail.queued_next = command else object.app.queue_head = command;
object.app.queue_tail = command; object.app.queue_tail = command;
@ -297,6 +309,7 @@ pub fn finish(
abandon(command); abandon(command);
return; return;
} }
if (status == abi.OK and command.data.op == c.Z_WINDOW) if (status == abi.OK and command.data.op == c.Z_WINDOW)
fromObjectHandle(command.data.target).ready = true; fromObjectHandle(command.data.target).ready = true;
if (command.data.op == c.Z_GL) { if (command.data.op == c.Z_GL) {
@ -304,12 +317,14 @@ pub fn finish(
window.payload.window.gl_status = status; window.payload.window.gl_status = status;
window.payload.window.gl_ready = true; window.payload.window.gl_ready = true;
} }
const redraw = command.completion == .resource and status == abi.OK and command.data.op == c.Z_GL; const redraw = command.completion == .resource and status == abi.OK and command.data.op == c.Z_GL;
const redraw_window = if (redraw) fromObjectHandle(command.data.target) else null; const redraw_window = if (redraw) fromObjectHandle(command.data.target) else null;
if (command.completion == .resource) { if (command.completion == .resource) {
if (command.data.op == c.Z_WINDOW) if (command.data.op == c.Z_WINDOW)
fromObjectHandle(command.data.target).creation_status = status; fromObjectHandle(command.data.target).creation_status = status;
} }
if (status != abi.OK) discardCreation(command); if (status != abi.OK) discardCreation(command);
const node = command.node; const node = command.node;
const publish = switch (command.completion) { const publish = switch (command.completion) {
@ -324,21 +339,26 @@ pub fn finish(
node.event.data.request.value = std.mem.zeroes(@TypeOf(node.event.data.request.value)); node.event.data.request.value = std.mem.zeroes(@TypeOf(node.event.data.request.value));
node.event.data.request.diagnostic = .{ .ptr = null, .len = 0 }; node.event.data.request.diagnostic = .{ .ptr = null, .len = 0 };
}; };
break :request true; break :request true;
}, },
.resource => false, .resource => false,
.discard => false, .discard => false,
}; };
application.lock(); application.lock();
if (command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) application.io_pending -= 1; if (command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) application.io_pending -= 1;
var link = &application.requests; var link = &application.requests;
while (link.*) |request| { while (link.*) |request| {
if (request == command) { if (request == command) {
link.* = request.next; link.* = request.next;
break; break;
} }
link = &request.next; link = &request.next;
} }
if (publish) publishLocked(application, node); if (publish) publishLocked(application, node);
application.unlock(); application.unlock();
if (!publish) destroyEvent(node); if (!publish) destroyEvent(node);
@ -350,10 +370,12 @@ pub fn finish(
pub fn hasFrame(application: *Application) bool { pub fn hasFrame(application: *Application) bool {
application.lock(); application.lock();
defer application.unlock(); defer application.unlock();
var cursor = application.objects; var cursor = application.objects;
while (cursor) |object| : (cursor = object.next) { while (cursor) |object| : (cursor = object.next) {
if (object.payload == .window and object.payload.window.bracket) return true; if (object.payload == .window and object.payload.window.bracket) return true;
} }
return false; return false;
} }
@ -363,6 +385,7 @@ pub fn ioMain(application: *Application) void {
profile.thread("UHDK file I/O"); profile.thread("UHDK file I/O");
while (true) { while (true) {
application.lock(); application.lock();
const command = application.io_head orelse { const command = application.io_head orelse {
const done = application.io_exit; const done = application.io_exit;
application.io_available.reset(); application.io_available.reset();
@ -371,6 +394,7 @@ pub fn ioMain(application: *Application) void {
application.io_available.waitUncancelable(application.io); application.io_available.waitUncancelable(application.io);
continue; continue;
}; };
application.io_head = command.queued_next; application.io_head = command.queued_next;
if (application.io_head == null) application.io_tail = null; if (application.io_head == null) application.io_tail = null;
command.queued_next = null; command.queued_next = null;
@ -379,6 +403,7 @@ pub fn ioMain(application: *Application) void {
if (comptime @import("builtin").is_test) { if (comptime @import("builtin").is_test) {
if (application.io_test_hook) |hook| hook.before(hook.context); if (application.io_test_hook) |hook| hook.before(hook.context);
} }
if (command.data.op == c.Z_WATCH) { if (command.data.op == c.Z_WATCH) {
if (isCancelled(application, command)) { if (isCancelled(application, command)) {
command.io_status = abi.CANCELLED; command.io_status = abi.CANCELLED;
@ -387,6 +412,7 @@ pub fn ioMain(application: *Application) void {
command.io_result.value.watch = @ptrCast(command.data.other); command.io_result.value.watch = @ptrCast(command.data.other);
} }
} else while (!fileStep(application, command)) {} } else while (!fileStep(application, command)) {}
// Close OS file handles on the worker, before result retirement on main. // Close OS file handles on the worker, before result retirement on main.
// Read results remain owned by FileOperation until main copies them. // Read results remain owned by FileOperation until main copies them.
if (command.file_operation) |*operation| operation.close(); if (command.file_operation) |*operation| operation.close();
@ -406,6 +432,7 @@ fn finishIo(command: *Request, status: abi.Status, value: ?*const c.z_request_re
pub fn createObjectCommand(handle: anytype, kind: u32, op: u32) !*Request { pub fn createObjectCommand(handle: anytype, kind: u32, op: u32) !*Request {
if (handle == null) return error.Invalid; if (handle == null) return error.Invalid;
const object = fromObjectHandle(handle); const object = fromObjectHandle(handle);
if (validateMainThreadSessionReady(object.app) != abi.OK) return error.WrongThread; if (validateMainThreadSessionReady(object.app) != abi.OK) return error.WrongThread;
if (object.kind() != kind) return error.Invalid; if (object.kind() != kind) return error.Invalid;
@ -430,6 +457,7 @@ pub fn scalarCommandValue(handle: ?*c.uhdk_window, kind: u32, op: u32, value: u6
pub fn textCommandValue(handle: ?*c.uhdk_window, kind: u32, op: u32, text: c.uhdk_text) abi.Status { pub fn textCommandValue(handle: ?*c.uhdk_window, kind: u32, op: u32, text: c.uhdk_text) abi.Status {
if (!abi.validText(text, true)) return abi.INVALID; if (!abi.validText(text, true)) return abi.INVALID;
const command = createObjectCommand(handle, kind, op) catch |err| return objectError(err); const command = createObjectCommand(handle, kind, op) catch |err| return objectError(err);
command.data.text = abi.copyText(command.arena.allocator(), text) catch { command.data.text = abi.copyText(command.arena.allocator(), text) catch {
abandon(command); abandon(command);
@ -462,10 +490,12 @@ pub fn destroyObject(object: *Resource) void {
c.z_native_destroy(c.Z_KIND_GL, object.native); c.z_native_destroy(c.Z_KIND_GL, object.native);
object.payload.window.gl_ready = false; object.payload.window.gl_ready = false;
} }
// Find one child under the registry lock, then recurse without the lock. // Find one child under the registry lock, then recurse without the lock.
// Files can be released concurrently by the other thread. // Files can be released concurrently by the other thread.
while (true) { while (true) {
object.app.lock(); object.app.lock();
var cursor = object.app.objects; var cursor = object.app.objects;
const child: ?*Resource = while (cursor) |candidate| : (cursor = candidate.next) { const child: ?*Resource = while (cursor) |candidate| : (cursor = candidate.next) {
if (candidate.payload == .window and if (candidate.payload == .window and
@ -477,20 +507,24 @@ pub fn destroyObject(object: *Resource) void {
object.app.unlock(); object.app.unlock();
if (child) |resource| destroyObject(resource) else break; if (child) |resource| destroyObject(resource) else break;
} }
object.app.lock(); object.app.lock();
object.alive = false; object.alive = false;
var req = object.app.requests; var req = object.app.requests;
while (req) |request| : (req = request.next) { while (req) |request| : (req = request.next) {
if (request.data.target == castHandle(?*anyopaque, object) or if (request.data.target == castHandle(?*anyopaque, object) or
request.data.other == castHandle(?*anyopaque, object) or request.data.other == castHandle(?*anyopaque, object) or
(request.data.op == c.Z_DIALOG and request.data.dialog.parent == castHandle(?*c.uhdk_window, object))) request.cancelled = true; (request.data.op == c.Z_DIALOG and request.data.dialog.parent == castHandle(?*c.uhdk_window, object))) request.cancelled = true;
} }
object.app.unlock(); object.app.unlock();
notifyCommand(object, c.Z_DESTROY); notifyCommand(object, c.Z_DESTROY);
} }
pub fn glCall(handle: ?*c.uhdk_window, op: u32, out: ?*anyopaque) abi.Status { pub fn glCall(handle: ?*c.uhdk_window, op: u32, out: ?*anyopaque) abi.Status {
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const object = fromObjectHandle(handle); const object = fromObjectHandle(handle);
const status = validateMainThreadObjectReady(object, c.Z_KIND_WINDOW); const status = validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status; if (status != abi.OK) return status;
@ -508,6 +542,7 @@ pub fn copyDialog(command: *Request) !void {
d.suggested_name = try abi.copyText(arena, d.suggested_name); d.suggested_name = try abi.copyText(arena, d.suggested_name);
if (d.parent) |handle| try pin(&command.pins, fromObjectHandle(handle)); if (d.parent) |handle| try pin(&command.pins, fromObjectHandle(handle));
if (d.initial_directory) |f| try pin(&command.pins, fromObjectHandle(f)); if (d.initial_directory) |f| try pin(&command.pins, fromObjectHandle(f));
const filters = try arena.alloc(c.uhdk_file_filter, @intCast(d.filters_len)); const filters = try arena.alloc(c.uhdk_file_filter, @intCast(d.filters_len));
for (filters, 0..) |*f, i| { for (filters, 0..) |*f, i| {
f.* = d.filters[i]; f.* = d.filters[i];
@ -515,6 +550,7 @@ pub fn copyDialog(command: *Request) !void {
!abi.validSpan(f.extensions.ptr, f.extensions.len) or !abi.validSpan(f.extensions.ptr, f.extensions.len) or
f.extensions.len > 256) return error.Invalid; f.extensions.len > 256) return error.Invalid;
f.label = try abi.copyText(arena, f.label); f.label = try abi.copyText(arena, f.label);
const extensions = try arena.alloc(c.uhdk_text, @intCast(f.extensions.len)); const extensions = try arena.alloc(c.uhdk_text, @intCast(f.extensions.len));
for (extensions, 0..) |*ext, j| { for (extensions, 0..) |*ext, j| {
const event = f.extensions.ptr[j]; const event = f.extensions.ptr[j];
@ -522,8 +558,10 @@ pub fn copyDialog(command: *Request) !void {
std.mem.findAny(u8, abi.textBytes(event), "/\\.") != null) return error.Invalid; std.mem.findAny(u8, abi.textBytes(event), "/\\.") != null) return error.Invalid;
ext.* = try abi.copyText(arena, event); ext.* = try abi.copyText(arena, event);
} }
f.extensions.ptr = extensions.ptr; f.extensions.ptr = extensions.ptr;
} }
d.filters = filters.ptr; d.filters = filters.ptr;
} }
@ -546,6 +584,7 @@ pub fn fileStep(application: *Application, command: *Request) bool {
finishIo(command, abi.CANCELLED, null); finishIo(command, abi.CANCELLED, null);
return true; return true;
} }
if (command.file_operation == null) { if (command.file_operation == null) {
command.file_operation = FileOperation.init( command.file_operation = FileOperation.init(
application.gpa, application.gpa,
@ -560,10 +599,12 @@ pub fn fileStep(application: *Application, command: *Request) bool {
command.data.limit, command.data.limit,
); );
} }
const result = command.file_operation.?.step() catch |err| { const result = command.file_operation.?.step() catch |err| {
finishIo(command, fileError(err), null); finishIo(command, fileError(err), null);
return true; return true;
}; };
var value = std.mem.zeroes(c.z_request_result); var value = std.mem.zeroes(c.z_request_result);
switch (result) { switch (result) {
.pending => return false, .pending => return false,
@ -580,17 +621,20 @@ pub fn fileStep(application: *Application, command: *Request) bool {
.reserved = 0, .reserved = 0,
}, },
} }
finishIo(command, abi.OK, &value); finishIo(command, abi.OK, &value);
return true; return true;
} }
pub fn validateMenu(object: *Resource, ids: *std.AutoHashMap(u64, void), depth: usize) !void { pub fn validateMenu(object: *Resource, ids: *std.AutoHashMap(u64, void), depth: usize) !void {
if (depth > 16) return error.Invalid; if (depth > 16) return error.Invalid;
for (object.payload.menu.items) |item| { for (object.payload.menu.items) |item| {
if (item.command_id != 0) { if (item.command_id != 0) {
const entry = try ids.getOrPut(item.command_id); const entry = try ids.getOrPut(item.command_id);
if (entry.found_existing) return error.Invalid; if (entry.found_existing) return error.Invalid;
} }
if (item.submenu) |sub| try validateMenu(fromObjectHandle(sub), ids, depth + 1); if (item.submenu) |sub| try validateMenu(fromObjectHandle(sub), ids, depth + 1);
} }
} }
@ -609,12 +653,14 @@ pub fn attachMenu(
abandon(command); abandon(command);
return abi.UNAVAILABLE; return abi.UNAVAILABLE;
} }
command.data.target = fromObjectHandle(w); command.data.target = fromObjectHandle(w);
pin(&command.pins, fromObjectHandle(w)) catch { pin(&command.pins, fromObjectHandle(w)) catch {
abandon(command); abandon(command);
return abi.OOM; return abi.OOM;
}; };
} }
if (menu) |m| { if (menu) |m| {
command.data.other = fromObjectHandle(m); command.data.other = fromObjectHandle(m);
pin(&command.pins, fromObjectHandle(m)) catch { pin(&command.pins, fromObjectHandle(m)) catch {
@ -622,6 +668,7 @@ pub fn attachMenu(
return abi.OOM; return abi.OOM;
}; };
} }
return submitCommand(fromAppHandle(handle), command); return submitCommand(fromAppHandle(handle), command);
} }
@ -629,13 +676,16 @@ pub fn setMenuFlags(object: *Resource, id: u64, flags: u32) bool {
for (object.payload.menu.items) |*item| { for (object.payload.menu.items) |*item| {
if (item.command_id == id) { if (item.command_id == id) {
if (item.flags & c.UHDK_MENU_SEPARATOR != 0) return false; if (item.flags & c.UHDK_MENU_SEPARATOR != 0) return false;
item.flags = flags; item.flags = flags;
return true; return true;
} }
if (item.submenu) |sub| { if (item.submenu) |sub| {
if (setMenuFlags(fromObjectHandle(sub), id, flags)) return true; if (setMenuFlags(fromObjectHandle(sub), id, flags)) return true;
} }
} }
return false; return false;
} }
@ -646,6 +696,7 @@ fn publishCycleEnds(application: *Application, window: *c.uhdk_window, ended: @i
application.notify(); application.notify();
return; return;
}; };
node.* = .{ .gpa = application.gpa, .arena = .init(application.gpa) }; node.* = .{ .gpa = application.gpa, .arena = .init(application.gpa) };
node.event.type = c.UHDK_EVENT_CYCLE_END; node.event.type = c.UHDK_EVENT_CYCLE_END;
node.event.window = window; node.event.window = window;
@ -664,6 +715,7 @@ pub fn emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void {
application.unlock(); application.unlock();
return; return;
}; };
node.* = .{ .event = event.*, .gpa = application.gpa, .arena = .init(application.gpa) }; node.* = .{ .event = event.*, .gpa = application.gpa, .arena = .init(application.gpa) };
copyPayload(node) catch { copyPayload(node) catch {
destroyEvent(node); destroyEvent(node);
@ -673,6 +725,7 @@ pub fn emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void {
application.unlock(); application.unlock();
return; return;
}; };
application.lock(); application.lock();
defer application.unlock(); defer application.unlock();
if (application.stopped_sent or (node.event.window != null and !fromObjectHandle(node.event.window).alive)) { if (application.stopped_sent or (node.event.window != null and !fromObjectHandle(node.event.window).alive)) {
@ -681,6 +734,7 @@ pub fn emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void {
application.lock(); application.lock();
return; return;
} }
// Redraw and wake have no payload; coalesce only while still pending. // Redraw and wake have no payload; coalesce only while still pending.
if (event.*.type == c.UHDK_EVENT_WINDOW_REDRAW or event.*.type == c.UHDK_EVENT_WAKE) { if (event.*.type == c.UHDK_EVENT_WINDOW_REDRAW or event.*.type == c.UHDK_EVENT_WAKE) {
var cursor = application.pending_head; var cursor = application.pending_head;
@ -693,6 +747,7 @@ pub fn emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void {
} }
} }
} }
if (node.event.window) |window| { if (node.event.window) |window| {
const ended = fromObjectHandle(window).payload.window.cycles.apply(&application.next_cycle, &node.event) catch { const ended = fromObjectHandle(window).payload.window.cycles.apply(&application.next_cycle, &node.event) catch {
application.event_error = abi.UNAVAILABLE; application.event_error = abi.UNAVAILABLE;
@ -702,6 +757,7 @@ pub fn emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void {
application.lock(); application.lock();
return; return;
}; };
publishLocked(application, node); publishLocked(application, node);
publishCycleEnds(application, window, ended); publishCycleEnds(application, window, ended);
} else { } else {
@ -715,6 +771,7 @@ pub fn emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void {
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)); 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); publishLocked(application, node);
} }
} }
@ -727,6 +784,7 @@ pub fn complete(
) void { ) void {
const application = fromAppHandle(handle); const application = fromAppHandle(handle);
application.lock(); application.lock();
var cursor = application.requests; var cursor = application.requests;
while (cursor) |command| : (cursor = command.next) { while (cursor) |command| : (cursor = command.next) {
if (command.id == id) { if (command.id == id) {
@ -735,12 +793,14 @@ pub fn complete(
return; return;
} }
} }
application.unlock(); application.unlock();
} }
pub fn dispatch(handle: ?*c.uhdk_session) void { pub fn dispatch(handle: ?*c.uhdk_session) void {
const zone = profile.begin(@src(), "UHDK platform dispatch"); const zone = profile.begin(@src(), "UHDK platform dispatch");
defer zone.end(); defer zone.end();
const application = fromAppHandle(handle); const application = fromAppHandle(handle);
// Native tracking loops can reenter the run loop; never reenter application command. // Native tracking loops can reenter the run loop; never reenter application command.
if (application.in_dispatch) return; if (application.in_dispatch) return;
@ -748,10 +808,12 @@ pub fn dispatch(handle: ?*c.uhdk_session) void {
defer application.in_dispatch = false; defer application.in_dispatch = false;
while (true) { while (true) {
application.lock(); application.lock();
const completed = application.io_completed_head orelse { const completed = application.io_completed_head orelse {
application.unlock(); application.unlock();
break; break;
}; };
application.io_completed_head = completed.queued_next; application.io_completed_head = completed.queued_next;
if (application.io_completed_head == null) application.io_completed_tail = null; if (application.io_completed_head == null) application.io_completed_tail = null;
application.unlock(); application.unlock();
@ -764,17 +826,21 @@ pub fn dispatch(handle: ?*c.uhdk_session) void {
completed.io_status = abi.CANCELLED; completed.io_status = abi.CANCELLED;
} }
} }
finish(application, completed, completed.io_status, &completed.io_result); finish(application, completed, completed.io_status, &completed.io_result);
} }
const start = now(application.io); const start = now(application.io);
var count: usize = 0; var count: usize = 0;
var blocked_on_resource = false; var blocked_on_resource = false;
while (count < 64 and now(application.io) - start < 2_000_000) : (count += 1) { while (count < 64 and now(application.io) - start < 2_000_000) : (count += 1) {
application.lock(); application.lock();
const command = application.queue_head orelse { const command = application.queue_head orelse {
application.unlock(); application.unlock();
break; break;
}; };
application.queue_head = command.queued_next; application.queue_head = command.queued_next;
if (application.queue_head == null) application.queue_tail = null; if (application.queue_head == null) application.queue_tail = null;
command.queued_next = null; command.queued_next = null;
@ -783,10 +849,12 @@ pub fn dispatch(handle: ?*c.uhdk_session) void {
finish(application, command, abi.CANCELLED, null); finish(application, command, abi.CANCELLED, null);
continue; continue;
} }
if (command.data.target != null and !fromObjectHandle(command.data.target).alive and command.data.op != c.Z_DESTROY) { if (command.data.target != null and !fromObjectHandle(command.data.target).alive and command.data.op != c.Z_DESTROY) {
finish(application, command, abi.CANCELLED, null); finish(application, command, abi.CANCELLED, null);
continue; continue;
} }
if (command.data.op != c.Z_WINDOW and command.data.op != c.Z_DESTROY and command.data.target != null and if (command.data.op != c.Z_WINDOW and command.data.op != c.Z_DESTROY and command.data.target != null and
!fromObjectHandle(command.data.target).ready) !fromObjectHandle(command.data.target).ready)
{ {
@ -798,6 +866,7 @@ pub fn dispatch(handle: ?*c.uhdk_session) void {
blocked_on_resource = true; blocked_on_resource = true;
break; break;
} }
if (command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) { if (command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) {
application.lock(); application.lock();
if (application.io_tail) |tail| tail.queued_next = command else application.io_head = command; if (application.io_tail) |tail| tail.queued_next = command else application.io_head = command;
@ -806,9 +875,11 @@ pub fn dispatch(handle: ?*c.uhdk_session) void {
application.unlock(); application.unlock();
continue; continue;
} }
var result = std.mem.zeroes(c.z_request_result); var result = std.mem.zeroes(c.z_request_result);
if (command.data.op == c.Z_MENU_FLAGS) { if (command.data.op == c.Z_MENU_FLAGS) {
application.lock(); application.lock();
const found = setMenuFlags(fromObjectHandle(command.data.target), command.data.number, @intCast(command.data.limit)); const found = setMenuFlags(fromObjectHandle(command.data.target), command.data.number, @intCast(command.data.limit));
application.unlock(); application.unlock();
if (!found) { if (!found) {
@ -816,8 +887,10 @@ pub fn dispatch(handle: ?*c.uhdk_session) void {
continue; continue;
} }
} }
// Mark before entering native code: a backend may complete inline. // Mark before entering native code: a backend may complete inline.
command.native_deferred = true; command.native_deferred = true;
const status = c.z_native_execute(handle, &command.data, command.id, &result); const status = c.z_native_execute(handle, &command.data, command.id, &result);
if (status != c.Z_DEFERRED and command.data.op == c.Z_DESTROY) { if (status != c.Z_DEFERRED and command.data.op == c.Z_DESTROY) {
const resource = fromObjectHandle(command.data.target); const resource = fromObjectHandle(command.data.target);
@ -826,12 +899,15 @@ pub fn dispatch(handle: ?*c.uhdk_session) void {
resource.payload.watch.owner = null; resource.payload.watch.owner = null;
} }
} }
if (status != c.Z_DEFERRED) { if (status != c.Z_DEFERRED) {
finish(application, command, status, &result); finish(application, command, status, &result);
} }
} }
// Only operations dispatched to native code need native cancellation hooks. // Only operations dispatched to native code need native cancellation hooks.
application.lock(); application.lock();
var cursor = application.requests; var cursor = application.requests;
var ids: [64]u64 = undefined; var ids: [64]u64 = undefined;
var node: usize = 0; var node: usize = 0;
@ -843,9 +919,11 @@ pub fn dispatch(handle: ?*c.uhdk_session) void {
node += 1; node += 1;
} }
} }
application.unlock(); application.unlock();
for (ids[0..node]) |id| c.z_native_cancel(id); for (ids[0..node]) |id| c.z_native_cancel(id);
application.lock(); application.lock();
const empty = application.requests == null and application.queue_head == null and application.io_active == null and application.io_head == null; const empty = application.requests == null and application.queue_head == null and application.io_active == null and application.io_head == null;
if (application.stopping and empty and !application.stopped_sent) { if (application.stopping and empty and !application.stopped_sent) {
application.unlock(); application.unlock();
@ -853,6 +931,7 @@ pub fn dispatch(handle: ?*c.uhdk_session) void {
application.lock(); application.lock();
application.stopped_sent = true; application.stopped_sent = true;
} }
const again = (!blocked_on_resource and application.queue_head != null) or application.io_completed_head != null or node == ids.len; const again = (!blocked_on_resource and application.queue_head != null) or application.io_completed_head != null or node == ids.len;
application.unlock(); application.unlock();
if (again) c.z_native_again(); if (again) c.z_native_again();