From ddb1aac08845afce6d5bc6adeb1a9a5ca0d0bef2 Mon Sep 17 00:00:00 2001 From: Peterino2 Date: Mon, 21 Sep 2026 09:07:31 -0700 Subject: [PATCH] api updates and new validators, fixing up some naming inconsistencies in linux --- src/Application.zig | 2 +- src/Resource.zig | 13 +-- src/api/app.zig | 19 ++--- src/api/desktop.zig | 2 +- src/api/files.zig | 6 +- src/api/graphics.zig | 65 +++++++-------- src/api/menus.zig | 2 +- src/api/session.zig | 58 +++++++++----- src/api/windows.zig | 8 +- src/linux/Data.zig | 164 +++++++++++++++++++------------------- src/linux/Desktop.zig | 90 ++++++++++----------- src/linux/Egl.zig | 3 +- src/linux/Input.zig | 20 ++--- src/linux/KdeAppMenu.zig | 70 ++++++++-------- src/linux/Popup.zig | 128 ++++++++++++++--------------- src/linux/Portal.zig | 168 +++++++++++++++++++-------------------- src/linux/Watch.zig | 38 ++++----- src/linux/bindings.h | 2 - src/linux/libraries.c | 5 -- src/linux/native.zig | 18 +++-- src/macos/native.m | 16 ++-- src/native.h | 2 +- src/runtime.zig | 62 +++++++-------- src/windows/native.c | 20 +++-- 24 files changed, 494 insertions(+), 487 deletions(-) diff --git a/src/Application.zig b/src/Application.zig index 84501e9..8ded981 100644 --- a/src/Application.zig +++ b/src/Application.zig @@ -54,7 +54,7 @@ stats: c.uhdk_stats = std.mem.zeroes(c.uhdk_stats), last_frame_time: ?u64 = null, session_gl: c.uhdk_gl_functions = std.mem.zeroes(c.uhdk_gl_functions), session_window: ?*c.uhdk_window = null, -session_context: ?*c.z_gl_context = null, +session_has_gl: bool = false, session_status: abi.Status = abi.OK, session_active: bool = false, session_drawable: bool = false, diff --git a/src/Resource.zig b/src/Resource.zig index 1a7f70b..07cf6ce 100644 --- a/src/Resource.zig +++ b/src/Resource.zig @@ -18,7 +18,6 @@ payload: Payload, pub const Kind = enum(u32) { window = c.Z_KIND_WINDOW, - gl = c.Z_KIND_GL, file = c.Z_KIND_FILE, menu = c.Z_KIND_MENU, watch = c.Z_KIND_WATCH, @@ -26,7 +25,6 @@ pub const Kind = enum(u32) { pub const Payload = union(Kind) { window: Window, - gl: Gl, file: File, menu: Menu, watch: Watch, @@ -34,13 +32,11 @@ pub const Payload = union(Kind) { pub const Window = struct { cycles: @import("Cycles.zig") = .{}, - context: ?*Resource = null, parent: ?*Resource = null, metrics: c.uhdk_window_metrics = std.mem.zeroes(c.uhdk_window_metrics), -}; - -pub const Gl = struct { - owner: ?*Resource = null, + gl_requested: bool = false, + gl_ready: bool = false, + gl_status: u32 = 0, bracket: bool = false, frame_cpu_start: u64 = 0, swap_cpu_time: u64 = 0, @@ -68,10 +64,9 @@ pub fn init(application: *Application, resource_kind: Kind) Resource { .app = application, .gpa = application.gpa, .arena = .init(application.gpa), - .ready = resource_kind != .window and resource_kind != .gl, + .ready = resource_kind != .window, .payload = switch (resource_kind) { .window => .{ .window = .{} }, - .gl => .{ .gl = .{} }, .file => .{ .file = .{} }, .menu => .{ .menu = .{} }, .watch => .{ .watch = .{} }, diff --git a/src/api/app.zig b/src/api/app.zig index 0b419c4..dc513c6 100644 --- a/src/api/app.zig +++ b/src/api/app.zig @@ -86,15 +86,12 @@ fn shutdown(application: *Application) void { } } cursor = application.objects; - while (cursor) |object| : (cursor = object.next) { - if (object.kind() == c.Z_KIND_GL and object.native != null) { - c.z_native_destroy(object.kind(), object.native); - object.native = null; - } - } - cursor = application.objects; while (cursor) |object| : (cursor = object.next) { if (object.kind() == c.Z_KIND_WINDOW and object.native != null) { + if (object.payload.window.gl_ready and object.payload.window.gl_status == abi.OK) { + c.z_native_destroy(c.Z_KIND_GL, object.native); + object.payload.window.gl_ready = false; + } c.z_native_destroy(object.kind(), object.native); object.native = null; } @@ -112,7 +109,7 @@ pub fn poll( ) abi.Status { if (handle == null or out == null) return abi.INVALID; const application = runtime.fromAppHandle(handle); - if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; + if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (runtime.hasFrame(application)) return c.UHDK_STATUS_BUSY; const poll_zone = profile.begin(@src(), "UHDK poll events (includes wait)"); defer poll_zone.end(); @@ -196,7 +193,7 @@ pub fn poll( pub export fn uhdk_get_stats(handle: ?*c.uhdk_session, out: [*c]c.uhdk_stats) abi.Status { if (handle == null) return abi.INVALID; const application = runtime.fromAppHandle(handle); - if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; + if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; return abi.writeOutput(c.uhdk_stats, out, application.stats); } @@ -224,7 +221,7 @@ 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 { if (handle == null) return abi.INVALID; const application = runtime.fromAppHandle(handle); - if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; + if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; application.lock(); application.deadline = deadline; application.notify(); @@ -248,7 +245,7 @@ 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 { if (handle == null or tag == 0) return abi.INVALID; const application = runtime.fromAppHandle(handle); - if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; + if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; application.lock(); var cursor = application.requests; while (cursor) |command| : (cursor = command.next) { diff --git a/src/api/desktop.zig b/src/api/desktop.zig index 6663404..49dd461 100644 --- a/src/api/desktop.zig +++ b/src/api/desktop.zig @@ -70,7 +70,7 @@ pub export fn uhdk_get_preferences( ) abi.Status { if (handle == null) return abi.INVALID; const application = runtime.fromAppHandle(handle); - if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; + if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; application.lock(); defer application.unlock(); return abi.writeOutput(c.uhdk_preferences, out, application.preferences); diff --git a/src/api/files.zig b/src/api/files.zig index 5302aca..2008de2 100644 --- a/src/api/files.zig +++ b/src/api/files.zig @@ -41,7 +41,7 @@ pub export fn uhdk_file_create_from_native_path( path.len == 0) return abi.INVALID; if (@import("builtin").os.tag != .windows and (abi.bytes(path)[0] != '/' or std.mem.findScalar(u8, abi.bytes(path), 0) != null)) return abi.INVALID; - if (runtime.checkThread(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 status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), path, .{ .ptr = null, .len = 0 }, null); if (status != abi.OK) { @@ -58,7 +58,7 @@ pub export fn uhdk_file_create_from_uri( out: [*c]?*c.uhdk_file, ) abi.Status { if (handle == null or out == null or !abi.validText(uri, true)) return abi.INVALID; - if (runtime.checkThread(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 status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), .{ .ptr = null, .len = 0 }, uri, null); if (status != abi.OK) { @@ -86,7 +86,7 @@ pub export fn uhdk_file_copy_representation( ) abi.Status { if (handle == null or out == null or !abi.validSpan(buffer, capacity)) return abi.INVALID; const object = runtime.fromObjectHandle(handle); - const status = runtime.checkObject(object, c.Z_KIND_FILE); + const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_FILE); if (status != abi.OK) return status; const data = switch (form) { c.UHDK_FILE_DISPLAY_NAME => object.payload.file.display, diff --git a/src/api/graphics.zig b/src/api/graphics.zig index a4b035e..1f4c75e 100644 --- a/src/api/graphics.zig +++ b/src/api/graphics.zig @@ -5,51 +5,42 @@ const c = @import("native"); const runtime = @import("../runtime.zig"); const abi = @import("../abi.zig"); -pub fn create(handle: ?*c.uhdk_window, out: [*c]?*c.z_gl_context) abi.Status { - if (out == null) return abi.INVALID; +pub fn create(handle: ?*c.uhdk_window) abi.Status { const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_GL) catch |err| return runtime.objectError(err); const w = runtime.fromObjectHandle(handle); - if (w.payload.window.context != null) { + if (w.payload.window.gl_requested) { runtime.abandon(command); return c.UHDK_STATUS_BUSY; } - const object = runtime.createObject(w.app, c.Z_KIND_GL) catch { - runtime.abandon(command); - return abi.OOM; - }; - object.payload.gl.owner = w; - w.payload.window.context = object; - command.data.other = object; - const status = runtime.submitResource(w.app, command); - if (status == abi.OK) out.* = runtime.castHandle(*c.z_gl_context, object); - return status; + w.payload.window.gl_requested = true; + return runtime.submitResource(w.app, command); } -pub fn acquire(handle: ?*c.z_gl_context) abi.Status { +pub fn acquire(handle: ?*c.uhdk_window) abi.Status { const zone = profile.begin(@src(), "UHDK acquire GL context"); defer zone.end(); if (handle == null) return abi.INVALID; const object = runtime.fromObjectHandle(handle); - if (object.payload.gl.bracket) return c.UHDK_STATUS_BUSY; + if (object.payload.window.bracket) return c.UHDK_STATUS_BUSY; const status = runtime.glCall(handle, 1, null); if (status == abi.OK) { - object.payload.gl.bracket = true; - object.payload.gl.frame_cpu_start = runtime.threadCpuTime(object.app.io); - object.payload.gl.swap_cpu_time = 0; - object.payload.gl.presented = false; + object.payload.window.bracket = true; + object.payload.window.frame_cpu_start = runtime.threadCpuTime(object.app.io); + object.payload.window.swap_cpu_time = 0; + object.payload.window.presented = false; } return status; } -pub fn release(handle: ?*c.z_gl_context) abi.Status { +pub fn release(handle: ?*c.uhdk_window) abi.Status { const status = runtime.glCall(handle, 2, null); if (status == abi.OK) { const object = runtime.fromObjectHandle(handle); - object.payload.gl.bracket = false; - if (object.payload.gl.presented) { + object.payload.window.bracket = false; + if (object.payload.window.presented) { const stats = &object.app.stats; - const elapsed = runtime.threadCpuTime(object.app.io) -| object.payload.gl.frame_cpu_start; - stats.render_time_ns = elapsed -| object.payload.gl.swap_cpu_time; + 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.frame_count +|= 1; const now = runtime.now(object.app.io); if (object.app.last_frame_time) |previous| { @@ -62,24 +53,24 @@ pub fn release(handle: ?*c.z_gl_context) abi.Status { return status; } -pub fn present(handle: ?*c.z_gl_context) abi.Status { +pub fn present(handle: ?*c.uhdk_window) abi.Status { const zone = profile.begin(@src(), "UHDK present (includes vsync)"); defer zone.end(); if (handle == null) return abi.INVALID; const object = runtime.fromObjectHandle(handle); - const valid = runtime.checkObject(object, c.Z_KIND_GL); + const valid = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW); if (valid != abi.OK) return valid; - if (!object.payload.gl.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. const start = runtime.threadCpuTime(object.app.io); const status = runtime.glCall(handle, 6, null); - object.payload.gl.swap_cpu_time +|= runtime.threadCpuTime(object.app.io) -| start; - if (status == abi.OK) object.payload.gl.presented = true; + object.payload.window.swap_cpu_time +|= runtime.threadCpuTime(object.app.io) -| start; + if (status == abi.OK) object.payload.window.presented = true; return status; } pub fn setSwapInterval( - handle: ?*c.z_gl_context, + handle: ?*c.uhdk_window, interval: i32, ) abi.Status { if (interval != 0 and interval != 1) return abi.INVALID; @@ -88,18 +79,16 @@ pub fn setSwapInterval( } pub fn getProc( - handle: ?*c.z_gl_context, + handle: ?*c.uhdk_window, name: c.uhdk_text, out: [*c]c.uhdk_gl_proc, ) abi.Status { - if (handle == null or - out == null or - !abi.validText(name, true) or - name.len == 0 or - name.len > 255) return abi.INVALID; + if (handle == null or out == null or !abi.validText(name, true) or name.len == 0 or name.len > 255) + return abi.INVALID; + const object = runtime.fromObjectHandle(handle); - const status = runtime.checkObject(object, c.Z_KIND_GL); + const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW); if (status != abi.OK) return status; - if (!object.payload.gl.bracket) return c.UHDK_STATUS_BUSY; + if (!object.payload.window.bracket) return c.UHDK_STATUS_BUSY; return c.z_native_gl_proc(object.native, name, out); } diff --git a/src/api/menus.zig b/src/api/menus.zig index e9d94da..60cb364 100644 --- a/src/api/menus.zig +++ b/src/api/menus.zig @@ -12,7 +12,7 @@ pub export fn uhdk_menu_create( ) abi.Status { if (handle == null or out == null or !abi.validSpan(items, len) or len > 4096) return abi.INVALID; const application = runtime.fromAppHandle(handle); - if (runtime.checkThread(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; object.payload.menu.items = object.arena.allocator().alloc(c.uhdk_menu_item, @intCast(len)) catch { runtime.release(object); diff --git a/src/api/session.zig b/src/api/session.zig index 929987a..41829f3 100644 --- a/src/api/session.zig +++ b/src/api/session.zig @@ -15,14 +15,16 @@ fn handle(a: *Application) *c.uhdk_session { return runtime.toAppHandle(a); } pub fn acquire(a: *Application) abi.Status { - const context = a.session_context orelse return abi.OK; - if (runtime.fromObjectHandle(context).payload.gl.bracket) return abi.OK; - return graphics.acquire(context); + if (!a.session_has_gl) return abi.OK; + const window = runtime.fromObjectHandle(a.session_window); + if (window.payload.window.bracket) return abi.OK; + return graphics.acquire(a.session_window); } pub fn release(a: *Application) abi.Status { - const context = a.session_context orelse return abi.OK; - if (!runtime.fromObjectHandle(context).payload.gl.bracket) return abi.OK; - return graphics.release(context); + if (!a.session_has_gl) return abi.OK; + const window = runtime.fromObjectHandle(a.session_window); + if (!window.payload.window.bracket) return abi.OK; + return graphics.release(a.session_window); } pub fn ready(a: *Application, resource: anytype, deadline: u64) abi.Status { const object = runtime.fromObjectHandle(resource); @@ -37,6 +39,19 @@ pub fn ready(a: *Application, resource: anytype, deadline: u64) abi.Status { } return abi.OK; } +fn readyGl(a: *Application, deadline: u64) abi.Status { + const window = runtime.fromObjectHandle(a.session_window); + while (!window.payload.window.gl_ready) { + if (!window.alive) return abi.UNAVAILABLE; + if (a.native_error != abi.OK) return a.native_error; + if (a.event_error != abi.OK) return a.event_error; + const now = runtime.now(a.io); + if (now >= deadline) return abi.UNAVAILABLE; + runtime.dispatch(handle(a)); + c.z_native_pump(@min(deadline - now, 10 * std.time.ns_per_ms)); + } + return window.payload.window.gl_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; @@ -81,10 +96,11 @@ pub export fn uhdk_open(options: [*c]const c.uhdk_options, out: [*c]?*c.uhdk_ses status = ready(a, a.session_window, deadline); if (status != abi.OK) return status; if (opts.no_opengl == 0) { - status = graphics.create(a.session_window, &a.session_context); + status = graphics.create(a.session_window); if (status != abi.OK) return status; - status = ready(a, a.session_context, deadline); + status = readyGl(a, deadline); if (status != abi.OK) return status; + a.session_has_gl = true; } status = windows.uhdk_window_set_visible(a.session_window, 1); if (status != abi.OK) return status; @@ -98,9 +114,9 @@ pub export fn uhdk_open(options: [*c]const c.uhdk_options, out: [*c]?*c.uhdk_ses status = acquire(a); if (status != abi.OK) return status; if (opts.no_opengl == 0) { - status = graphics.setSwapInterval(a.session_context, 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 (c.z_gl_load(runtime.fromObjectHandle(a.session_context).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); success = true; @@ -109,7 +125,7 @@ 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 { const a = state(session orelse return 0); - if (runtime.checkThread(a) != abi.OK) return 0; + if (runtime.validateMainThreadSessionReady(a) != abi.OK) return 0; if (out == null or a.session_active) { a.session_status = if (out == null) abi.INVALID else c.UHDK_STATUS_BUSY; return 0; @@ -129,7 +145,7 @@ pub export fn uhdk_next_frame(session: ?*c.uhdk_session, out: [*c]c.uhdk_frame) if (a.session_status != abi.OK) return 0; a.session_status = windows.uhdk_window_get_metrics(a.session_window, &metrics); if (a.session_status != abi.OK) return 0; - out.*.gl = if (a.session_context != null) &a.session_gl else null; + out.*.gl = if (a.session_has_gl) &a.session_gl else null; out.*.metrics = metrics; a.session_drawable = !a.stopping and drawable(metrics); out.*.drawable = @intFromBool(a.session_drawable); @@ -150,11 +166,11 @@ fn drawable(metrics: c.uhdk_window_metrics) bool { pub export fn uhdk_end_frame(session: ?*c.uhdk_session) abi.Status { const a = state(session orelse return abi.INVALID); - if (runtime.checkThread(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; a.session_active = false; var status: abi.Status = abi.OK; - if (a.session_drawable and !a.stopping and a.session_context != null) status = graphics.present(a.session_context); + if (a.session_drawable and !a.stopping and a.session_has_gl) status = graphics.present(a.session_window); const end_status = release(a); const begin_status = if (end_status == abi.OK) acquire(a) else end_status; a.session_status = if (status != abi.OK) status else begin_status; @@ -163,31 +179,31 @@ pub export fn uhdk_end_frame(session: ?*c.uhdk_session) abi.Status { pub export fn uhdk_get_status(session: ?*c.uhdk_session) abi.Status { const a = state(session orelse return abi.INVALID); - if (runtime.checkThread(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; } pub export fn uhdk_get_gl(session: ?*c.uhdk_session) [*c]const c.uhdk_gl_functions { const a = state(session orelse return null); - return if (a.session_context != null) &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 { return state(session orelse return null).session_window; } pub export fn uhdk_close(session: ?*c.uhdk_session) void { const a = state(session orelse return); - std.debug.assert(runtime.checkThread(a) == abi.OK); + std.debug.assert(runtime.validateMainThreadSessionReady(a) == abi.OK); _ = release(a); app.destroy(handle(a)); } pub export fn uhdk_get_gl_proc(session: ?*c.uhdk_session, name: c.uhdk_text, out: [*c]c.uhdk_gl_proc) abi.Status { const a = state(session orelse return abi.INVALID); - if (a.session_context == null) return c.UHDK_STATUS_UNSUPPORTED; - return graphics.getProc(a.session_context, name, out); + if (!a.session_has_gl) return c.UHDK_STATUS_UNSUPPORTED; + return graphics.getProc(a.session_window, name, out); } pub export fn uhdk_set_vsync(session: ?*c.uhdk_session, enabled: c.uhdk_bool) abi.Status { const a = state(session orelse return abi.INVALID); if (enabled != 0 and enabled != 1) return abi.INVALID; - if (a.session_context == null) return c.UHDK_STATUS_UNSUPPORTED; - return graphics.setSwapInterval(a.session_context, enabled); + if (!a.session_has_gl) return c.UHDK_STATUS_UNSUPPORTED; + return graphics.setSwapInterval(a.session_window, enabled); } diff --git a/src/api/windows.zig b/src/api/windows.zig index 2bbd39b..e651aa9 100644 --- a/src/api/windows.zig +++ b/src/api/windows.zig @@ -91,7 +91,7 @@ pub export fn uhdk_window_get_metrics( ) abi.Status { if (handle == null) return abi.INVALID; const object = runtime.fromObjectHandle(handle); - const status = runtime.checkObject(object, c.Z_KIND_WINDOW); + const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW); if (status != abi.OK) return status; object.app.lock(); defer object.app.unlock(); @@ -108,7 +108,7 @@ pub export fn uhdk_window_get_native( ) abi.Status { if (handle == null or out == null or out.*.struct_size < @sizeOf(c.uhdk_native_window)) return abi.INVALID; const object = runtime.fromObjectHandle(handle); - const status = runtime.checkObject(object, c.Z_KIND_WINDOW); + const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW); if (status != abi.OK) return status; c.z_native_handles(object.native, out); return abi.OK; @@ -119,7 +119,7 @@ pub export fn uhdk_window_create(handle: ?*c.uhdk_session, desc: [*c]const c.uhd out.* = null; if (handle == null or !abi.validDescriptor(c.uhdk_window_desc, desc) or desc.*.reserved != 0) return abi.INVALID; const a = runtime.fromAppHandle(handle); - if (runtime.checkThread(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; + if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; if (a.session_active) return c.UHDK_STATUS_BUSY; const session = @import("session.zig"); const d: c.z_window_desc = .{ @@ -151,7 +151,7 @@ pub export fn uhdk_window_create(handle: ?*c.uhdk_session, desc: [*c]const c.uhd pub export fn uhdk_window_destroy(window: ?*c.uhdk_window) abi.Status { if (window == null) return abi.OK; const object = runtime.fromObjectHandle(window); - const status = runtime.checkObject(object, c.Z_KIND_WINDOW); + const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW); if (status != abi.OK) return status; if (object.app.session_window == window) return abi.INVALID; runtime.destroyObject(object); diff --git a/src/linux/Data.zig b/src/linux/Data.zig index a5f941d..00241f9 100644 --- a/src/linux/Data.zig +++ b/src/linux/Data.zig @@ -43,43 +43,43 @@ pub const State = struct { position: n.uhdk_point = .{ .x = 0, .y = 0 }, transfers: ?*Transfer = null, }; -fn b() *native.Backend { +fn backend() *native.Backend { return native.instance.?; } -fn s() *State { - return &b().data; +fn dataState() *State { + return &backend().data; } fn data(comptime T: type, raw: ?*anyopaque) *T { return @ptrCast(@alignCast(raw.?)); } 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) - s().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 { - if (s().manager != null and Input.state().seat != null and s().device == null) { - s().device = c.wl_data_device_manager_get_data_device(s().manager, Input.state().seat); - if (s().device != null) _ = c.wl_data_device_add_listener(s().device, &device_listener, 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); + if (dataState().device != null) _ = c.wl_data_device_add_listener(dataState().device, &device_listener, null); } - native.setCapability(n.UHDK_CAP_CLIPBOARD, s().device != null); - native.setCapability(n.UHDK_CAP_DROP_FILES, s().device != null); + native.setCapability(n.UHDK_CAP_CLIPBOARD, dataState().device != null); + native.setCapability(n.UHDK_CAP_DROP_FILES, dataState().device != null); } fn unref(o: *Offer) void { o.refs -= 1; if (o.refs != 0) return; - var link = &s().offers; + var link = &dataState().offers; while (link.* != o) link = &link.*.?.next; link.* = o.next; c.wl_data_offer_destroy(o.proxy); - b().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 { - const o = b().app.gpa.create(Offer) catch { + const o = backend().app.gpa.create(Offer) catch { c.wl_data_offer_destroy(proxy); return; }; - o.* = .{ .next = s().offers, .proxy = proxy }; - s().offers = o; + o.* = .{ .next = dataState().offers, .proxy = proxy }; + dataState().offers = 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 { @@ -96,39 +96,39 @@ fn action(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, value: u32) callconv(.c } 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 { - var o = s().offers; + var o = dataState().offers; while (o) |item| : (o = item.next) if (item.proxy == proxy) return item; return null; } fn selection(_: ?*anyopaque, _: ?*c.struct_wl_data_device, proxy: ?*c.struct_wl_data_offer) callconv(.c) void { - if (s().selection) |old| unref(old); - s().selection = lookup(proxy); // Takes the initial offer reference. + if (dataState().selection) |old| unref(old); + 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 { leave(null, null); - s().drag = lookup(proxy); - s().drag_window = Input.find(surface); - s().drag_serial = serial; - s().position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 }; + dataState().drag = lookup(proxy); + dataState().drag_window = Input.find(surface); + dataState().drag_serial = serial; + dataState().position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 }; negotiate(); } fn negotiate() void { - const o = s().drag orelse return; - const accepted = o.uris and s().drag_window != null and s().drag_window.?.drop_enabled; - c.wl_data_offer_accept(o.proxy, s().drag_serial, if (accepted) "text/uri-list" else null); + const o = dataState().drag orelse return; + 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_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 { - if (s().drag) |o| unref(o); - s().drag = null; - s().drag_window = null; + if (dataState().drag) |o| unref(o); + dataState().drag = null; + dataState().drag_window = null; } fn motion(_: ?*anyopaque, _: ?*c.struct_wl_data_device, _: u32, x: i32, y: i32) callconv(.c) void { - s().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 { - const o = s().drag orelse return; - const w = s().drag_window orelse return; + const o = dataState().drag 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; _ = receive(o, "text/uri-list", 0, 16 * 1024 * 1024, w); // drop ends the drag session; no leave is required after a successful drop. @@ -136,19 +136,19 @@ fn drop(_: ?*anyopaque, _: ?*c.struct_wl_data_device) callconv(.c) void { } 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 { - if (s().device == null) return n.UHDK_STATUS_UNSUPPORTED; + if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED; w.drop_enabled = enabled; - if (s().drag_window == w) negotiate(); + if (dataState().drag_window == w) negotiate(); return abi.OK; } fn sourceUnref(source: *Source) void { source.refs -= 1; if (source.refs != 0) return; - var link = &s().sources; + var link = &dataState().sources; while (link.* != source) link = &link.*.?.next; link.* = source.next; - b().app.gpa.free(source.bytes); - b().app.gpa.destroy(source); + backend().app.gpa.free(source.bytes); + backend().app.gpa.destroy(source); } 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 { @@ -158,13 +158,13 @@ fn send(raw: ?*anyopaque, _: ?*c.struct_wl_data_source, name: [*c]const u8, fd: _ = c.close(fd); return; } - const transfer = b().app.gpa.create(Transfer) catch { + const transfer = backend().app.gpa.create(Transfer) catch { _ = c.close(fd); return; }; source.refs += 1; - transfer.* = .{ .next = s().transfers, .fd = fd, .source = source, .deadline = runtime.now(b().app.io) + 10 * std.time.ns_per_s }; - s().transfers = transfer; + transfer.* = .{ .next = dataState().transfers, .fd = fd, .source = source, .deadline = runtime.now(backend().app.io) + 10 * std.time.ns_per_s }; + dataState().transfers = transfer; } fn cancelled(raw: ?*anyopaque, proxy: ?*c.struct_wl_data_source) callconv(.c) void { const source = data(Source, raw); @@ -176,60 +176,60 @@ fn unused(_: ?*anyopaque, _: ?*c.struct_wl_data_source) 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 }; pub fn write(text: n.uhdk_text) u32 { - if (s().device == null) return n.UHDK_STATUS_UNSUPPORTED; + if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED; const input = Input.state(); // Selection changes require an actual input serial. Never queue a write to // hijack an unrelated future keystroke when the app has no input focus. if (input.key_focus == null or input.serial == 0) return abi.UNAVAILABLE; - const source = b().app.gpa.create(Source) catch return abi.OOM; - const bytes = b().app.gpa.dupe(u8, abi.textBytes(text)) catch { - b().app.gpa.destroy(source); + const source = backend().app.gpa.create(Source) catch return abi.OOM; + const bytes = backend().app.gpa.dupe(u8, abi.textBytes(text)) catch { + backend().app.gpa.destroy(source); return abi.OOM; }; - const proxy = c.wl_data_device_manager_create_data_source(s().manager) orelse { - b().app.gpa.free(bytes); - b().app.gpa.destroy(source); + const proxy = c.wl_data_device_manager_create_data_source(dataState().manager) orelse { + backend().app.gpa.free(bytes); + backend().app.gpa.destroy(source); return abi.OOM; }; - source.* = .{ .next = s().sources, .proxy = proxy, .bytes = bytes }; - s().sources = source; + source.* = .{ .next = dataState().sources, .proxy = proxy, .bytes = bytes }; + dataState().sources = source; _ = c.wl_data_source_add_listener(proxy, &source_listener, source); c.wl_data_source_offer(proxy, "text/plain;charset=utf-8"); c.wl_data_source_offer(proxy, "text/plain"); - c.wl_data_device_set_selection(s().device, proxy, input.serial); + c.wl_data_device_set_selection(dataState().device, proxy, input.serial); return abi.OK; } pub fn read(id: u64, limit: u64) u32 { - if (s().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; - const o = s().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; return receive(o, format, id, limit, null); } fn receive(o: *Offer, format: [*:0]const u8, id: u64, limit: u64, w: ?*native.Window) u32 { var fds: [2]c_int = undefined; if (c.z_linux_pipe(&fds) != 0) return n.UHDK_STATUS_OS_ERROR; - const transfer = b().app.gpa.create(Transfer) catch { + const transfer = backend().app.gpa.create(Transfer) catch { _ = c.close(fds[0]); _ = c.close(fds[1]); return abi.OOM; }; o.refs += 1; - transfer.* = .{ .next = s().transfers, .fd = fds[0], .request = id, .offer = o, .window = w, .position = s().position, .limit = limit, .deadline = runtime.now(b().app.io) + 10 * std.time.ns_per_s }; - s().transfers = transfer; + 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; c.wl_data_offer_receive(o.proxy, format, fds[1]); _ = c.close(fds[1]); return n.Z_DEFERRED; } pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void { - var t = s().transfers; - while (t) |item| : (t = item.next) try fds.append(b().app.gpa, .{ .fd = item.fd, .events = if (item.source != null) c.POLLOUT else c.POLLIN, .revents = 0 }); + 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 }); } pub fn tick() i32 { - var t = s().transfers; + var t = dataState().transfers; while (t) |item| { t = item.next; - if (runtime.now(b().app.io) >= item.deadline) { + if (runtime.now(backend().app.io) >= item.deadline) { finish(item, abi.UNAVAILABLE); continue; } @@ -250,46 +250,46 @@ pub fn tick() i32 { finish(item, n.UHDK_STATUS_BUFFER_TOO_SMALL); continue; } - item.bytes.appendSlice(b().app.gpa, buffer[0..length]) catch { + item.bytes.appendSlice(backend().app.gpa, buffer[0..length]) catch { finish(item, abi.OOM); continue; }; } else if (c.z_linux_errno() != c.EAGAIN and c.z_linux_errno() != c.EINTR) finish(item, abi.UNAVAILABLE); } } - return if (s().transfers != null) 100 else -1; + return if (dataState().transfers != null) 100 else -1; } fn finish(t: *Transfer, status: u32) void { if (t.request != 0) { var result = std.mem.zeroes(n.z_request_result); result.value.text = abi.textSpan(t.bytes.items); - n.z_complete(runtime.toAppHandle(b().app), t.request, if (status == abi.OK and !std.unicode.utf8ValidateSlice(t.bytes.items)) abi.INVALID else status, &result); + n.z_complete(runtime.toAppHandle(backend().app), t.request, if (status == abi.OK and !std.unicode.utf8ValidateSlice(t.bytes.items)) abi.INVALID else status, &result); } 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); } - var link = &s().transfers; + var link = &dataState().transfers; while (link.* != t) link = &link.*.?.next; link.* = t.next; _ = c.close(t.fd); if (t.offer) |o| unref(o); if (t.source) |source| sourceUnref(source); - t.bytes.deinit(b().app.gpa); - b().app.gpa.destroy(t); + t.bytes.deinit(backend().app.gpa); + backend().app.gpa.destroy(t); } fn emitDrop(w: *native.Window, bytes: []const u8, position: n.uhdk_point) bool { var files: std.ArrayList(?*n.uhdk_file) = .empty; defer { for (files.items) |file| n.uhdk_file_release(file); - files.deinit(b().app.gpa); + files.deinit(backend().app.gpa); } var lines = std.mem.splitScalar(u8, bytes, '\n'); while (lines.next()) |line| { const uri = std.mem.trim(u8, line, "\r"); if (uri.len == 0 or uri[0] == '#') continue; - const path = Files.decode(b().app.gpa, uri) catch return false; - defer b().app.gpa.free(path); - const file = n.z_file_from_url(runtime.toAppHandle(b().app), .{ .ptr = path.ptr, .len = path.len }, null) orelse return false; - files.append(b().app.gpa, file) catch { + const path = Files.decode(backend().app.gpa, uri) catch return false; + 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; + files.append(backend().app.gpa, file) catch { n.uhdk_file_release(file); return false; }; @@ -302,7 +302,7 @@ fn emitDrop(w: *native.Window, bytes: []const u8, position: n.uhdk_point) bool { return true; } pub fn cancel(id: u64) bool { - var t = s().transfers; + var t = dataState().transfers; while (t) |item| : (t = item.next) if (item.request == id) { finish(item, abi.CANCELLED); return true; @@ -310,11 +310,11 @@ pub fn cancel(id: u64) bool { return false; } pub fn forget(w: *native.Window) void { - if (s().drag_window == w) { - s().drag_window = null; + if (dataState().drag_window == w) { + dataState().drag_window = null; negotiate(); } - var t = s().transfers; + var t = dataState().transfers; while (t) |item| { t = item.next; if (item.window == w) { @@ -324,22 +324,22 @@ pub fn forget(w: *native.Window) void { } } pub fn releaseSeat() void { - while (s().transfers) |t| finish(t, abi.CANCELLED); - s().selection = null; - s().drag = null; - s().drag_window = null; - while (s().offers) |o| unref(o); - while (s().sources) |source| { + while (dataState().transfers) |t| finish(t, abi.CANCELLED); + dataState().selection = null; + dataState().drag = null; + dataState().drag_window = null; + while (dataState().offers) |o| unref(o); + while (dataState().sources) |source| { if (source.proxy != null) c.wl_data_source_destroy(source.proxy); sourceUnref(source); } - if (s().device != null) c.wl_data_device_release(s().device); - s().device = null; + if (dataState().device != null) c.wl_data_device_release(dataState().device); + dataState().device = null; native.setCapability(n.UHDK_CAP_CLIPBOARD, false); native.setCapability(n.UHDK_CAP_DROP_FILES, false); } pub fn deinit() void { releaseSeat(); - if (s().manager != null) c.wl_data_device_manager_destroy(s().manager); - s().manager = null; + if (dataState().manager != null) c.wl_data_device_manager_destroy(dataState().manager); + dataState().manager = null; } diff --git a/src/linux/Desktop.zig b/src/linux/Desktop.zig index e3e4ec5..f76d96d 100644 --- a/src/linux/Desktop.zig +++ b/src/linux/Desktop.zig @@ -17,21 +17,21 @@ pub const State = struct { pending: ?*Activation = null, launch: ?[:0]u8 = null, }; -fn b() *native.Backend { +fn backend() *native.Backend { return native.instance.?; } -fn s() *State { - return &b().desktop; +fn desktopState() *State { + return &backend().desktop; } pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void { - if (std.mem.eql(u8, interface, "xdg_activation_v1")) s().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")) { - s().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_toplevel_icon_manager_v1_interface, 1)); - if (s().manager != null) _ = c.xdg_toplevel_icon_manager_v1_add_listener(s().manager, &icon_listener, null); + 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)); + if (desktopState().manager != null) _ = c.xdg_toplevel_icon_manager_v1_add_listener(desktopState().manager, &icon_listener, null); } else if (std.mem.eql(u8, interface, "wl_shm")) { - s().shm = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wl_shm_interface, 1)); - if (s().shm != null) _ = c.wl_shm_add_listener(s().shm, &shm_listener, null); + 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); } - native.setCapability(n.UHDK_CAP_APP_ICON, s().manager != null and s().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 iconDone(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel_icon_manager_v1) callconv(.c) void {} @@ -41,63 +41,63 @@ const shm_listener: c.struct_wl_shm_listener = .{ .format = format }; pub fn initialize() void { const token = c.getenv("XDG_ACTIVATION_TOKEN"); if (token != null and token[0] != 0) { - s().launch = b().app.gpa.dupeZ(u8, std.mem.span(token)) catch null; + desktopState().launch = backend().app.gpa.dupeZ(u8, std.mem.span(token)) catch null; _ = c.unsetenv("XDG_ACTIVATION_TOKEN"); } } pub fn focus(w: *native.Window, id: u64) u32 { - if (s().activation == null) return n.UHDK_STATUS_UNSUPPORTED; - if (s().launch) |token| { - c.xdg_activation_v1_activate(s().activation, token, w.surface); - b().app.gpa.free(token); - s().launch = null; + if (desktopState().activation == null) return n.UHDK_STATUS_UNSUPPORTED; + if (desktopState().launch) |token| { + c.xdg_activation_v1_activate(desktopState().activation, token, w.surface); + backend().app.gpa.free(token); + desktopState().launch = null; return abi.OK; } const input = Input.state(); - if (input.serial == 0 or input.key_focus == null or runtime.now(b().app.io) -| input.serial_time > 5 * std.time.ns_per_s) return abi.UNAVAILABLE; - const p = b().app.gpa.create(Activation) catch return abi.OOM; - const token = c.xdg_activation_v1_get_activation_token(s().activation) orelse { - b().app.gpa.destroy(p); + if (input.serial == 0 or input.key_focus == null or runtime.now(backend().app.io) -| input.serial_time > 5 * std.time.ns_per_s) return abi.UNAVAILABLE; + const p = backend().app.gpa.create(Activation) catch return abi.OOM; + const token = c.xdg_activation_v1_get_activation_token(desktopState().activation) orelse { + backend().app.gpa.destroy(p); return abi.OOM; }; - p.* = .{ .next = s().pending, .id = id, .window = w, .token = token, .deadline = runtime.now(b().app.io) + 5 * std.time.ns_per_s }; - s().pending = p; + p.* = .{ .next = desktopState().pending, .id = id, .window = w, .token = token, .deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s }; + desktopState().pending = 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_surface(token, input.key_focus.?.surface); - const app_id = b().app.gpa.dupeZ(u8, b().app.application_id) catch { + const app_id = backend().app.gpa.dupeZ(u8, backend().app.application_id) catch { finish(p, abi.OOM); return n.Z_DEFERRED; }; - defer b().app.gpa.free(app_id); + defer backend().app.gpa.free(app_id); c.xdg_activation_token_v1_set_app_id(token, app_id); c.xdg_activation_token_v1_commit(token); return n.Z_DEFERRED; } fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c]const u8) callconv(.c) void { const p: *Activation = @ptrCast(@alignCast(raw.?)); - c.xdg_activation_v1_activate(s().activation, token, p.window.surface); + c.xdg_activation_v1_activate(desktopState().activation, token, p.window.surface); finish(p, abi.OK); } const activation_listener: c.struct_xdg_activation_token_v1_listener = .{ .done = activated }; fn finish(p: *Activation, status: u32) void { - var link = &s().pending; + var link = &desktopState().pending; while (link.* != p) link = &link.*.?.next; link.* = p.next; c.xdg_activation_token_v1_destroy(p.token); - n.z_complete(runtime.toAppHandle(b().app), p.id, status, null); - b().app.gpa.destroy(p); + n.z_complete(runtime.toAppHandle(backend().app), p.id, status, null); + backend().app.gpa.destroy(p); } pub fn tick() i32 { - var cursor = s().pending; + var cursor = desktopState().pending; while (cursor) |p| { cursor = p.next; - if (runtime.now(b().app.io) >= p.deadline) finish(p, abi.UNAVAILABLE); + if (runtime.now(backend().app.io) >= p.deadline) finish(p, abi.UNAVAILABLE); } - return if (s().pending != null) 100 else -1; + return if (desktopState().pending != null) 100 else -1; } pub fn cancel(id: u64) bool { - var cursor = s().pending; + var cursor = desktopState().pending; while (cursor) |p| : (cursor = p.next) if (p.id == id) { finish(p, abi.CANCELLED); return true; @@ -105,14 +105,14 @@ pub fn cancel(id: u64) bool { return false; } pub fn forget(w: *native.Window) void { - var cursor = s().pending; + var cursor = desktopState().pending; while (cursor) |p| { cursor = p.next; if (p.window == w) finish(p, abi.CANCELLED); } } pub fn applyIcon(w: *native.Window) void { - if (s().icon) |icon| c.xdg_toplevel_icon_manager_v1_set_icon(s().manager, w.top, icon.proxy); + if (desktopState().icon) |icon| 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, /// premultiplied channels. Pad rectangular images to a transparent square. @@ -131,7 +131,7 @@ pub fn pixels(destination: []u32, side: usize, image: n.uhdk_image) void { }; } pub fn setIcon(image: n.uhdk_image) u32 { - if (s().manager == null or s().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 size: usize = @as(usize, side) * side * 4; const fd = c.memfd_create("uhdk-icon", c.MFD_CLOEXEC); @@ -146,18 +146,18 @@ pub fn setIcon(image: n.uhdk_image) u32 { }; const words: [*]u32 = @ptrCast(@alignCast(mapping.?)); pixels(words[0 .. size / 4], side, image); - const pool = c.wl_shm_create_pool(s().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); const buffer = c.wl_shm_pool_create_buffer(pool, 0, @intCast(side), @intCast(side), @intCast(side * 4), c.WL_SHM_FORMAT_ARGB8888) orelse return abi.OOM; - const proxy = c.xdg_toplevel_icon_manager_v1_create_icon(s().manager) orelse { + const proxy = c.xdg_toplevel_icon_manager_v1_create_icon(desktopState().manager) orelse { c.wl_buffer_destroy(buffer); return abi.OOM; }; c.xdg_toplevel_icon_v1_add_buffer(proxy, buffer, 1); - const old = s().icon; - s().icon = .{ .proxy = proxy, .buffer = buffer, .mapping = mapping.?, .size = size }; + const old = desktopState().icon; + desktopState().icon = .{ .proxy = proxy, .buffer = buffer, .mapping = mapping.?, .size = size }; retained = true; - var cursor = b().windows; + var cursor = backend().windows; while (cursor) |w| : (cursor = w.next) applyIcon(w); if (old) |icon| destroyIcon(icon); return abi.OK; @@ -168,12 +168,12 @@ fn destroyIcon(icon: Icon) void { _ = c.munmap(icon.mapping, icon.size); } pub fn deinit() void { - while (s().pending) |p| finish(p, abi.CANCELLED); - if (s().icon) |icon| destroyIcon(icon); - if (s().launch) |token| b().app.gpa.free(token); - if (s().manager != null) c.xdg_toplevel_icon_manager_v1_destroy(s().manager); - if (s().shm != null) c.wl_shm_destroy(s().shm); - if (s().activation != null) c.xdg_activation_v1_destroy(s().activation); + while (desktopState().pending) |p| finish(p, abi.CANCELLED); + if (desktopState().icon) |icon| destroyIcon(icon); + if (desktopState().launch) |token| backend().app.gpa.free(token); + if (desktopState().manager != null) c.xdg_toplevel_icon_manager_v1_destroy(desktopState().manager); + if (desktopState().shm != null) c.wl_shm_destroy(desktopState().shm); + if (desktopState().activation != null) c.xdg_activation_v1_destroy(desktopState().activation); } test "icons premultiply RGBA and pad rectangular images" { const rgba = [_]u8{ 255, 128, 0, 128, 0, 255, 0, 255 }; diff --git a/src/linux/Egl.zig b/src/linux/Egl.zig index 5ddfd5a..624ab1b 100644 --- a/src/linux/Egl.zig +++ b/src/linux/Egl.zig @@ -42,7 +42,7 @@ pub fn finish(b: *native.Backend) void { b.egl_display = null; } } -pub fn create(b: *native.Backend, w: *native.Window, object: ?*anyopaque) 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 (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; @@ -68,7 +68,6 @@ pub fn create(b: *native.Backend, w: *native.Window, object: ?*anyopaque) u32 { }; ctx.* = .{ .window = w, .native = win, .surface = surface, .context = context }; w.egl = ctx; - n.z_object_set_native(object, ctx); return abi.OK; } pub fn destroy(ctx: *Context) void { diff --git a/src/linux/Input.zig b/src/linux/Input.zig index 01a5327..358285f 100644 --- a/src/linux/Input.zig +++ b/src/linux/Input.zig @@ -69,14 +69,14 @@ pub const State = struct { axis_stop: bool = false, scrolling: bool = false, }; -fn b() *native.Backend { +fn backend() *native.Backend { return native.instance.?; } pub fn state() *State { - return &b().input; + return &backend().input; } pub fn find(surface: ?*c.struct_wl_surface) ?*native.Window { - var item = b().windows; + var item = backend().windows; while (item) |w| : (item = w.next) if (w.surface == surface) return w; return null; } @@ -90,7 +90,7 @@ pub fn id() u64 { } pub fn provenance(serial: u32) void { state().serial = serial; - state().serial_time = runtime.now(b().app.io); + state().serial_time = runtime.now(backend().app.io); } pub fn initialize() void { const s = state(); @@ -223,12 +223,12 @@ fn key(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, serial: u32, _: u32, code: u32 // authoritative modifiers event supply the public post-event flags even // when the key and modifier messages arrive in separate socket reads. if (s.key_sync == null) { - s.key_sync = c.wl_display_sync(b().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 (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_at = runtime.now(b().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; } fn prepareKey(code: u32, down: bool, repeated: bool) Key { @@ -298,11 +298,11 @@ pub fn tick() i32 { var event = std.mem.zeroes(n.z_event); event.type = n.UHDK_EVENT_APP_ACTIVATION; event.data.active = @intFromBool(active); - n.z_emit(runtime.toAppHandle(b().app), &event); + n.z_emit(runtime.toAppHandle(backend().app), &event); } if (s.pending_key != null) return -1; if (s.repeat_key) |code| { - const now = runtime.now(b().app.io); + const now = runtime.now(backend().app.io); if (now >= s.repeat_at) { deliverKey(code, true, true); s.repeat_at = now + std.time.ns_per_s / @max(1, s.repeat_rate); @@ -404,7 +404,7 @@ fn button(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, _: u32, code: u if (pressed != 0) { s.buttons |= mask; - const now = runtime.now(b().app.io); + const now = runtime.now(backend().app.io); const dx = s.position.x - s.last_click_position.x; 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; @@ -500,7 +500,7 @@ fn popupTrigger(w: ?*native.Window, serial: u32) void { const s = state(); s.popup_window = w; s.popup_serial = serial; - s.popup_time = runtime.now(b().app.io); + s.popup_time = runtime.now(backend().app.io); } pub fn beginPopup() void { normal(n.UHDK_CYCLE_CAPTURE_LOST); diff --git a/src/linux/KdeAppMenu.zig b/src/linux/KdeAppMenu.zig index 3d92176..ef3bfaf 100644 --- a/src/linux/KdeAppMenu.zig +++ b/src/linux/KdeAppMenu.zig @@ -38,48 +38,48 @@ pub const State = struct { sequence: u64 = 0, app_menu: ?*Resource = null, }; -fn b() *native.Backend { +fn backend() *native.Backend { return native.instance.?; } -fn s() *State { - return &b().menus; +fn menuState() *State { + return &backend().menus; } fn same(a: []const u8, z: []const u8) bool { return std.mem.eql(u8, a, z); } pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void { - if (!same(interface, "org_kde_kwin_appmenu_manager") or s().manager != null) return; - s().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_org_kde_kwin_appmenu_manager_interface, @min(version, 2))); - s().global_name = name; + if (!same(interface, "org_kde_kwin_appmenu_manager") or menuState().manager != null) return; + menuState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_org_kde_kwin_appmenu_manager_interface, @min(version, 2))); + menuState().global_name = name; ready(); } pub fn remove(name: u32) void { - if (name != s().global_name) return; + if (name != menuState().global_name) return; disconnected(); destroyManager(); } fn destroyManager() void { - if (s().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); } - s().manager = null; - s().global_name = 0; + menuState().manager = null; + menuState().global_name = 0; } pub fn ready() void { - native.setCapability(n.UHDK_CAP_APP_MENU, s().manager != null and b().portal.ready); - var cursor = b().windows; + native.setCapability(n.UHDK_CAP_APP_MENU, menuState().manager != null and backend().portal.ready); + var cursor = backend().windows; while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| associate(e); } fn associate(e: *Export) void { - if (e.proxy != null or s().manager == null or !b().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. - e.proxy = c.org_kde_kwin_appmenu_manager_create(s().manager, e.window.surface) orelse return; - c.org_kde_kwin_appmenu_set_address(e.proxy, b().portal.unique.?.ptr, e.path.ptr); + 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); } pub fn disconnected() void { native.setCapability(n.UHDK_CAP_APP_MENU, false); - var cursor = b().windows; + var cursor = backend().windows; while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| unassociate(e); } fn unassociate(e: *Export) void { @@ -90,7 +90,7 @@ fn destroy(e: *Export) void { unassociate(e); runtime.release(e.root); e.arena.deinit(); - b().app.gpa.destroy(e); + backend().app.gpa.destroy(e); } fn add(e: *Export, menu: *Resource, parent: usize) !void { var previous: usize = 0; @@ -113,12 +113,12 @@ fn add(e: *Export, menu: *Resource, parent: usize) !void { } } fn create(w: *native.Window, root: *Resource) !*Export { - const e = try b().app.gpa.create(Export); - errdefer b().app.gpa.destroy(e); - s().sequence += 1; - e.* = .{ .window = w, .root = root, .arena = .init(b().app.gpa), .path = "" }; + const e = try backend().app.gpa.create(Export); + errdefer backend().app.gpa.destroy(e); + menuState().sequence += 1; + e.* = .{ .window = w, .root = root, .arena = .init(backend().app.gpa), .path = "" }; errdefer e.arena.deinit(); - e.path = try std.fmt.allocPrintSentinel(e.arena.allocator(), prefix ++ "{d}", .{s().sequence}, 0); + e.path = try std.fmt.allocPrintSentinel(e.arena.allocator(), prefix ++ "{d}", .{menuState().sequence}, 0); try e.nodes.append(e.arena.allocator(), .{}); try add(e, root, 0); runtime.retain(root); @@ -131,16 +131,16 @@ fn replace(w: *native.Window, e: ?*Export) void { if (e) |value| associate(value); } pub fn inherit(w: *native.Window) !void { - if (s().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 { const root: ?*Resource = if (menu) |p| @ptrCast(@alignCast(p)) else null; if (root != null) { - if (s().manager == null) return n.UHDK_STATUS_UNSUPPORTED; - if (b().portal.connection == null) return abi.UNAVAILABLE; + if (menuState().manager == null) return n.UHDK_STATUS_UNSUPPORTED; + if (backend().portal.connection == null) return abi.UNAVAILABLE; } if (w) |window| { - const effective = root orelse s().app_menu; + const effective = root orelse menuState().app_menu; const e = if (effective) |r| create(window, r) catch return abi.OOM else null; if (root) |r| runtime.retain(r); if (window.menu_override) |r| runtime.release(r); @@ -154,7 +154,7 @@ pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 { destroy(e); }; if (root) |r| { - var cursor = b().windows; + var cursor = backend().windows; while (cursor) |window| : (cursor = window.next) if (window.menu_override == null) { const e = create(window, r) catch return abi.OOM; e.next = pending; @@ -162,10 +162,10 @@ pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 { }; runtime.retain(r); } - if (s().app_menu) |r| runtime.release(r); - s().app_menu = root; + if (menuState().app_menu) |r| runtime.release(r); + menuState().app_menu = root; if (root == null) { - var cursor = b().windows; + var cursor = backend().windows; while (cursor) |window| : (cursor = window.next) if (window.menu_override == null) { replace(window, null); }; @@ -184,8 +184,8 @@ pub fn forget(w: *native.Window) void { w.menu_override = null; } pub fn deinit() void { - if (s().app_menu) |root| runtime.release(root); - s().app_menu = null; + if (menuState().app_menu) |root| runtime.release(root); + menuState().app_menu = null; destroyManager(); } fn enabled(e: *Export, index: usize) bool { @@ -296,7 +296,7 @@ fn groupItem(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void try Bus.close(out, &tuple); } pub fn updateFlags() u32 { - var cursor = b().windows; + var cursor = backend().windows; while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| { changed(e) catch return abi.OOM; }; @@ -309,7 +309,7 @@ fn changed(e: *Export) !void { break; }; if (!dirty) return; - if (b().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; defer c.z_dbus_message_unref.?(message); var out = Bus.append(message); @@ -355,7 +355,7 @@ pub fn process(message: *Bus.Message) !bool { const path = c.z_dbus_message_get_path.?(message); if (path == null or !std.mem.startsWith(u8, std.mem.span(path), prefix)) return false; var found: ?*Export = null; - var cursor = b().windows; + var cursor = backend().windows; while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| { if (same(e.path, std.mem.span(path))) { found = e; diff --git a/src/linux/Popup.zig b/src/linux/Popup.zig index 1fa8aed..5855c26 100644 --- a/src/linux/Popup.zig +++ b/src/linux/Popup.zig @@ -40,17 +40,17 @@ pub const State = struct { serial: u32 = 0, hover_at: u64 = 0, }; -fn b() *native.Backend { +fn backend() *native.Backend { return native.instance.?; } -fn s() *State { - return &b().popup; +fn popupState() *State { + return &backend().popup; } pub fn active() bool { - return s().request != 0; + return popupState().request != 0; } pub fn capability() void { - native.setCapability(n.UHDK_CAP_CONTEXT_MENU, b().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 { return @ptrCast(@alignCast(raw.?)); @@ -67,12 +67,12 @@ fn rowY(p: *Panel, index: usize) i32 { return y - p.scroll; } fn lookup(surface: ?*c.struct_wl_surface) ?*Panel { - var cursor = s().top; + var cursor = popupState().top; while (cursor) |p| : (cursor = p.parent) if (p.surface == surface) return p; return null; } pub fn owner(surface: ?*c.struct_wl_surface) ?*native.Window { - return if (lookup(surface) != null) s().window else null; + return if (lookup(surface) != null) popupState().window else null; } fn freeBuffer(buf: *Buffer) void { if (buf.proxy != null) c.wl_buffer_destroy(buf.proxy); @@ -80,37 +80,37 @@ fn freeBuffer(buf: *Buffer) void { buf.* = .{}; } fn destroy(p: *Panel) void { - if (s().pointer == p) s().pointer = null; + if (popupState().pointer == p) popupState().pointer = null; if (p.popup != null) c.xdg_popup_destroy(p.popup); if (p.xdg != null) c.xdg_surface_destroy(p.xdg); if (p.surface != null) c.wl_surface_destroy(p.surface); for (&p.buffers) |*buf| freeBuffer(buf); - b().app.gpa.destroy(p); + backend().app.gpa.destroy(p); } fn closeChildren(p: *Panel) void { - while (s().top != p) { - const top = s().top orelse return; - s().top = top.parent; + while (popupState().top != p) { + const top = popupState().top orelse return; + popupState().top = top.parent; destroy(top); } } fn finish(status: u32) void { if (!active()) return; - const request_id = s().request; - while (s().top) |top| { - s().top = top.parent; + const request_id = popupState().request; + while (popupState().top) |top| { + popupState().top = top.parent; destroy(top); } - const root = s().root.?; - s().* = .{}; + const root = popupState().root.?; + popupState().* = .{}; runtime.release(root); - n.z_complete(runtime.toAppHandle(b().app), request_id, status, null); + n.z_complete(runtime.toAppHandle(backend().app), request_id, status, null); } pub fn forget(w: *native.Window) void { - if (s().window == w) finish(abi.CANCELLED); + if (popupState().window == w) finish(abi.CANCELLED); } pub fn cancel(id: u64) bool { - if (s().request != id or !active()) return false; + if (popupState().request != id or !active()) return false; finish(abi.CANCELLED); return true; } @@ -119,31 +119,31 @@ pub fn deinit() void { } pub fn request(cmd: *const n.z_command, id: u64) u32 { if (active()) return n.UHDK_STATUS_BUSY; - if (b().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 input = Input.state(); - if (!w.visible or !w.configured or input.popup_window != w or input.popup_serial == 0 or runtime.now(b().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.?)); if (root.payload.menu.items.len == 0) return abi.CANCELLED; - s().window = w; - s().root = root; - s().serial = input.popup_serial; + popupState().window = w; + popupState().root = root; + popupState().serial = input.popup_serial; 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 p = create(root, null, @intFromFloat(point.x), @intFromFloat(point.y), 1) catch { runtime.release(root); - s().* = .{}; + popupState().* = .{}; return abi.OOM; }; - s().top = p; - s().request = id; + popupState().top = p; + popupState().request = id; Input.beginPopup(); input.popup_serial = 0; // A root grab consumes its triggering action. return n.Z_DEFERRED; } fn create(menu: *Resource, parent: ?*Panel, x: i32, y: i32, anchor_height: i32) !*Panel { - const p = try b().app.gpa.create(Panel); - p.* = .{ .parent = parent, .menu = menu, .scale = @intCast(std.math.clamp((s().window.?.scale + 119) / 120, 1, 4)), .deadline = runtime.now(b().app.io) + 5 * std.time.ns_per_s }; + 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 }; errdefer destroy(p); for (menu.payload.menu.items) |item| { var buffer: [96]u8 = undefined; @@ -154,20 +154,20 @@ fn create(menu: *Resource, parent: ?*Panel, x: i32, y: i32, anchor_height: i32) p.height = @min(p.total, 480); p.pending_width = p.width; p.pending_height = p.height; - p.surface = c.wl_compositor_create_surface(b().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; - p.xdg = c.xdg_wm_base_get_xdg_surface(b().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; - const pos = c.xdg_wm_base_create_positioner(b().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); c.xdg_positioner_set_size(pos, p.width, p.height); c.xdg_positioner_set_anchor_rect(pos, x, y, 1, @max(1, anchor_height)); c.xdg_positioner_set_anchor(pos, if (parent != null) c.XDG_POSITIONER_ANCHOR_TOP_RIGHT else c.XDG_POSITIONER_ANCHOR_BOTTOM_LEFT); c.xdg_positioner_set_gravity(pos, c.XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT); 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 s().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; - c.xdg_popup_grab(p.popup, Input.state().seat, s().serial); + c.xdg_popup_grab(p.popup, Input.state().seat, popupState().serial); c.wl_surface_commit(p.surface); return p; } @@ -182,7 +182,7 @@ fn configure(raw: ?*anyopaque, _: ?*c.struct_xdg_popup, _: i32, _: i32, width: i p.pending_width = width; p.pending_height = height; p.configured = false; - p.deadline = runtime.now(b().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 { const p = panel(raw); @@ -202,7 +202,7 @@ fn done(raw: ?*anyopaque, _: ?*c.struct_xdg_popup) callconv(.c) void { const p = panel(raw); if (p.parent) |parent| { closeChildren(parent); - s().hover_at = 0; + popupState().hover_at = 0; } else finish(abi.CANCELLED); } fn repositioned(_: ?*anyopaque, _: ?*c.struct_xdg_popup, _: u32) callconv(.c) void {} @@ -237,7 +237,7 @@ fn allocateBuffer(p: *Panel, buf: *Buffer) !void { buf.mapping = mapping; buf.size = size; errdefer freeBuffer(buf); - const pool = c.wl_shm_create_pool(b().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); 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; @@ -250,7 +250,7 @@ fn render(p: *Panel) !void { if (buf.proxy == null) try allocateBuffer(p, buf); 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 }; - paint(canvas, p.menu.payload.menu.items, p.selected, p.scroll, b().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); c.wl_surface_set_buffer_scale(p.surface, p.scale); c.xdg_surface_set_window_geometry(p.xdg, 0, 0, p.width, p.height); c.wl_surface_attach(p.surface, buf.proxy, 0, 0); @@ -306,7 +306,7 @@ fn choose(p: *Panel, index: ?usize) void { p.selected = index; p.pressed = null; p.dirty = true; - s().hover_at = if (index != null and p.menu.payload.menu.items[index.?].submenu != null) runtime.now(b().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 { if (x < 3 or x >= @as(f32, @floatFromInt(p.width - 3)) or y < 4 or y >= @as(f32, @floatFromInt(p.height - 4))) return null; @@ -319,23 +319,23 @@ fn hit(p: *Panel, x: f32, y: f32) ?usize { return null; } pub fn pointerEnter(surface: ?*c.struct_wl_surface, x: f32, y: f32, serial: u32) bool { - s().pointer = lookup(surface); - const p = s().pointer orelse return false; + popupState().pointer = lookup(surface); + const p = popupState().pointer orelse return false; 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); choose(p, hit(p, x, y)); return true; } pub fn pointerLeave() void { - s().pointer = null; - s().hover_at = 0; + popupState().pointer = null; + popupState().hover_at = 0; } pub fn motion(x: f32, y: f32) void { - if (s().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 { - if (down) s().serial = serial; - const p = s().pointer orelse { + if (down) popupState().serial = serial; + const p = popupState().pointer orelse { if (down) finish(abi.CANCELLED); return; }; @@ -343,7 +343,7 @@ pub fn button(code: u32, down: bool, serial: u32) void { if (down) p.pressed = p.selected else if (p.pressed != null and p.pressed == p.selected) select(p); } fn openChild(p: *Panel) void { - s().hover_at = 0; + popupState().hover_at = 0; const index = p.selected orelse return; const item = p.menu.payload.menu.items[index]; if (!usable(item) or item.submenu == null) return; @@ -355,7 +355,7 @@ fn openChild(p: *Panel) void { finish(abi.OOM); return; }; - s().top = child; + popupState().top = child; } fn select(p: *Panel) void { const index = p.selected orelse return; @@ -365,7 +365,7 @@ fn select(p: *Panel) void { openChild(p); return; } - Menu.activate(s().window.?, item, Input.id()); + Menu.activate(popupState().window.?, item, Input.id()); finish(abi.OK); // Command event must precede request completion. } fn reveal(p: *Panel) void { @@ -384,7 +384,7 @@ fn move(p: *Panel, forward: bool) void { index = if (forward) (index + 1) % items.len else (index + items.len - 1) % items.len; if (usable(items[index])) { choose(p, index); - s().hover_at = 0; + popupState().hover_at = 0; reveal(p); return; } @@ -392,8 +392,8 @@ fn move(p: *Panel, forward: bool) void { } pub fn key(logical: u32, down: bool, serial: u32) void { if (!down) return; - const p = s().top orelse return; - s().serial = serial; + const p = popupState().top orelse return; + popupState().serial = serial; switch (logical) { n.UHDK_KEY_ESCAPE => finish(abi.CANCELLED), n.UHDK_KEY_UP => move(p, false), @@ -408,27 +408,27 @@ pub fn key(logical: u32, down: bool, serial: u32) void { }, n.UHDK_KEY_RIGHT => { openChild(p); - if (s().top != p and s().top != null) move(s().top.?, true); + if (popupState().top != p and popupState().top != null) move(popupState().top.?, true); }, n.UHDK_KEY_LEFT => if (p.parent) |parent| { closeChildren(parent); - s().hover_at = 0; + popupState().hover_at = 0; }, n.UHDK_KEY_ENTER, ' ' => select(p), else => {}, } } pub fn scroll(delta: f32) void { - const p = s().pointer orelse return; + const p = popupState().pointer orelse return; closeChildren(p); p.scroll = std.math.clamp(p.scroll + @as(i32, @intFromFloat(std.math.clamp(delta, -480, 480))), 0, @max(0, p.total - p.height)); p.selected = null; p.pressed = null; p.dirty = true; - s().hover_at = 0; + popupState().hover_at = 0; } pub fn flags() void { - var cursor = s().top; + var cursor = popupState().top; while (cursor) |p| : (cursor = p.parent) { p.dirty = true; if (p.selected) |index| if (!usable(p.menu.payload.menu.items[index])) { @@ -440,13 +440,13 @@ pub fn flags() void { } pub fn tick() i32 { if (!active()) return -1; - const now = runtime.now(b().app.io); - if (s().hover_at != 0 and now >= s().hover_at) { - if (s().pointer) |p| openChild(p); - s().hover_at = 0; + const now = runtime.now(backend().app.io); + if (popupState().hover_at != 0 and now >= popupState().hover_at) { + if (popupState().pointer) |p| openChild(p); + popupState().hover_at = 0; } - var cursor = s().top; - var timeout: i32 = if (s().hover_at != 0) 25 else -1; + var cursor = popupState().top; + var timeout: i32 = if (popupState().hover_at != 0) 25 else -1; while (cursor) |p| : (cursor = p.parent) { if (!p.configured) { if (now >= p.deadline) { diff --git a/src/linux/Portal.zig b/src/linux/Portal.zig index dece15e..a3b79e9 100644 --- a/src/linux/Portal.zig +++ b/src/linux/Portal.zig @@ -44,19 +44,19 @@ pub const State = struct { 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 }, }; -fn b() *native.Backend { +fn backend() *native.Backend { return native.instance.?; } -fn s() *State { - return &b().portal; +fn portalState() *State { + return &backend().portal; } pub fn send(message: *Bus.Message) !u32 { var serial: u32 = 0; - if (c.z_dbus_connection_send.?(s().connection, message, &serial) == 0) return error.OutOfMemory; + if (c.z_dbus_connection_send.?(portalState().connection, message, &serial) == 0) return error.OutOfMemory; return serial; } pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void { - if (std.mem.eql(u8, interface, "zxdg_exporter_v2")) s().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 { if (c.z_linux_dbus_available() == 0 or c.z_dbus_threads_init_default.?() == 0) return; @@ -64,15 +64,15 @@ pub fn initialize() void { // address; absence disables portals without affecting windows or input. const address = c.getenv("DBUS_SESSION_BUS_ADDRESS"); if (address == null or !std.mem.startsWith(u8, std.mem.span(address), "unix:")) return; - s().connection = c.z_dbus_connection_open_private.?(address, null) orelse return; - c.z_dbus_connection_set_exit_on_disconnect.?(s().connection, 0); - s().startup_deadline = runtime.now(b().app.io) + 5 * std.time.ns_per_s; + portalState().connection = c.z_dbus_connection_open_private.?(address, null) orelse return; + 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; const message = Bus.method(dbus, dbus_path, dbus, "Hello") catch { disconnect(); return; }; defer c.z_dbus_message_unref.?(message); - s().hello = send(message) catch { + portalState().hello = send(message) catch { disconnect(); return; }; @@ -88,7 +88,7 @@ fn addMatches() !void { defer c.z_dbus_message_unref.?(message); var args = Bus.append(message); try Bus.string(&args, rule); - s().matches[i] = try send(message); + portalState().matches[i] = try send(message); } } fn discover() !void { @@ -97,7 +97,7 @@ fn discover() !void { var args = Bus.append(version); try Bus.string(&args, chooser); try Bus.string(&args, "version"); - s().version_serial = try send(version); + portalState().version_serial = try send(version); const read = try Bus.method(desktop, path, settings, "ReadAll"); defer c.z_dbus_message_unref.?(read); args = Bus.append(read); @@ -105,16 +105,16 @@ fn discover() !void { errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&args, &namespaces); try Bus.string(&namespaces, "org.freedesktop.appearance"); try Bus.close(&args, &namespaces); - s().settings_serial = try send(read); + portalState().settings_serial = try send(read); } pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void { - const connection = s().connection orelse return; + const connection = portalState().connection orelse return; var fd: c_int = -1; if (c.z_dbus_connection_get_unix_fd.?(connection, &fd) != 0) - try fds.append(b().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 { - const connection = s().connection orelse return -1; + const connection = portalState().connection orelse return -1; if (c.z_dbus_connection_read_write.?(connection, 0) == 0) { disconnect(); return -1; @@ -127,14 +127,14 @@ pub fn tick() i32 { disconnect(); return -1; }; - if (s().connection == null) return -1; + if (portalState().connection == null) return -1; } else return 0; - const now = runtime.now(b().app.io); - if (!s().ready and now >= s().startup_deadline) { + const now = runtime.now(backend().app.io); + if (!portalState().ready and now >= portalState().startup_deadline) { disconnect(); return -1; } - var cursor = s().pending; + var cursor = portalState().pending; while (cursor) |pending| { cursor = pending.next; if (pending.deadline != 0 and now >= pending.deadline) { @@ -143,54 +143,54 @@ pub fn tick() i32 { destroy(pending); } } - return if (s().pending != null or !s().ready) 100 else -1; + return if (portalState().pending != null or !portalState().ready) 100 else -1; } fn setOwner(message: *Bus.Message) !void { const sender = c.z_dbus_message_get_sender.?(message); if (sender == null) return; - if (s().owner) |old| b().app.gpa.free(old); - s().owner = try b().app.gpa.dupeZ(u8, std.mem.span(sender)); + if (portalState().owner) |old| backend().app.gpa.free(old); + portalState().owner = try backend().app.gpa.dupeZ(u8, std.mem.span(sender)); } fn process(message: *Bus.Message) !void { if (try KdeAppMenu.process(message)) return; const serial = c.z_dbus_message_get_reply_serial.?(message); const failed = c.z_dbus_message_get_type.?(message) == c.DBUS_MESSAGE_TYPE_ERROR; var args = Bus.parse(message); - if (serial != 0 and serial == s().hello) { - s().hello = 0; + if (serial != 0 and serial == portalState().hello) { + portalState().hello = 0; if (failed or c.z_dbus_message_has_signature.?(message, "s") == 0) { disconnect(); return; } - s().unique = try b().app.gpa.dupeZ(u8, Bus.str(&args).?); + portalState().unique = try backend().app.gpa.dupeZ(u8, Bus.str(&args).?); try addMatches(); return; } - for (&s().matches) |*match| if (serial != 0 and serial == match.*) { + for (&portalState().matches) |*match| if (serial != 0 and serial == match.*) { if (failed) { disconnect(); return; } match.* = 0; - if (std.mem.allEqual(u32, &s().matches, 0)) { - s().ready = true; + if (std.mem.allEqual(u32, &portalState().matches, 0)) { + portalState().ready = true; KdeAppMenu.ready(); try discover(); } return; }; - if (serial != 0 and serial == s().version_serial) { - s().version_serial = 0; + if (serial != 0 and serial == portalState().version_serial) { + portalState().version_serial = 0; if (!failed) { var value = Bus.variant(&args) orelse return; - s().chooser_version = Bus.uint(&value) orelse 0; + portalState().chooser_version = Bus.uint(&value) orelse 0; try setOwner(message); - native.setCapability(n.UHDK_CAP_FILE_DIALOGS, s().chooser_version >= 3); + native.setCapability(n.UHDK_CAP_FILE_DIALOGS, portalState().chooser_version >= 3); } return; } - if (serial != 0 and serial == s().settings_serial) { - s().settings_serial = 0; + if (serial != 0 and serial == portalState().settings_serial) { + portalState().settings_serial = 0; if (!failed and c.z_dbus_message_has_signature.?(message, "a{sa{sv}}") != 0) { try setOwner(message); var appearance = Bus.entry(&args, "org.freedesktop.appearance") orelse return; @@ -215,26 +215,26 @@ fn process(message: *Bus.Message) !void { _ = Bus.next(&args); const new = Bus.str(&args).?; if (old.len != 0) { - while (s().pending) |p| { + while (portalState().pending) |p| { complete(p, abi.UNAVAILABLE, null); destroy(p); } - s().chooser_version = 0; + portalState().chooser_version = 0; native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false); - if (s().owner) |owner| b().app.gpa.free(owner); - s().owner = null; + if (portalState().owner) |owner| backend().app.gpa.free(owner); + portalState().owner = null; preference("color-scheme", 0); preference("contrast", 0); preference("reduced-motion", 0); } if (new.len != 0) { - if (s().owner) |owner| b().app.gpa.free(owner); - s().owner = try b().app.gpa.dupeZ(u8, new); + if (portalState().owner) |owner| backend().app.gpa.free(owner); + portalState().owner = try backend().app.gpa.dupeZ(u8, new); try discover(); } return; } - var cursor = s().pending; + var cursor = portalState().pending; while (cursor) |pending| : (cursor = pending.next) { if (serial != 0 and serial == pending.serial) { pending.replied = true; @@ -248,8 +248,8 @@ fn process(message: *Bus.Message) !void { destroy(pending); return; } - const handle = try b().app.gpa.dupeZ(u8, Bus.str(&args).?); - b().app.gpa.free(pending.handle); + const handle = try backend().app.gpa.dupeZ(u8, Bus.str(&args).?); + backend().app.gpa.free(pending.handle); pending.handle = handle; if (pending.id == 0) { if (pending.cancelled) closeRequest(pending.handle); @@ -261,7 +261,7 @@ fn process(message: *Bus.Message) !void { // Match rules are installed on the bus, and sender validation also protects // against unrelated unicast signals sent directly to our private connection. const sender = c.z_dbus_message_get_sender.?(message); - if (sender == null or s().owner == null or !std.mem.eql(u8, std.mem.span(sender), s().owner.?)) return; + if (sender == null or portalState().owner == null or !std.mem.eql(u8, std.mem.span(sender), portalState().owner.?)) return; 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; _ = Bus.next(&args); @@ -272,7 +272,7 @@ fn process(message: *Bus.Message) !void { } 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) { const response_path = c.z_dbus_message_get_path.?(message); if (response_path == null) return; - cursor = s().pending; + cursor = portalState().pending; while (cursor) |pending| : (cursor = pending.next) if (std.mem.eql(u8, pending.handle, std.mem.span(response_path))) { const code = Bus.uint(&args).?; _ = Bus.next(&args); @@ -290,34 +290,34 @@ fn errorStatus(message: *Bus.Message) u32 { return n.UHDK_STATUS_OS_ERROR; } fn preference(key: []const u8, value: u32) void { - const old = s().preferences; - if (std.mem.eql(u8, key, "color-scheme")) s().preferences.appearance = switch (value) { + const old = portalState().preferences; + if (std.mem.eql(u8, key, "color-scheme")) portalState().preferences.appearance = switch (value) { 1 => n.UHDK_APPEARANCE_DARK, 2 => n.UHDK_APPEARANCE_LIGHT, else => n.UHDK_APPEARANCE_UNKNOWN, - } else if (std.mem.eql(u8, key, "contrast")) s().preferences.high_contrast = @intFromBool(value == 1) else if (std.mem.eql(u8, key, "reduced-motion")) s().preferences.reduced_motion = @intFromBool(value == 1); - if (!std.meta.eql(old, s().preferences)) n.z_preferences(runtime.toAppHandle(b().app), &s().preferences); + } 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); } pub fn request(cmd: *const n.z_command, id: u64) u32 { - if (!s().ready or s().connection == null) return abi.UNAVAILABLE; - if (cmd.op == n.Z_DIALOG and s().chooser_version < 3) return n.UHDK_STATUS_UNSUPPORTED; + 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; const p = allocate(cmd, id) catch return abi.OOM; - p.next = s().pending; - s().pending = p; - if (cmd.op == n.Z_DIALOG and cmd.dialog.parent != null and s().exporter != null) { + p.next = portalState().pending; + portalState().pending = p; + if (cmd.op == n.Z_DIALOG and cmd.dialog.parent != null and portalState().exporter != null) { const w: *native.Window = @ptrCast(@alignCast(n.z_object_native(cmd.dialog.parent) orelse { destroy(p); return abi.UNAVAILABLE; })); - p.exported = c.zxdg_exporter_v2_export_toplevel(s().exporter, w.surface) orelse { + p.exported = c.zxdg_exporter_v2_export_toplevel(portalState().exporter, w.surface) orelse { destroy(p); return abi.OOM; }; _ = c.zxdg_exported_v2_add_listener(p.exported, &export_listener, p); - } else if (cmd.op == n.Z_URL and b().desktop.activation != null and Input.state().key_focus != null and - Input.state().serial != 0 and runtime.now(b().app.io) -| Input.state().serial_time <= 5 * std.time.ns_per_s) + } 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) { - p.activation = c.xdg_activation_v1_get_activation_token(b().desktop.activation) orelse { + p.activation = c.xdg_activation_v1_get_activation_token(backend().desktop.activation) orelse { destroy(p); return abi.OOM; }; @@ -332,26 +332,26 @@ pub fn request(cmd: *const n.z_command, id: u64) u32 { return n.Z_DEFERRED; } fn allocate(cmd: *const n.z_command, id: u64) !*Pending { - const gpa = b().app.gpa; + const gpa = backend().app.gpa; const p = try gpa.create(Pending); errdefer gpa.destroy(p); const token = try std.fmt.allocPrintSentinel(gpa, "uhdk_{x}", .{id}, 0); errdefer gpa.free(token); - const unique = s().unique.?; + const unique = portalState().unique.?; const name = try gpa.dupe(u8, unique[1..]); defer gpa.free(name); std.mem.replaceScalar(u8, name, '.', '_'); - p.* = .{ .id = id, .command = cmd, .token = token, .handle = try std.fmt.allocPrintSentinel(gpa, path ++ "/request/{s}/{s}", .{ name, token }, 0), .deadline = runtime.now(b().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; } fn exported(raw: ?*anyopaque, _: ?*c.struct_zxdg_exported_v2, handle: [*c]const u8) callconv(.c) void { const p: *Pending = @ptrCast(@alignCast(raw.?)); - const parent = std.fmt.allocPrintSentinel(b().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 { complete(p, abi.OOM, null); destroy(p); return; }; - defer b().app.gpa.free(parent); + defer backend().app.gpa.free(parent); submit(p, parent, null) catch { complete(p, abi.OOM, null); destroy(p); @@ -371,7 +371,7 @@ fn submit(p: *Pending, parent: [*:0]const u8, activation_token: ?[*:0]const u8) 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"); defer c.z_dbus_message_unref.?(message); - var arena: std.heap.ArenaAllocator = .init(b().app.gpa); + var arena: std.heap.ArenaAllocator = .init(backend().app.gpa); defer arena.deinit(); const gpa = arena.allocator(); var args = Bus.append(message); @@ -455,23 +455,23 @@ fn responseFiles(p: *Pending, args: *Bus.Iter) void { var files: std.ArrayList(?*n.uhdk_file) = .empty; defer { for (files.items) |file| n.uhdk_file_release(file); - files.deinit(b().app.gpa); + files.deinit(backend().app.gpa); } while (Bus.kind(&strings) != c.DBUS_TYPE_INVALID) { const uri = Bus.str(&strings) orelse { complete(p, n.UHDK_STATUS_OS_ERROR, null); return; }; - const bytes = Files.decode(b().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); return; }; - defer b().app.gpa.free(bytes); - const file = n.z_file_from_url(runtime.toAppHandle(b().app), .{ .ptr = bytes.ptr, .len = bytes.len }, null) orelse { + defer backend().app.gpa.free(bytes); + const file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = bytes.ptr, .len = bytes.len }, null) orelse { complete(p, abi.OOM, null); return; }; - files.append(b().app.gpa, file) catch { + files.append(backend().app.gpa, file) catch { n.uhdk_file_release(file); complete(p, abi.OOM, null); return; @@ -483,19 +483,19 @@ fn responseFiles(p: *Pending, args: *Bus.Iter) void { 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 { - if (p.id != 0) n.z_complete(runtime.toAppHandle(b().app), p.id, status, result); + if (p.id != 0) n.z_complete(runtime.toAppHandle(backend().app), p.id, status, result); p.id = 0; p.command = null; } fn closeRequest(handle: [*:0]const u8) void { - if (s().connection == null) return; + if (portalState().connection == null) return; const message = Bus.method(desktop, handle, "org.freedesktop.portal.Request", "Close") catch return; defer c.z_dbus_message_unref.?(message); c.z_dbus_message_set_no_reply.?(message, 1); _ = send(message) catch {}; } pub fn cancel(id: u64) bool { - var cursor = s().pending; + var cursor = portalState().pending; while (cursor) |p| : (cursor = p.next) if (p.id == id) { if (p.serial != 0) closeRequest(p.handle); p.cancelled = true; @@ -506,34 +506,34 @@ pub fn cancel(id: u64) bool { return false; } fn destroy(p: *Pending) void { - var link = &s().pending; + var link = &portalState().pending; while (link.* != p) link = &link.*.?.next; link.* = p.next; if (p.exported != null) c.zxdg_exported_v2_destroy(p.exported); if (p.activation != null) c.xdg_activation_token_v1_destroy(p.activation); - b().app.gpa.free(p.handle); - b().app.gpa.free(p.token); - b().app.gpa.destroy(p); + backend().app.gpa.free(p.handle); + backend().app.gpa.free(p.token); + backend().app.gpa.destroy(p); } fn disconnect() void { KdeAppMenu.disconnected(); - while (s().pending) |p| { + while (portalState().pending) |p| { complete(p, abi.UNAVAILABLE, null); destroy(p); } - if (s().connection) |connection| { + if (portalState().connection) |connection| { c.z_dbus_connection_close.?(connection); c.z_dbus_connection_unref.?(connection); } - s().connection = null; - s().ready = false; + portalState().connection = null; + portalState().ready = false; native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false); } pub fn deinit() void { - var cursor = s().pending; + var cursor = portalState().pending; while (cursor) |p| : (cursor = p.next) closeRequest(p.handle); disconnect(); - if (s().unique) |unique| b().app.gpa.free(unique); - if (s().owner) |owner| b().app.gpa.free(owner); - if (s().exporter != null) c.zxdg_exporter_v2_destroy(s().exporter); + if (portalState().unique) |unique| backend().app.gpa.free(unique); + if (portalState().owner) |owner| backend().app.gpa.free(owner); + if (portalState().exporter != null) c.zxdg_exporter_v2_destroy(portalState().exporter); } diff --git a/src/linux/Watch.zig b/src/linux/Watch.zig index 72aa0fe..29b7fe3 100644 --- a/src/linux/Watch.zig +++ b/src/linux/Watch.zig @@ -14,16 +14,16 @@ pub const Watch = struct { directory: []u8, name: []u8, }; -fn b() *native.Backend { +fn backend() *native.Backend { return native.instance.?; } pub fn prepare(root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, out: *?*anyopaque) u32 { - const path = b().app.gpa.dupeZ(u8, abi.bytes(n.z_file_path(root))) catch return abi.OOM; - defer b().app.gpa.free(path); + const path = backend().app.gpa.dupeZ(u8, abi.bytes(n.z_file_path(root))) catch return abi.OOM; + defer backend().app.gpa.free(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; - const directory = b().app.gpa.dupeZ(u8, if (kind == 1) path else std.fs.path.dirname(path) orelse "/") catch return abi.OOM; - defer b().app.gpa.free(directory); + 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); const fd = c.inotify_init1(c.IN_NONBLOCK | c.IN_CLOEXEC); 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; @@ -40,13 +40,13 @@ pub fn prepare(root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, out: *?*anyopaque) u } pub fn commit(handle: ?*n.uhdk_watch, prepared: *anyopaque) void { const w: *Watch = @ptrCast(@alignCast(prepared)); - w.next = b().watches; - b().watches = w; + w.next = backend().watches; + backend().watches = w; n.z_object_set_native(handle, w); } fn allocate(fd: c_int, root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, directory: []const u8, name: []const u8) !*Watch { - const gpa = b().app.gpa; + const gpa = backend().app.gpa; const w = try gpa.create(Watch); errdefer gpa.destroy(w); const dir = try gpa.dupe(u8, directory); @@ -55,8 +55,8 @@ fn allocate(fd: c_int, root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, directory: [ return w; } pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void { - var w = b().watches; - while (w) |item| : (w = item.next) if (item.fd >= 0) try fds.append(b().app.gpa, .{ .fd = item.fd, .events = c.POLLIN, .revents = 0 }); + 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 }); } pub fn flags(mask: u32) u32 { var value: u32 = 0; @@ -72,20 +72,20 @@ pub fn flags(mask: u32) u32 { fn emit(w: *Watch, changes: u32, name: []const u8, status: u32) void { var file = w.root; if (w.name.len == 0 and name.len != 0) { - const path = std.fs.path.join(b().app.gpa, &.{ w.directory, name }) catch null; + const path = std.fs.path.join(backend().app.gpa, &.{ w.directory, name }) catch null; if (path) |p| { - defer b().app.gpa.free(p); - file = n.z_file_from_url(runtime.toAppHandle(b().app), .{ .ptr = p.ptr, .len = p.len }, null); + defer backend().app.gpa.free(p); + file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = p.ptr, .len = p.len }, null); } else file = null; } defer if (file != null and file != w.root) n.uhdk_file_release(file); var event = std.mem.zeroes(n.z_event); event.type = n.UHDK_EVENT_WATCH; event.data.watch = .{ .watch = w.handle, .flags = changes, .status = status, .file = file }; - n.z_emit(runtime.toAppHandle(b().app), &event); + n.z_emit(runtime.toAppHandle(backend().app), &event); } pub fn tick() void { - var cursor = b().watches; + var cursor = backend().watches; while (cursor) |w| : (cursor = w.next) { if (w.fd < 0) continue; var buffer: [65536]u8 align(@alignOf(c.struct_inotify_event)) = undefined; @@ -118,13 +118,13 @@ pub fn tick() void { } } pub fn destroy(w: *Watch) void { - var link = &b().watches; + var link = &backend().watches; while (link.* != w) link = &link.*.?.next; link.* = w.next; if (w.fd >= 0) _ = c.close(w.fd); - b().app.gpa.free(w.directory); - b().app.gpa.free(w.name); - b().app.gpa.destroy(w); + backend().app.gpa.free(w.directory); + backend().app.gpa.free(w.name); + backend().app.gpa.destroy(w); } 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)); diff --git a/src/linux/bindings.h b/src/linux/bindings.h index 3910bf4..4612848 100644 --- a/src/linux/bindings.h +++ b/src/linux/bindings.h @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -50,5 +49,4 @@ int z_linux_poll(struct pollfd *, nfds_t, int); ssize_t z_linux_read(int, void *, size_t); ssize_t z_linux_write(int, const void *, size_t); ssize_t z_linux_pipe_write(int, const void *, size_t); -int z_linux_is_main_thread(void); #endif diff --git a/src/linux/libraries.c b/src/linux/libraries.c index c34c4d3..949fa0f 100644 --- a/src/linux/libraries.c +++ b/src/linux/libraries.c @@ -6,7 +6,6 @@ #include #include #include -#include #include #include #include "wayland-client-core.h" @@ -105,10 +104,6 @@ int z_linux_egl_available(void) { int z_linux_errno(void) { return errno; } -int z_linux_is_main_thread(void) { - return syscall(SYS_gettid) == getpid(); -} - /* Keep libc's optimization/fortify inline implementation on the C side. */ int z_linux_poll(struct pollfd *fds, nfds_t count, int timeout) { return poll(fds, count, timeout); diff --git a/src/linux/native.zig b/src/linux/native.zig index c52cc94..0fa76b4 100644 --- a/src/linux/native.zig +++ b/src/linux/native.zig @@ -101,7 +101,9 @@ pub fn setCapability(cap: u32, available: bool) void { } export fn z_native_is_main_thread() c_int { - return c.z_linux_is_main_thread(); + // Wayland connections are thread-affine, but do not require the process's + // initial thread. The first session records and enforces its owner thread. + return 1; } export fn z_native_start(handle: ?*n.uhdk_session, _: n.uhdk_text) u32 { const app = runtime.fromAppHandle(handle); @@ -646,7 +648,7 @@ export fn z_native_execute(_: ?*n.uhdk_session, raw: [*c]const n.z_command, id: n.Z_TEXT_CANCEL => Text.cancel(w), n.Z_FOCUS => return Desktop.focus(w, id), n.Z_REDRAW => emit(w, n.UHDK_EVENT_WINDOW_REDRAW), - n.Z_GL => return Egl.create(b, w, cmd.other), + n.Z_GL => return Egl.create(b, w), else => return n.UHDK_STATUS_UNSUPPORTED, } return abi.OK; @@ -670,7 +672,10 @@ export fn z_native_destroy(kind: u32, ptr: ?*anyopaque) void { if (w.request != 0) completeCreation(w, abi.CANCELLED) else destroyWindow(w); }, n.Z_KIND_WATCH => Watch.destroy(@ptrCast(@alignCast(p))), - n.Z_KIND_GL => Egl.destroy(@ptrCast(@alignCast(p))), + n.Z_KIND_GL => { + const w: *Window = @ptrCast(@alignCast(p)); + if (w.egl) |ctx| Egl.destroy(ctx); + }, else => {}, } } @@ -679,10 +684,13 @@ export fn z_native_handles(ptr: ?*anyopaque, out: [*c]n.uhdk_native_window) void 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 { - return Egl.call(ptr, op, out); + if (op == 4) return Egl.call(null, op, out); + const w: *Window = @ptrCast(@alignCast(ptr orelse return abi.INVALID)); + 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 { - return Egl.proc(ptr, name, out); + const w: *Window = @ptrCast(@alignCast(ptr orelse return abi.INVALID)); + 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 { return @import("Files.zig").init(file, path, uri, grant); diff --git a/src/macos/native.m b/src/macos/native.m index d0636bb..e0bbdcf 100644 --- a/src/macos/native.m +++ b/src/macos/native.m @@ -1427,7 +1427,7 @@ void z_native_destroy(uint32_t kind, void *native) { if (!native) return; @autoreleasepool { - id value = CFBridgingRelease(native); + id value = kind == Z_KIND_GL ? (__bridge id)native : CFBridgingRelease(native); if (kind == Z_KIND_WINDOW) { ZWindow *w = value; if (w.menu) { @@ -1441,11 +1441,14 @@ void z_native_destroy(uint32_t kind, void *native) { [host.windows removeObject:w]; [host refreshMenus]; } else if (kind == Z_KIND_GL) { - ZGL *gl = value; + ZWindow *w = value; + ZGL *gl = w.gl; + if (!gl) + return; CGLLockContext(gl.context.CGLContextObj); [gl.context clearDrawable]; CGLUnlockContext(gl.context.CGLContextObj); - gl.owner.gl = nil; + w.gl = nil; } } } @@ -1588,7 +1591,6 @@ uhdk_status z_native_execute( !(profile & GL_CONTEXT_CORE_PROFILE_BIT)) return UHDK_STATUS_UNSUPPORTED; w.gl = gl; - z_object_set_native(cmd->other, (__bridge_retained void *)gl); [w metrics]; break; } @@ -1798,11 +1800,12 @@ uhdk_status z_native_execute( } uhdk_status z_native_gl(void *native, uint32_t op, void *out) { @autoreleasepool { - ZGL *gl = (__bridge ZGL *)native; if (op == 4) { [NSOpenGLContext clearCurrentContext]; return UHDK_STATUS_OK; } + ZWindow *w = (__bridge ZWindow *)native; + ZGL *gl = w.gl; if (!gl) return UHDK_STATUS_UNAVAILABLE; if (op == 1) { @@ -1828,7 +1831,8 @@ uhdk_status z_native_gl(void *native, uint32_t op, void *out) { } } uhdk_status z_native_gl_proc(void *native, uhdk_text name, uhdk_gl_proc *out) { - ZGL *gl = (__bridge ZGL *)native; + ZWindow *w = (__bridge ZWindow *)native; + ZGL *gl = w.gl; if (NSOpenGLContext.currentContext != gl.context) return UHDK_STATUS_UNAVAILABLE; char symbol[256]; diff --git a/src/native.h b/src/native.h index 8cb7bed..bd196e4 100644 --- a/src/native.h +++ b/src/native.h @@ -7,7 +7,6 @@ #include "uhdk.h" #include #include "edit_keys.h" -typedef struct z_gl_context z_gl_context; enum { Z_WINDOW_OPENGL = 1u << 3 }; @@ -101,6 +100,7 @@ enum { }; enum { Z_KIND_WINDOW = 1, + /* Native-only discriminator for destroying a window's GL state. */ Z_KIND_GL, Z_KIND_FILE, Z_KIND_MENU, diff --git a/src/runtime.zig b/src/runtime.zig index cbf9821..49d265b 100644 --- a/src/runtime.zig +++ b/src/runtime.zig @@ -33,15 +33,16 @@ pub fn threadCpuTime(io: std.Io) u64 { return @intCast(@max(0, std.Io.Timestamp.now(io, .cpu_thread).nanoseconds)); } -pub fn checkThread(application: *Application) abi.Status { +pub fn validateMainThreadSessionReady(application: *Application) abi.Status { application.lock(); defer application.unlock(); return if (application.running and std.Thread.getCurrentId() == application.main_thread) abi.OK else c.UHDK_STATUS_WRONG_THREAD; } -pub fn checkObject(object: *Resource, kind: u32) abi.Status { - if (checkThread(object.app) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; - return if (object.kind() == kind and object.alive) abi.OK else abi.UNAVAILABLE; +pub fn validateMainThreadObjectReady(object: *Resource, kind: u32) abi.Status { + const status = validateMainThreadSessionReady(object.app); + if (status != abi.OK) return status; + return if (object.kind() == kind and object.alive and object.ready) abi.OK else abi.UNAVAILABLE; } pub fn createObject(application: *Application, kind: u32) !*Resource { @@ -193,12 +194,8 @@ fn discardCreation(command: *Request) void { c.Z_WINDOW => if (command.data.target) |target| { fromObjectHandle(target).alive = false; }, - c.Z_GL => if (command.data.other) |other| { - const object = fromObjectHandle(other); - object.alive = false; - if (object.payload.gl.owner) |window| { - if (window.payload.window.context == object) window.payload.window.context = null; - } + c.Z_GL => if (command.data.target) |target| { + fromObjectHandle(target).payload.window.gl_requested = false; }, c.Z_WATCH => if (command.data.other) |other| { const object = fromObjectHandle(other); @@ -211,7 +208,7 @@ fn discardCreation(command: *Request) void { } pub fn submit(application: *Application, command: *Request, tag: u64) abi.Status { - if ((command.completion == .request and tag == 0) or checkThread(application) != abi.OK) { + if ((command.completion == .request and tag == 0) or validateMainThreadSessionReady(application) != abi.OK) { const status: abi.Status = if (command.completion == .request and tag == 0) abi.INVALID else c.UHDK_STATUS_WRONG_THREAD; abandon(command); return status; @@ -300,16 +297,18 @@ pub fn finish( abandon(command); return; } - if (status == abi.OK) switch (command.data.op) { - c.Z_WINDOW => fromObjectHandle(command.data.target).ready = true, - c.Z_GL => fromObjectHandle(command.data.other).ready = true, - else => {}, - }; + if (status == abi.OK and command.data.op == c.Z_WINDOW) + fromObjectHandle(command.data.target).ready = true; + if (command.data.op == c.Z_GL) { + const window = fromObjectHandle(command.data.target); + window.payload.window.gl_status = status; + window.payload.window.gl_ready = true; + } const redraw = command.completion == .resource and status == abi.OK and command.data.op == c.Z_GL; - const redraw_window = if (redraw) fromObjectHandle(command.data.other).payload.gl.owner else null; + const redraw_window = if (redraw) fromObjectHandle(command.data.target) else null; if (command.completion == .resource) { - const object = fromObjectHandle(if (command.data.op == c.Z_WINDOW) command.data.target else command.data.other); - object.creation_status = status; + if (command.data.op == c.Z_WINDOW) + fromObjectHandle(command.data.target).creation_status = status; } if (status != abi.OK) discardCreation(command); const node = command.node; @@ -353,7 +352,7 @@ pub fn hasFrame(application: *Application) bool { defer application.unlock(); var cursor = application.objects; while (cursor) |object| : (cursor = object.next) { - if (object.payload == .gl and object.payload.gl.bracket) return true; + if (object.payload == .window and object.payload.window.bracket) return true; } return false; } @@ -408,7 +407,7 @@ fn finishIo(command: *Request, status: abi.Status, value: ?*const c.z_request_re pub fn createObjectCommand(handle: anytype, kind: u32, op: u32) !*Request { if (handle == null) return error.Invalid; const object = fromObjectHandle(handle); - if (checkThread(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.alive) return error.Unavailable; return createCommand(object.app, op, object); @@ -441,7 +440,7 @@ pub fn textCommandValue(handle: ?*c.uhdk_window, kind: u32, op: u32, text: c.uhd pub fn createAppCommand(handle: ?*c.uhdk_session, op: u32) !*Request { if (handle == null) return error.Invalid; - if (checkThread(fromAppHandle(handle)) != abi.OK) return error.WrongThread; + if (validateMainThreadSessionReady(fromAppHandle(handle)) != abi.OK) return error.WrongThread; return createCommand(fromAppHandle(handle), op, null); } @@ -455,16 +454,14 @@ pub fn applicationError(err: anyerror) abi.Status { pub fn destroyObject(object: *Resource) void { if (!object.alive) return; - std.debug.assert(checkThread(object.app) == abi.OK); - if (object.payload == .gl) { - std.debug.assert(!object.payload.gl.bracket); + std.debug.assert(validateMainThreadSessionReady(object.app) == abi.OK); + if (object.payload == .window and object.payload.window.gl_ready and object.payload.window.gl_status == abi.OK) { + std.debug.assert(!object.payload.window.bracket); if ((@import("builtin").os.tag == .windows or @import("builtin").os.tag == .linux) and object.native != null) _ = c.z_native_gl(object.native, 8, null); + c.z_native_destroy(c.Z_KIND_GL, object.native); + object.payload.window.gl_ready = false; } - if (object.payload == .window) if (object.payload.window.context) |ctx| { - destroyObject(ctx); - object.payload.window.context = null; - }; // Find one child under the registry lock, then recurse without the lock. // Files can be released concurrently by the other thread. while (true) { @@ -492,13 +489,14 @@ pub fn destroyObject(object: *Resource) void { notifyCommand(object, c.Z_DESTROY); } -pub fn glCall(handle: ?*c.z_gl_context, 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; const object = fromObjectHandle(handle); - const status = checkObject(object, c.Z_KIND_GL); + const status = validateMainThreadObjectReady(object, c.Z_KIND_WINDOW); if (status != abi.OK) return status; if (object.native == null) return abi.UNAVAILABLE; - if (op != 1 and !object.payload.gl.bracket) return c.UHDK_STATUS_BUSY; + if (!object.payload.window.gl_ready or object.payload.window.gl_status != abi.OK) return abi.UNAVAILABLE; + if (op != 1 and !object.payload.window.bracket) return c.UHDK_STATUS_BUSY; return c.z_native_gl(object.native, op, out); } diff --git a/src/windows/native.c b/src/windows/native.c index 0007346..8a5c55c 100644 --- a/src/windows/native.c +++ b/src/windows/native.c @@ -66,6 +66,7 @@ struct Window { uhdk_point pointer; HCURSOR cursor; HMENU menu; + Graphics *graphics; uhdk_menu *menu_source; WINDOWPLACEMENT placement; LONG_PTR saved_style; @@ -857,7 +858,7 @@ static PROC glProc(const char *name) { p = GetProcAddress(GetModuleHandleW(L"opengl32.dll"), name); return p; } -static uhdk_status createGraphics(Window *w, void *handle) { +static uhdk_status createGraphics(Window *w) { if (!(w->flags & Z_WINDOW_OPENGL)) return UHDK_STATUS_INVALID_ARGUMENT; Graphics *g = profileCalloc(1, sizeof(*g)); @@ -923,7 +924,7 @@ static uhdk_status createGraphics(Window *w, void *handle) { g->major = (uint32_t)major; g->minor = (uint32_t)minor; InitializeCriticalSection(&g->lock); - z_object_set_native(handle, g); + w->graphics = g; return UHDK_STATUS_OK; failed: if (g->rc) @@ -933,9 +934,10 @@ failed: return UHDK_STATUS_UNSUPPORTED; } uhdk_status z_native_gl(void *native, uint32_t op, void *out) { - Graphics *g = native; if (op == 4) return wglMakeCurrent(NULL, NULL) ? UHDK_STATUS_OK : UHDK_STATUS_OS_ERROR; + Window *w = native; + Graphics *g = w ? w->graphics : NULL; if (!g) return UHDK_STATUS_UNAVAILABLE; if (op == 8) @@ -967,7 +969,8 @@ uhdk_status z_native_gl(void *native, uint32_t op, void *out) { return UHDK_STATUS_INVALID_ARGUMENT; } uhdk_status z_native_gl_proc(void *native, uhdk_text name, uhdk_gl_proc *out) { - Graphics *g = native; + Window *w = native; + Graphics *g = w ? w->graphics : NULL; if (!g || wglGetCurrentContext() != g->rc) return UHDK_STATUS_UNAVAILABLE; if (name.len > 255) @@ -1504,13 +1507,17 @@ void z_native_destroy(uint32_t kind, void *native) { if (!native) return; if (kind == Z_KIND_GL) { - Graphics *g = native; + Window *w = native; + Graphics *g = w->graphics; + if (!g) + return; EnterCriticalSection(&g->lock); wglDeleteContext(g->rc); ReleaseDC(g->window, g->dc); LeaveCriticalSection(&g->lock); DeleteCriticalSection(&g->lock); profileFree(g); + w->graphics = NULL; } else if (kind == Z_KIND_WINDOW) { Window *w = native; Window **link = &host.windows; @@ -1658,6 +1665,7 @@ static uhdk_status setIcon(const uhdk_image *image) { host.icon = icon; return UHDK_STATUS_OK; } + uhdk_status z_native_execute( uhdk_session *app, const z_command *cmd, @@ -1851,7 +1859,7 @@ uhdk_status z_native_execute( metrics(w); break; case Z_GL: { - uhdk_status status = createGraphics(w, cmd->other); + uhdk_status status = createGraphics(w); return status; } case Z_CURSOR: {