api updates and new validators, fixing up some naming inconsistencies in linux

This commit is contained in:
Peterino2 2026-09-21 09:07:31 -07:00
parent 51ca8bd438
commit ddb1aac088
24 changed files with 494 additions and 487 deletions

View File

@ -54,7 +54,7 @@ stats: c.uhdk_stats = std.mem.zeroes(c.uhdk_stats),
last_frame_time: ?u64 = null, last_frame_time: ?u64 = null,
session_gl: c.uhdk_gl_functions = std.mem.zeroes(c.uhdk_gl_functions), session_gl: c.uhdk_gl_functions = std.mem.zeroes(c.uhdk_gl_functions),
session_window: ?*c.uhdk_window = null, session_window: ?*c.uhdk_window = null,
session_context: ?*c.z_gl_context = null, session_has_gl: bool = false,
session_status: abi.Status = abi.OK, session_status: abi.Status = abi.OK,
session_active: bool = false, session_active: bool = false,
session_drawable: bool = false, session_drawable: bool = false,

View File

@ -18,7 +18,6 @@ payload: Payload,
pub const Kind = enum(u32) { pub const Kind = enum(u32) {
window = c.Z_KIND_WINDOW, window = c.Z_KIND_WINDOW,
gl = c.Z_KIND_GL,
file = c.Z_KIND_FILE, file = c.Z_KIND_FILE,
menu = c.Z_KIND_MENU, menu = c.Z_KIND_MENU,
watch = c.Z_KIND_WATCH, watch = c.Z_KIND_WATCH,
@ -26,7 +25,6 @@ pub const Kind = enum(u32) {
pub const Payload = union(Kind) { pub const Payload = union(Kind) {
window: Window, window: Window,
gl: Gl,
file: File, file: File,
menu: Menu, menu: Menu,
watch: Watch, watch: Watch,
@ -34,13 +32,11 @@ pub const Payload = union(Kind) {
pub const Window = struct { pub const Window = struct {
cycles: @import("Cycles.zig") = .{}, cycles: @import("Cycles.zig") = .{},
context: ?*Resource = null,
parent: ?*Resource = null, parent: ?*Resource = null,
metrics: c.uhdk_window_metrics = std.mem.zeroes(c.uhdk_window_metrics), metrics: c.uhdk_window_metrics = std.mem.zeroes(c.uhdk_window_metrics),
}; gl_requested: bool = false,
gl_ready: bool = false,
pub const Gl = struct { gl_status: u32 = 0,
owner: ?*Resource = null,
bracket: bool = false, bracket: bool = false,
frame_cpu_start: u64 = 0, frame_cpu_start: u64 = 0,
swap_cpu_time: u64 = 0, swap_cpu_time: u64 = 0,
@ -68,10 +64,9 @@ pub fn init(application: *Application, resource_kind: Kind) Resource {
.app = application, .app = application,
.gpa = application.gpa, .gpa = application.gpa,
.arena = .init(application.gpa), .arena = .init(application.gpa),
.ready = resource_kind != .window and resource_kind != .gl, .ready = resource_kind != .window,
.payload = switch (resource_kind) { .payload = switch (resource_kind) {
.window => .{ .window = .{} }, .window => .{ .window = .{} },
.gl => .{ .gl = .{} },
.file => .{ .file = .{} }, .file => .{ .file = .{} },
.menu => .{ .menu = .{} }, .menu => .{ .menu = .{} },
.watch => .{ .watch = .{} }, .watch => .{ .watch = .{} },

View File

@ -86,15 +86,12 @@ fn shutdown(application: *Application) void {
} }
} }
cursor = application.objects; 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) { while (cursor) |object| : (cursor = object.next) {
if (object.kind() == c.Z_KIND_WINDOW and object.native != null) { if (object.kind() == c.Z_KIND_WINDOW and object.native != null) {
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); c.z_native_destroy(object.kind(), object.native);
object.native = null; object.native = null;
} }
@ -112,7 +109,7 @@ pub fn poll(
) abi.Status { ) abi.Status {
if (handle == null or out == null) return abi.INVALID; if (handle == null or out == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
if (runtime.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; if (runtime.hasFrame(application)) return c.UHDK_STATUS_BUSY;
const poll_zone = profile.begin(@src(), "UHDK poll events (includes wait)"); const poll_zone = profile.begin(@src(), "UHDK poll events (includes wait)");
defer poll_zone.end(); defer poll_zone.end();
@ -196,7 +193,7 @@ pub fn poll(
pub export fn uhdk_get_stats(handle: ?*c.uhdk_session, out: [*c]c.uhdk_stats) abi.Status { pub export fn uhdk_get_stats(handle: ?*c.uhdk_session, out: [*c]c.uhdk_stats) abi.Status {
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
if (runtime.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); 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 { pub export fn uhdk_set_wake_deadline(handle: ?*c.uhdk_session, deadline: u64) abi.Status {
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
if (runtime.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.lock();
application.deadline = deadline; application.deadline = deadline;
application.notify(); 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 { pub export fn uhdk_request_cancel(handle: ?*c.uhdk_session, tag: u64) abi.Status {
if (handle == null or tag == 0) return abi.INVALID; if (handle == null or tag == 0) return abi.INVALID;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
if (runtime.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.lock();
var cursor = application.requests; var cursor = application.requests;
while (cursor) |command| : (cursor = command.next) { while (cursor) |command| : (cursor = command.next) {

View File

@ -70,7 +70,7 @@ pub export fn uhdk_get_preferences(
) abi.Status { ) abi.Status {
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
if (runtime.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.lock();
defer application.unlock(); defer application.unlock();
return abi.writeOutput(c.uhdk_preferences, out, application.preferences); return abi.writeOutput(c.uhdk_preferences, out, application.preferences);

View File

@ -41,7 +41,7 @@ pub export fn uhdk_file_create_from_native_path(
path.len == 0) return abi.INVALID; path.len == 0) return abi.INVALID;
if (@import("builtin").os.tag != .windows and if (@import("builtin").os.tag != .windows and
(abi.bytes(path)[0] != '/' or std.mem.findScalar(u8, abi.bytes(path), 0) != null)) return abi.INVALID; (abi.bytes(path)[0] != '/' or std.mem.findScalar(u8, abi.bytes(path), 0) != null)) return abi.INVALID;
if (runtime.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 object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_FILE) catch return abi.OOM;
const status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), path, .{ .ptr = null, .len = 0 }, null); const status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), path, .{ .ptr = null, .len = 0 }, null);
if (status != abi.OK) { if (status != abi.OK) {
@ -58,7 +58,7 @@ pub export fn uhdk_file_create_from_uri(
out: [*c]?*c.uhdk_file, out: [*c]?*c.uhdk_file,
) abi.Status { ) abi.Status {
if (handle == null or out == null or !abi.validText(uri, true)) return abi.INVALID; if (handle == null or out == null or !abi.validText(uri, true)) return abi.INVALID;
if (runtime.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 object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_FILE) catch return abi.OOM;
const status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), .{ .ptr = null, .len = 0 }, uri, null); const status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), .{ .ptr = null, .len = 0 }, uri, null);
if (status != abi.OK) { if (status != abi.OK) {
@ -86,7 +86,7 @@ pub export fn uhdk_file_copy_representation(
) abi.Status { ) abi.Status {
if (handle == null or out == null or !abi.validSpan(buffer, capacity)) return abi.INVALID; if (handle == null or out == null or !abi.validSpan(buffer, capacity)) return abi.INVALID;
const object = runtime.fromObjectHandle(handle); const object = runtime.fromObjectHandle(handle);
const status = runtime.checkObject(object, c.Z_KIND_FILE); const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_FILE);
if (status != abi.OK) return status; if (status != abi.OK) return status;
const data = switch (form) { const data = switch (form) {
c.UHDK_FILE_DISPLAY_NAME => object.payload.file.display, c.UHDK_FILE_DISPLAY_NAME => object.payload.file.display,

View File

@ -5,51 +5,42 @@ const c = @import("native");
const runtime = @import("../runtime.zig"); const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig"); const abi = @import("../abi.zig");
pub fn create(handle: ?*c.uhdk_window, out: [*c]?*c.z_gl_context) abi.Status { pub fn create(handle: ?*c.uhdk_window) abi.Status {
if (out == null) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_GL) catch |err| return runtime.objectError(err); const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_GL) catch |err| return runtime.objectError(err);
const w = runtime.fromObjectHandle(handle); const w = runtime.fromObjectHandle(handle);
if (w.payload.window.context != null) { if (w.payload.window.gl_requested) {
runtime.abandon(command); runtime.abandon(command);
return c.UHDK_STATUS_BUSY; return c.UHDK_STATUS_BUSY;
} }
const object = runtime.createObject(w.app, c.Z_KIND_GL) catch { w.payload.window.gl_requested = true;
runtime.abandon(command); return runtime.submitResource(w.app, 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;
} }
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"); const zone = profile.begin(@src(), "UHDK acquire GL context");
defer zone.end(); defer zone.end();
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle); const object = runtime.fromObjectHandle(handle);
if (object.payload.gl.bracket) return c.UHDK_STATUS_BUSY; if (object.payload.window.bracket) return c.UHDK_STATUS_BUSY;
const status = runtime.glCall(handle, 1, null); const status = runtime.glCall(handle, 1, null);
if (status == abi.OK) { if (status == abi.OK) {
object.payload.gl.bracket = true; object.payload.window.bracket = true;
object.payload.gl.frame_cpu_start = runtime.threadCpuTime(object.app.io); object.payload.window.frame_cpu_start = runtime.threadCpuTime(object.app.io);
object.payload.gl.swap_cpu_time = 0; object.payload.window.swap_cpu_time = 0;
object.payload.gl.presented = false; object.payload.window.presented = false;
} }
return status; 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); const status = runtime.glCall(handle, 2, null);
if (status == abi.OK) { if (status == abi.OK) {
const object = runtime.fromObjectHandle(handle); const object = runtime.fromObjectHandle(handle);
object.payload.gl.bracket = false; object.payload.window.bracket = false;
if (object.payload.gl.presented) { if (object.payload.window.presented) {
const stats = &object.app.stats; const stats = &object.app.stats;
const elapsed = runtime.threadCpuTime(object.app.io) -| object.payload.gl.frame_cpu_start; const elapsed = runtime.threadCpuTime(object.app.io) -| object.payload.window.frame_cpu_start;
stats.render_time_ns = elapsed -| object.payload.gl.swap_cpu_time; stats.render_time_ns = elapsed -| object.payload.window.swap_cpu_time;
stats.frame_count +|= 1; stats.frame_count +|= 1;
const now = runtime.now(object.app.io); const now = runtime.now(object.app.io);
if (object.app.last_frame_time) |previous| { if (object.app.last_frame_time) |previous| {
@ -62,24 +53,24 @@ pub fn release(handle: ?*c.z_gl_context) abi.Status {
return 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)"); const zone = profile.begin(@src(), "UHDK present (includes vsync)");
defer zone.end(); defer zone.end();
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle); const object = runtime.fromObjectHandle(handle);
const valid = runtime.checkObject(object, c.Z_KIND_GL); const valid = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (valid != abi.OK) return valid; 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. // Exclude even driver CPU work/spinning inside presentation, not just sleep.
const start = runtime.threadCpuTime(object.app.io); const start = runtime.threadCpuTime(object.app.io);
const status = runtime.glCall(handle, 6, null); const status = runtime.glCall(handle, 6, null);
object.payload.gl.swap_cpu_time +|= runtime.threadCpuTime(object.app.io) -| start; object.payload.window.swap_cpu_time +|= runtime.threadCpuTime(object.app.io) -| start;
if (status == abi.OK) object.payload.gl.presented = true; if (status == abi.OK) object.payload.window.presented = true;
return status; return status;
} }
pub fn setSwapInterval( pub fn setSwapInterval(
handle: ?*c.z_gl_context, handle: ?*c.uhdk_window,
interval: i32, interval: i32,
) abi.Status { ) abi.Status {
if (interval != 0 and interval != 1) return abi.INVALID; if (interval != 0 and interval != 1) return abi.INVALID;
@ -88,18 +79,16 @@ pub fn setSwapInterval(
} }
pub fn getProc( pub fn getProc(
handle: ?*c.z_gl_context, handle: ?*c.uhdk_window,
name: c.uhdk_text, name: c.uhdk_text,
out: [*c]c.uhdk_gl_proc, out: [*c]c.uhdk_gl_proc,
) abi.Status { ) abi.Status {
if (handle == null or if (handle == null or out == null or !abi.validText(name, true) or name.len == 0 or name.len > 255)
out == null or return abi.INVALID;
!abi.validText(name, true) or
name.len == 0 or
name.len > 255) return abi.INVALID;
const object = runtime.fromObjectHandle(handle); 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 (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); return c.z_native_gl_proc(object.native, name, out);
} }

View File

@ -12,7 +12,7 @@ pub export fn uhdk_menu_create(
) abi.Status { ) abi.Status {
if (handle == null or out == null or !abi.validSpan(items, len) or len > 4096) return abi.INVALID; if (handle == null or out == null or !abi.validSpan(items, len) or len > 4096) return abi.INVALID;
const application = runtime.fromAppHandle(handle); const application = runtime.fromAppHandle(handle);
if (runtime.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; const object = runtime.createObject(application, c.Z_KIND_MENU) catch return abi.OOM;
object.payload.menu.items = object.arena.allocator().alloc(c.uhdk_menu_item, @intCast(len)) catch { object.payload.menu.items = object.arena.allocator().alloc(c.uhdk_menu_item, @intCast(len)) catch {
runtime.release(object); runtime.release(object);

View File

@ -15,14 +15,16 @@ fn handle(a: *Application) *c.uhdk_session {
return runtime.toAppHandle(a); return runtime.toAppHandle(a);
} }
pub fn acquire(a: *Application) abi.Status { pub fn acquire(a: *Application) abi.Status {
const context = a.session_context orelse return abi.OK; if (!a.session_has_gl) return abi.OK;
if (runtime.fromObjectHandle(context).payload.gl.bracket) return abi.OK; const window = runtime.fromObjectHandle(a.session_window);
return graphics.acquire(context); if (window.payload.window.bracket) return abi.OK;
return graphics.acquire(a.session_window);
} }
pub fn release(a: *Application) abi.Status { pub fn release(a: *Application) abi.Status {
const context = a.session_context orelse return abi.OK; if (!a.session_has_gl) return abi.OK;
if (!runtime.fromObjectHandle(context).payload.gl.bracket) return abi.OK; const window = runtime.fromObjectHandle(a.session_window);
return graphics.release(context); 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 { pub fn ready(a: *Application, resource: anytype, deadline: u64) abi.Status {
const object = runtime.fromObjectHandle(resource); const object = runtime.fromObjectHandle(resource);
@ -37,6 +39,19 @@ pub fn ready(a: *Application, resource: anytype, deadline: u64) abi.Status {
} }
return abi.OK; 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 { pub export fn uhdk_open(options: [*c]const c.uhdk_options, out: [*c]?*c.uhdk_session) abi.Status {
if (out == null) return abi.INVALID; if (out == null) return abi.INVALID;
@ -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); status = ready(a, a.session_window, deadline);
if (status != abi.OK) return status; if (status != abi.OK) return status;
if (opts.no_opengl == 0) { if (opts.no_opengl == 0) {
status = graphics.create(a.session_window, &a.session_context); status = graphics.create(a.session_window);
if (status != abi.OK) return status; if (status != abi.OK) return status;
status = ready(a, a.session_context, deadline); status = readyGl(a, deadline);
if (status != abi.OK) return status; if (status != abi.OK) return status;
a.session_has_gl = true;
} }
status = windows.uhdk_window_set_visible(a.session_window, 1); status = windows.uhdk_window_set_visible(a.session_window, 1);
if (status != abi.OK) return status; if (status != abi.OK) return status;
@ -98,9 +114,9 @@ pub export fn uhdk_open(options: [*c]const c.uhdk_options, out: [*c]?*c.uhdk_ses
status = acquire(a); status = acquire(a);
if (status != abi.OK) return status; if (status != abi.OK) return status;
if (opts.no_opengl == 0) { if (opts.no_opengl == 0) {
status = graphics.setSwapInterval(a.session_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 (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); out.* = @ptrCast(a);
success = true; 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 { pub export fn uhdk_next_frame(session: ?*c.uhdk_session, out: [*c]c.uhdk_frame) c.uhdk_bool {
const a = state(session orelse return 0); const a = state(session orelse return 0);
if (runtime.checkThread(a) != abi.OK) return 0; if (runtime.validateMainThreadSessionReady(a) != abi.OK) return 0;
if (out == null or a.session_active) { if (out == null or a.session_active) {
a.session_status = if (out == null) abi.INVALID else c.UHDK_STATUS_BUSY; a.session_status = if (out == null) abi.INVALID else c.UHDK_STATUS_BUSY;
return 0; return 0;
@ -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; if (a.session_status != abi.OK) return 0;
a.session_status = windows.uhdk_window_get_metrics(a.session_window, &metrics); a.session_status = windows.uhdk_window_get_metrics(a.session_window, &metrics);
if (a.session_status != abi.OK) return 0; if (a.session_status != abi.OK) return 0;
out.*.gl = if (a.session_context != null) &a.session_gl else null; out.*.gl = if (a.session_has_gl) &a.session_gl else null;
out.*.metrics = metrics; out.*.metrics = metrics;
a.session_drawable = !a.stopping and drawable(metrics); a.session_drawable = !a.stopping and drawable(metrics);
out.*.drawable = @intFromBool(a.session_drawable); 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 { pub export fn uhdk_end_frame(session: ?*c.uhdk_session) abi.Status {
const a = state(session orelse return abi.INVALID); const a = state(session orelse return abi.INVALID);
if (runtime.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; if (!a.session_active) return c.UHDK_STATUS_BUSY;
a.session_active = false; a.session_active = false;
var status: abi.Status = abi.OK; var status: abi.Status = abi.OK;
if (a.session_drawable and !a.stopping and a.session_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 end_status = release(a);
const begin_status = if (end_status == abi.OK) acquire(a) else end_status; const begin_status = if (end_status == abi.OK) acquire(a) else end_status;
a.session_status = if (status != abi.OK) status else begin_status; a.session_status = if (status != abi.OK) status else begin_status;
@ -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 { pub export fn uhdk_get_status(session: ?*c.uhdk_session) abi.Status {
const a = state(session orelse return abi.INVALID); 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; return a.session_status;
} }
pub export fn uhdk_get_gl(session: ?*c.uhdk_session) [*c]const c.uhdk_gl_functions { pub export fn uhdk_get_gl(session: ?*c.uhdk_session) [*c]const c.uhdk_gl_functions {
const a = state(session orelse return null); const a = state(session orelse return null);
return if (a.session_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 { pub export fn uhdk_get_window(session: ?*c.uhdk_session) ?*c.uhdk_window {
return state(session orelse return null).session_window; return state(session orelse return null).session_window;
} }
pub export fn uhdk_close(session: ?*c.uhdk_session) void { pub export fn uhdk_close(session: ?*c.uhdk_session) void {
const a = state(session orelse return); const a = state(session orelse return);
std.debug.assert(runtime.checkThread(a) == abi.OK); std.debug.assert(runtime.validateMainThreadSessionReady(a) == abi.OK);
_ = release(a); _ = release(a);
app.destroy(handle(a)); app.destroy(handle(a));
} }
pub export fn uhdk_get_gl_proc(session: ?*c.uhdk_session, name: c.uhdk_text, out: [*c]c.uhdk_gl_proc) abi.Status { 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); const a = state(session orelse return abi.INVALID);
if (a.session_context == null) return c.UHDK_STATUS_UNSUPPORTED; if (!a.session_has_gl) return c.UHDK_STATUS_UNSUPPORTED;
return graphics.getProc(a.session_context, name, out); return graphics.getProc(a.session_window, name, out);
} }
pub export fn uhdk_set_vsync(session: ?*c.uhdk_session, enabled: c.uhdk_bool) abi.Status { pub export fn uhdk_set_vsync(session: ?*c.uhdk_session, enabled: c.uhdk_bool) abi.Status {
const a = state(session orelse return abi.INVALID); const a = state(session orelse return abi.INVALID);
if (enabled != 0 and enabled != 1) return abi.INVALID; if (enabled != 0 and enabled != 1) return abi.INVALID;
if (a.session_context == null) return c.UHDK_STATUS_UNSUPPORTED; if (!a.session_has_gl) return c.UHDK_STATUS_UNSUPPORTED;
return graphics.setSwapInterval(a.session_context, enabled); return graphics.setSwapInterval(a.session_window, enabled);
} }

View File

@ -91,7 +91,7 @@ pub export fn uhdk_window_get_metrics(
) abi.Status { ) abi.Status {
if (handle == null) return abi.INVALID; if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle); const object = runtime.fromObjectHandle(handle);
const status = runtime.checkObject(object, c.Z_KIND_WINDOW); const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status; if (status != abi.OK) return status;
object.app.lock(); object.app.lock();
defer object.app.unlock(); defer object.app.unlock();
@ -108,7 +108,7 @@ pub export fn uhdk_window_get_native(
) abi.Status { ) abi.Status {
if (handle == null or out == null or out.*.struct_size < @sizeOf(c.uhdk_native_window)) return abi.INVALID; if (handle == null or out == null or out.*.struct_size < @sizeOf(c.uhdk_native_window)) return abi.INVALID;
const object = runtime.fromObjectHandle(handle); const object = runtime.fromObjectHandle(handle);
const status = runtime.checkObject(object, c.Z_KIND_WINDOW); const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status; if (status != abi.OK) return status;
c.z_native_handles(object.native, out); c.z_native_handles(object.native, out);
return abi.OK; return abi.OK;
@ -119,7 +119,7 @@ pub export fn uhdk_window_create(handle: ?*c.uhdk_session, desc: [*c]const c.uhd
out.* = null; out.* = null;
if (handle == null or !abi.validDescriptor(c.uhdk_window_desc, desc) or desc.*.reserved != 0) return abi.INVALID; if (handle == null or !abi.validDescriptor(c.uhdk_window_desc, desc) or desc.*.reserved != 0) return abi.INVALID;
const a = runtime.fromAppHandle(handle); const a = runtime.fromAppHandle(handle);
if (runtime.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; if (a.session_active) return c.UHDK_STATUS_BUSY;
const session = @import("session.zig"); const session = @import("session.zig");
const d: c.z_window_desc = .{ const d: c.z_window_desc = .{
@ -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 { pub export fn uhdk_window_destroy(window: ?*c.uhdk_window) abi.Status {
if (window == null) return abi.OK; if (window == null) return abi.OK;
const object = runtime.fromObjectHandle(window); const object = runtime.fromObjectHandle(window);
const status = runtime.checkObject(object, c.Z_KIND_WINDOW); const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status; if (status != abi.OK) return status;
if (object.app.session_window == window) return abi.INVALID; if (object.app.session_window == window) return abi.INVALID;
runtime.destroyObject(object); runtime.destroyObject(object);

View File

@ -43,43 +43,43 @@ pub const State = struct {
position: n.uhdk_point = .{ .x = 0, .y = 0 }, position: n.uhdk_point = .{ .x = 0, .y = 0 },
transfers: ?*Transfer = null, transfers: ?*Transfer = null,
}; };
fn b() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
fn s() *State { fn dataState() *State {
return &b().data; return &backend().data;
} }
fn data(comptime T: type, raw: ?*anyopaque) *T { fn data(comptime T: type, raw: ?*anyopaque) *T {
return @ptrCast(@alignCast(raw.?)); return @ptrCast(@alignCast(raw.?));
} }
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void { pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void {
if (std.mem.eql(u8, interface, "wl_data_device_manager") and version >= 3) if (std.mem.eql(u8, interface, "wl_data_device_manager") and version >= 3)
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 { pub fn setup() void {
if (s().manager != null and Input.state().seat != null and s().device == null) { if (dataState().manager != null and Input.state().seat != null and dataState().device == null) {
s().device = c.wl_data_device_manager_get_data_device(s().manager, Input.state().seat); dataState().device = c.wl_data_device_manager_get_data_device(dataState().manager, Input.state().seat);
if (s().device != null) _ = c.wl_data_device_add_listener(s().device, &device_listener, null); if (dataState().device != null) _ = c.wl_data_device_add_listener(dataState().device, &device_listener, null);
} }
native.setCapability(n.UHDK_CAP_CLIPBOARD, s().device != null); native.setCapability(n.UHDK_CAP_CLIPBOARD, dataState().device != null);
native.setCapability(n.UHDK_CAP_DROP_FILES, s().device != null); native.setCapability(n.UHDK_CAP_DROP_FILES, dataState().device != null);
} }
fn unref(o: *Offer) void { fn unref(o: *Offer) void {
o.refs -= 1; o.refs -= 1;
if (o.refs != 0) return; if (o.refs != 0) return;
var link = &s().offers; var link = &dataState().offers;
while (link.* != o) link = &link.*.?.next; while (link.* != o) link = &link.*.?.next;
link.* = o.next; link.* = o.next;
c.wl_data_offer_destroy(o.proxy); c.wl_data_offer_destroy(o.proxy);
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 { 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); c.wl_data_offer_destroy(proxy);
return; return;
}; };
o.* = .{ .next = s().offers, .proxy = proxy }; o.* = .{ .next = dataState().offers, .proxy = proxy };
s().offers = o; dataState().offers = o;
_ = c.wl_data_offer_add_listener(proxy, &offer_listener, o); _ = c.wl_data_offer_add_listener(proxy, &offer_listener, o);
} }
fn mime(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, name: [*c]const u8) callconv(.c) void { fn mime(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, name: [*c]const u8) callconv(.c) void {
@ -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 }; const offer_listener: c.struct_wl_data_offer_listener = .{ .offer = mime, .source_actions = actions, .action = action };
fn lookup(proxy: ?*c.struct_wl_data_offer) ?*Offer { fn lookup(proxy: ?*c.struct_wl_data_offer) ?*Offer {
var o = s().offers; var o = dataState().offers;
while (o) |item| : (o = item.next) if (item.proxy == proxy) return item; while (o) |item| : (o = item.next) if (item.proxy == proxy) return item;
return null; return null;
} }
fn selection(_: ?*anyopaque, _: ?*c.struct_wl_data_device, proxy: ?*c.struct_wl_data_offer) callconv(.c) void { fn selection(_: ?*anyopaque, _: ?*c.struct_wl_data_device, proxy: ?*c.struct_wl_data_offer) callconv(.c) void {
if (s().selection) |old| unref(old); if (dataState().selection) |old| unref(old);
s().selection = lookup(proxy); // Takes the initial offer reference. dataState().selection = lookup(proxy); // Takes the initial offer reference.
} }
fn enter(_: ?*anyopaque, _: ?*c.struct_wl_data_device, serial: u32, surface: ?*c.struct_wl_surface, x: i32, y: i32, proxy: ?*c.struct_wl_data_offer) callconv(.c) void { fn enter(_: ?*anyopaque, _: ?*c.struct_wl_data_device, serial: u32, surface: ?*c.struct_wl_surface, x: i32, y: i32, proxy: ?*c.struct_wl_data_offer) callconv(.c) void {
leave(null, null); leave(null, null);
s().drag = lookup(proxy); dataState().drag = lookup(proxy);
s().drag_window = Input.find(surface); dataState().drag_window = Input.find(surface);
s().drag_serial = serial; dataState().drag_serial = serial;
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 };
negotiate(); negotiate();
} }
fn negotiate() void { fn negotiate() void {
const o = s().drag orelse return; const o = dataState().drag orelse return;
const accepted = o.uris and s().drag_window != null and s().drag_window.?.drop_enabled; const accepted = o.uris and dataState().drag_window != null and dataState().drag_window.?.drop_enabled;
c.wl_data_offer_accept(o.proxy, s().drag_serial, if (accepted) "text/uri-list" else null); c.wl_data_offer_accept(o.proxy, dataState().drag_serial, if (accepted) "text/uri-list" else null);
c.wl_data_offer_set_actions(o.proxy, if (accepted) c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY else 0, if (accepted) c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY else 0); c.wl_data_offer_set_actions(o.proxy, if (accepted) c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY else 0, if (accepted) c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY else 0);
} }
fn leave(_: ?*anyopaque, _: ?*c.struct_wl_data_device) callconv(.c) void { fn leave(_: ?*anyopaque, _: ?*c.struct_wl_data_device) callconv(.c) void {
if (s().drag) |o| unref(o); if (dataState().drag) |o| unref(o);
s().drag = null; dataState().drag = null;
s().drag_window = null; dataState().drag_window = null;
} }
fn motion(_: ?*anyopaque, _: ?*c.struct_wl_data_device, _: u32, x: i32, y: i32) callconv(.c) void { fn motion(_: ?*anyopaque, _: ?*c.struct_wl_data_device, _: u32, x: i32, y: i32) callconv(.c) void {
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 { fn drop(_: ?*anyopaque, _: ?*c.struct_wl_data_device) callconv(.c) void {
const o = s().drag orelse return; const o = dataState().drag orelse return;
const w = s().drag_window orelse return; const w = dataState().drag_window orelse return;
if (!w.drop_enabled or !o.uris or o.action != c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY) return; if (!w.drop_enabled or !o.uris or o.action != c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY) return;
_ = receive(o, "text/uri-list", 0, 16 * 1024 * 1024, w); _ = receive(o, "text/uri-list", 0, 16 * 1024 * 1024, w);
// drop ends the drag session; no leave is required after a successful drop. // drop ends the drag session; no leave is required after a successful drop.
@ -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 }; const device_listener: c.struct_wl_data_device_listener = .{ .data_offer = offer, .enter = enter, .leave = leave, .motion = motion, .drop = drop, .selection = selection };
pub fn enable(w: *native.Window, enabled: bool) u32 { pub fn enable(w: *native.Window, enabled: bool) u32 {
if (s().device == null) return n.UHDK_STATUS_UNSUPPORTED; if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED;
w.drop_enabled = enabled; w.drop_enabled = enabled;
if (s().drag_window == w) negotiate(); if (dataState().drag_window == w) negotiate();
return abi.OK; return abi.OK;
} }
fn sourceUnref(source: *Source) void { fn sourceUnref(source: *Source) void {
source.refs -= 1; source.refs -= 1;
if (source.refs != 0) return; if (source.refs != 0) return;
var link = &s().sources; var link = &dataState().sources;
while (link.* != source) link = &link.*.?.next; while (link.* != source) link = &link.*.?.next;
link.* = source.next; link.* = source.next;
b().app.gpa.free(source.bytes); backend().app.gpa.free(source.bytes);
b().app.gpa.destroy(source); backend().app.gpa.destroy(source);
} }
fn target(_: ?*anyopaque, _: ?*c.struct_wl_data_source, _: [*c]const u8) callconv(.c) void {} fn target(_: ?*anyopaque, _: ?*c.struct_wl_data_source, _: [*c]const u8) callconv(.c) void {}
fn send(raw: ?*anyopaque, _: ?*c.struct_wl_data_source, name: [*c]const u8, fd: i32) callconv(.c) void { fn send(raw: ?*anyopaque, _: ?*c.struct_wl_data_source, name: [*c]const u8, fd: i32) callconv(.c) void {
@ -158,13 +158,13 @@ fn send(raw: ?*anyopaque, _: ?*c.struct_wl_data_source, name: [*c]const u8, fd:
_ = c.close(fd); _ = c.close(fd);
return; return;
} }
const transfer = b().app.gpa.create(Transfer) catch { const transfer = backend().app.gpa.create(Transfer) catch {
_ = c.close(fd); _ = c.close(fd);
return; return;
}; };
source.refs += 1; source.refs += 1;
transfer.* = .{ .next = s().transfers, .fd = fd, .source = source, .deadline = runtime.now(b().app.io) + 10 * std.time.ns_per_s }; transfer.* = .{ .next = dataState().transfers, .fd = fd, .source = source, .deadline = runtime.now(backend().app.io) + 10 * std.time.ns_per_s };
s().transfers = transfer; dataState().transfers = transfer;
} }
fn cancelled(raw: ?*anyopaque, proxy: ?*c.struct_wl_data_source) callconv(.c) void { fn cancelled(raw: ?*anyopaque, proxy: ?*c.struct_wl_data_source) callconv(.c) void {
const source = data(Source, raw); const source = data(Source, raw);
@ -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 {} fn unusedAction(_: ?*anyopaque, _: ?*c.struct_wl_data_source, _: u32) callconv(.c) void {}
const source_listener: c.struct_wl_data_source_listener = .{ .target = target, .send = send, .cancelled = cancelled, .dnd_drop_performed = unused, .dnd_finished = unused, .action = unusedAction }; const source_listener: c.struct_wl_data_source_listener = .{ .target = target, .send = send, .cancelled = cancelled, .dnd_drop_performed = unused, .dnd_finished = unused, .action = unusedAction };
pub fn write(text: n.uhdk_text) u32 { pub fn write(text: n.uhdk_text) u32 {
if (s().device == null) return n.UHDK_STATUS_UNSUPPORTED; if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED;
const input = Input.state(); const input = Input.state();
// Selection changes require an actual input serial. Never queue a write to // Selection changes require an actual input serial. Never queue a write to
// hijack an unrelated future keystroke when the app has no input focus. // hijack an unrelated future keystroke when the app has no input focus.
if (input.key_focus == null or input.serial == 0) return abi.UNAVAILABLE; if (input.key_focus == null or input.serial == 0) return abi.UNAVAILABLE;
const source = b().app.gpa.create(Source) catch return abi.OOM; const source = backend().app.gpa.create(Source) catch return abi.OOM;
const bytes = b().app.gpa.dupe(u8, abi.textBytes(text)) catch { const bytes = backend().app.gpa.dupe(u8, abi.textBytes(text)) catch {
b().app.gpa.destroy(source); backend().app.gpa.destroy(source);
return abi.OOM; return abi.OOM;
}; };
const proxy = c.wl_data_device_manager_create_data_source(s().manager) orelse { const proxy = c.wl_data_device_manager_create_data_source(dataState().manager) orelse {
b().app.gpa.free(bytes); backend().app.gpa.free(bytes);
b().app.gpa.destroy(source); backend().app.gpa.destroy(source);
return abi.OOM; return abi.OOM;
}; };
source.* = .{ .next = s().sources, .proxy = proxy, .bytes = bytes }; source.* = .{ .next = dataState().sources, .proxy = proxy, .bytes = bytes };
s().sources = source; dataState().sources = source;
_ = c.wl_data_source_add_listener(proxy, &source_listener, source); _ = c.wl_data_source_add_listener(proxy, &source_listener, source);
c.wl_data_source_offer(proxy, "text/plain;charset=utf-8"); c.wl_data_source_offer(proxy, "text/plain;charset=utf-8");
c.wl_data_source_offer(proxy, "text/plain"); 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; return abi.OK;
} }
pub fn read(id: u64, limit: u64) u32 { 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; 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; const format = o.text orelse return n.UHDK_STATUS_NOT_FOUND;
return receive(o, format, id, limit, null); return receive(o, format, id, limit, null);
} }
fn receive(o: *Offer, format: [*:0]const u8, id: u64, limit: u64, w: ?*native.Window) u32 { fn receive(o: *Offer, format: [*:0]const u8, id: u64, limit: u64, w: ?*native.Window) u32 {
var fds: [2]c_int = undefined; var fds: [2]c_int = undefined;
if (c.z_linux_pipe(&fds) != 0) return n.UHDK_STATUS_OS_ERROR; if (c.z_linux_pipe(&fds) != 0) return n.UHDK_STATUS_OS_ERROR;
const transfer = b().app.gpa.create(Transfer) catch { const transfer = backend().app.gpa.create(Transfer) catch {
_ = c.close(fds[0]); _ = c.close(fds[0]);
_ = c.close(fds[1]); _ = c.close(fds[1]);
return abi.OOM; return abi.OOM;
}; };
o.refs += 1; o.refs += 1;
transfer.* = .{ .next = 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 }; 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 };
s().transfers = transfer; dataState().transfers = transfer;
c.wl_data_offer_receive(o.proxy, format, fds[1]); c.wl_data_offer_receive(o.proxy, format, fds[1]);
_ = c.close(fds[1]); _ = c.close(fds[1]);
return n.Z_DEFERRED; return n.Z_DEFERRED;
} }
pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void { pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
var t = s().transfers; var t = dataState().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 }); while (t) |item| : (t = item.next) try fds.append(backend().app.gpa, .{ .fd = item.fd, .events = if (item.source != null) c.POLLOUT else c.POLLIN, .revents = 0 });
} }
pub fn tick() i32 { pub fn tick() i32 {
var t = s().transfers; var t = dataState().transfers;
while (t) |item| { while (t) |item| {
t = item.next; t = item.next;
if (runtime.now(b().app.io) >= item.deadline) { if (runtime.now(backend().app.io) >= item.deadline) {
finish(item, abi.UNAVAILABLE); finish(item, abi.UNAVAILABLE);
continue; continue;
} }
@ -250,46 +250,46 @@ pub fn tick() i32 {
finish(item, n.UHDK_STATUS_BUFFER_TOO_SMALL); finish(item, n.UHDK_STATUS_BUFFER_TOO_SMALL);
continue; continue;
} }
item.bytes.appendSlice(b().app.gpa, buffer[0..length]) catch { item.bytes.appendSlice(backend().app.gpa, buffer[0..length]) catch {
finish(item, abi.OOM); finish(item, abi.OOM);
continue; continue;
}; };
} else if (c.z_linux_errno() != c.EAGAIN and c.z_linux_errno() != c.EINTR) finish(item, abi.UNAVAILABLE); } else if (c.z_linux_errno() != c.EAGAIN and c.z_linux_errno() != c.EINTR) finish(item, abi.UNAVAILABLE);
} }
} }
return if (s().transfers != null) 100 else -1; return if (dataState().transfers != null) 100 else -1;
} }
fn finish(t: *Transfer, status: u32) void { fn finish(t: *Transfer, status: u32) void {
if (t.request != 0) { if (t.request != 0) {
var result = std.mem.zeroes(n.z_request_result); var result = std.mem.zeroes(n.z_request_result);
result.value.text = abi.textSpan(t.bytes.items); 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| { } else if (t.window) |w| {
if (status == abi.OK and w.drop_enabled and emitDrop(w, t.bytes.items, t.position)) c.wl_data_offer_finish(t.offer.?.proxy); if (status == abi.OK and w.drop_enabled and emitDrop(w, t.bytes.items, t.position)) c.wl_data_offer_finish(t.offer.?.proxy);
} }
var link = &s().transfers; var link = &dataState().transfers;
while (link.* != t) link = &link.*.?.next; while (link.* != t) link = &link.*.?.next;
link.* = t.next; link.* = t.next;
_ = c.close(t.fd); _ = c.close(t.fd);
if (t.offer) |o| unref(o); if (t.offer) |o| unref(o);
if (t.source) |source| sourceUnref(source); if (t.source) |source| sourceUnref(source);
t.bytes.deinit(b().app.gpa); t.bytes.deinit(backend().app.gpa);
b().app.gpa.destroy(t); backend().app.gpa.destroy(t);
} }
fn emitDrop(w: *native.Window, bytes: []const u8, position: n.uhdk_point) bool { fn emitDrop(w: *native.Window, bytes: []const u8, position: n.uhdk_point) bool {
var files: std.ArrayList(?*n.uhdk_file) = .empty; var files: std.ArrayList(?*n.uhdk_file) = .empty;
defer { defer {
for (files.items) |file| n.uhdk_file_release(file); for (files.items) |file| n.uhdk_file_release(file);
files.deinit(b().app.gpa); files.deinit(backend().app.gpa);
} }
var lines = std.mem.splitScalar(u8, bytes, '\n'); var lines = std.mem.splitScalar(u8, bytes, '\n');
while (lines.next()) |line| { while (lines.next()) |line| {
const uri = std.mem.trim(u8, line, "\r"); const uri = std.mem.trim(u8, line, "\r");
if (uri.len == 0 or uri[0] == '#') continue; if (uri.len == 0 or uri[0] == '#') continue;
const path = Files.decode(b().app.gpa, uri) catch return false; const path = Files.decode(backend().app.gpa, uri) catch return false;
defer b().app.gpa.free(path); defer backend().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; const file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = path.ptr, .len = path.len }, null) orelse return false;
files.append(b().app.gpa, file) catch { files.append(backend().app.gpa, file) catch {
n.uhdk_file_release(file); n.uhdk_file_release(file);
return false; return false;
}; };
@ -302,7 +302,7 @@ fn emitDrop(w: *native.Window, bytes: []const u8, position: n.uhdk_point) bool {
return true; return true;
} }
pub fn cancel(id: u64) bool { pub fn cancel(id: u64) bool {
var t = s().transfers; var t = dataState().transfers;
while (t) |item| : (t = item.next) if (item.request == id) { while (t) |item| : (t = item.next) if (item.request == id) {
finish(item, abi.CANCELLED); finish(item, abi.CANCELLED);
return true; return true;
@ -310,11 +310,11 @@ pub fn cancel(id: u64) bool {
return false; return false;
} }
pub fn forget(w: *native.Window) void { pub fn forget(w: *native.Window) void {
if (s().drag_window == w) { if (dataState().drag_window == w) {
s().drag_window = null; dataState().drag_window = null;
negotiate(); negotiate();
} }
var t = s().transfers; var t = dataState().transfers;
while (t) |item| { while (t) |item| {
t = item.next; t = item.next;
if (item.window == w) { if (item.window == w) {
@ -324,22 +324,22 @@ pub fn forget(w: *native.Window) void {
} }
} }
pub fn releaseSeat() void { pub fn releaseSeat() void {
while (s().transfers) |t| finish(t, abi.CANCELLED); while (dataState().transfers) |t| finish(t, abi.CANCELLED);
s().selection = null; dataState().selection = null;
s().drag = null; dataState().drag = null;
s().drag_window = null; dataState().drag_window = null;
while (s().offers) |o| unref(o); while (dataState().offers) |o| unref(o);
while (s().sources) |source| { while (dataState().sources) |source| {
if (source.proxy != null) c.wl_data_source_destroy(source.proxy); if (source.proxy != null) c.wl_data_source_destroy(source.proxy);
sourceUnref(source); sourceUnref(source);
} }
if (s().device != null) c.wl_data_device_release(s().device); if (dataState().device != null) c.wl_data_device_release(dataState().device);
s().device = null; dataState().device = null;
native.setCapability(n.UHDK_CAP_CLIPBOARD, false); native.setCapability(n.UHDK_CAP_CLIPBOARD, false);
native.setCapability(n.UHDK_CAP_DROP_FILES, false); native.setCapability(n.UHDK_CAP_DROP_FILES, false);
} }
pub fn deinit() void { pub fn deinit() void {
releaseSeat(); releaseSeat();
if (s().manager != null) c.wl_data_device_manager_destroy(s().manager); if (dataState().manager != null) c.wl_data_device_manager_destroy(dataState().manager);
s().manager = null; dataState().manager = null;
} }

View File

@ -17,21 +17,21 @@ pub const State = struct {
pending: ?*Activation = null, pending: ?*Activation = null,
launch: ?[:0]u8 = null, launch: ?[:0]u8 = null,
}; };
fn b() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
fn s() *State { fn desktopState() *State {
return &b().desktop; return &backend().desktop;
} }
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void { pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void {
if (std.mem.eql(u8, interface, "xdg_activation_v1")) 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")) { 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")) {
s().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_toplevel_icon_manager_v1_interface, 1)); desktopState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_toplevel_icon_manager_v1_interface, 1));
if (s().manager != null) _ = c.xdg_toplevel_icon_manager_v1_add_listener(s().manager, &icon_listener, null); 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")) { } 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)); desktopState().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); 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 iconSize(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel_icon_manager_v1, _: i32) callconv(.c) void {}
fn iconDone(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel_icon_manager_v1) callconv(.c) void {} fn iconDone(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel_icon_manager_v1) callconv(.c) void {}
@ -41,63 +41,63 @@ const shm_listener: c.struct_wl_shm_listener = .{ .format = format };
pub fn initialize() void { pub fn initialize() void {
const token = c.getenv("XDG_ACTIVATION_TOKEN"); const token = c.getenv("XDG_ACTIVATION_TOKEN");
if (token != null and token[0] != 0) { 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"); _ = c.unsetenv("XDG_ACTIVATION_TOKEN");
} }
} }
pub fn focus(w: *native.Window, id: u64) u32 { pub fn focus(w: *native.Window, id: u64) u32 {
if (s().activation == null) return n.UHDK_STATUS_UNSUPPORTED; if (desktopState().activation == null) return n.UHDK_STATUS_UNSUPPORTED;
if (s().launch) |token| { if (desktopState().launch) |token| {
c.xdg_activation_v1_activate(s().activation, token, w.surface); c.xdg_activation_v1_activate(desktopState().activation, token, w.surface);
b().app.gpa.free(token); backend().app.gpa.free(token);
s().launch = null; desktopState().launch = null;
return abi.OK; return abi.OK;
} }
const input = Input.state(); const input = Input.state();
if (input.serial == 0 or input.key_focus == null or runtime.now(b().app.io) -| input.serial_time > 5 * std.time.ns_per_s) return abi.UNAVAILABLE; 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 = b().app.gpa.create(Activation) catch return abi.OOM; const p = backend().app.gpa.create(Activation) catch return abi.OOM;
const token = c.xdg_activation_v1_get_activation_token(s().activation) orelse { const token = c.xdg_activation_v1_get_activation_token(desktopState().activation) orelse {
b().app.gpa.destroy(p); backend().app.gpa.destroy(p);
return abi.OOM; 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 }; p.* = .{ .next = desktopState().pending, .id = id, .window = w, .token = token, .deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s };
s().pending = p; desktopState().pending = p;
_ = c.xdg_activation_token_v1_add_listener(token, &activation_listener, p); _ = c.xdg_activation_token_v1_add_listener(token, &activation_listener, p);
c.xdg_activation_token_v1_set_serial(token, input.serial, input.seat); c.xdg_activation_token_v1_set_serial(token, input.serial, input.seat);
c.xdg_activation_token_v1_set_surface(token, input.key_focus.?.surface); c.xdg_activation_token_v1_set_surface(token, input.key_focus.?.surface);
const app_id = 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); finish(p, abi.OOM);
return n.Z_DEFERRED; 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_set_app_id(token, app_id);
c.xdg_activation_token_v1_commit(token); c.xdg_activation_token_v1_commit(token);
return n.Z_DEFERRED; return n.Z_DEFERRED;
} }
fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c]const u8) callconv(.c) void { fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c]const u8) callconv(.c) void {
const p: *Activation = @ptrCast(@alignCast(raw.?)); const p: *Activation = @ptrCast(@alignCast(raw.?));
c.xdg_activation_v1_activate(s().activation, token, p.window.surface); c.xdg_activation_v1_activate(desktopState().activation, token, p.window.surface);
finish(p, abi.OK); finish(p, abi.OK);
} }
const activation_listener: c.struct_xdg_activation_token_v1_listener = .{ .done = activated }; const activation_listener: c.struct_xdg_activation_token_v1_listener = .{ .done = activated };
fn finish(p: *Activation, status: u32) void { fn finish(p: *Activation, status: u32) void {
var link = &s().pending; var link = &desktopState().pending;
while (link.* != p) link = &link.*.?.next; while (link.* != p) link = &link.*.?.next;
link.* = p.next; link.* = p.next;
c.xdg_activation_token_v1_destroy(p.token); c.xdg_activation_token_v1_destroy(p.token);
n.z_complete(runtime.toAppHandle(b().app), p.id, status, null); n.z_complete(runtime.toAppHandle(backend().app), p.id, status, null);
b().app.gpa.destroy(p); backend().app.gpa.destroy(p);
} }
pub fn tick() i32 { pub fn tick() i32 {
var cursor = s().pending; var cursor = desktopState().pending;
while (cursor) |p| { while (cursor) |p| {
cursor = p.next; 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 { pub fn cancel(id: u64) bool {
var cursor = s().pending; var cursor = desktopState().pending;
while (cursor) |p| : (cursor = p.next) if (p.id == id) { while (cursor) |p| : (cursor = p.next) if (p.id == id) {
finish(p, abi.CANCELLED); finish(p, abi.CANCELLED);
return true; return true;
@ -105,14 +105,14 @@ pub fn cancel(id: u64) bool {
return false; return false;
} }
pub fn forget(w: *native.Window) void { pub fn forget(w: *native.Window) void {
var cursor = s().pending; var cursor = desktopState().pending;
while (cursor) |p| { while (cursor) |p| {
cursor = p.next; cursor = p.next;
if (p.window == w) finish(p, abi.CANCELLED); if (p.window == w) finish(p, abi.CANCELLED);
} }
} }
pub fn applyIcon(w: *native.Window) void { pub fn applyIcon(w: *native.Window) void {
if (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, /// Public pixels are straight RGBA; wl_shm ARGB8888 uses native-endian,
/// premultiplied channels. Pad rectangular images to a transparent square. /// premultiplied channels. Pad rectangular images to a transparent square.
@ -131,7 +131,7 @@ pub fn pixels(destination: []u32, side: usize, image: n.uhdk_image) void {
}; };
} }
pub fn setIcon(image: n.uhdk_image) u32 { 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 side = @max(image.width, image.height);
const size: usize = @as(usize, side) * side * 4; const size: usize = @as(usize, side) * side * 4;
const fd = c.memfd_create("uhdk-icon", c.MFD_CLOEXEC); const fd = c.memfd_create("uhdk-icon", c.MFD_CLOEXEC);
@ -146,18 +146,18 @@ pub fn setIcon(image: n.uhdk_image) u32 {
}; };
const words: [*]u32 = @ptrCast(@alignCast(mapping.?)); const words: [*]u32 = @ptrCast(@alignCast(mapping.?));
pixels(words[0 .. size / 4], side, image); pixels(words[0 .. size / 4], side, image);
const pool = c.wl_shm_create_pool(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); 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 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); c.wl_buffer_destroy(buffer);
return abi.OOM; return abi.OOM;
}; };
c.xdg_toplevel_icon_v1_add_buffer(proxy, buffer, 1); c.xdg_toplevel_icon_v1_add_buffer(proxy, buffer, 1);
const old = s().icon; const old = desktopState().icon;
s().icon = .{ .proxy = proxy, .buffer = buffer, .mapping = mapping.?, .size = size }; desktopState().icon = .{ .proxy = proxy, .buffer = buffer, .mapping = mapping.?, .size = size };
retained = true; retained = true;
var cursor = b().windows; var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) applyIcon(w); while (cursor) |w| : (cursor = w.next) applyIcon(w);
if (old) |icon| destroyIcon(icon); if (old) |icon| destroyIcon(icon);
return abi.OK; return abi.OK;
@ -168,12 +168,12 @@ fn destroyIcon(icon: Icon) void {
_ = c.munmap(icon.mapping, icon.size); _ = c.munmap(icon.mapping, icon.size);
} }
pub fn deinit() void { pub fn deinit() void {
while (s().pending) |p| finish(p, abi.CANCELLED); while (desktopState().pending) |p| finish(p, abi.CANCELLED);
if (s().icon) |icon| destroyIcon(icon); if (desktopState().icon) |icon| destroyIcon(icon);
if (s().launch) |token| b().app.gpa.free(token); if (desktopState().launch) |token| backend().app.gpa.free(token);
if (s().manager != null) c.xdg_toplevel_icon_manager_v1_destroy(s().manager); if (desktopState().manager != null) c.xdg_toplevel_icon_manager_v1_destroy(desktopState().manager);
if (s().shm != null) c.wl_shm_destroy(s().shm); if (desktopState().shm != null) c.wl_shm_destroy(desktopState().shm);
if (s().activation != null) c.xdg_activation_v1_destroy(s().activation); if (desktopState().activation != null) c.xdg_activation_v1_destroy(desktopState().activation);
} }
test "icons premultiply RGBA and pad rectangular images" { test "icons premultiply RGBA and pad rectangular images" {
const rgba = [_]u8{ 255, 128, 0, 128, 0, 255, 0, 255 }; const rgba = [_]u8{ 255, 128, 0, 128, 0, 255, 0, 255 };

View File

@ -42,7 +42,7 @@ pub fn finish(b: *native.Backend) void {
b.egl_display = null; 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 (b.egl_display == null or w.flags & n.Z_WINDOW_OPENGL == 0) return n.UHDK_STATUS_UNSUPPORTED;
if (w.egl != null) return n.UHDK_STATUS_BUSY; if (w.egl != null) return n.UHDK_STATUS_BUSY;
if (c.z_eglBindAPI.?(c.EGL_OPENGL_API) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR; if (c.z_eglBindAPI.?(c.EGL_OPENGL_API) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR;
@ -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 }; ctx.* = .{ .window = w, .native = win, .surface = surface, .context = context };
w.egl = ctx; w.egl = ctx;
n.z_object_set_native(object, ctx);
return abi.OK; return abi.OK;
} }
pub fn destroy(ctx: *Context) void { pub fn destroy(ctx: *Context) void {

View File

@ -69,14 +69,14 @@ pub const State = struct {
axis_stop: bool = false, axis_stop: bool = false,
scrolling: bool = false, scrolling: bool = false,
}; };
fn b() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
pub fn state() *State { pub fn state() *State {
return &b().input; return &backend().input;
} }
pub fn find(surface: ?*c.struct_wl_surface) ?*native.Window { pub fn find(surface: ?*c.struct_wl_surface) ?*native.Window {
var item = b().windows; var item = backend().windows;
while (item) |w| : (item = w.next) if (w.surface == surface) return w; while (item) |w| : (item = w.next) if (w.surface == surface) return w;
return null; return null;
} }
@ -90,7 +90,7 @@ pub fn id() u64 {
} }
pub fn provenance(serial: u32) void { pub fn provenance(serial: u32) void {
state().serial = serial; state().serial = serial;
state().serial_time = runtime.now(b().app.io); state().serial_time = runtime.now(backend().app.io);
} }
pub fn initialize() void { pub fn initialize() void {
const s = state(); 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 // authoritative modifiers event supply the public post-event flags even
// when the key and modifier messages arrive in separate socket reads. // when the key and modifier messages arrive in separate socket reads.
if (s.key_sync == null) { 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 (s.key_sync != null) _ = c.wl_callback_add_listener(s.key_sync, &key_sync_listener, null) else flushKey();
} }
if (pressed != 0 and s.repeat_rate > 0 and s.keymap != null and c.z_xkb_keymap_key_repeats.?(s.keymap, code + 8) != 0) { if (pressed != 0 and s.repeat_rate > 0 and s.keymap != null and c.z_xkb_keymap_key_repeats.?(s.keymap, code + 8) != 0) {
s.repeat_key = code; s.repeat_key = code;
s.repeat_at = runtime.now(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; } else if (s.repeat_key == code) s.repeat_key = null;
} }
fn prepareKey(code: u32, down: bool, repeated: bool) Key { fn prepareKey(code: u32, down: bool, repeated: bool) Key {
@ -298,11 +298,11 @@ pub fn tick() i32 {
var event = std.mem.zeroes(n.z_event); var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_APP_ACTIVATION; event.type = n.UHDK_EVENT_APP_ACTIVATION;
event.data.active = @intFromBool(active); event.data.active = @intFromBool(active);
n.z_emit(runtime.toAppHandle(b().app), &event); n.z_emit(runtime.toAppHandle(backend().app), &event);
} }
if (s.pending_key != null) return -1; if (s.pending_key != null) return -1;
if (s.repeat_key) |code| { if (s.repeat_key) |code| {
const now = runtime.now(b().app.io); const now = runtime.now(backend().app.io);
if (now >= s.repeat_at) { if (now >= s.repeat_at) {
deliverKey(code, true, true); deliverKey(code, true, true);
s.repeat_at = now + std.time.ns_per_s / @max(1, s.repeat_rate); s.repeat_at = now + std.time.ns_per_s / @max(1, s.repeat_rate);
@ -404,7 +404,7 @@ fn button(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, _: u32, code: u
if (pressed != 0) { if (pressed != 0) {
s.buttons |= mask; 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 dx = s.position.x - s.last_click_position.x;
const dy = s.position.y - s.last_click_position.y; const dy = s.position.y - s.last_click_position.y;
s.click_count = if (s.last_click_button == mapped and now -| s.last_click_time <= 500 * std.time.ns_per_ms and dx * dx + dy * dy <= 25) @min(3, s.click_count + 1) else 1; 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(); const s = state();
s.popup_window = w; s.popup_window = w;
s.popup_serial = serial; s.popup_serial = serial;
s.popup_time = runtime.now(b().app.io); s.popup_time = runtime.now(backend().app.io);
} }
pub fn beginPopup() void { pub fn beginPopup() void {
normal(n.UHDK_CYCLE_CAPTURE_LOST); normal(n.UHDK_CYCLE_CAPTURE_LOST);

View File

@ -38,48 +38,48 @@ pub const State = struct {
sequence: u64 = 0, sequence: u64 = 0,
app_menu: ?*Resource = null, app_menu: ?*Resource = null,
}; };
fn b() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
fn s() *State { fn menuState() *State {
return &b().menus; return &backend().menus;
} }
fn same(a: []const u8, z: []const u8) bool { fn same(a: []const u8, z: []const u8) bool {
return std.mem.eql(u8, a, z); return std.mem.eql(u8, a, z);
} }
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void { pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void {
if (!same(interface, "org_kde_kwin_appmenu_manager") or s().manager != null) return; if (!same(interface, "org_kde_kwin_appmenu_manager") or menuState().manager != null) return;
s().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_org_kde_kwin_appmenu_manager_interface, @min(version, 2))); menuState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_org_kde_kwin_appmenu_manager_interface, @min(version, 2)));
s().global_name = name; menuState().global_name = name;
ready(); ready();
} }
pub fn remove(name: u32) void { pub fn remove(name: u32) void {
if (name != s().global_name) return; if (name != menuState().global_name) return;
disconnected(); disconnected();
destroyManager(); destroyManager();
} }
fn destroyManager() void { 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); 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; menuState().manager = null;
s().global_name = 0; menuState().global_name = 0;
} }
pub fn ready() void { pub fn ready() void {
native.setCapability(n.UHDK_CAP_APP_MENU, s().manager != null and b().portal.ready); native.setCapability(n.UHDK_CAP_APP_MENU, menuState().manager != null and backend().portal.ready);
var cursor = b().windows; var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| associate(e); while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| associate(e);
} }
fn associate(e: *Export) void { fn associate(e: *Export) void {
if (e.proxy != null or 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. // 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; 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, b().portal.unique.?.ptr, e.path.ptr); c.org_kde_kwin_appmenu_set_address(e.proxy, backend().portal.unique.?.ptr, e.path.ptr);
} }
pub fn disconnected() void { pub fn disconnected() void {
native.setCapability(n.UHDK_CAP_APP_MENU, false); native.setCapability(n.UHDK_CAP_APP_MENU, false);
var cursor = b().windows; var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| unassociate(e); while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| unassociate(e);
} }
fn unassociate(e: *Export) void { fn unassociate(e: *Export) void {
@ -90,7 +90,7 @@ fn destroy(e: *Export) void {
unassociate(e); unassociate(e);
runtime.release(e.root); runtime.release(e.root);
e.arena.deinit(); e.arena.deinit();
b().app.gpa.destroy(e); backend().app.gpa.destroy(e);
} }
fn add(e: *Export, menu: *Resource, parent: usize) !void { fn add(e: *Export, menu: *Resource, parent: usize) !void {
var previous: usize = 0; var previous: usize = 0;
@ -113,12 +113,12 @@ fn add(e: *Export, menu: *Resource, parent: usize) !void {
} }
} }
fn create(w: *native.Window, root: *Resource) !*Export { fn create(w: *native.Window, root: *Resource) !*Export {
const e = try b().app.gpa.create(Export); const e = try backend().app.gpa.create(Export);
errdefer b().app.gpa.destroy(e); errdefer backend().app.gpa.destroy(e);
s().sequence += 1; menuState().sequence += 1;
e.* = .{ .window = w, .root = root, .arena = .init(b().app.gpa), .path = "" }; e.* = .{ .window = w, .root = root, .arena = .init(backend().app.gpa), .path = "" };
errdefer e.arena.deinit(); 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 e.nodes.append(e.arena.allocator(), .{});
try add(e, root, 0); try add(e, root, 0);
runtime.retain(root); runtime.retain(root);
@ -131,16 +131,16 @@ fn replace(w: *native.Window, e: ?*Export) void {
if (e) |value| associate(value); if (e) |value| associate(value);
} }
pub fn inherit(w: *native.Window) !void { pub fn inherit(w: *native.Window) !void {
if (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 { pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 {
const root: ?*Resource = if (menu) |p| @ptrCast(@alignCast(p)) else null; const root: ?*Resource = if (menu) |p| @ptrCast(@alignCast(p)) else null;
if (root != null) { if (root != null) {
if (s().manager == null) return n.UHDK_STATUS_UNSUPPORTED; if (menuState().manager == null) return n.UHDK_STATUS_UNSUPPORTED;
if (b().portal.connection == null) return abi.UNAVAILABLE; if (backend().portal.connection == null) return abi.UNAVAILABLE;
} }
if (w) |window| { 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; const e = if (effective) |r| create(window, r) catch return abi.OOM else null;
if (root) |r| runtime.retain(r); if (root) |r| runtime.retain(r);
if (window.menu_override) |r| runtime.release(r); if (window.menu_override) |r| runtime.release(r);
@ -154,7 +154,7 @@ pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 {
destroy(e); destroy(e);
}; };
if (root) |r| { if (root) |r| {
var cursor = b().windows; var cursor = backend().windows;
while (cursor) |window| : (cursor = window.next) if (window.menu_override == null) { while (cursor) |window| : (cursor = window.next) if (window.menu_override == null) {
const e = create(window, r) catch return abi.OOM; const e = create(window, r) catch return abi.OOM;
e.next = pending; e.next = pending;
@ -162,10 +162,10 @@ pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 {
}; };
runtime.retain(r); runtime.retain(r);
} }
if (s().app_menu) |r| runtime.release(r); if (menuState().app_menu) |r| runtime.release(r);
s().app_menu = root; menuState().app_menu = root;
if (root == null) { if (root == null) {
var cursor = b().windows; var cursor = backend().windows;
while (cursor) |window| : (cursor = window.next) if (window.menu_override == null) { while (cursor) |window| : (cursor = window.next) if (window.menu_override == null) {
replace(window, null); replace(window, null);
}; };
@ -184,8 +184,8 @@ pub fn forget(w: *native.Window) void {
w.menu_override = null; w.menu_override = null;
} }
pub fn deinit() void { pub fn deinit() void {
if (s().app_menu) |root| runtime.release(root); if (menuState().app_menu) |root| runtime.release(root);
s().app_menu = null; menuState().app_menu = null;
destroyManager(); destroyManager();
} }
fn enabled(e: *Export, index: usize) bool { 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); try Bus.close(out, &tuple);
} }
pub fn updateFlags() u32 { pub fn updateFlags() u32 {
var cursor = b().windows; var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| { while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| {
changed(e) catch return abi.OOM; changed(e) catch return abi.OOM;
}; };
@ -309,7 +309,7 @@ fn changed(e: *Export) !void {
break; break;
}; };
if (!dirty) return; 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; const message = c.z_dbus_message_new_signal.?(e.path.ptr, iface, "ItemsPropertiesUpdated") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(message); defer c.z_dbus_message_unref.?(message);
var out = Bus.append(message); var out = Bus.append(message);
@ -355,7 +355,7 @@ pub fn process(message: *Bus.Message) !bool {
const path = c.z_dbus_message_get_path.?(message); const path = c.z_dbus_message_get_path.?(message);
if (path == null or !std.mem.startsWith(u8, std.mem.span(path), prefix)) return false; if (path == null or !std.mem.startsWith(u8, std.mem.span(path), prefix)) return false;
var found: ?*Export = null; var found: ?*Export = null;
var cursor = b().windows; var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| { while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| {
if (same(e.path, std.mem.span(path))) { if (same(e.path, std.mem.span(path))) {
found = e; found = e;

View File

@ -40,17 +40,17 @@ pub const State = struct {
serial: u32 = 0, serial: u32 = 0,
hover_at: u64 = 0, hover_at: u64 = 0,
}; };
fn b() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
fn s() *State { fn popupState() *State {
return &b().popup; return &backend().popup;
} }
pub fn active() bool { pub fn active() bool {
return s().request != 0; return popupState().request != 0;
} }
pub fn capability() void { 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 { fn panel(raw: ?*anyopaque) *Panel {
return @ptrCast(@alignCast(raw.?)); return @ptrCast(@alignCast(raw.?));
@ -67,12 +67,12 @@ fn rowY(p: *Panel, index: usize) i32 {
return y - p.scroll; return y - p.scroll;
} }
fn lookup(surface: ?*c.struct_wl_surface) ?*Panel { fn lookup(surface: ?*c.struct_wl_surface) ?*Panel {
var cursor = s().top; var cursor = popupState().top;
while (cursor) |p| : (cursor = p.parent) if (p.surface == surface) return p; while (cursor) |p| : (cursor = p.parent) if (p.surface == surface) return p;
return null; return null;
} }
pub fn owner(surface: ?*c.struct_wl_surface) ?*native.Window { pub fn owner(surface: ?*c.struct_wl_surface) ?*native.Window {
return if (lookup(surface) != null) s().window else null; return if (lookup(surface) != null) popupState().window else null;
} }
fn freeBuffer(buf: *Buffer) void { fn freeBuffer(buf: *Buffer) void {
if (buf.proxy != null) c.wl_buffer_destroy(buf.proxy); if (buf.proxy != null) c.wl_buffer_destroy(buf.proxy);
@ -80,37 +80,37 @@ fn freeBuffer(buf: *Buffer) void {
buf.* = .{}; buf.* = .{};
} }
fn destroy(p: *Panel) void { 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.popup != null) c.xdg_popup_destroy(p.popup);
if (p.xdg != null) c.xdg_surface_destroy(p.xdg); if (p.xdg != null) c.xdg_surface_destroy(p.xdg);
if (p.surface != null) c.wl_surface_destroy(p.surface); if (p.surface != null) c.wl_surface_destroy(p.surface);
for (&p.buffers) |*buf| freeBuffer(buf); for (&p.buffers) |*buf| freeBuffer(buf);
b().app.gpa.destroy(p); backend().app.gpa.destroy(p);
} }
fn closeChildren(p: *Panel) void { fn closeChildren(p: *Panel) void {
while (s().top != p) { while (popupState().top != p) {
const top = s().top orelse return; const top = popupState().top orelse return;
s().top = top.parent; popupState().top = top.parent;
destroy(top); destroy(top);
} }
} }
fn finish(status: u32) void { fn finish(status: u32) void {
if (!active()) return; if (!active()) return;
const request_id = s().request; const request_id = popupState().request;
while (s().top) |top| { while (popupState().top) |top| {
s().top = top.parent; popupState().top = top.parent;
destroy(top); destroy(top);
} }
const root = s().root.?; const root = popupState().root.?;
s().* = .{}; popupState().* = .{};
runtime.release(root); 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 { 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 { 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); finish(abi.CANCELLED);
return true; return true;
} }
@ -119,31 +119,31 @@ pub fn deinit() void {
} }
pub fn request(cmd: *const n.z_command, id: u64) u32 { pub fn request(cmd: *const n.z_command, id: u64) u32 {
if (active()) return n.UHDK_STATUS_BUSY; if (active()) return n.UHDK_STATUS_BUSY;
if (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 w: *native.Window = @ptrCast(@alignCast(n.z_object_native(cmd.other) orelse return abi.UNAVAILABLE));
const input = Input.state(); const input = Input.state();
if (!w.visible or !w.configured or input.popup_window != w or input.popup_serial == 0 or runtime.now(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.?)); const root: *Resource = @ptrCast(@alignCast(cmd.target.?));
if (root.payload.menu.items.len == 0) return abi.CANCELLED; if (root.payload.menu.items.len == 0) return abi.CANCELLED;
s().window = w; popupState().window = w;
s().root = root; popupState().root = root;
s().serial = input.popup_serial; popupState().serial = input.popup_serial;
runtime.retain(root); runtime.retain(root);
const point: n.uhdk_point = .{ .x = std.math.clamp(cmd.point.x, 0, @as(f32, @floatFromInt(@max(0, w.width - 1)))), .y = std.math.clamp(cmd.point.y, 0, @as(f32, @floatFromInt(@max(0, w.height - 1)))) }; const point: n.uhdk_point = .{ .x = std.math.clamp(cmd.point.x, 0, @as(f32, @floatFromInt(@max(0, w.width - 1)))), .y = std.math.clamp(cmd.point.y, 0, @as(f32, @floatFromInt(@max(0, w.height - 1)))) };
const p = create(root, null, @intFromFloat(point.x), @intFromFloat(point.y), 1) catch { const p = create(root, null, @intFromFloat(point.x), @intFromFloat(point.y), 1) catch {
runtime.release(root); runtime.release(root);
s().* = .{}; popupState().* = .{};
return abi.OOM; return abi.OOM;
}; };
s().top = p; popupState().top = p;
s().request = id; popupState().request = id;
Input.beginPopup(); Input.beginPopup();
input.popup_serial = 0; // A root grab consumes its triggering action. input.popup_serial = 0; // A root grab consumes its triggering action.
return n.Z_DEFERRED; return n.Z_DEFERRED;
} }
fn create(menu: *Resource, parent: ?*Panel, x: i32, y: i32, anchor_height: i32) !*Panel { fn create(menu: *Resource, parent: ?*Panel, x: i32, y: i32, anchor_height: i32) !*Panel {
const p = try b().app.gpa.create(Panel); const p = try backend().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 }; 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); errdefer destroy(p);
for (menu.payload.menu.items) |item| { for (menu.payload.menu.items) |item| {
var buffer: [96]u8 = undefined; 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.height = @min(p.total, 480);
p.pending_width = p.width; p.pending_width = p.width;
p.pending_height = p.height; p.pending_height = p.height;
p.surface = c.wl_compositor_create_surface(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; 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; 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); defer c.xdg_positioner_destroy(pos);
c.xdg_positioner_set_size(pos, p.width, p.height); c.xdg_positioner_set_size(pos, p.width, p.height);
c.xdg_positioner_set_anchor_rect(pos, x, y, 1, @max(1, anchor_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_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_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); 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; 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); c.wl_surface_commit(p.surface);
return p; return p;
} }
@ -182,7 +182,7 @@ fn configure(raw: ?*anyopaque, _: ?*c.struct_xdg_popup, _: i32, _: i32, width: i
p.pending_width = width; p.pending_width = width;
p.pending_height = height; p.pending_height = height;
p.configured = false; 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 { fn configured(raw: ?*anyopaque, _: ?*c.struct_xdg_surface, serial: u32) callconv(.c) void {
const p = panel(raw); const p = panel(raw);
@ -202,7 +202,7 @@ fn done(raw: ?*anyopaque, _: ?*c.struct_xdg_popup) callconv(.c) void {
const p = panel(raw); const p = panel(raw);
if (p.parent) |parent| { if (p.parent) |parent| {
closeChildren(parent); closeChildren(parent);
s().hover_at = 0; popupState().hover_at = 0;
} else finish(abi.CANCELLED); } else finish(abi.CANCELLED);
} }
fn repositioned(_: ?*anyopaque, _: ?*c.struct_xdg_popup, _: u32) callconv(.c) void {} fn repositioned(_: ?*anyopaque, _: ?*c.struct_xdg_popup, _: u32) callconv(.c) void {}
@ -237,7 +237,7 @@ fn allocateBuffer(p: *Panel, buf: *Buffer) !void {
buf.mapping = mapping; buf.mapping = mapping;
buf.size = size; buf.size = size;
errdefer freeBuffer(buf); errdefer freeBuffer(buf);
const pool = c.wl_shm_create_pool(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); defer c.wl_shm_pool_destroy(pool);
buf.proxy = c.wl_shm_pool_create_buffer(pool, 0, p.width * p.scale, p.height * p.scale, p.width * p.scale * 4, c.WL_SHM_FORMAT_ARGB8888) orelse return error.OutOfMemory; buf.proxy = c.wl_shm_pool_create_buffer(pool, 0, p.width * p.scale, p.height * p.scale, p.width * p.scale * 4, c.WL_SHM_FORMAT_ARGB8888) orelse return error.OutOfMemory;
if (c.wl_buffer_add_listener(buf.proxy, &buffer_listener, p) != 0) return error.OutOfMemory; if (c.wl_buffer_add_listener(buf.proxy, &buffer_listener, p) != 0) return error.OutOfMemory;
@ -250,7 +250,7 @@ fn render(p: *Panel) !void {
if (buf.proxy == null) try allocateBuffer(p, buf); if (buf.proxy == null) try allocateBuffer(p, buf);
const words: [*]u32 = @ptrCast(@alignCast(buf.mapping.?)); const words: [*]u32 = @ptrCast(@alignCast(buf.mapping.?));
const canvas: Bitmap.Canvas = .{ .pixels = words[0 .. buf.size / 4], .width = p.width, .height = p.height, .scale = p.scale }; const canvas: Bitmap.Canvas = .{ .pixels = words[0 .. buf.size / 4], .width = p.width, .height = p.height, .scale = p.scale };
paint(canvas, p.menu.payload.menu.items, p.selected, p.scroll, 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.wl_surface_set_buffer_scale(p.surface, p.scale);
c.xdg_surface_set_window_geometry(p.xdg, 0, 0, p.width, p.height); c.xdg_surface_set_window_geometry(p.xdg, 0, 0, p.width, p.height);
c.wl_surface_attach(p.surface, buf.proxy, 0, 0); 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.selected = index;
p.pressed = null; p.pressed = null;
p.dirty = true; 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 { fn hit(p: *Panel, x: f32, y: f32) ?usize {
if (x < 3 or x >= @as(f32, @floatFromInt(p.width - 3)) or y < 4 or y >= @as(f32, @floatFromInt(p.height - 4))) return null; if (x < 3 or x >= @as(f32, @floatFromInt(p.width - 3)) or y < 4 or y >= @as(f32, @floatFromInt(p.height - 4))) return null;
@ -319,23 +319,23 @@ fn hit(p: *Panel, x: f32, y: f32) ?usize {
return null; return null;
} }
pub fn pointerEnter(surface: ?*c.struct_wl_surface, x: f32, y: f32, serial: u32) bool { pub fn pointerEnter(surface: ?*c.struct_wl_surface, x: f32, y: f32, serial: u32) bool {
s().pointer = lookup(surface); popupState().pointer = lookup(surface);
const p = s().pointer orelse return false; const p = popupState().pointer orelse return false;
const input = Input.state(); const input = Input.state();
if (input.cursor_device != null) c.wp_cursor_shape_device_v1_set_shape(input.cursor_device, serial, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT); if (input.cursor_device != null) c.wp_cursor_shape_device_v1_set_shape(input.cursor_device, serial, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT);
choose(p, hit(p, x, y)); choose(p, hit(p, x, y));
return true; return true;
} }
pub fn pointerLeave() void { pub fn pointerLeave() void {
s().pointer = null; popupState().pointer = null;
s().hover_at = 0; popupState().hover_at = 0;
} }
pub fn motion(x: f32, y: f32) void { 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 { pub fn button(code: u32, down: bool, serial: u32) void {
if (down) s().serial = serial; if (down) popupState().serial = serial;
const p = s().pointer orelse { const p = popupState().pointer orelse {
if (down) finish(abi.CANCELLED); if (down) finish(abi.CANCELLED);
return; 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); if (down) p.pressed = p.selected else if (p.pressed != null and p.pressed == p.selected) select(p);
} }
fn openChild(p: *Panel) void { fn openChild(p: *Panel) void {
s().hover_at = 0; popupState().hover_at = 0;
const index = p.selected orelse return; const index = p.selected orelse return;
const item = p.menu.payload.menu.items[index]; const item = p.menu.payload.menu.items[index];
if (!usable(item) or item.submenu == null) return; if (!usable(item) or item.submenu == null) return;
@ -355,7 +355,7 @@ fn openChild(p: *Panel) void {
finish(abi.OOM); finish(abi.OOM);
return; return;
}; };
s().top = child; popupState().top = child;
} }
fn select(p: *Panel) void { fn select(p: *Panel) void {
const index = p.selected orelse return; const index = p.selected orelse return;
@ -365,7 +365,7 @@ fn select(p: *Panel) void {
openChild(p); openChild(p);
return; return;
} }
Menu.activate(s().window.?, item, Input.id()); Menu.activate(popupState().window.?, item, Input.id());
finish(abi.OK); // Command event must precede request completion. finish(abi.OK); // Command event must precede request completion.
} }
fn reveal(p: *Panel) void { fn reveal(p: *Panel) void {
@ -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; index = if (forward) (index + 1) % items.len else (index + items.len - 1) % items.len;
if (usable(items[index])) { if (usable(items[index])) {
choose(p, index); choose(p, index);
s().hover_at = 0; popupState().hover_at = 0;
reveal(p); reveal(p);
return; return;
} }
@ -392,8 +392,8 @@ fn move(p: *Panel, forward: bool) void {
} }
pub fn key(logical: u32, down: bool, serial: u32) void { pub fn key(logical: u32, down: bool, serial: u32) void {
if (!down) return; if (!down) return;
const p = s().top orelse return; const p = popupState().top orelse return;
s().serial = serial; popupState().serial = serial;
switch (logical) { switch (logical) {
n.UHDK_KEY_ESCAPE => finish(abi.CANCELLED), n.UHDK_KEY_ESCAPE => finish(abi.CANCELLED),
n.UHDK_KEY_UP => move(p, false), 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 => { n.UHDK_KEY_RIGHT => {
openChild(p); 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| { n.UHDK_KEY_LEFT => if (p.parent) |parent| {
closeChildren(parent); closeChildren(parent);
s().hover_at = 0; popupState().hover_at = 0;
}, },
n.UHDK_KEY_ENTER, ' ' => select(p), n.UHDK_KEY_ENTER, ' ' => select(p),
else => {}, else => {},
} }
} }
pub fn scroll(delta: f32) void { pub fn scroll(delta: f32) void {
const p = s().pointer orelse return; const p = popupState().pointer orelse return;
closeChildren(p); 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.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.selected = null;
p.pressed = null; p.pressed = null;
p.dirty = true; p.dirty = true;
s().hover_at = 0; popupState().hover_at = 0;
} }
pub fn flags() void { pub fn flags() void {
var cursor = s().top; var cursor = popupState().top;
while (cursor) |p| : (cursor = p.parent) { while (cursor) |p| : (cursor = p.parent) {
p.dirty = true; p.dirty = true;
if (p.selected) |index| if (!usable(p.menu.payload.menu.items[index])) { if (p.selected) |index| if (!usable(p.menu.payload.menu.items[index])) {
@ -440,13 +440,13 @@ pub fn flags() void {
} }
pub fn tick() i32 { pub fn tick() i32 {
if (!active()) return -1; if (!active()) return -1;
const now = runtime.now(b().app.io); const now = runtime.now(backend().app.io);
if (s().hover_at != 0 and now >= s().hover_at) { if (popupState().hover_at != 0 and now >= popupState().hover_at) {
if (s().pointer) |p| openChild(p); if (popupState().pointer) |p| openChild(p);
s().hover_at = 0; popupState().hover_at = 0;
} }
var cursor = s().top; var cursor = popupState().top;
var timeout: i32 = if (s().hover_at != 0) 25 else -1; var timeout: i32 = if (popupState().hover_at != 0) 25 else -1;
while (cursor) |p| : (cursor = p.parent) { while (cursor) |p| : (cursor = p.parent) {
if (!p.configured) { if (!p.configured) {
if (now >= p.deadline) { if (now >= p.deadline) {

View File

@ -44,19 +44,19 @@ pub const State = struct {
exporter: ?*c.struct_zxdg_exporter_v2 = null, exporter: ?*c.struct_zxdg_exporter_v2 = null,
preferences: n.uhdk_preferences = .{ .struct_size = @sizeOf(n.uhdk_preferences), .appearance = n.UHDK_APPEARANCE_UNKNOWN, .reduced_motion = 0, .high_contrast = 0 }, preferences: n.uhdk_preferences = .{ .struct_size = @sizeOf(n.uhdk_preferences), .appearance = n.UHDK_APPEARANCE_UNKNOWN, .reduced_motion = 0, .high_contrast = 0 },
}; };
fn b() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
fn s() *State { fn portalState() *State {
return &b().portal; return &backend().portal;
} }
pub fn send(message: *Bus.Message) !u32 { pub fn send(message: *Bus.Message) !u32 {
var serial: u32 = 0; var serial: u32 = 0;
if (c.z_dbus_connection_send.?(s().connection, message, &serial) == 0) return error.OutOfMemory; if (c.z_dbus_connection_send.?(portalState().connection, message, &serial) == 0) return error.OutOfMemory;
return serial; return serial;
} }
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void { pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void {
if (std.mem.eql(u8, interface, "zxdg_exporter_v2")) 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 { pub fn initialize() void {
if (c.z_linux_dbus_available() == 0 or c.z_dbus_threads_init_default.?() == 0) return; if (c.z_linux_dbus_available() == 0 or c.z_dbus_threads_init_default.?() == 0) return;
@ -64,15 +64,15 @@ pub fn initialize() void {
// address; absence disables portals without affecting windows or input. // address; absence disables portals without affecting windows or input.
const address = c.getenv("DBUS_SESSION_BUS_ADDRESS"); const address = c.getenv("DBUS_SESSION_BUS_ADDRESS");
if (address == null or !std.mem.startsWith(u8, std.mem.span(address), "unix:")) return; 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; portalState().connection = c.z_dbus_connection_open_private.?(address, null) orelse return;
c.z_dbus_connection_set_exit_on_disconnect.?(s().connection, 0); c.z_dbus_connection_set_exit_on_disconnect.?(portalState().connection, 0);
s().startup_deadline = runtime.now(b().app.io) + 5 * std.time.ns_per_s; portalState().startup_deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s;
const message = Bus.method(dbus, dbus_path, dbus, "Hello") catch { const message = Bus.method(dbus, dbus_path, dbus, "Hello") catch {
disconnect(); disconnect();
return; return;
}; };
defer c.z_dbus_message_unref.?(message); defer c.z_dbus_message_unref.?(message);
s().hello = send(message) catch { portalState().hello = send(message) catch {
disconnect(); disconnect();
return; return;
}; };
@ -88,7 +88,7 @@ fn addMatches() !void {
defer c.z_dbus_message_unref.?(message); defer c.z_dbus_message_unref.?(message);
var args = Bus.append(message); var args = Bus.append(message);
try Bus.string(&args, rule); try Bus.string(&args, rule);
s().matches[i] = try send(message); portalState().matches[i] = try send(message);
} }
} }
fn discover() !void { fn discover() !void {
@ -97,7 +97,7 @@ fn discover() !void {
var args = Bus.append(version); var args = Bus.append(version);
try Bus.string(&args, chooser); try Bus.string(&args, chooser);
try Bus.string(&args, "version"); try Bus.string(&args, "version");
s().version_serial = try send(version); portalState().version_serial = try send(version);
const read = try Bus.method(desktop, path, settings, "ReadAll"); const read = try Bus.method(desktop, path, settings, "ReadAll");
defer c.z_dbus_message_unref.?(read); defer c.z_dbus_message_unref.?(read);
args = Bus.append(read); args = Bus.append(read);
@ -105,16 +105,16 @@ fn discover() !void {
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&args, &namespaces); errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&args, &namespaces);
try Bus.string(&namespaces, "org.freedesktop.appearance"); try Bus.string(&namespaces, "org.freedesktop.appearance");
try Bus.close(&args, &namespaces); try Bus.close(&args, &namespaces);
s().settings_serial = try send(read); portalState().settings_serial = try send(read);
} }
pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void { pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
const connection = s().connection orelse return; const connection = portalState().connection orelse return;
var fd: c_int = -1; var fd: c_int = -1;
if (c.z_dbus_connection_get_unix_fd.?(connection, &fd) != 0) if (c.z_dbus_connection_get_unix_fd.?(connection, &fd) != 0)
try fds.append(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 { 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) { if (c.z_dbus_connection_read_write.?(connection, 0) == 0) {
disconnect(); disconnect();
return -1; return -1;
@ -127,14 +127,14 @@ pub fn tick() i32 {
disconnect(); disconnect();
return -1; return -1;
}; };
if (s().connection == null) return -1; if (portalState().connection == null) return -1;
} else return 0; } else return 0;
const now = runtime.now(b().app.io); const now = runtime.now(backend().app.io);
if (!s().ready and now >= s().startup_deadline) { if (!portalState().ready and now >= portalState().startup_deadline) {
disconnect(); disconnect();
return -1; return -1;
} }
var cursor = s().pending; var cursor = portalState().pending;
while (cursor) |pending| { while (cursor) |pending| {
cursor = pending.next; cursor = pending.next;
if (pending.deadline != 0 and now >= pending.deadline) { if (pending.deadline != 0 and now >= pending.deadline) {
@ -143,54 +143,54 @@ pub fn tick() i32 {
destroy(pending); 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 { fn setOwner(message: *Bus.Message) !void {
const sender = c.z_dbus_message_get_sender.?(message); const sender = c.z_dbus_message_get_sender.?(message);
if (sender == null) return; if (sender == null) return;
if (s().owner) |old| b().app.gpa.free(old); if (portalState().owner) |old| backend().app.gpa.free(old);
s().owner = try b().app.gpa.dupeZ(u8, std.mem.span(sender)); portalState().owner = try backend().app.gpa.dupeZ(u8, std.mem.span(sender));
} }
fn process(message: *Bus.Message) !void { fn process(message: *Bus.Message) !void {
if (try KdeAppMenu.process(message)) return; if (try KdeAppMenu.process(message)) return;
const serial = c.z_dbus_message_get_reply_serial.?(message); const serial = c.z_dbus_message_get_reply_serial.?(message);
const failed = c.z_dbus_message_get_type.?(message) == c.DBUS_MESSAGE_TYPE_ERROR; const failed = c.z_dbus_message_get_type.?(message) == c.DBUS_MESSAGE_TYPE_ERROR;
var args = Bus.parse(message); var args = Bus.parse(message);
if (serial != 0 and serial == s().hello) { if (serial != 0 and serial == portalState().hello) {
s().hello = 0; portalState().hello = 0;
if (failed or c.z_dbus_message_has_signature.?(message, "s") == 0) { if (failed or c.z_dbus_message_has_signature.?(message, "s") == 0) {
disconnect(); disconnect();
return; 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(); try addMatches();
return; return;
} }
for (&s().matches) |*match| if (serial != 0 and serial == match.*) { for (&portalState().matches) |*match| if (serial != 0 and serial == match.*) {
if (failed) { if (failed) {
disconnect(); disconnect();
return; return;
} }
match.* = 0; match.* = 0;
if (std.mem.allEqual(u32, &s().matches, 0)) { if (std.mem.allEqual(u32, &portalState().matches, 0)) {
s().ready = true; portalState().ready = true;
KdeAppMenu.ready(); KdeAppMenu.ready();
try discover(); try discover();
} }
return; return;
}; };
if (serial != 0 and serial == s().version_serial) { if (serial != 0 and serial == portalState().version_serial) {
s().version_serial = 0; portalState().version_serial = 0;
if (!failed) { if (!failed) {
var value = Bus.variant(&args) orelse return; 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); 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; return;
} }
if (serial != 0 and serial == s().settings_serial) { if (serial != 0 and serial == portalState().settings_serial) {
s().settings_serial = 0; portalState().settings_serial = 0;
if (!failed and c.z_dbus_message_has_signature.?(message, "a{sa{sv}}") != 0) { if (!failed and c.z_dbus_message_has_signature.?(message, "a{sa{sv}}") != 0) {
try setOwner(message); try setOwner(message);
var appearance = Bus.entry(&args, "org.freedesktop.appearance") orelse return; var appearance = Bus.entry(&args, "org.freedesktop.appearance") orelse return;
@ -215,26 +215,26 @@ fn process(message: *Bus.Message) !void {
_ = Bus.next(&args); _ = Bus.next(&args);
const new = Bus.str(&args).?; const new = Bus.str(&args).?;
if (old.len != 0) { if (old.len != 0) {
while (s().pending) |p| { while (portalState().pending) |p| {
complete(p, abi.UNAVAILABLE, null); complete(p, abi.UNAVAILABLE, null);
destroy(p); destroy(p);
} }
s().chooser_version = 0; portalState().chooser_version = 0;
native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false); native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false);
if (s().owner) |owner| b().app.gpa.free(owner); if (portalState().owner) |owner| backend().app.gpa.free(owner);
s().owner = null; portalState().owner = null;
preference("color-scheme", 0); preference("color-scheme", 0);
preference("contrast", 0); preference("contrast", 0);
preference("reduced-motion", 0); preference("reduced-motion", 0);
} }
if (new.len != 0) { if (new.len != 0) {
if (s().owner) |owner| b().app.gpa.free(owner); if (portalState().owner) |owner| backend().app.gpa.free(owner);
s().owner = try b().app.gpa.dupeZ(u8, new); portalState().owner = try backend().app.gpa.dupeZ(u8, new);
try discover(); try discover();
} }
return; return;
} }
var cursor = s().pending; var cursor = portalState().pending;
while (cursor) |pending| : (cursor = pending.next) { while (cursor) |pending| : (cursor = pending.next) {
if (serial != 0 and serial == pending.serial) { if (serial != 0 and serial == pending.serial) {
pending.replied = true; pending.replied = true;
@ -248,8 +248,8 @@ fn process(message: *Bus.Message) !void {
destroy(pending); destroy(pending);
return; return;
} }
const handle = try b().app.gpa.dupeZ(u8, Bus.str(&args).?); const handle = try backend().app.gpa.dupeZ(u8, Bus.str(&args).?);
b().app.gpa.free(pending.handle); backend().app.gpa.free(pending.handle);
pending.handle = handle; pending.handle = handle;
if (pending.id == 0) { if (pending.id == 0) {
if (pending.cancelled) closeRequest(pending.handle); 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 // Match rules are installed on the bus, and sender validation also protects
// against unrelated unicast signals sent directly to our private connection. // against unrelated unicast signals sent directly to our private connection.
const sender = c.z_dbus_message_get_sender.?(message); const sender = c.z_dbus_message_get_sender.?(message);
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 (c.z_dbus_message_is_signal.?(message, settings, "SettingChanged") != 0 and c.z_dbus_message_has_signature.?(message, "ssv") != 0) {
if (!std.mem.eql(u8, Bus.str(&args).?, "org.freedesktop.appearance")) return; if (!std.mem.eql(u8, Bus.str(&args).?, "org.freedesktop.appearance")) return;
_ = Bus.next(&args); _ = Bus.next(&args);
@ -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) { } 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); const response_path = c.z_dbus_message_get_path.?(message);
if (response_path == null) return; 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))) { while (cursor) |pending| : (cursor = pending.next) if (std.mem.eql(u8, pending.handle, std.mem.span(response_path))) {
const code = Bus.uint(&args).?; const code = Bus.uint(&args).?;
_ = Bus.next(&args); _ = Bus.next(&args);
@ -290,34 +290,34 @@ fn errorStatus(message: *Bus.Message) u32 {
return n.UHDK_STATUS_OS_ERROR; return n.UHDK_STATUS_OS_ERROR;
} }
fn preference(key: []const u8, value: u32) void { fn preference(key: []const u8, value: u32) void {
const old = s().preferences; const old = portalState().preferences;
if (std.mem.eql(u8, key, "color-scheme")) s().preferences.appearance = switch (value) { if (std.mem.eql(u8, key, "color-scheme")) portalState().preferences.appearance = switch (value) {
1 => n.UHDK_APPEARANCE_DARK, 1 => n.UHDK_APPEARANCE_DARK,
2 => n.UHDK_APPEARANCE_LIGHT, 2 => n.UHDK_APPEARANCE_LIGHT,
else => n.UHDK_APPEARANCE_UNKNOWN, 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); } 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, s().preferences)) n.z_preferences(runtime.toAppHandle(b().app), &s().preferences); if (!std.meta.eql(old, portalState().preferences)) n.z_preferences(runtime.toAppHandle(backend().app), &portalState().preferences);
} }
pub fn request(cmd: *const n.z_command, id: u64) u32 { pub fn request(cmd: *const n.z_command, id: u64) u32 {
if (!s().ready or s().connection == null) return abi.UNAVAILABLE; if (!portalState().ready or portalState().connection == null) return abi.UNAVAILABLE;
if (cmd.op == n.Z_DIALOG and s().chooser_version < 3) return n.UHDK_STATUS_UNSUPPORTED; if (cmd.op == n.Z_DIALOG and portalState().chooser_version < 3) return n.UHDK_STATUS_UNSUPPORTED;
const p = allocate(cmd, id) catch return abi.OOM; const p = allocate(cmd, id) catch return abi.OOM;
p.next = s().pending; p.next = portalState().pending;
s().pending = p; portalState().pending = p;
if (cmd.op == n.Z_DIALOG and cmd.dialog.parent != null and s().exporter != null) { 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 { const w: *native.Window = @ptrCast(@alignCast(n.z_object_native(cmd.dialog.parent) orelse {
destroy(p); destroy(p);
return abi.UNAVAILABLE; 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); destroy(p);
return abi.OOM; return abi.OOM;
}; };
_ = c.zxdg_exported_v2_add_listener(p.exported, &export_listener, p); _ = c.zxdg_exported_v2_add_listener(p.exported, &export_listener, p);
} else if (cmd.op == n.Z_URL and b().desktop.activation != null and Input.state().key_focus != null and } else if (cmd.op == n.Z_URL and backend().desktop.activation != null and Input.state().key_focus != null and
Input.state().serial != 0 and runtime.now(b().app.io) -| Input.state().serial_time <= 5 * std.time.ns_per_s) Input.state().serial != 0 and runtime.now(backend().app.io) -| Input.state().serial_time <= 5 * std.time.ns_per_s)
{ {
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); destroy(p);
return abi.OOM; return abi.OOM;
}; };
@ -332,26 +332,26 @@ pub fn request(cmd: *const n.z_command, id: u64) u32 {
return n.Z_DEFERRED; return n.Z_DEFERRED;
} }
fn allocate(cmd: *const n.z_command, id: u64) !*Pending { fn allocate(cmd: *const n.z_command, id: u64) !*Pending {
const gpa = b().app.gpa; const gpa = backend().app.gpa;
const p = try gpa.create(Pending); const p = try gpa.create(Pending);
errdefer gpa.destroy(p); errdefer gpa.destroy(p);
const token = try std.fmt.allocPrintSentinel(gpa, "uhdk_{x}", .{id}, 0); const token = try std.fmt.allocPrintSentinel(gpa, "uhdk_{x}", .{id}, 0);
errdefer gpa.free(token); errdefer gpa.free(token);
const unique = s().unique.?; const unique = portalState().unique.?;
const name = try gpa.dupe(u8, unique[1..]); const name = try gpa.dupe(u8, unique[1..]);
defer gpa.free(name); defer gpa.free(name);
std.mem.replaceScalar(u8, 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; return p;
} }
fn exported(raw: ?*anyopaque, _: ?*c.struct_zxdg_exported_v2, handle: [*c]const u8) callconv(.c) void { fn exported(raw: ?*anyopaque, _: ?*c.struct_zxdg_exported_v2, handle: [*c]const u8) callconv(.c) void {
const p: *Pending = @ptrCast(@alignCast(raw.?)); const p: *Pending = @ptrCast(@alignCast(raw.?));
const parent = std.fmt.allocPrintSentinel(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); complete(p, abi.OOM, null);
destroy(p); destroy(p);
return; return;
}; };
defer b().app.gpa.free(parent); defer backend().app.gpa.free(parent);
submit(p, parent, null) catch { submit(p, parent, null) catch {
complete(p, abi.OOM, null); complete(p, abi.OOM, null);
destroy(p); 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 dialog = cmd.op == n.Z_DIALOG;
const message = try Bus.method(desktop, path, if (dialog) chooser else "org.freedesktop.portal.OpenURI", if (!dialog) "OpenURI" else if (cmd.dialog.kind == n.UHDK_DIALOG_SAVE_FILE) "SaveFile" else "OpenFile"); const message = try Bus.method(desktop, path, if (dialog) chooser else "org.freedesktop.portal.OpenURI", if (!dialog) "OpenURI" else if (cmd.dialog.kind == n.UHDK_DIALOG_SAVE_FILE) "SaveFile" else "OpenFile");
defer c.z_dbus_message_unref.?(message); defer c.z_dbus_message_unref.?(message);
var arena: std.heap.ArenaAllocator = .init(b().app.gpa); var arena: std.heap.ArenaAllocator = .init(backend().app.gpa);
defer arena.deinit(); defer arena.deinit();
const gpa = arena.allocator(); const gpa = arena.allocator();
var args = Bus.append(message); var args = Bus.append(message);
@ -455,23 +455,23 @@ fn responseFiles(p: *Pending, args: *Bus.Iter) void {
var files: std.ArrayList(?*n.uhdk_file) = .empty; var files: std.ArrayList(?*n.uhdk_file) = .empty;
defer { defer {
for (files.items) |file| n.uhdk_file_release(file); for (files.items) |file| n.uhdk_file_release(file);
files.deinit(b().app.gpa); files.deinit(backend().app.gpa);
} }
while (Bus.kind(&strings) != c.DBUS_TYPE_INVALID) { while (Bus.kind(&strings) != c.DBUS_TYPE_INVALID) {
const uri = Bus.str(&strings) orelse { const uri = Bus.str(&strings) orelse {
complete(p, n.UHDK_STATUS_OS_ERROR, null); complete(p, n.UHDK_STATUS_OS_ERROR, null);
return; return;
}; };
const bytes = Files.decode(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); complete(p, if (err == error.OutOfMemory) abi.OOM else n.UHDK_STATUS_UNSUPPORTED, null);
return; return;
}; };
defer b().app.gpa.free(bytes); defer backend().app.gpa.free(bytes);
const file = n.z_file_from_url(runtime.toAppHandle(b().app), .{ .ptr = bytes.ptr, .len = bytes.len }, null) orelse { const file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = bytes.ptr, .len = bytes.len }, null) orelse {
complete(p, abi.OOM, null); complete(p, abi.OOM, null);
return; return;
}; };
files.append(b().app.gpa, file) catch { files.append(backend().app.gpa, file) catch {
n.uhdk_file_release(file); n.uhdk_file_release(file);
complete(p, abi.OOM, null); complete(p, abi.OOM, null);
return; return;
@ -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); complete(p, if (files.items.len == 0) abi.CANCELLED else abi.OK, &result);
} }
fn complete(p: *Pending, status: u32, result: ?*n.z_request_result) void { fn complete(p: *Pending, status: u32, result: ?*n.z_request_result) void {
if (p.id != 0) n.z_complete(runtime.toAppHandle(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.id = 0;
p.command = null; p.command = null;
} }
fn closeRequest(handle: [*:0]const u8) void { 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; const message = Bus.method(desktop, handle, "org.freedesktop.portal.Request", "Close") catch return;
defer c.z_dbus_message_unref.?(message); defer c.z_dbus_message_unref.?(message);
c.z_dbus_message_set_no_reply.?(message, 1); c.z_dbus_message_set_no_reply.?(message, 1);
_ = send(message) catch {}; _ = send(message) catch {};
} }
pub fn cancel(id: u64) bool { pub fn cancel(id: u64) bool {
var cursor = s().pending; var cursor = portalState().pending;
while (cursor) |p| : (cursor = p.next) if (p.id == id) { while (cursor) |p| : (cursor = p.next) if (p.id == id) {
if (p.serial != 0) closeRequest(p.handle); if (p.serial != 0) closeRequest(p.handle);
p.cancelled = true; p.cancelled = true;
@ -506,34 +506,34 @@ pub fn cancel(id: u64) bool {
return false; return false;
} }
fn destroy(p: *Pending) void { fn destroy(p: *Pending) void {
var link = &s().pending; var link = &portalState().pending;
while (link.* != p) link = &link.*.?.next; while (link.* != p) link = &link.*.?.next;
link.* = p.next; link.* = p.next;
if (p.exported != null) c.zxdg_exported_v2_destroy(p.exported); if (p.exported != null) c.zxdg_exported_v2_destroy(p.exported);
if (p.activation != null) c.xdg_activation_token_v1_destroy(p.activation); if (p.activation != null) c.xdg_activation_token_v1_destroy(p.activation);
b().app.gpa.free(p.handle); backend().app.gpa.free(p.handle);
b().app.gpa.free(p.token); backend().app.gpa.free(p.token);
b().app.gpa.destroy(p); backend().app.gpa.destroy(p);
} }
fn disconnect() void { fn disconnect() void {
KdeAppMenu.disconnected(); KdeAppMenu.disconnected();
while (s().pending) |p| { while (portalState().pending) |p| {
complete(p, abi.UNAVAILABLE, null); complete(p, abi.UNAVAILABLE, null);
destroy(p); destroy(p);
} }
if (s().connection) |connection| { if (portalState().connection) |connection| {
c.z_dbus_connection_close.?(connection); c.z_dbus_connection_close.?(connection);
c.z_dbus_connection_unref.?(connection); c.z_dbus_connection_unref.?(connection);
} }
s().connection = null; portalState().connection = null;
s().ready = false; portalState().ready = false;
native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false); native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false);
} }
pub fn deinit() void { pub fn deinit() void {
var cursor = s().pending; var cursor = portalState().pending;
while (cursor) |p| : (cursor = p.next) closeRequest(p.handle); while (cursor) |p| : (cursor = p.next) closeRequest(p.handle);
disconnect(); disconnect();
if (s().unique) |unique| b().app.gpa.free(unique); if (portalState().unique) |unique| backend().app.gpa.free(unique);
if (s().owner) |owner| b().app.gpa.free(owner); if (portalState().owner) |owner| backend().app.gpa.free(owner);
if (s().exporter != null) c.zxdg_exporter_v2_destroy(s().exporter); if (portalState().exporter != null) c.zxdg_exporter_v2_destroy(portalState().exporter);
} }

View File

@ -14,16 +14,16 @@ pub const Watch = struct {
directory: []u8, directory: []u8,
name: []u8, name: []u8,
}; };
fn b() *native.Backend { fn backend() *native.Backend {
return native.instance.?; return native.instance.?;
} }
pub fn prepare(root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, out: *?*anyopaque) u32 { pub fn prepare(root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, out: *?*anyopaque) u32 {
const path = b().app.gpa.dupeZ(u8, abi.bytes(n.z_file_path(root))) catch return abi.OOM; const path = backend().app.gpa.dupeZ(u8, abi.bytes(n.z_file_path(root))) catch return abi.OOM;
defer b().app.gpa.free(path); defer backend().app.gpa.free(path);
const kind = c.z_linux_is_directory(path); const kind = c.z_linux_is_directory(path);
if (kind < 0 and c.z_linux_errno() != c.ENOENT) return n.UHDK_STATUS_OS_ERROR; if (kind < 0 and c.z_linux_errno() != c.ENOENT) return n.UHDK_STATUS_OS_ERROR;
const directory = b().app.gpa.dupeZ(u8, if (kind == 1) path else std.fs.path.dirname(path) orelse "/") catch return abi.OOM; const directory = backend().app.gpa.dupeZ(u8, if (kind == 1) path else std.fs.path.dirname(path) orelse "/") catch return abi.OOM;
defer b().app.gpa.free(directory); defer backend().app.gpa.free(directory);
const fd = c.inotify_init1(c.IN_NONBLOCK | c.IN_CLOEXEC); const fd = c.inotify_init1(c.IN_NONBLOCK | c.IN_CLOEXEC);
if (fd < 0) return n.UHDK_STATUS_OS_ERROR; if (fd < 0) return n.UHDK_STATUS_OS_ERROR;
const mask = c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_FROM | c.IN_MOVED_TO | c.IN_MODIFY | c.IN_ATTRIB | c.IN_DELETE_SELF | c.IN_MOVE_SELF | c.IN_ONLYDIR; const mask = c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_FROM | c.IN_MOVED_TO | c.IN_MODIFY | c.IN_ATTRIB | c.IN_DELETE_SELF | c.IN_MOVE_SELF | c.IN_ONLYDIR;
@ -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 { pub fn commit(handle: ?*n.uhdk_watch, prepared: *anyopaque) void {
const w: *Watch = @ptrCast(@alignCast(prepared)); const w: *Watch = @ptrCast(@alignCast(prepared));
w.next = b().watches; w.next = backend().watches;
b().watches = w; backend().watches = w;
n.z_object_set_native(handle, 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 { 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); const w = try gpa.create(Watch);
errdefer gpa.destroy(w); errdefer gpa.destroy(w);
const dir = try gpa.dupe(u8, directory); const dir = try gpa.dupe(u8, directory);
@ -55,8 +55,8 @@ fn allocate(fd: c_int, root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, directory: [
return w; return w;
} }
pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void { pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
var w = b().watches; var w = backend().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 }); while (w) |item| : (w = item.next) if (item.fd >= 0) try fds.append(backend().app.gpa, .{ .fd = item.fd, .events = c.POLLIN, .revents = 0 });
} }
pub fn flags(mask: u32) u32 { pub fn flags(mask: u32) u32 {
var value: u32 = 0; var value: u32 = 0;
@ -72,20 +72,20 @@ pub fn flags(mask: u32) u32 {
fn emit(w: *Watch, changes: u32, name: []const u8, status: u32) void { fn emit(w: *Watch, changes: u32, name: []const u8, status: u32) void {
var file = w.root; var file = w.root;
if (w.name.len == 0 and name.len != 0) { if (w.name.len == 0 and name.len != 0) {
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| { if (path) |p| {
defer b().app.gpa.free(p); defer backend().app.gpa.free(p);
file = n.z_file_from_url(runtime.toAppHandle(b().app), .{ .ptr = p.ptr, .len = p.len }, null); file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = p.ptr, .len = p.len }, null);
} else file = null; } else file = null;
} }
defer if (file != null and file != w.root) n.uhdk_file_release(file); defer if (file != null and file != w.root) n.uhdk_file_release(file);
var event = std.mem.zeroes(n.z_event); var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_WATCH; event.type = n.UHDK_EVENT_WATCH;
event.data.watch = .{ .watch = w.handle, .flags = changes, .status = status, .file = file }; event.data.watch = .{ .watch = w.handle, .flags = changes, .status = status, .file = file };
n.z_emit(runtime.toAppHandle(b().app), &event); n.z_emit(runtime.toAppHandle(backend().app), &event);
} }
pub fn tick() void { pub fn tick() void {
var cursor = b().watches; var cursor = backend().watches;
while (cursor) |w| : (cursor = w.next) { while (cursor) |w| : (cursor = w.next) {
if (w.fd < 0) continue; if (w.fd < 0) continue;
var buffer: [65536]u8 align(@alignOf(c.struct_inotify_event)) = undefined; var buffer: [65536]u8 align(@alignOf(c.struct_inotify_event)) = undefined;
@ -118,13 +118,13 @@ pub fn tick() void {
} }
} }
pub fn destroy(w: *Watch) void { pub fn destroy(w: *Watch) void {
var link = &b().watches; var link = &backend().watches;
while (link.* != w) link = &link.*.?.next; while (link.* != w) link = &link.*.?.next;
link.* = w.next; link.* = w.next;
if (w.fd >= 0) _ = c.close(w.fd); if (w.fd >= 0) _ = c.close(w.fd);
b().app.gpa.free(w.directory); backend().app.gpa.free(w.directory);
b().app.gpa.free(w.name); backend().app.gpa.free(w.name);
b().app.gpa.destroy(w); backend().app.gpa.destroy(w);
} }
test "watch replacement is remove/create, overflow and invalidation stay distinct" { test "watch replacement is remove/create, overflow and invalidation stay distinct" {
try std.testing.expectEqual(@as(u32, n.UHDK_CHANGE_CREATED | n.UHDK_CHANGE_RENAMED), flags(c.IN_MOVED_TO)); try std.testing.expectEqual(@as(u32, n.UHDK_CHANGE_CREATED | n.UHDK_CHANGE_RENAMED), flags(c.IN_MOVED_TO));

View File

@ -5,7 +5,6 @@
#include <poll.h> #include <poll.h>
#include <sys/eventfd.h> #include <sys/eventfd.h>
#include <sys/inotify.h> #include <sys/inotify.h>
#include <sys/syscall.h>
#include <unistd.h> #include <unistd.h>
#include <sys/mman.h> #include <sys/mman.h>
#include <stdlib.h> #include <stdlib.h>
@ -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_read(int, void *, size_t);
ssize_t z_linux_write(int, const void *, size_t); ssize_t z_linux_write(int, const void *, size_t);
ssize_t z_linux_pipe_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 #endif

View File

@ -6,7 +6,6 @@
#include <pthread.h> #include <pthread.h>
#include <fcntl.h> #include <fcntl.h>
#include <stdio.h> #include <stdio.h>
#include <sys/syscall.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <unistd.h> #include <unistd.h>
#include "wayland-client-core.h" #include "wayland-client-core.h"
@ -105,10 +104,6 @@ int z_linux_egl_available(void) {
int z_linux_errno(void) { int z_linux_errno(void) {
return errno; 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. */ /* Keep libc's optimization/fortify inline implementation on the C side. */
int z_linux_poll(struct pollfd *fds, nfds_t count, int timeout) { int z_linux_poll(struct pollfd *fds, nfds_t count, int timeout) {
return poll(fds, count, timeout); return poll(fds, count, timeout);

View File

@ -101,7 +101,9 @@ pub fn setCapability(cap: u32, available: bool) void {
} }
export fn z_native_is_main_thread() c_int { 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 { export fn z_native_start(handle: ?*n.uhdk_session, _: n.uhdk_text) u32 {
const app = runtime.fromAppHandle(handle); 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_TEXT_CANCEL => Text.cancel(w),
n.Z_FOCUS => return Desktop.focus(w, id), n.Z_FOCUS => return Desktop.focus(w, id),
n.Z_REDRAW => emit(w, n.UHDK_EVENT_WINDOW_REDRAW), 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, else => return n.UHDK_STATUS_UNSUPPORTED,
} }
return abi.OK; 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); if (w.request != 0) completeCreation(w, abi.CANCELLED) else destroyWindow(w);
}, },
n.Z_KIND_WATCH => Watch.destroy(@ptrCast(@alignCast(p))), 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 => {}, 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 }; out.* = .{ .struct_size = @sizeOf(n.uhdk_native_window), .backend = n.UHDK_BACKEND_WAYLAND, .primary = instance.?.display, .secondary = w.surface, .value = 0 };
} }
export fn z_native_gl(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 { export fn z_native_gl(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 {
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 { 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 { export fn z_native_file_init(file: ?*n.uhdk_file, path: n.uhdk_bytes, uri: n.uhdk_text, grant: ?*anyopaque) u32 {
return @import("Files.zig").init(file, path, uri, grant); return @import("Files.zig").init(file, path, uri, grant);

View File

@ -1427,7 +1427,7 @@ void z_native_destroy(uint32_t kind, void *native) {
if (!native) if (!native)
return; return;
@autoreleasepool { @autoreleasepool {
id value = CFBridgingRelease(native); id value = kind == Z_KIND_GL ? (__bridge id)native : CFBridgingRelease(native);
if (kind == Z_KIND_WINDOW) { if (kind == Z_KIND_WINDOW) {
ZWindow *w = value; ZWindow *w = value;
if (w.menu) { if (w.menu) {
@ -1441,11 +1441,14 @@ void z_native_destroy(uint32_t kind, void *native) {
[host.windows removeObject:w]; [host.windows removeObject:w];
[host refreshMenus]; [host refreshMenus];
} else if (kind == Z_KIND_GL) { } else if (kind == Z_KIND_GL) {
ZGL *gl = value; ZWindow *w = value;
ZGL *gl = w.gl;
if (!gl)
return;
CGLLockContext(gl.context.CGLContextObj); CGLLockContext(gl.context.CGLContextObj);
[gl.context clearDrawable]; [gl.context clearDrawable];
CGLUnlockContext(gl.context.CGLContextObj); 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)) !(profile & GL_CONTEXT_CORE_PROFILE_BIT))
return UHDK_STATUS_UNSUPPORTED; return UHDK_STATUS_UNSUPPORTED;
w.gl = gl; w.gl = gl;
z_object_set_native(cmd->other, (__bridge_retained void *)gl);
[w metrics]; [w metrics];
break; break;
} }
@ -1798,11 +1800,12 @@ uhdk_status z_native_execute(
} }
uhdk_status z_native_gl(void *native, uint32_t op, void *out) { uhdk_status z_native_gl(void *native, uint32_t op, void *out) {
@autoreleasepool { @autoreleasepool {
ZGL *gl = (__bridge ZGL *)native;
if (op == 4) { if (op == 4) {
[NSOpenGLContext clearCurrentContext]; [NSOpenGLContext clearCurrentContext];
return UHDK_STATUS_OK; return UHDK_STATUS_OK;
} }
ZWindow *w = (__bridge ZWindow *)native;
ZGL *gl = w.gl;
if (!gl) if (!gl)
return UHDK_STATUS_UNAVAILABLE; return UHDK_STATUS_UNAVAILABLE;
if (op == 1) { 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) { 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) if (NSOpenGLContext.currentContext != gl.context)
return UHDK_STATUS_UNAVAILABLE; return UHDK_STATUS_UNAVAILABLE;
char symbol[256]; char symbol[256];

View File

@ -7,7 +7,6 @@
#include "uhdk.h" #include "uhdk.h"
#include <stddef.h> #include <stddef.h>
#include "edit_keys.h" #include "edit_keys.h"
typedef struct z_gl_context z_gl_context;
enum { enum {
Z_WINDOW_OPENGL = 1u << 3 Z_WINDOW_OPENGL = 1u << 3
}; };
@ -101,6 +100,7 @@ enum {
}; };
enum { enum {
Z_KIND_WINDOW = 1, Z_KIND_WINDOW = 1,
/* Native-only discriminator for destroying a window's GL state. */
Z_KIND_GL, Z_KIND_GL,
Z_KIND_FILE, Z_KIND_FILE,
Z_KIND_MENU, Z_KIND_MENU,

View File

@ -33,15 +33,16 @@ pub fn threadCpuTime(io: std.Io) u64 {
return @intCast(@max(0, std.Io.Timestamp.now(io, .cpu_thread).nanoseconds)); 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(); application.lock();
defer application.unlock(); defer application.unlock();
return if (application.running and std.Thread.getCurrentId() == application.main_thread) abi.OK else c.UHDK_STATUS_WRONG_THREAD; return if (application.running and std.Thread.getCurrentId() == application.main_thread) abi.OK else c.UHDK_STATUS_WRONG_THREAD;
} }
pub fn checkObject(object: *Resource, kind: u32) abi.Status { pub fn validateMainThreadObjectReady(object: *Resource, kind: u32) abi.Status {
if (checkThread(object.app) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD; const status = validateMainThreadSessionReady(object.app);
return if (object.kind() == kind and object.alive) abi.OK else abi.UNAVAILABLE; 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 { 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| { c.Z_WINDOW => if (command.data.target) |target| {
fromObjectHandle(target).alive = false; fromObjectHandle(target).alive = false;
}, },
c.Z_GL => if (command.data.other) |other| { c.Z_GL => if (command.data.target) |target| {
const object = fromObjectHandle(other); fromObjectHandle(target).payload.window.gl_requested = false;
object.alive = false;
if (object.payload.gl.owner) |window| {
if (window.payload.window.context == object) window.payload.window.context = null;
}
}, },
c.Z_WATCH => if (command.data.other) |other| { c.Z_WATCH => if (command.data.other) |other| {
const object = fromObjectHandle(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 { 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; const status: abi.Status = if (command.completion == .request and tag == 0) abi.INVALID else c.UHDK_STATUS_WRONG_THREAD;
abandon(command); abandon(command);
return status; return status;
@ -300,16 +297,18 @@ pub fn finish(
abandon(command); abandon(command);
return; return;
} }
if (status == abi.OK) switch (command.data.op) { if (status == abi.OK and command.data.op == c.Z_WINDOW)
c.Z_WINDOW => fromObjectHandle(command.data.target).ready = true, fromObjectHandle(command.data.target).ready = true;
c.Z_GL => fromObjectHandle(command.data.other).ready = true, if (command.data.op == c.Z_GL) {
else => {}, 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 = 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) { if (command.completion == .resource) {
const object = fromObjectHandle(if (command.data.op == c.Z_WINDOW) command.data.target else command.data.other); if (command.data.op == c.Z_WINDOW)
object.creation_status = status; fromObjectHandle(command.data.target).creation_status = status;
} }
if (status != abi.OK) discardCreation(command); if (status != abi.OK) discardCreation(command);
const node = command.node; const node = command.node;
@ -353,7 +352,7 @@ pub fn hasFrame(application: *Application) bool {
defer application.unlock(); defer application.unlock();
var cursor = application.objects; var cursor = application.objects;
while (cursor) |object| : (cursor = object.next) { while (cursor) |object| : (cursor = object.next) {
if (object.payload == .gl and object.payload.gl.bracket) return true; if (object.payload == .window and object.payload.window.bracket) return true;
} }
return false; 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 { pub fn createObjectCommand(handle: anytype, kind: u32, op: u32) !*Request {
if (handle == null) return error.Invalid; if (handle == null) return error.Invalid;
const object = fromObjectHandle(handle); const object = fromObjectHandle(handle);
if (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.kind() != kind) return error.Invalid;
if (!object.alive) return error.Unavailable; if (!object.alive) return error.Unavailable;
return createCommand(object.app, op, object); 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 { pub fn createAppCommand(handle: ?*c.uhdk_session, op: u32) !*Request {
if (handle == null) return error.Invalid; 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); return createCommand(fromAppHandle(handle), op, null);
} }
@ -455,16 +454,14 @@ pub fn applicationError(err: anyerror) abi.Status {
pub fn destroyObject(object: *Resource) void { pub fn destroyObject(object: *Resource) void {
if (!object.alive) return; if (!object.alive) return;
std.debug.assert(checkThread(object.app) == abi.OK); std.debug.assert(validateMainThreadSessionReady(object.app) == abi.OK);
if (object.payload == .gl) { if (object.payload == .window and object.payload.window.gl_ready and object.payload.window.gl_status == abi.OK) {
std.debug.assert(!object.payload.gl.bracket); std.debug.assert(!object.payload.window.bracket);
if ((@import("builtin").os.tag == .windows or @import("builtin").os.tag == .linux) and object.native != null) 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_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. // Find one child under the registry lock, then recurse without the lock.
// Files can be released concurrently by the other thread. // Files can be released concurrently by the other thread.
while (true) { while (true) {
@ -492,13 +489,14 @@ pub fn destroyObject(object: *Resource) void {
notifyCommand(object, c.Z_DESTROY); 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; if (handle == null) return abi.INVALID;
const object = fromObjectHandle(handle); 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 (status != abi.OK) return status;
if (object.native == null) return abi.UNAVAILABLE; 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); return c.z_native_gl(object.native, op, out);
} }

View File

@ -66,6 +66,7 @@ struct Window {
uhdk_point pointer; uhdk_point pointer;
HCURSOR cursor; HCURSOR cursor;
HMENU menu; HMENU menu;
Graphics *graphics;
uhdk_menu *menu_source; uhdk_menu *menu_source;
WINDOWPLACEMENT placement; WINDOWPLACEMENT placement;
LONG_PTR saved_style; LONG_PTR saved_style;
@ -857,7 +858,7 @@ static PROC glProc(const char *name) {
p = GetProcAddress(GetModuleHandleW(L"opengl32.dll"), name); p = GetProcAddress(GetModuleHandleW(L"opengl32.dll"), name);
return p; return p;
} }
static uhdk_status createGraphics(Window *w, void *handle) { static uhdk_status createGraphics(Window *w) {
if (!(w->flags & Z_WINDOW_OPENGL)) if (!(w->flags & Z_WINDOW_OPENGL))
return UHDK_STATUS_INVALID_ARGUMENT; return UHDK_STATUS_INVALID_ARGUMENT;
Graphics *g = profileCalloc(1, sizeof(*g)); Graphics *g = profileCalloc(1, sizeof(*g));
@ -923,7 +924,7 @@ static uhdk_status createGraphics(Window *w, void *handle) {
g->major = (uint32_t)major; g->major = (uint32_t)major;
g->minor = (uint32_t)minor; g->minor = (uint32_t)minor;
InitializeCriticalSection(&g->lock); InitializeCriticalSection(&g->lock);
z_object_set_native(handle, g); w->graphics = g;
return UHDK_STATUS_OK; return UHDK_STATUS_OK;
failed: failed:
if (g->rc) if (g->rc)
@ -933,9 +934,10 @@ failed:
return UHDK_STATUS_UNSUPPORTED; return UHDK_STATUS_UNSUPPORTED;
} }
uhdk_status z_native_gl(void *native, uint32_t op, void *out) { uhdk_status z_native_gl(void *native, uint32_t op, void *out) {
Graphics *g = native;
if (op == 4) if (op == 4)
return wglMakeCurrent(NULL, NULL) ? UHDK_STATUS_OK : UHDK_STATUS_OS_ERROR; return wglMakeCurrent(NULL, NULL) ? UHDK_STATUS_OK : UHDK_STATUS_OS_ERROR;
Window *w = native;
Graphics *g = w ? w->graphics : NULL;
if (!g) if (!g)
return UHDK_STATUS_UNAVAILABLE; return UHDK_STATUS_UNAVAILABLE;
if (op == 8) if (op == 8)
@ -967,7 +969,8 @@ uhdk_status z_native_gl(void *native, uint32_t op, void *out) {
return UHDK_STATUS_INVALID_ARGUMENT; return UHDK_STATUS_INVALID_ARGUMENT;
} }
uhdk_status z_native_gl_proc(void *native, uhdk_text name, uhdk_gl_proc *out) { 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) if (!g || wglGetCurrentContext() != g->rc)
return UHDK_STATUS_UNAVAILABLE; return UHDK_STATUS_UNAVAILABLE;
if (name.len > 255) if (name.len > 255)
@ -1504,13 +1507,17 @@ void z_native_destroy(uint32_t kind, void *native) {
if (!native) if (!native)
return; return;
if (kind == Z_KIND_GL) { if (kind == Z_KIND_GL) {
Graphics *g = native; Window *w = native;
Graphics *g = w->graphics;
if (!g)
return;
EnterCriticalSection(&g->lock); EnterCriticalSection(&g->lock);
wglDeleteContext(g->rc); wglDeleteContext(g->rc);
ReleaseDC(g->window, g->dc); ReleaseDC(g->window, g->dc);
LeaveCriticalSection(&g->lock); LeaveCriticalSection(&g->lock);
DeleteCriticalSection(&g->lock); DeleteCriticalSection(&g->lock);
profileFree(g); profileFree(g);
w->graphics = NULL;
} else if (kind == Z_KIND_WINDOW) { } else if (kind == Z_KIND_WINDOW) {
Window *w = native; Window *w = native;
Window **link = &host.windows; Window **link = &host.windows;
@ -1658,6 +1665,7 @@ static uhdk_status setIcon(const uhdk_image *image) {
host.icon = icon; host.icon = icon;
return UHDK_STATUS_OK; return UHDK_STATUS_OK;
} }
uhdk_status z_native_execute( uhdk_status z_native_execute(
uhdk_session *app, uhdk_session *app,
const z_command *cmd, const z_command *cmd,
@ -1851,7 +1859,7 @@ uhdk_status z_native_execute(
metrics(w); metrics(w);
break; break;
case Z_GL: { case Z_GL: {
uhdk_status status = createGraphics(w, cmd->other); uhdk_status status = createGraphics(w);
return status; return status;
} }
case Z_CURSOR: { case Z_CURSOR: {