diff --git a/README.md b/README.md
index f761a80..3834d2b 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
# Uhdk
A small desktop platform library written in Zig 0.16.0 with a C99 ABI.
-It provides windows, input and IME, clipboard, file dialogs, drag and drop, menus,
+It provides windows, input and IME, clipboard, file dialogs, drag and drop, menus, tray icons,
async file operations, file watching, and OpenGL context creation. The macOS
backend uses AppKit, OpenGL, and FSEvents through a private Objective-C bridge.
File dialog filters accept suffixes without a leading dot, including compound
@@ -36,6 +36,36 @@ and handles presentation at the frame boundary. All services accept that same
session handle. Additional native windows can be created synchronously between
iterations for external rendering; they do not have independent UHDK GL contexts.
+## Tray icons
+
+Create a session-owned `uhdk_tray` with `uhdk_tray_create`, replace its complete
+description with `uhdk_tray_update`, and remove it with `uhdk_tray_destroy`.
+Create/update belong between frames. The descriptor copies UTF-8 text and a
+1–512 pixel RGBA8 image, and retains its optional `uhdk_menu`. Keep its nonempty
+`id` stable across updates and unique within the session. Set `hidden` to remove
+it temporarily, `menu_on_primary` to open its menu on primary activation, or
+`template_image` for a macOS template icon. Other backends ignore that hint.
+
+`UHDK_EVENT_TRAY_ACTIVATE` carries the tray and primary/secondary action.
+Menu commands carry their origin in `uhdk_menu_event.tray`, with a NULL window;
+ordinary window menu commands have a NULL tray. Tray menus support ordinary
+commands, submenus, separators, enabled/checked flags and the QUIT role. Other
+window-dependent roles are rejected. Menu shortcuts are not global shortcuts.
+
+Query `uhdk_tray_get_state` and handle `UHDK_EVENT_TRAY_STATE`. `available` means
+registered with the host, not guaranteed onscreen: the desktop may hide icons.
+`UHDK_CAP_TRAY` reports mechanism/host availability. On Linux, discovery is
+asynchronous; creation can succeed before a StatusNotifier host exists, then
+register automatically when one appears. Keep processing frames while windows
+are hidden. The session still opens with a visible primary window, which the
+application may hide once it has an available tray item.
+
+Backends use AppKit `NSStatusItem`, Win32 `Shell_NotifyIconW` (including Explorer
+restart recovery), and Linux StatusNotifierItem plus D-BusMenu. Linux needs a
+session bus and a compatible tray host; no GTK or Qt dependency is added.
+Session close removes all items. Destroy invalidates the handle immediately and
+suppresses queued tray events; native removal occurs at the next frame or close.
+
## Experimental desktop input and window observations
macOS uses AppKit editing selectors. Windows and Wayland share Ctrl-based defaults
diff --git a/include/uhdk.h b/include/uhdk.h
index 49b7b79..6858836 100644
--- a/include/uhdk.h
+++ b/include/uhdk.h
@@ -186,6 +186,8 @@ typedef struct uhdk_watch uhdk_watch;
* attached menus are retained by UHDK. Release owned references and do not use
* them after session close. */
typedef struct uhdk_menu uhdk_menu;
+/* Session-owned status/tray item. Destroy explicitly or close the session. */
+typedef struct uhdk_tray uhdk_tray;
/* Generally all asynchronous interfaces in uhdk will ask you to pass in a caller
* defined tag. This will associate the transaction with the tag for the life time
* of the interaction, callbacks, cancellations, state polling shall all have this
@@ -273,7 +275,8 @@ enum {
UHDK_CAP_APP_ICON = 8,
UHDK_CAP_POINTER_CAPTURE = 12,
UHDK_CAP_TEXT_INPUT = 16,
- UHDK_CAP_OPENGL = 18
+ UHDK_CAP_OPENGL = 18,
+ UHDK_CAP_TRAY = 19
};
typedef struct uhdk_event uhdk_event;
@@ -893,6 +896,58 @@ UHDK_API uhdk_status UHDK_CALL uhdk_menu_popup_async(
);
UHDK_API uhdk_status UHDK_CALL uhdk_set_icon(uhdk_session *session, const uhdk_image *image);
+/* Tray configuration is a complete copied snapshot; menu is retained. All calls
+ * belong to OS main. Create/update run between frames (BUSY inside a frame).
+ * id is a nonempty application-defined identity, stable across updates/sessions
+ * and unique among this session's live items (at most 255 UTF-8 bytes).
+ * title/tooltip are plain UTF-8, at most 4096 bytes each; native display limits
+ * may truncate tooltips (Windows: 127 UTF-16 code units).
+ * icon is required, at most 512 x 512 RGBA8; backends scale it for their UI.
+ * template_image requests native monochrome rendering where supported (macOS).
+ * menu_on_primary opens the attached menu on primary activation where supported;
+ * otherwise primary activation emits TRAY_ACTIVATE. Secondary/context gestures
+ * follow desktop conventions. A menu is required when menu_on_primary is true.
+ * Tray menus support ordinary commands and QUIT; other roles are rejected.
+ * Their shortcuts are labels, not global keyboard bindings.
+ */
+typedef struct uhdk_tray_desc {
+ uint32_t struct_size;
+ uhdk_bool hidden;
+ uhdk_bool menu_on_primary;
+ uhdk_bool template_image;
+ uint8_t reserved;
+ uhdk_text id;
+ uhdk_text title;
+ uhdk_text tooltip;
+ uhdk_image icon;
+ uhdk_menu *menu;
+} uhdk_tray_desc;
+
+/* available means registered with a usable desktop host, not guaranteed visible
+ * on screen. Hidden items report false/OK. Pending or absent hosts report
+ * false/UNAVAILABLE. Linux registration is asynchronous and recovers after
+ * watcher/host restart; a session-bus disconnect requires reopening the session.
+ * Creation may succeed before a host exists; inspect state and TRAY_STATE events.
+ */
+typedef struct uhdk_tray_state {
+ uint32_t struct_size;
+ uhdk_status status;
+ uhdk_bool available;
+} uhdk_tray_state;
+
+UHDK_API uhdk_status UHDK_CALL uhdk_tray_create(
+ uhdk_session *session,
+ const uhdk_tray_desc *desc,
+ uhdk_tray **out
+);
+/* id cannot change. Validation/allocation failures preserve the old snapshot.
+ * Host failures are reported through state; accepted desired state is retained. */
+UHDK_API uhdk_status UHDK_CALL uhdk_tray_update(uhdk_tray *tray, const uhdk_tray_desc *desc);
+/* NULL safe. Invalidates the handle and suppresses queued tray events; native
+ * removal occurs at the next dispatch boundary. Does not close any windows. */
+UHDK_API uhdk_status UHDK_CALL uhdk_tray_destroy(uhdk_tray *tray);
+UHDK_API uhdk_status UHDK_CALL uhdk_tray_get_state(uhdk_tray *tray, uhdk_tray_state *out);
+
/* Successful shell completion means handed off to the OS, not that a target
* application finished loading. URLs are not shell command strings. */
UHDK_API uhdk_status UHDK_CALL uhdk_shell_open_url_async(
@@ -995,7 +1050,11 @@ enum {
/* An accepted asynchronous request reached its terminal result. */
UHDK_EVENT_REQUEST_DONE,
/* The input interaction identified by cycle_id reached its terminal state. */
- UHDK_EVENT_CYCLE_END
+ UHDK_EVENT_CYCLE_END,
+ /* The desktop requested primary or secondary activation of a tray item. */
+ UHDK_EVENT_TRAY_ACTIVATE,
+ /* Tray host availability or registration status changed. */
+ UHDK_EVENT_TRAY_STATE
};
typedef uint32_t uhdk_request_kind;
@@ -1144,8 +1203,23 @@ typedef struct uhdk_drop_files_event {
typedef struct uhdk_menu_event {
uint64_t command_id;
+ uhdk_tray *tray; /* NULL for application/window/context menus. */
} uhdk_menu_event;
+typedef uint32_t uhdk_tray_activation;
+enum {
+ UHDK_TRAY_ACTIVATE_PRIMARY = 0,
+ UHDK_TRAY_ACTIVATE_SECONDARY = 1
+};
+typedef struct uhdk_tray_event {
+ uhdk_tray *tray;
+ uhdk_tray_activation activation;
+} uhdk_tray_event;
+typedef struct uhdk_tray_state_event {
+ uhdk_tray *tray;
+ uhdk_tray_state state;
+} uhdk_tray_state_event;
+
typedef struct uhdk_watch_event {
uhdk_watch *watch;
uhdk_change_flags flags;
@@ -1259,7 +1333,7 @@ struct uhdk_event {
* Boundaries: no widget/layout engine, text rasterizer, high-level renderer,
* networking, process spawning, global input hooks, or streaming filesystem API.
* Deferred: generic clipboard data, outgoing drag/drop, custom cursors, relative
- * pointer input, transparent windows, display enumeration/positioning, tray items,
+ * pointer input, transparent windows, display enumeration/positioning,
* badges/progress/attention, recursive watching, accent colors, accessibility
* semantic trees, notifications, persistent access bookmarks and streaming data.
*/
diff --git a/src/EventPayload.zig b/src/EventPayload.zig
index 20732e3..d8375b9 100644
--- a/src/EventPayload.zig
+++ b/src/EventPayload.zig
@@ -33,8 +33,7 @@ fn result(allocator: std.mem.Allocator, source: c.z_request_result) !c.uhdk_requ
.tag = source.tag,
.kind = source.kind,
.status = source.status,
- .diagnostic = if (source.status != abi.OK
- and source.diagnostic.len == 0)
+ .diagnostic = if (source.status != abi.OK and source.diagnostic.len == 0)
abi.statusMessage(source.status)
else
try abi.copyText(allocator, source.diagnostic),
@@ -69,6 +68,8 @@ pub fn pack(allocator: std.mem.Allocator, source: c.z_event) !c.uhdk_event {
break :data try store(c.uhdk_drop_files_event, allocator, drop);
},
c.UHDK_EVENT_MENU_COMMAND => try store(c.uhdk_menu_event, allocator, source.data.menu),
+ c.UHDK_EVENT_TRAY_ACTIVATE => try store(c.uhdk_tray_event, allocator, source.data.tray),
+ c.UHDK_EVENT_TRAY_STATE => try store(c.uhdk_tray_state_event, allocator, source.data.tray_state),
c.UHDK_EVENT_WATCH => try store(c.uhdk_watch_event, allocator, source.data.watch),
c.UHDK_EVENT_CYCLE_END => try store(c.uhdk_cycle_end_event, allocator, source.data.cycle_end),
c.UHDK_EVENT_REQUEST_DONE => try store(c.uhdk_request_result, allocator, try result(allocator, source.data.request)),
diff --git a/src/Resource.zig b/src/Resource.zig
index 07cf6ce..ca0ccdc 100644
--- a/src/Resource.zig
+++ b/src/Resource.zig
@@ -21,6 +21,7 @@ pub const Kind = enum(u32) {
file = c.Z_KIND_FILE,
menu = c.Z_KIND_MENU,
watch = c.Z_KIND_WATCH,
+ tray = c.Z_KIND_TRAY,
};
pub const Payload = union(Kind) {
@@ -28,6 +29,7 @@ pub const Payload = union(Kind) {
file: File,
menu: Menu,
watch: Watch,
+ tray: Tray,
};
pub const Window = struct {
@@ -59,6 +61,20 @@ pub const Watch = struct {
owner: ?*Resource = null,
};
+pub const TraySnapshot = struct {
+ arena: std.heap.ArenaAllocator,
+ desc: c.uhdk_tray_desc,
+};
+
+pub const Tray = struct {
+ snapshot: ?*TraySnapshot = null,
+ state: c.uhdk_tray_state = .{
+ .struct_size = @sizeOf(c.uhdk_tray_state),
+ .status = c.UHDK_STATUS_UNAVAILABLE,
+ .available = 0,
+ },
+};
+
pub fn init(application: *Application, resource_kind: Kind) Resource {
return .{
.app = application,
@@ -70,6 +86,7 @@ pub fn init(application: *Application, resource_kind: Kind) Resource {
.file => .{ .file = .{} },
.menu => .{ .menu = .{} },
.watch => .{ .watch = .{} },
+ .tray => .{ .tray = .{} },
},
};
}
diff --git a/src/api/app.zig b/src/api/app.zig
index 2319654..526835f 100644
--- a/src/api/app.zig
+++ b/src/api/app.zig
@@ -92,6 +92,12 @@ fn shutdown(application: *Application) void {
// Native sources stop before any of their Zig records can be released.
var cursor = application.objects;
while (cursor) |object| : (cursor = object.next) {
+ if (object.payload == .tray) {
+ object.alive = false;
+ if (object.native) |native| c.z_native_destroy(c.Z_KIND_TRAY, native);
+ object.native = null;
+ @import("tray.zig").clear(object);
+ }
if (object.kind() == c.Z_KIND_WATCH and object.native != null) {
c.z_native_destroy(object.kind(), object.native);
object.native = null;
@@ -198,6 +204,13 @@ pub fn poll(
const event = node.event;
if (event.window != null and !runtime.fromObjectHandle(event.window).alive) continue;
if (event.type == c.UHDK_EVENT_WATCH and !runtime.fromObjectHandle(event.data.watch.watch).alive) continue;
+ const tray = switch (event.type) {
+ c.UHDK_EVENT_TRAY_ACTIVATE => event.data.tray.tray,
+ c.UHDK_EVENT_TRAY_STATE => event.data.tray_state.tray,
+ c.UHDK_EVENT_MENU_COMMAND => event.data.menu.tray,
+ else => null,
+ };
+ if (tray != null and !runtime.fromObjectHandle(tray).alive) continue;
events[len] = @import("../EventPayload.zig").pack(allocator, event) catch return abi.OOM;
len += 1;
@@ -270,7 +283,7 @@ pub export fn uhdk_get_backend(handle: ?*c.uhdk_session) c.uhdk_backend {
pub export fn uhdk_has_capability(handle: ?*c.uhdk_session, cap: c.uhdk_capability) c.uhdk_bool {
if (@import("builtin").os.tag == .linux) return @import("../linux/native.zig").capability(handle, cap);
return switch (cap) {
- c.UHDK_CAP_FILE_DIALOGS, c.UHDK_CAP_CLIPBOARD, c.UHDK_CAP_DROP_FILES, c.UHDK_CAP_APP_MENU, c.UHDK_CAP_CONTEXT_MENU, c.UHDK_CAP_APP_ICON, c.UHDK_CAP_POINTER_CAPTURE, c.UHDK_CAP_TEXT_INPUT, c.UHDK_CAP_OPENGL => 1,
+ c.UHDK_CAP_FILE_DIALOGS, c.UHDK_CAP_CLIPBOARD, c.UHDK_CAP_DROP_FILES, c.UHDK_CAP_APP_MENU, c.UHDK_CAP_CONTEXT_MENU, c.UHDK_CAP_APP_ICON, c.UHDK_CAP_POINTER_CAPTURE, c.UHDK_CAP_TEXT_INPUT, c.UHDK_CAP_OPENGL, c.UHDK_CAP_TRAY => 1,
else => 0,
};
}
diff --git a/src/api/tray.zig b/src/api/tray.zig
new file mode 100644
index 0000000..b1dcdd2
--- /dev/null
+++ b/src/api/tray.zig
@@ -0,0 +1,142 @@
+//! Session-owned tray snapshots. Native hosts never borrow application storage.
+const std = @import("std");
+const c = @import("native");
+const abi = @import("../abi.zig");
+const runtime = @import("../runtime.zig");
+const Resource = @import("../Resource.zig");
+const session = @import("session.zig");
+
+fn validMenu(menu: *Resource) bool {
+ if (menu.payload != .menu or !menu.alive) return false;
+ for (menu.payload.menu.items) |item| {
+ if (item.role != c.UHDK_MENU_ROLE_NONE and item.role != c.UHDK_MENU_ROLE_QUIT) return false;
+ if (item.submenu) |sub| if (!validMenu(runtime.fromObjectHandle(sub))) return false;
+ }
+ return true;
+}
+
+fn snapshot(object: *Resource, desc: [*c]const c.uhdk_tray_desc) !*Resource.TraySnapshot {
+ if (!abi.validDescriptor(c.uhdk_tray_desc, desc)) return error.Invalid;
+ const d = desc.*;
+ const icon = d.icon;
+ if (d.reserved != 0 or d.hidden < 0 or d.hidden > 1) return error.Invalid;
+ if (d.menu_on_primary < 0 or d.menu_on_primary > 1) return error.Invalid;
+ if (d.template_image < 0 or d.template_image > 1) return error.Invalid;
+ if (!abi.validText(d.id, true) or d.id.len == 0 or d.id.len > 255) return error.Invalid;
+ if (!abi.validText(d.title, true) or d.title.len > 4096) return error.Invalid;
+ if (!abi.validText(d.tooltip, true) or d.tooltip.len > 4096) return error.Invalid;
+ if (d.menu_on_primary != 0 and d.menu == null) return error.Invalid;
+ if (!abi.validDescriptor(c.uhdk_image, &d.icon) or icon.reserved != 0) return error.Invalid;
+ if (icon.width == 0 or icon.height == 0 or icon.width > 512 or icon.height > 512) return error.Invalid;
+ if (icon.pixels.len != @as(u64, icon.width) * icon.height * 4) return error.Invalid;
+ if (!abi.validSpan(icon.pixels.ptr, icon.pixels.len)) return error.Invalid;
+
+ if (d.menu) |menu| {
+ const root = runtime.fromObjectHandle(menu);
+ if (root.app != object.app or !validMenu(root)) return error.Invalid;
+ }
+ if (object.payload.tray.snapshot) |old| {
+ if (!std.mem.eql(u8, abi.textBytes(old.desc.id), abi.textBytes(d.id))) return error.Invalid;
+ }
+ {
+ object.app.lock();
+ defer object.app.unlock();
+ var cursor = object.app.objects;
+ while (cursor) |other| : (cursor = other.next) {
+ if (other != object and other.alive and other.payload == .tray) {
+ if (other.payload.tray.snapshot) |s| {
+ if (std.mem.eql(u8, abi.textBytes(s.desc.id), abi.textBytes(d.id))) return error.Invalid;
+ }
+ }
+ }
+ }
+
+ const s = try object.gpa.create(Resource.TraySnapshot);
+ errdefer object.gpa.destroy(s);
+ s.* = .{ .arena = .init(object.gpa), .desc = d };
+ errdefer s.arena.deinit();
+ const a = s.arena.allocator();
+ s.desc.id = abi.textSpan(try a.dupeZ(u8, abi.textBytes(d.id)));
+ s.desc.title = abi.textSpan(try a.dupeZ(u8, abi.textBytes(d.title)));
+ s.desc.tooltip = abi.textSpan(try a.dupeZ(u8, abi.textBytes(d.tooltip)));
+ s.desc.icon.pixels = try abi.copyBytes(a, icon.pixels);
+ if (d.menu) |menu| runtime.retain(runtime.fromObjectHandle(menu));
+ return s;
+}
+
+pub fn freeSnapshot(object: *Resource, s: *Resource.TraySnapshot) void {
+ if (s.desc.menu) |menu| runtime.release(runtime.fromObjectHandle(menu));
+ s.arena.deinit();
+ object.gpa.destroy(s);
+}
+
+pub fn clear(object: *Resource) void {
+ if (object.payload.tray.snapshot) |s| freeSnapshot(object, s);
+ object.payload.tray.snapshot = null;
+}
+
+fn update(object: *Resource, desc: [*c]const c.uhdk_tray_desc) abi.Status {
+ if (object.app.session_active) return c.UHDK_STATUS_BUSY;
+ const next = snapshot(object, desc) catch |err| return runtime.objectError(err);
+ const released = session.release(object.app);
+ if (released != abi.OK) {
+ freeSnapshot(object, next);
+ return released;
+ }
+ const old = object.payload.tray.snapshot;
+ object.payload.tray.snapshot = next;
+ const status = c.z_native_tray_update(@ptrCast(object), &next.desc);
+ if (status != abi.OK) {
+ object.payload.tray.snapshot = old;
+ freeSnapshot(object, next);
+ } else if (old) |s| freeSnapshot(object, s);
+ const restored = session.acquire(object.app);
+ if (restored != abi.OK) {
+ object.app.session_status = restored;
+ return restored;
+ }
+ return status;
+}
+
+pub export fn uhdk_tray_create(handle: ?*c.uhdk_session, desc: [*c]const c.uhdk_tray_desc, out: [*c]?*c.uhdk_tray) abi.Status {
+ if (out == null) return abi.INVALID;
+ out.* = null;
+ if (handle == null) return abi.INVALID;
+ const app = runtime.fromAppHandle(handle);
+ const ready = runtime.validateMainThreadSessionReady(app);
+ if (ready != abi.OK) return ready;
+ if (app.session_active) return c.UHDK_STATUS_BUSY;
+ const object = runtime.createObject(app, c.Z_KIND_TRAY) catch return abi.OOM;
+ const status = update(object, desc);
+ if (status != abi.OK) {
+ runtime.destroyObject(object);
+ return status;
+ }
+ out.* = @ptrCast(object);
+ return abi.OK;
+}
+
+pub export fn uhdk_tray_update(handle: ?*c.uhdk_tray, desc: [*c]const c.uhdk_tray_desc) abi.Status {
+ if (handle == null) return abi.INVALID;
+ const object = runtime.fromObjectHandle(handle);
+ const ready = runtime.validateMainThreadObjectReady(object, c.Z_KIND_TRAY);
+ if (ready != abi.OK) return ready;
+ return update(object, desc);
+}
+
+pub export fn uhdk_tray_destroy(handle: ?*c.uhdk_tray) abi.Status {
+ if (handle == null) return abi.OK;
+ const object = runtime.fromObjectHandle(handle);
+ const ready = runtime.validateMainThreadObjectReady(object, c.Z_KIND_TRAY);
+ if (ready != abi.OK) return ready;
+ runtime.destroyObject(object);
+ return abi.OK;
+}
+
+pub export fn uhdk_tray_get_state(handle: ?*c.uhdk_tray, out: [*c]c.uhdk_tray_state) abi.Status {
+ if (handle == null) return abi.INVALID;
+ const object = runtime.fromObjectHandle(handle);
+ const ready = runtime.validateMainThreadObjectReady(object, c.Z_KIND_TRAY);
+ if (ready != abi.OK) return ready;
+ return abi.writeOutput(c.uhdk_tray_state, out, object.payload.tray.state);
+}
diff --git a/src/callbacks.zig b/src/callbacks.zig
index c0d69a8..3a83541 100644
--- a/src/callbacks.zig
+++ b/src/callbacks.zig
@@ -4,6 +4,41 @@ const c = @import("native");
const abi = @import("abi.zig");
const runtime = @import("runtime.zig");
+export fn z_tray_desc(handle: ?*c.uhdk_tray) [*c]const c.uhdk_tray_desc {
+ return &runtime.fromObjectHandle(handle).payload.tray.snapshot.?.desc;
+}
+
+export fn z_tray_state(handle: ?*c.uhdk_tray, available: c.uhdk_bool, status: c.uhdk_status) void {
+ const object = runtime.fromObjectHandle(handle);
+ if (!object.alive) return;
+ const state = &object.payload.tray.state;
+ if (state.available == available and state.status == status) return;
+ state.available = available;
+ state.status = status;
+ var event = std.mem.zeroes(c.z_event);
+ event.type = c.UHDK_EVENT_TRAY_STATE;
+ event.data.tray_state = .{ .tray = handle, .state = state.* };
+ c.z_emit(runtime.toAppHandle(object.app), &event);
+}
+
+export fn z_tray_activate(handle: ?*c.uhdk_tray, activation: c.uhdk_tray_activation) void {
+ const object = runtime.fromObjectHandle(handle);
+ if (!object.alive) return;
+ var event = std.mem.zeroes(c.z_event);
+ event.type = c.UHDK_EVENT_TRAY_ACTIVATE;
+ event.data.tray = .{ .tray = handle, .activation = activation };
+ c.z_emit(runtime.toAppHandle(object.app), &event);
+}
+
+export fn z_tray_command(handle: ?*c.uhdk_tray, item: [*c]const c.uhdk_menu_item) void {
+ const object = runtime.fromObjectHandle(handle);
+ if (!object.alive or item == null or item.*.flags & (c.UHDK_MENU_DISABLED | c.UHDK_MENU_SEPARATOR) != 0 or item.*.submenu != null) return;
+ var event = std.mem.zeroes(c.z_event);
+ event.type = if (item.*.role == c.UHDK_MENU_ROLE_QUIT) c.UHDK_EVENT_QUIT_REQUESTED else c.UHDK_EVENT_MENU_COMMAND;
+ event.data.menu = .{ .command_id = item.*.command_id, .tray = handle };
+ c.z_emit(runtime.toAppHandle(object.app), &event);
+}
+
export fn z_emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void {
runtime.emit(handle, event);
}
diff --git a/src/linux/Desktop.zig b/src/linux/Desktop.zig
index 710ef6b..0ecbdc6 100644
--- a/src/linux/Desktop.zig
+++ b/src/linux/Desktop.zig
@@ -29,6 +29,8 @@ pub const State = struct {
icon: ?Icon = null,
pending: ?*Activation = null,
launch: ?[:0]u8 = null,
+ tray_token: ?[:0]u8 = null,
+ tray_token_deadline: u64 = 0,
};
fn backend() *native.Backend {
@@ -65,8 +67,24 @@ pub fn initialize() void {
}
}
+// A tray host supplies provenance that a hidden application's own seat lacks.
+// Consume it once, promptly, without modifying the process environment.
+pub fn trayToken(token: []const u8) !void {
+ const copy = if (token.len != 0) try backend().app.gpa.dupeZ(u8, token) else null;
+ if (desktopState().tray_token) |old| backend().app.gpa.free(old);
+ desktopState().tray_token = copy;
+ desktopState().tray_token_deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s;
+}
+
pub fn focus(w: *native.Window, id: u64) u32 {
if (desktopState().activation == null) return n.UHDK_STATUS_UNSUPPORTED;
+ if (desktopState().tray_token) |token| {
+ const fresh = runtime.now(backend().app.io) < desktopState().tray_token_deadline;
+ if (fresh) c.xdg_activation_v1_activate(desktopState().activation, token, w.surface);
+ backend().app.gpa.free(token);
+ desktopState().tray_token = null;
+ if (fresh) return abi.OK;
+ }
if (desktopState().launch) |token| {
c.xdg_activation_v1_activate(desktopState().activation, token, w.surface);
backend().app.gpa.free(token);
@@ -232,6 +250,7 @@ pub fn deinit() void {
while (desktopState().pending) |p| finish(p, abi.CANCELLED);
if (desktopState().icon) |icon| destroyIcon(icon);
if (desktopState().launch) |token| backend().app.gpa.free(token);
+ if (desktopState().tray_token) |token| backend().app.gpa.free(token);
if (desktopState().manager != null) c.xdg_toplevel_icon_manager_v1_destroy(desktopState().manager);
if (desktopState().shm != null) c.wl_shm_destroy(desktopState().shm);
if (desktopState().activation != null) c.xdg_activation_v1_destroy(desktopState().activation);
diff --git a/src/linux/KdeAppMenu.zig b/src/linux/KdeAppMenu.zig
index dac1b2d..63a43f2 100644
--- a/src/linux/KdeAppMenu.zig
+++ b/src/linux/KdeAppMenu.zig
@@ -26,7 +26,10 @@ const Node = struct {
pub const Export = struct {
next: ?*Export = null, // Temporary transaction list, never an object registry.
- window: *native.Window,
+ window: ?*native.Window,
+ tray: ?*n.uhdk_tray = null,
+ registry_next: ?*Export = null,
+ connection: ?*c.DBusConnection = null,
root: *Resource,
arena: std.heap.ArenaAllocator,
nodes: std.ArrayList(Node) = .empty,
@@ -39,6 +42,7 @@ pub const State = struct {
global_name: u32 = 0,
sequence: u64 = 0,
app_menu: ?*Resource = null,
+ exports: ?*Export = null,
};
fn backend() *native.Backend {
@@ -83,10 +87,11 @@ pub fn ready() void {
}
fn associate(e: *Export) void {
+ const window = e.window orelse return;
if (e.proxy != null or menuState().manager == null or !backend().portal.ready) return;
// The export is already reachable by process() before advertising it.
- e.proxy = c.org_kde_kwin_appmenu_manager_create(menuState().manager, e.window.surface) orelse return;
+ e.proxy = c.org_kde_kwin_appmenu_manager_create(menuState().manager, window.surface) orelse return;
c.org_kde_kwin_appmenu_set_address(e.proxy, backend().portal.unique.?.ptr, e.path.ptr);
}
@@ -102,7 +107,10 @@ fn unassociate(e: *Export) void {
e.proxy = null;
}
-fn destroy(e: *Export) void {
+pub fn destroy(e: *Export) void {
+ var link = &menuState().exports;
+ while (link.* != e) link = &link.*.?.registry_next;
+ link.* = e.registry_next;
unassociate(e);
runtime.release(e.root);
e.arena.deinit();
@@ -133,7 +141,7 @@ 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 backend().app.gpa.create(Export);
errdefer backend().app.gpa.destroy(e);
menuState().sequence += 1;
@@ -143,6 +151,14 @@ fn create(w: *native.Window, root: *Resource) !*Export {
try e.nodes.append(e.arena.allocator(), .{});
try add(e, root, 0);
runtime.retain(root);
+ e.registry_next = menuState().exports;
+ menuState().exports = e;
+ return e;
+}
+
+pub fn createTray(tray: *n.uhdk_tray, root: *Resource) !*Export {
+ const e = try create(null, root);
+ e.tray = tray;
return e;
}
@@ -202,7 +218,7 @@ pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 {
while (pending) |e| {
pending = e.next;
e.next = null;
- replace(e.window, e);
+ replace(e.window.?, e);
}
}
@@ -230,7 +246,7 @@ fn enabled(e: *Export, index: usize) bool {
fn activate(e: *Export, index: usize, input_id: u64) void {
const item = e.nodes.items[index].item orelse return;
if (!enabled(e, index) or item.flags & n.UHDK_MENU_SEPARATOR != 0 or item.submenu != null) return;
- Menu.activate(e.window, item, input_id);
+ if (e.tray) |tray| n.z_tray_command(tray, item) else Menu.activate(e.window.?, item, input_id);
}
fn folded(key: u32) u32 {
@@ -351,10 +367,10 @@ fn groupItem(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void
}
pub fn updateFlags() u32 {
- var cursor = backend().windows;
- while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| {
+ var cursor = menuState().exports;
+ while (cursor) |e| : (cursor = e.registry_next) {
changed(e) catch return abi.OOM;
- };
+ }
return abi.OK;
}
@@ -366,7 +382,7 @@ fn changed(e: *Export) !void {
};
if (!dirty) return;
- if (backend().portal.ready and e.proxy != null) {
+ if ((backend().portal.ready and e.proxy != null) or e.connection != null) {
const message = c.z_dbus_message_new_signal.?(e.path.ptr, iface, "ItemsPropertiesUpdated") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(message);
@@ -380,18 +396,27 @@ fn changed(e: *Export) !void {
var removed = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ias)");
try Bus.close(&out, &removed);
- _ = try Portal.send(message);
+ _ = try send(e, message);
}
for (e.nodes.items[1..]) |*node| node.flags = node.item.?.flags;
}
-fn fail(message: *Bus.Message, name: [*:0]const u8) !void {
+fn send(e: *Export, message: *Bus.Message) !u32 {
+ if (e.connection) |connection| {
+ var serial: u32 = 0;
+ if (c.z_dbus_connection_send.?(connection, message, &serial) == 0) return error.OutOfMemory;
+ return serial;
+ }
+ return Portal.send(message);
+}
+
+fn fail(e: *Export, message: *Bus.Message, name: [*:0]const u8) !void {
if (c.z_dbus_message_get_no_reply.?(message) != 0) return;
const reply = c.z_dbus_message_new_error.?(message, name, "Menu request could not be handled") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(reply);
- _ = try Portal.send(reply);
+ _ = try send(e, reply);
}
const invalid = "org.freedesktop.DBus.Error.InvalidArgs";
@@ -425,37 +450,44 @@ pub fn process(message: *Bus.Message) !bool {
if (path == null or !std.mem.startsWith(u8, std.mem.span(path), prefix)) return false;
var found: ?*Export = null;
- var cursor = backend().windows;
- while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| {
- if (same(e.path, std.mem.span(path))) {
+ var cursor = menuState().exports;
+ while (cursor) |e| : (cursor = e.registry_next) {
+ if (e.tray == null and same(e.path, std.mem.span(path))) {
found = e;
break;
}
- };
+ }
- if (found) |e| try dispatch(e, message) else try fail(message, "org.freedesktop.DBus.Error.UnknownObject");
+ if (found) |e| {
+ try dispatch(e, message);
+ } else {
+ if (c.z_dbus_message_get_no_reply.?(message) != 0) return true;
+ const reply = c.z_dbus_message_new_error.?(message, "org.freedesktop.DBus.Error.UnknownObject", "Unknown menu") orelse return error.OutOfMemory;
+ defer c.z_dbus_message_unref.?(reply);
+ _ = try Portal.send(reply);
+ }
return true;
}
-fn dispatch(e: *Export, message: *Bus.Message) !void {
+pub fn dispatch(e: *Export, message: *Bus.Message) !void {
const reply = c.z_dbus_message_new_method_return.?(message) orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(reply);
var out = Bus.append(reply);
var args = Bus.parse(message);
if (callIs(message, "org.freedesktop.DBus.Introspectable", "Introspect")) {
- if (!signature(message, "")) return fail(message, invalid);
+ if (!signature(message, "")) return fail(e, message, invalid);
try Bus.string(&out, @embedFile("dbusmenu.xml"));
} else if (callIs(message, "org.freedesktop.DBus.Peer", "Ping")) {
- if (!signature(message, "")) return fail(message, invalid);
+ if (!signature(message, "")) return fail(e, message, invalid);
} else if (callIs(message, "org.freedesktop.DBus.Properties", "Get") or callIs(message, "org.freedesktop.DBus.Properties", "GetAll")) {
const single = callIs(message, "org.freedesktop.DBus.Properties", "Get");
- if (!signature(message, if (single) "ss" else "s")) return fail(message, invalid);
- if (!same(Bus.str(&args).?, iface)) return fail(message, "org.freedesktop.DBus.Error.UnknownInterface");
+ if (!signature(message, if (single) "ss" else "s")) return fail(e, message, invalid);
+ if (!same(Bus.str(&args).?, iface)) return fail(e, message, "org.freedesktop.DBus.Error.UnknownInterface");
if (single) {
_ = Bus.next(&args);
- if (!try globalProperty(Bus.str(&args).?, &out)) return fail(message, "org.freedesktop.DBus.Error.UnknownProperty");
+ if (!try globalProperty(Bus.str(&args).?, &out)) return fail(e, message, "org.freedesktop.DBus.Error.UnknownProperty");
} else {
var dict = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "{sv}");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &dict);
@@ -470,19 +502,19 @@ fn dispatch(e: *Export, message: *Bus.Message) !void {
try Bus.close(&out, &dict);
}
} else if (callIs(message, iface, "GetLayout")) {
- if (!signature(message, "iias")) return fail(message, invalid);
+ if (!signature(message, "iias")) return fail(e, message, invalid);
- const index = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing);
+ const index = nodeId(e, Bus.int(&args).?) orelse return fail(e, message, missing);
_ = Bus.next(&args);
const depth = Bus.int(&args).?;
- if (depth < -1) return fail(message, invalid);
+ if (depth < -1) return fail(e, message, invalid);
_ = Bus.next(&args);
try Bus.basic(&out, c.DBUS_TYPE_UINT32, @as(u32, 1));
try layout(e, index, depth, Bus.child(&args), &out);
} else if (callIs(message, iface, "GetGroupProperties")) {
- if (!signature(message, "aias")) return fail(message, invalid);
+ if (!signature(message, "aias")) return fail(e, message, invalid);
var ids = Bus.child(&args);
_ = Bus.next(&args);
@@ -499,25 +531,25 @@ fn dispatch(e: *Export, message: *Bus.Message) !void {
try Bus.close(&out, &items);
} else if (callIs(message, iface, "GetProperty")) {
- if (!signature(message, "is")) return fail(message, invalid);
+ if (!signature(message, "is")) return fail(e, message, invalid);
- const index = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing);
+ const index = nodeId(e, Bus.int(&args).?) orelse return fail(e, message, missing);
_ = Bus.next(&args);
- if (!try property(e, index, Bus.str(&args).?, &out)) return fail(message, "org.freedesktop.DBus.Error.UnknownProperty");
+ if (!try property(e, index, Bus.str(&args).?, &out)) return fail(e, message, "org.freedesktop.DBus.Error.UnknownProperty");
} else if (callIs(message, iface, "Event")) {
- if (!signature(message, "isvu")) return fail(message, invalid);
+ if (!signature(message, "isvu")) return fail(e, message, invalid);
- const index = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing);
+ const index = nodeId(e, Bus.int(&args).?) orelse return fail(e, message, missing);
_ = Bus.next(&args);
if (same(Bus.str(&args).?, "clicked")) activate(e, index, Input.id());
} else if (callIs(message, iface, "AboutToShow")) {
- if (!signature(message, "i")) return fail(message, invalid);
+ if (!signature(message, "i")) return fail(e, message, invalid);
- _ = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing);
+ _ = nodeId(e, Bus.int(&args).?) orelse return fail(e, message, missing);
try Bus.basic(&out, c.DBUS_TYPE_BOOLEAN, @as(u32, 0));
} else if (callIs(message, iface, "EventGroup") or callIs(message, iface, "AboutToShowGroup")) {
const events = callIs(message, iface, "EventGroup");
- if (!signature(message, if (events) "a(isvu)" else "ai")) return fail(message, invalid);
+ if (!signature(message, if (events) "a(isvu)" else "ai")) return fail(e, message, invalid);
var ids = Bus.child(&args);
if (!events) {
@@ -548,7 +580,7 @@ fn dispatch(e: *Export, message: *Bus.Message) !void {
}
try Bus.close(&out, &errors);
- if (valid_count == 0 and error_count != 0) return fail(message, missing);
- } else return fail(message, "org.freedesktop.DBus.Error.UnknownMethod");
- if (c.z_dbus_message_get_no_reply.?(message) == 0) _ = try Portal.send(reply);
+ if (valid_count == 0 and error_count != 0) return fail(e, message, missing);
+ } else return fail(e, message, "org.freedesktop.DBus.Error.UnknownMethod");
+ if (c.z_dbus_message_get_no_reply.?(message) == 0) _ = try send(e, reply);
}
diff --git a/src/linux/Portal.zig b/src/linux/Portal.zig
index a5bac90..8c1b5b4 100644
--- a/src/linux/Portal.zig
+++ b/src/linux/Portal.zig
@@ -6,6 +6,7 @@ const n = @import("native");
const native = @import("native.zig");
const KdeAppMenu = @import("KdeAppMenu.zig");
const Bus = @import("Bus.zig");
+const Tray = @import("Tray.zig");
const Files = @import("Files.zig");
const Input = @import("Input.zig");
const runtime = @import("../runtime.zig");
@@ -35,7 +36,7 @@ pub const State = struct {
unique: ?[:0]u8 = null,
owner: ?[:0]u8 = null,
hello: u32 = 0,
- matches: [3]u32 = @splat(0),
+ matches: [5]u32 = @splat(0),
ready: bool = false,
version_serial: u32 = 0,
settings_serial: u32 = 0,
@@ -91,6 +92,8 @@ fn addMatches() !void {
"type='signal',sender='org.freedesktop.portal.Desktop',interface='org.freedesktop.portal.Request',member='Response'",
"type='signal',sender='org.freedesktop.portal.Desktop',interface='org.freedesktop.portal.Settings',member='SettingChanged',path='/org/freedesktop/portal/desktop'",
"type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.portal.Desktop'",
+ "type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.kde.StatusNotifierWatcher'",
+ "type='signal',sender='org.kde.StatusNotifierWatcher',interface='org.kde.StatusNotifierWatcher',path='/StatusNotifierWatcher'",
};
for (rules, 0..) |rule, i| {
@@ -176,6 +179,7 @@ fn setOwner(message: *Bus.Message) !void {
}
fn process(message: *Bus.Message) !void {
+ if (try Tray.process(message)) return;
if (try KdeAppMenu.process(message)) return;
const serial = c.z_dbus_message_get_reply_serial.?(message);
@@ -203,6 +207,7 @@ fn process(message: *Bus.Message) !void {
if (std.mem.allEqual(u32, &portalState().matches, 0)) {
portalState().ready = true;
KdeAppMenu.ready();
+ try Tray.ready();
try discover();
}
@@ -604,6 +609,7 @@ fn destroy(p: *Pending) void {
}
fn disconnect() void {
+ Tray.disconnected();
KdeAppMenu.disconnected();
while (portalState().pending) |p| {
complete(p, abi.UNAVAILABLE, null);
diff --git a/src/linux/README.md b/src/linux/README.md
index 8076c38..067043e 100644
--- a/src/linux/README.md
+++ b/src/linux/README.md
@@ -7,7 +7,7 @@ logical/pixel metrics, EGL desktop OpenGL, and local POSIX file references.
Keyboard/pointer input, cursor shapes, XKB composition, text-input-v3 IME,
clipboard, incoming file drops, portal dialogs/URLs/preferences, activation,
application icons, inotify file watches, Plasma app/window menu export, and
-software-rendered context menus are also implemented.
+software-rendered context menus and StatusNotifier tray icons are also implemented.
A cursor-theme fallback, library-rendered client-side decorations, and X11
remain unsupported. Applications can disable native decoration and render their
@@ -176,6 +176,18 @@ NixOS with Plasma 6.5.6 and Mesa 25.2.6; other systems are not runtime-qualified
menu. Enabled/checked changes are signalled to consumers, and disabled parents
block their descendants. Labels are literal UTF-8, with mnemonic markers
escaped. The current API has no separate checkable/radio or RTL setting.
+- Tray icons use `org.kde.StatusNotifierWatcher`/`org.kde.StatusNotifierItem` and
+ the same D-BusMenu exporter. They do not require KDE's Wayland appmenu protocol.
+ A compatible StatusNotifier host is required (for example Plasma's tray or a
+ configured Waybar tray); desktops without one report `UHDK_CAP_TRAY` false.
+ Registration is asynchronous and recovers when the watcher or host returns.
+ Each item owns a private bus identity so hiding/destroying one unregisters it
+ independently. Full session-bus replacement requires reopening the session.
+ Hosts render menus themselves; a host that only calls `ContextMenu` without
+ supporting D-BusMenu cannot display the tray menu. Secondary activation and
+ the primary-menu hint depend on host support. Host-supplied Wayland activation
+ tokens are consumed once by the next window focus request within five seconds.
+ RGBA pixels are exported as network-order ARGB; no icon installation is needed.
- Menu accelerators use logical keys and Shift/Control/Alt/Super, ignoring lock
flags and ASCII letter case. They dispatch menu/edit/quit events before raw
keys or text; matching key releases and repeats are consumed. They remain
diff --git a/src/linux/Tray.zig b/src/linux/Tray.zig
new file mode 100644
index 0000000..40193f0
--- /dev/null
+++ b/src/linux/Tray.zig
@@ -0,0 +1,440 @@
+//! StatusNotifierItem without a toolkit. Each item has a private bus identity so
+//! disconnecting it removes it from watchers that offer no unregister method.
+const std = @import("std");
+const c = @import("linux_c");
+const n = @import("native");
+const native = @import("native.zig");
+const runtime = @import("../runtime.zig");
+const abi = @import("../abi.zig");
+const Bus = @import("Bus.zig");
+const Portal = @import("Portal.zig");
+const Menus = @import("KdeAppMenu.zig");
+const Desktop = @import("Desktop.zig");
+const watcher = "org.kde.StatusNotifierWatcher";
+const watcher_path = "/StatusNotifierWatcher";
+const iface = "org.kde.StatusNotifierItem";
+const path = "/StatusNotifierItem";
+const properties = "org.freedesktop.DBus.Properties";
+const dbus = "org.freedesktop.DBus";
+
+pub const Item = struct {
+ next: ?*Item = null,
+ handle: *n.uhdk_tray,
+ menu: ?*Menus.Export = null,
+ connection: ?*c.DBusConnection = null,
+ hello: u32 = 0,
+ registration: u32 = 0,
+ registered: bool = false,
+ deadline: u64 = 0,
+};
+
+pub const State = struct {
+ items: ?*Item = null,
+ owner: ?[:0]u8 = null,
+ owner_query: u32 = 0,
+ host_query: u32 = 0,
+ host: bool = false,
+};
+
+fn backend() *native.Backend {
+ return native.instance.?;
+}
+fn state() *State {
+ return &backend().tray;
+}
+fn same(a: []const u8, b: []const u8) bool {
+ return std.mem.eql(u8, a, b);
+}
+fn send(connection: *c.DBusConnection, message: *Bus.Message) !u32 {
+ var serial: u32 = 0;
+ if (c.z_dbus_connection_send.?(connection, message, &serial) == 0) return error.OutOfMemory;
+ return serial;
+}
+fn report(item: *Item) void {
+ const hidden = n.z_tray_desc(item.handle).*.hidden != 0;
+ n.z_tray_state(item.handle, @intFromBool(item.registered and !hidden), if (hidden or item.registered) abi.OK else abi.UNAVAILABLE);
+}
+fn stop(item: *Item) void {
+ if (item.menu) |menu| menu.connection = null;
+ if (item.connection) |conn| {
+ c.z_dbus_connection_close.?(conn);
+ c.z_dbus_connection_unref.?(conn);
+ }
+ item.connection = null;
+ item.hello = 0;
+ item.registration = 0;
+ item.registered = false;
+ item.deadline = 0;
+ report(item);
+}
+fn start(item: *Item) !void {
+ if (!state().host or item.connection != null or n.z_tray_desc(item.handle).*.hidden != 0) {
+ report(item);
+ return;
+ }
+ const address = c.getenv("DBUS_SESSION_BUS_ADDRESS") orelse return;
+ const conn = c.z_dbus_connection_open_private.?(address, null) orelse return;
+ item.connection = conn;
+ errdefer stop(item);
+ c.z_dbus_connection_set_exit_on_disconnect.?(conn, 0);
+ const hello = try Bus.method(dbus, "/org/freedesktop/DBus", dbus, "Hello");
+ defer c.z_dbus_message_unref.?(hello);
+ item.hello = try send(conn, hello);
+ item.deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s;
+}
+
+pub fn update(handle: *n.uhdk_tray, desc: *const n.uhdk_tray_desc) u32 {
+ const existing = n.z_object_native(handle);
+ const item: *Item = if (existing) |p| @ptrCast(@alignCast(p)) else backend().app.gpa.create(Item) catch return abi.OOM;
+ const menu = if (desc.menu) |root| Menus.createTray(handle, runtime.fromObjectHandle(root)) catch {
+ if (existing == null) backend().app.gpa.destroy(item);
+ return abi.OOM;
+ } else null;
+ if (existing == null) {
+ item.* = .{ .handle = handle, .next = state().items };
+ state().items = item;
+ n.z_object_set_native(handle, item);
+ }
+ if (item.menu) |old| Menus.destroy(old);
+ item.menu = menu;
+ if (menu) |m| m.connection = if (item.hello == 0) item.connection else null;
+ if (desc.hidden != 0) {
+ stop(item);
+ } else {
+ start(item) catch {};
+ if (item.registered) changed(item) catch {
+ stop(item);
+ };
+ }
+ report(item);
+ return abi.OK;
+}
+
+pub fn destroy(item: *Item) void {
+ stop(item);
+ if (item.menu) |menu| Menus.destroy(menu);
+ var link = &state().items;
+ while (link.* != item) link = &link.*.?.next;
+ link.* = item.next;
+ backend().app.gpa.destroy(item);
+}
+
+pub fn ready() !void {
+ const query = try Bus.method(dbus, "/org/freedesktop/DBus", dbus, "GetNameOwner");
+ defer c.z_dbus_message_unref.?(query);
+ var args = Bus.append(query);
+ try Bus.string(&args, watcher);
+ state().owner_query = try Portal.send(query);
+}
+
+fn setOwner(owner: []const u8) !void {
+ const copied = if (owner.len != 0) try backend().app.gpa.dupeZ(u8, owner) else null;
+ if (state().owner) |old| backend().app.gpa.free(old);
+ state().owner = copied;
+ state().host_query = 0;
+ state().host = false;
+ native.setCapability(n.UHDK_CAP_TRAY, false);
+ var cursor = state().items;
+ while (cursor) |item| : (cursor = item.next) stop(item);
+ if (copied) |name| {
+ const query = try Bus.method(name.ptr, watcher_path, properties, "Get");
+ defer c.z_dbus_message_unref.?(query);
+ var args = Bus.append(query);
+ try Bus.string(&args, watcher);
+ try Bus.string(&args, "IsStatusNotifierHostRegistered");
+ state().host_query = try Portal.send(query);
+ }
+}
+
+fn setHost(host: bool) void {
+ state().host = host;
+ native.setCapability(n.UHDK_CAP_TRAY, host);
+ var cursor = state().items;
+ while (cursor) |item| : (cursor = item.next) {
+ if (host) start(item) catch {} else stop(item);
+ }
+}
+
+pub fn process(message: *Bus.Message) !bool {
+ const serial = c.z_dbus_message_get_reply_serial.?(message);
+ const failed = c.z_dbus_message_get_type.?(message) == c.DBUS_MESSAGE_TYPE_ERROR;
+ var args = Bus.parse(message);
+ if (serial != 0 and serial == state().owner_query) {
+ state().owner_query = 0;
+ try setOwner(if (!failed) Bus.str(&args) orelse "" else "");
+ return true;
+ }
+ if (serial != 0 and serial == state().host_query) {
+ state().host_query = 0;
+ if (!failed) {
+ var value = Bus.variant(&args) orelse return true;
+ if (Bus.kind(&value) == c.DBUS_TYPE_BOOLEAN) {
+ var yes: c.dbus_bool_t = 0;
+ c.z_dbus_message_iter_get_basic.?(&value, &yes);
+ setHost(yes != 0);
+ }
+ }
+ return true;
+ }
+ const sender = c.z_dbus_message_get_sender.?(message) orelse return false;
+ if (same(std.mem.span(sender), dbus) and c.z_dbus_message_is_signal.?(message, dbus, "NameOwnerChanged") != 0 and c.z_dbus_message_has_signature.?(message, "sss") != 0 and same(Bus.str(&args).?, watcher)) {
+ _ = Bus.next(&args);
+ _ = Bus.next(&args);
+ state().owner_query = 0; // Do not resurrect a superseded discovery reply.
+ try setOwner(Bus.str(&args).?);
+ return true;
+ }
+ if (state().owner) |owner| {
+ if (same(std.mem.span(sender), owner)) {
+ if (c.z_dbus_message_is_signal.?(message, watcher, "StatusNotifierHostRegistered") != 0) {
+ state().host_query = 0;
+ setHost(true);
+ return true;
+ }
+ if (c.z_dbus_message_is_signal.?(message, watcher, "StatusNotifierHostUnregistered") != 0) {
+ state().host_query = 0;
+ setHost(false);
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+pub fn disconnected() void {
+ state().owner_query = 0;
+ state().host_query = 0;
+ setHost(false);
+ if (state().owner) |owner| backend().app.gpa.free(owner);
+ state().owner = null;
+}
+
+pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
+ var cursor = state().items;
+ while (cursor) |item| : (cursor = item.next) {
+ if (item.connection) |conn| {
+ var fd: c_int = -1;
+ if (c.z_dbus_connection_get_unix_fd.?(conn, &fd) != 0) try fds.append(backend().app.gpa, .{
+ .fd = fd,
+ .events = @as(c_short, c.POLLIN) | @as(c_short, if (c.z_dbus_connection_has_messages_to_send.?(conn) != 0) c.POLLOUT else 0),
+ .revents = 0,
+ });
+ }
+ }
+}
+
+pub fn tick() i32 {
+ var pending = false;
+ var cursor = state().items;
+ while (cursor) |item| : (cursor = item.next) {
+ const conn = item.connection orelse continue;
+ if (c.z_dbus_connection_read_write.?(conn, 0) == 0) {
+ stop(item);
+ continue;
+ }
+ for (0..32) |_| {
+ const message = c.z_dbus_connection_pop_message.?(conn) orelse break;
+ defer c.z_dbus_message_unref.?(message);
+ dispatch(item, message) catch {
+ stop(item);
+ break;
+ };
+ if (item.connection == null) break;
+ } else pending = true;
+ if (item.deadline != 0) {
+ if (runtime.now(backend().app.io) >= item.deadline) stop(item) else pending = true;
+ }
+ }
+ return if (pending) 10 else -1;
+}
+
+fn fail(item: *Item, message: *Bus.Message, name: [*:0]const u8) !void {
+ if (c.z_dbus_message_get_no_reply.?(message) != 0) return;
+ const reply = c.z_dbus_message_new_error.?(message, name, "Tray request could not be handled") orelse return error.OutOfMemory;
+ defer c.z_dbus_message_unref.?(reply);
+ _ = try send(item.connection.?, reply);
+}
+
+fn variant(out: *Bus.Iter, comptime signature: [:0]const u8, value: anytype) !void {
+ var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, signature);
+ errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v);
+ try Bus.basic(&v, signature[0], value);
+ try Bus.close(out, &v);
+}
+fn textVariant(out: *Bus.Iter, text: n.uhdk_text) !void {
+ // Tray snapshots own sentinel-terminated copies of public spans.
+ try variant(out, "s", text.ptr);
+}
+fn pixmap(out: *Bus.Iter, icon: ?*const n.uhdk_image) !void {
+ var list = try Bus.open(out, c.DBUS_TYPE_ARRAY, "(iiay)");
+ errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &list);
+ if (icon) |i| {
+ var tuple = try Bus.open(&list, c.DBUS_TYPE_STRUCT, null);
+ errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&list, &tuple);
+ try Bus.basic(&tuple, c.DBUS_TYPE_INT32, @as(i32, @intCast(i.width)));
+ try Bus.basic(&tuple, c.DBUS_TYPE_INT32, @as(i32, @intCast(i.height)));
+ var bytes = try Bus.open(&tuple, c.DBUS_TYPE_ARRAY, "y");
+ errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&tuple, &bytes);
+ var offset: usize = 0;
+ while (offset < i.pixels.len) : (offset += 4) {
+ for ([_]usize{ 3, 0, 1, 2 }) |channel| try Bus.basic(&bytes, c.DBUS_TYPE_BYTE, i.pixels.ptr[offset + channel]);
+ }
+ try Bus.close(&tuple, &bytes);
+ try Bus.close(&list, &tuple);
+ }
+ try Bus.close(out, &list);
+}
+
+const names = [_][:0]const u8{ "Category", "Id", "Title", "Status", "WindowId", "IconName", "IconPixmap", "OverlayIconName", "OverlayIconPixmap", "AttentionIconName", "AttentionIconPixmap", "AttentionMovieName", "IconThemePath", "ToolTip", "ItemIsMenu", "Menu" };
+fn property(item: *Item, name: []const u8, out: *Bus.Iter) !bool {
+ const d = n.z_tray_desc(item.handle);
+ if (same(name, "Id")) {
+ try textVariant(out, d.*.id);
+ } else if (same(name, "Title")) {
+ try textVariant(out, d.*.title);
+ } else if (same(name, "Category")) {
+ try variant(out, "s", @as([*:0]const u8, "ApplicationStatus"));
+ } else if (same(name, "Status")) {
+ try variant(out, "s", @as([*:0]const u8, if (d.*.hidden != 0) "Passive" else "Active"));
+ } else if (same(name, "WindowId")) {
+ try variant(out, "i", @as(i32, 0));
+ } else if (same(name, "ItemIsMenu")) {
+ try variant(out, "b", @as(u32, @intCast(d.*.menu_on_primary)));
+ } else if (same(name, "Menu")) {
+ try variant(out, "o", @as([*:0]const u8, if (item.menu) |menu| menu.path.ptr else "/NO_DBUSMENU"));
+ } else if (same(name, "IconPixmap") or same(name, "OverlayIconPixmap") or same(name, "AttentionIconPixmap")) {
+ var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, "a(iiay)");
+ errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v);
+ try pixmap(&v, if (same(name, "IconPixmap")) &d.*.icon else null);
+ try Bus.close(out, &v);
+ } else if (same(name, "ToolTip")) {
+ var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, "(sa(iiay)ss)");
+ errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v);
+ var tuple = try Bus.open(&v, c.DBUS_TYPE_STRUCT, null);
+ errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&v, &tuple);
+ try Bus.string(&tuple, "");
+ try pixmap(&tuple, null);
+ try Bus.string(&tuple, if (d.*.tooltip.len != 0) d.*.tooltip.ptr else d.*.title.ptr);
+ // Hosts may interpret the body as markup; plain text belongs in title.
+ // Include tooltip as the title when provided and leave the markup body empty.
+ try Bus.string(&tuple, "");
+ try Bus.close(&v, &tuple);
+ try Bus.close(out, &v);
+ } else {
+ for ([_][]const u8{ "IconName", "OverlayIconName", "AttentionIconName", "AttentionMovieName", "IconThemePath" }) |key| {
+ if (same(name, key)) {
+ try variant(out, "s", @as([*:0]const u8, ""));
+ return true;
+ }
+ }
+ return false;
+ }
+ return true;
+}
+
+fn changed(item: *Item) !void {
+ for ([_][*:0]const u8{ "NewTitle", "NewIcon", "NewToolTip" }) |name| {
+ const message = c.z_dbus_message_new_signal.?(path, iface, name) orelse return error.OutOfMemory;
+ defer c.z_dbus_message_unref.?(message);
+ _ = try send(item.connection.?, message);
+ }
+ const message = c.z_dbus_message_new_signal.?(path, properties, "PropertiesChanged") orelse return error.OutOfMemory;
+ defer c.z_dbus_message_unref.?(message);
+ var out = Bus.append(message);
+ try Bus.string(&out, iface);
+ var dict = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "{sv}");
+ errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &dict);
+ for ([_][:0]const u8{ "Menu", "ItemIsMenu" }) |name| {
+ var pair = try Bus.open(&dict, c.DBUS_TYPE_DICT_ENTRY, null);
+ errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&dict, &pair);
+ try Bus.string(&pair, name.ptr);
+ _ = try property(item, name, &pair);
+ try Bus.close(&dict, &pair);
+ }
+ try Bus.close(&out, &dict);
+ var invalidated = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "s");
+ try Bus.close(&out, &invalidated);
+ _ = try send(item.connection.?, message);
+}
+
+fn dispatch(item: *Item, message: *Bus.Message) !void {
+ const serial = c.z_dbus_message_get_reply_serial.?(message);
+ const failed = c.z_dbus_message_get_type.?(message) == c.DBUS_MESSAGE_TYPE_ERROR;
+ var args = Bus.parse(message);
+ if (serial != 0 and serial == item.hello) {
+ item.hello = 0;
+ if (failed or Bus.str(&args) == null) {
+ stop(item);
+ return;
+ }
+ if (item.menu) |menu| menu.connection = item.connection;
+ const request = try Bus.method(state().owner.?.ptr, watcher_path, watcher, "RegisterStatusNotifierItem");
+ defer c.z_dbus_message_unref.?(request);
+ var out = Bus.append(request);
+ try Bus.string(&out, @ptrCast(Bus.str(&args).?.ptr));
+ item.registration = try send(item.connection.?, request);
+ return;
+ }
+ if (serial != 0 and serial == item.registration) {
+ item.registration = 0;
+ item.deadline = 0;
+ if (failed) stop(item) else {
+ item.registered = true;
+ report(item);
+ }
+ return;
+ }
+ if (c.z_dbus_message_get_type.?(message) != c.DBUS_MESSAGE_TYPE_METHOD_CALL) return;
+ const raw_path = c.z_dbus_message_get_path.?(message) orelse return;
+ if (item.menu) |menu| {
+ if (same(std.mem.span(raw_path), menu.path)) return Menus.dispatch(menu, message);
+ }
+ if (!same(std.mem.span(raw_path), path)) return fail(item, message, "org.freedesktop.DBus.Error.UnknownObject");
+ const raw_iface = c.z_dbus_message_get_interface.?(message) orelse return fail(item, message, "org.freedesktop.DBus.Error.UnknownInterface");
+ const raw_member = c.z_dbus_message_get_member.?(message) orelse return;
+ const interface = std.mem.span(raw_iface);
+ const member = std.mem.span(raw_member);
+ const reply = c.z_dbus_message_new_method_return.?(message) orelse return error.OutOfMemory;
+ defer c.z_dbus_message_unref.?(reply);
+ var out = Bus.append(reply);
+ const invalid = "org.freedesktop.DBus.Error.InvalidArgs";
+ if (same(interface, properties) and (same(member, "Get") or same(member, "GetAll"))) {
+ const single = same(member, "Get");
+ if (c.z_dbus_message_has_signature.?(message, if (single) "ss" else "s") == 0) return fail(item, message, invalid);
+ if (!same(Bus.str(&args).?, iface)) return fail(item, message, "org.freedesktop.DBus.Error.UnknownInterface");
+ if (single) {
+ _ = Bus.next(&args);
+ if (!try property(item, Bus.str(&args).?, &out)) return fail(item, message, "org.freedesktop.DBus.Error.UnknownProperty");
+ } else {
+ var dict = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "{sv}");
+ errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &dict);
+ for (names) |name| {
+ var pair = try Bus.open(&dict, c.DBUS_TYPE_DICT_ENTRY, null);
+ errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&dict, &pair);
+ try Bus.string(&pair, name.ptr);
+ _ = try property(item, name, &pair);
+ try Bus.close(&dict, &pair);
+ }
+ try Bus.close(&out, &dict);
+ }
+ } else if (same(interface, "org.freedesktop.DBus.Introspectable") and same(member, "Introspect")) {
+ if (c.z_dbus_message_has_signature.?(message, "") == 0) return fail(item, message, invalid);
+ try Bus.string(&out, @embedFile("tray.xml"));
+ } else if (same(interface, "org.freedesktop.DBus.Peer") and same(member, "Ping")) {
+ if (c.z_dbus_message_has_signature.?(message, "") == 0) return fail(item, message, invalid);
+ } else if (same(interface, iface) and (same(member, "Activate") or same(member, "SecondaryActivate"))) {
+ if (c.z_dbus_message_has_signature.?(message, "ii") == 0) return fail(item, message, invalid);
+ n.z_tray_activate(item.handle, if (same(member, "Activate")) n.UHDK_TRAY_ACTIVATE_PRIMARY else n.UHDK_TRAY_ACTIVATE_SECONDARY);
+ } else if (same(interface, iface) and same(member, "ContextMenu")) {
+ if (c.z_dbus_message_has_signature.?(message, "ii") == 0) return fail(item, message, invalid);
+ return fail(item, message, "org.freedesktop.DBus.Error.NotSupported"); // Host renders Menu.
+ } else if (same(interface, iface) and same(member, "ProvideXdgActivationToken")) {
+ if (c.z_dbus_message_has_signature.?(message, "s") == 0) return fail(item, message, invalid);
+ const token = Bus.str(&args).?;
+ if (token.len > 4096) return fail(item, message, invalid);
+ try Desktop.trayToken(token);
+ } else if (same(interface, iface) and same(member, "Scroll")) {
+ if (c.z_dbus_message_has_signature.?(message, "is") == 0) return fail(item, message, invalid);
+ } else return fail(item, message, "org.freedesktop.DBus.Error.UnknownMethod");
+ if (c.z_dbus_message_get_no_reply.?(message) == 0) _ = try send(item.connection.?, reply);
+}
diff --git a/src/linux/native.zig b/src/linux/native.zig
index 961b603..62d07e6 100644
--- a/src/linux/native.zig
+++ b/src/linux/native.zig
@@ -11,6 +11,7 @@ const Input = @import("Input.zig");
const Desktop = @import("Desktop.zig");
const WindowState = @import("WindowState.zig");
const Portal = @import("Portal.zig");
+const Tray = @import("Tray.zig");
const Watch = @import("Watch.zig");
const Data = @import("Data.zig");
const Popup = @import("Popup.zig");
@@ -73,6 +74,7 @@ pub const Backend = struct {
data: Data.State = .{},
watches: ?*Watch.Watch = null,
portal: Portal.State = .{},
+ tray: Tray.State = .{},
desktop: Desktop.State = .{},
menus: KdeAppMenu.State = .{},
popup: Popup.State = .{},
@@ -283,6 +285,9 @@ export fn z_native_pump(timeout_ns: u64) void {
const portal_timeout = Portal.tick();
if (portal_timeout >= 0) timeout = if (timeout < 0) portal_timeout else @min(timeout, portal_timeout);
+ const tray_timeout = Tray.tick();
+ if (tray_timeout >= 0) timeout = if (timeout < 0) tray_timeout else @min(timeout, tray_timeout);
+
const data_timeout = Data.tick();
if (data_timeout >= 0) timeout = if (timeout < 0) data_timeout else @min(timeout, data_timeout);
while (cursor) |w| {
@@ -336,6 +341,12 @@ export fn z_native_pump(timeout_ns: u64) void {
break :pump;
};
+ Tray.poll(&fds) catch {
+ if (reading) c.z_wl_display_cancel_read.?(b.display);
+ fail(b);
+ break :pump;
+ };
+
Portal.poll(&fds) catch {
if (reading) c.z_wl_display_cancel_read.?(b.display);
fail(b);
@@ -767,6 +778,10 @@ export fn z_native_cancel(id: u64) void {
}
}
+export fn z_native_tray_update(handle: ?*n.uhdk_tray, desc: [*c]const n.uhdk_tray_desc) u32 {
+ return Tray.update(handle.?, desc);
+}
+
export fn z_native_destroy(kind: u32, ptr: ?*anyopaque) void {
const p = ptr orelse return;
switch (kind) {
@@ -774,6 +789,7 @@ export fn z_native_destroy(kind: u32, ptr: ?*anyopaque) void {
const w: *Window = @ptrCast(@alignCast(p));
if (w.request != 0) completeCreation(w, abi.CANCELLED) else destroyWindow(w);
},
+ n.Z_KIND_TRAY => Tray.destroy(@ptrCast(@alignCast(p))),
n.Z_KIND_WATCH => Watch.destroy(@ptrCast(@alignCast(p))),
n.Z_KIND_GL => {
const w: *Window = @ptrCast(@alignCast(p));
diff --git a/src/linux/tray.xml b/src/linux/tray.xml
new file mode 100644
index 0000000..82f6930
--- /dev/null
+++ b/src/linux/tray.xml
@@ -0,0 +1,48 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/macos/native.m b/src/macos/native.m
index e0bbdcf..930c9a4 100644
--- a/src/macos/native.m
+++ b/src/macos/native.m
@@ -28,10 +28,11 @@ static uhdk_modifier_flags mods(NSEventModifierFlags f) {
((f & NSEventModifierFlagCommand) ? UHDK_MOD_SUPER : 0) |
((f & NSEventModifierFlagCapsLock) ? UHDK_MOD_CAPS_LOCK : 0);
}
-@class ZWindow, ZView, ZGL;
+@class ZWindow, ZView, ZGL, ZTray;
@interface ZHost : NSObject
@property(nonatomic) uhdk_session *app;
@property(nonatomic, strong) NSMutableArray *windows;
+@property(nonatomic, strong) NSMutableArray *trays;
@property(nonatomic, strong) NSMutableArray *observers;
@property(nonatomic, strong) NSTimer *workTimer;
@property(nonatomic, strong) NSMenu *fallbackMenu;
@@ -45,6 +46,13 @@ static uhdk_modifier_flags mods(NSEventModifierFlags f) {
- (void)refreshMenus;
- (void)preferences;
@end
+@interface ZTray : NSObject
+@property(nonatomic) uhdk_tray *handle;
+@property(nonatomic, strong) NSStatusItem *item;
+@property(nonatomic, strong) NSMenu *menu;
+- (void)invoke:(id)sender;
+- (void)refreshMenu;
+@end
@interface ZGL : NSObject
@property(nonatomic, strong) NSOpenGLContext *context;
@property(nonatomic, weak) ZWindow *owner;
@@ -857,6 +865,7 @@ static uhdk_key logical(NSEvent *e) {
@end
@interface ZMenuAction : NSObject
@property(nonatomic) uint64_t command;
+@property(nonatomic) uhdk_tray *tray;
@property(nonatomic) uint32_t role;
@property(nonatomic, weak) ZWindow *window;
- (void)invoke:(id)sender;
@@ -864,6 +873,13 @@ static uhdk_key logical(NSEvent *e) {
@implementation ZMenuAction
- (void)invoke:(id)sender {
(void)sender;
+ if (self.tray) {
+ uhdk_menu_item item = {0};
+ item.command_id = self.command;
+ item.role = self.role;
+ z_tray_command(self.tray, &item);
+ return;
+ }
host.popupSelected = YES;
ZWindow *w = self.window;
if (!w)
@@ -928,7 +944,7 @@ static NSString *shortcut(uhdk_key key) {
encoding:NSUTF32LittleEndianStringEncoding];
return @"";
}
-static NSMenu *makeMenu(uhdk_menu *menu, ZWindow *window) {
+static NSMenu *makeMenuFor(uhdk_menu *menu, ZWindow *window, uhdk_tray *tray) {
NSMenu *native = [[NSMenu alloc] initWithTitle:@""];
native.autoenablesItems = NO;
uint64_t len = 0;
@@ -959,14 +975,19 @@ static NSMenu *makeMenu(uhdk_menu *menu, ZWindow *window) {
target.command = item->command_id;
target.role = item->role;
target.window = window;
+ target.tray = tray;
entry.target = target;
entry.representedObject = target;
if (item->submenu)
- entry.submenu = makeMenu(item->submenu, window);
+ entry.submenu = makeMenuFor(item->submenu, window, tray);
[native addItem:entry];
}
return native;
}
+static NSMenu *makeMenu(uhdk_menu *menu, ZWindow *window) {
+ return makeMenuFor(menu, window, NULL);
+}
+#include "tray.inc"
@implementation ZHost
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
(void)sender;
@@ -1016,6 +1037,8 @@ static NSMenu *makeMenu(uhdk_menu *menu, ZWindow *window) {
}
uhdk_menu *menu = selected.menu ?: self.appMenu;
NSApp.mainMenu = menu ? makeMenu(menu, selected) : self.fallbackMenu;
+ for (ZTray *tray in self.trays)
+ [tray refreshMenu];
}
- (void)preferences {
NSAppearanceName appearance = [NSApp.effectiveAppearance
@@ -1300,6 +1323,7 @@ uhdk_status z_native_start(uhdk_session *app, uhdk_text name) {
host = [ZHost new];
host.app = app;
host.windows = [NSMutableArray array];
+ host.trays = [NSMutableArray array];
host.observers = [NSMutableArray array];
NSMenu *menu = [NSMenu new];
NSMenuItem *item = [NSMenuItem new];
@@ -1428,7 +1452,15 @@ void z_native_destroy(uint32_t kind, void *native) {
return;
@autoreleasepool {
id value = kind == Z_KIND_GL ? (__bridge id)native : CFBridgingRelease(native);
- if (kind == Z_KIND_WINDOW) {
+ if (kind == Z_KIND_TRAY) {
+ ZTray *tray = value;
+ [tray.menu cancelTracking];
+ tray.item.menu = nil;
+ tray.item.button.target = nil;
+ [NSStatusBar.systemStatusBar removeStatusItem:tray.item];
+ tray.item = nil;
+ [host.trays removeObject:tray];
+ } else if (kind == Z_KIND_WINDOW) {
ZWindow *w = value;
if (w.menu) {
uhdk_menu_release(w.menu);
diff --git a/src/macos/tray.inc b/src/macos/tray.inc
new file mode 100644
index 0000000..a142026
--- /dev/null
+++ b/src/macos/tray.inc
@@ -0,0 +1,79 @@
+/* AppKit status items share the library's retained menu model and event queue. */
+@implementation ZTray
+- (void)refreshMenu {
+ const uhdk_tray_desc *desc = z_tray_desc(self.handle);
+ [self.menu cancelTracking];
+ self.menu = desc->menu ? makeMenuFor(desc->menu, nil, self.handle) : nil;
+ self.item.menu = desc->menu_on_primary ? self.menu : nil;
+}
+- (void)invoke:(id)sender {
+ (void)sender;
+ if (NSApp.currentEvent.type == NSEventTypeRightMouseUp) {
+ if (self.menu)
+ [self.menu popUpMenuPositioningItem:nil
+ atLocation:NSMakePoint(0, self.item.button.bounds.size.height)
+ inView:self.item.button];
+ } else {
+ z_tray_activate(
+ self.handle,
+ NSApp.currentEvent.type == NSEventTypeOtherMouseUp ? UHDK_TRAY_ACTIVATE_SECONDARY
+ : UHDK_TRAY_ACTIVATE_PRIMARY
+ );
+ }
+}
+@end
+
+uhdk_status z_native_tray_update(uhdk_tray *handle, const uhdk_tray_desc *desc) {
+ @autoreleasepool {
+ const uhdk_image *i = &desc->icon;
+ NSBitmapImageRep *rep =
+ [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
+ pixelsWide:i->width
+ pixelsHigh:i->height
+ bitsPerSample:8
+ samplesPerPixel:4
+ hasAlpha:YES
+ isPlanar:NO
+ colorSpaceName:NSCalibratedRGBColorSpace
+ bitmapFormat:NSBitmapFormatAlphaNonpremultiplied
+ bytesPerRow:i->width * 4
+ bitsPerPixel:32];
+ if (!rep)
+ return UHDK_STATUS_OUT_OF_MEMORY;
+ for (uint32_t y = 0; y < i->height; y++)
+ memcpy(
+ rep.bitmapData + (size_t)y * rep.bytesPerRow,
+ i->pixels.ptr + (size_t)y * i->width * 4,
+ (size_t)i->width * 4
+ );
+ CGFloat height = 18;
+ NSSize size = NSMakeSize(height * i->width / i->height, height);
+ rep.size = size;
+ NSImage *image = [[NSImage alloc] initWithSize:size];
+ [image addRepresentation:rep];
+ image.template = desc->template_image != 0;
+ ZTray *tray = (__bridge ZTray *)z_object_native(handle);
+ if (!tray) {
+ tray = [ZTray new];
+ tray.handle = handle;
+ tray.item =
+ [NSStatusBar.systemStatusBar statusItemWithLength:NSVariableStatusItemLength];
+ if (!tray.item)
+ return UHDK_STATUS_UNAVAILABLE;
+ tray.item.autosaveName = str(desc->id);
+ tray.item.button.target = tray;
+ tray.item.button.action = @selector(invoke:);
+ [tray.item.button sendActionOn:NSEventMaskLeftMouseUp | NSEventMaskRightMouseUp |
+ NSEventMaskOtherMouseUp];
+ [host.trays addObject:tray];
+ z_object_set_native(handle, (__bridge_retained void *)tray);
+ }
+ tray.item.button.image = image;
+ tray.item.button.toolTip = str(desc->tooltip.len ? desc->tooltip : desc->title);
+ [tray.item.button setAccessibilityLabel:str(desc->title)];
+ [tray refreshMenu];
+ tray.item.visible = !desc->hidden;
+ z_tray_state(handle, (uhdk_bool)tray.item.visible, UHDK_STATUS_OK);
+ return UHDK_STATUS_OK;
+ }
+}
diff --git a/src/native.h b/src/native.h
index bd196e4..48ab117 100644
--- a/src/native.h
+++ b/src/native.h
@@ -57,6 +57,8 @@ typedef struct z_event {
uhdk_edit_event edit;
uhdk_drop_files_event drop_files;
uhdk_menu_event menu;
+ uhdk_tray_event tray;
+ uhdk_tray_state_event tray_state;
uhdk_watch_event watch;
z_request_result request;
uhdk_cycle_end_event cycle_end;
@@ -104,7 +106,8 @@ enum {
Z_KIND_GL,
Z_KIND_FILE,
Z_KIND_MENU,
- Z_KIND_WATCH
+ Z_KIND_WATCH,
+ Z_KIND_TRAY
};
#define Z_DEFERRED UINT32_MAX
/* Generic command storage is private, never exposed to consumers. */
@@ -138,6 +141,11 @@ void z_native_destroy(uint32_t kind, void *native);
uhdk_status z_native_gl(void *context, uint32_t op, void *out);
uhdk_status z_native_gl_proc(void *context, uhdk_text, uhdk_gl_proc *);
void z_native_handles(void *, uhdk_native_window *);
+uhdk_status z_native_tray_update(uhdk_tray *, const uhdk_tray_desc *);
+const uhdk_tray_desc *z_tray_desc(uhdk_tray *);
+void z_tray_state(uhdk_tray *, uhdk_bool available, uhdk_status);
+void z_tray_activate(uhdk_tray *, uhdk_tray_activation);
+void z_tray_command(uhdk_tray *, const uhdk_menu_item *);
/* Pure path conversions (no file access); copied synchronously by z_file_init. */
uhdk_status z_native_file_init(uhdk_file *, uhdk_bytes path, uhdk_text uri, void *grant);
diff --git a/src/root.zig b/src/root.zig
index b8e7e80..2226941 100644
--- a/src/root.zig
+++ b/src/root.zig
@@ -10,6 +10,7 @@ comptime {
checkExports(@import("api/files.zig"));
checkExports(@import("api/menus.zig"));
checkExports(@import("api/desktop.zig"));
+ checkExports(@import("api/tray.zig"));
_ = @import("callbacks.zig");
if (@import("builtin").os.tag == .linux) _ = @import("linux/native.zig");
}
diff --git a/src/runtime.zig b/src/runtime.zig
index 76ac478..79621d5 100644
--- a/src/runtime.zig
+++ b/src/runtime.zig
@@ -898,6 +898,7 @@ pub fn dispatch(handle: ?*c.uhdk_session) void {
const status = c.z_native_execute(handle, &command.data, command.id, &result);
if (status != c.Z_DEFERRED and command.data.op == c.Z_DESTROY) {
const resource = fromObjectHandle(command.data.target);
+ if (resource.payload == .tray) @import("api/tray.zig").clear(resource);
if (resource.payload == .watch) {
if (resource.payload.watch.owner) |root| release(root);
resource.payload.watch.owner = null;
diff --git a/src/windows/native.c b/src/windows/native.c
index 8a5c55c..31a4028 100644
--- a/src/windows/native.c
+++ b/src/windows/native.c
@@ -1503,10 +1503,13 @@ void z_native_cancel(uint64_t id) {
if (host.popup_id == id)
EndMenu();
}
+static void destroyTray(void *native);
void z_native_destroy(uint32_t kind, void *native) {
if (!native)
return;
- if (kind == Z_KIND_GL) {
+ if (kind == Z_KIND_TRAY) {
+ destroyTray(native);
+ } else if (kind == Z_KIND_GL) {
Window *w = native;
Graphics *g = w->graphics;
if (!g)
@@ -1618,7 +1621,7 @@ static uhdk_status clipboardRead(uint64_t id, uint64_t limit) {
profileFree(text);
return Z_DEFERRED;
}
-static uhdk_status setIcon(const uhdk_image *image) {
+static HICON createIcon(const uhdk_image *image) {
BITMAPV5HEADER header = {0};
header.bV5Size = sizeof(header);
header.bV5Width = (LONG)image->width;
@@ -1635,7 +1638,7 @@ static uhdk_status setIcon(const uhdk_image *image) {
HBITMAP color = CreateDIBSection(dc, (BITMAPINFO *)&header, DIB_RGB_COLORS, &pixels, NULL, 0);
ReleaseDC(NULL, dc);
if (!color)
- return UHDK_STATUS_OS_ERROR;
+ return NULL;
for (uint32_t y = 0; y < image->height; y++)
for (uint32_t x = 0; x < image->width; x++) {
const uint8_t *p = image->pixels.ptr + ((size_t)y * image->width + x) * 4;
@@ -1654,6 +1657,14 @@ static uhdk_status setIcon(const uhdk_image *image) {
DeleteObject(color);
if (mask)
DeleteObject(mask);
+ if (!icon)
+ return NULL;
+ return icon;
+}
+#include "tray.inc"
+
+static uhdk_status setIcon(const uhdk_image *image) {
+ HICON icon = createIcon(image);
if (!icon)
return UHDK_STATUS_OS_ERROR;
for (Window *w = host.windows; w; w = w->next) {
diff --git a/src/windows/tray.inc b/src/windows/tray.inc
new file mode 100644
index 0000000..96fc9a2
--- /dev/null
+++ b/src/windows/tray.inc
@@ -0,0 +1,226 @@
+/* Included after image/menu helpers. Each icon owns a hidden top-level HWND to
+ * receive Shell recovery broadcasts even when application windows are hidden. */
+typedef struct Tray {
+ uhdk_tray *handle;
+ HWND window;
+ HICON icon;
+ GUID identity;
+ WCHAR tooltip[128];
+ BOOL added, destroyed;
+ unsigned refs;
+ HMENU tracking;
+} Tray;
+static const WCHAR tray_class[] = L"UHDK.Tray";
+static UINT tray_restart;
+#define Z_TRAY_MESSAGE (WM_APP + 20)
+
+static NOTIFYICONDATAW trayData(Tray *t) {
+ NOTIFYICONDATAW data = {0};
+ data.cbSize = sizeof(data);
+ data.hWnd = t->window;
+ data.uID = 1;
+ data.guidItem = t->identity;
+ data.uFlags = NIF_GUID | NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_SHOWTIP;
+ data.uCallbackMessage = Z_TRAY_MESSAGE;
+ data.hIcon = t->icon;
+ memcpy(data.szTip, t->tooltip, sizeof(t->tooltip));
+ return data;
+}
+static void traySync(Tray *t) {
+ NOTIFYICONDATAW data = trayData(t);
+ if (z_tray_desc(t->handle)->hidden) {
+ if (t->added)
+ Shell_NotifyIconW(NIM_DELETE, &data);
+ t->added = FALSE;
+ z_tray_state(t->handle, UHDK_FALSE, UHDK_STATUS_OK);
+ return;
+ }
+ BOOL was_added = t->added;
+ BOOL ok = Shell_NotifyIconW(was_added ? NIM_MODIFY : NIM_ADD, &data);
+ if (!ok && was_added)
+ ok = Shell_NotifyIconW(NIM_ADD, &data);
+ t->added = ok;
+ if (ok) {
+ data.uVersion = NOTIFYICON_VERSION_4;
+ if (!Shell_NotifyIconW(NIM_SETVERSION, &data)) {
+ Shell_NotifyIconW(NIM_DELETE, &data);
+ t->added = FALSE;
+ }
+ }
+ z_tray_state(
+ t->handle, (uhdk_bool)t->added, t->added ? UHDK_STATUS_OK : UHDK_STATUS_UNAVAILABLE
+ );
+}
+static void trayRelease(Tray *t) {
+ if (--t->refs == 0) {
+ if (t->icon)
+ DestroyIcon(t->icon);
+ profileFree(t);
+ }
+}
+static void trayMenu(Tray *t, POINT point) {
+ uhdk_menu *root = z_tray_desc(t->handle)->menu;
+ if (!root || t->tracking)
+ return;
+ HMENU menu = buildMenu(root, TRUE);
+ if (!menu)
+ return;
+ t->refs++;
+ uhdk_menu_retain(root);
+ t->tracking = menu;
+ if (point.x == -1 && point.y == -1) {
+ NOTIFYICONIDENTIFIER id = {0};
+ id.cbSize = sizeof(id);
+ id.hWnd = t->window;
+ id.uID = 1;
+ id.guidItem = t->identity;
+ RECT rect;
+ if (SUCCEEDED(Shell_NotifyIconGetRect(&id, &rect)))
+ point = (POINT){rect.left, rect.bottom};
+ else
+ GetCursorPos(&point);
+ }
+ SetForegroundWindow(t->window);
+ TrackPopupMenuEx(
+ menu, TPM_LEFTALIGN | TPM_BOTTOMALIGN | TPM_RIGHTBUTTON, point.x, point.y, t->window, NULL
+ );
+ t->tracking = NULL;
+ if (!t->destroyed) {
+ PostMessageW(t->window, WM_NULL, 0, 0);
+ NOTIFYICONDATAW data = trayData(t);
+ Shell_NotifyIconW(NIM_SETFOCUS, &data);
+ }
+ DestroyMenu(menu);
+ uhdk_menu_release(root);
+ trayRelease(t);
+}
+static LRESULT CALLBACK trayProc(HWND window, UINT message, WPARAM wp, LPARAM lp) {
+ Tray *t = (Tray *)GetWindowLongPtrW(window, GWLP_USERDATA);
+ if (message == WM_NCCREATE) {
+ t = ((CREATESTRUCTW *)lp)->lpCreateParams;
+ t->window = window;
+ SetWindowLongPtrW(window, GWLP_USERDATA, (LONG_PTR)t);
+ }
+ if (!t || t->destroyed)
+ return DefWindowProcW(window, message, wp, lp);
+ if (tray_restart && message == tray_restart) {
+ t->added = FALSE;
+ traySync(t);
+ return 0;
+ }
+ if (message == Z_TRAY_MESSAGE) {
+ POINT point = {GET_X_LPARAM(wp), GET_Y_LPARAM(wp)};
+ switch (LOWORD(lp)) {
+ case NIN_SELECT:
+ case NIN_KEYSELECT:
+ if (z_tray_desc(t->handle)->menu_on_primary)
+ trayMenu(t, point);
+ else
+ z_tray_activate(t->handle, UHDK_TRAY_ACTIVATE_PRIMARY);
+ break;
+ case WM_CONTEXTMENU:
+ trayMenu(t, point);
+ break;
+ case WM_MBUTTONUP:
+ z_tray_activate(t->handle, UHDK_TRAY_ACTIVATE_SECONDARY);
+ break;
+ }
+ return 0;
+ }
+ if (message == WM_MENUCOMMAND && t->tracking) {
+ MENUITEMINFOW item = {0};
+ item.cbSize = sizeof(item);
+ item.fMask = MIIM_DATA;
+ if (GetMenuItemInfoW((HMENU)lp, (UINT)wp, TRUE, &item))
+ z_tray_command(t->handle, (const uhdk_menu_item *)item.dwItemData);
+ return 0;
+ }
+ return DefWindowProcW(window, message, wp, lp);
+}
+
+uhdk_status z_native_tray_update(uhdk_tray *handle, const uhdk_tray_desc *desc) {
+ HICON icon = createIcon(&desc->icon);
+ if (!icon)
+ return UHDK_STATUS_OS_ERROR;
+ WCHAR *tooltip = wide(desc->tooltip.len ? desc->tooltip : desc->title);
+ if (!tooltip) {
+ DestroyIcon(icon);
+ return UHDK_STATUS_OUT_OF_MEMORY;
+ }
+ Tray *t = z_object_native(handle);
+ if (!t) {
+ t = profileCalloc(1, sizeof(*t));
+ if (!t) {
+ DestroyIcon(icon);
+ profileFree(tooltip);
+ return UHDK_STATUS_OUT_OF_MEMORY;
+ }
+ t->handle = handle;
+ t->refs = 1;
+ /* Stable identity scoped by executable and application-defined item ID. */
+ uint64_t hashes[2] = {14695981039346656037ull, 7809847782465536322ull};
+ WCHAR executable[32768];
+ DWORD len = GetModuleFileNameW(NULL, executable, 32768);
+ for (unsigned j = 0; j < 2; j++) {
+ for (DWORD i = 0; i < len; i++)
+ hashes[j] = (hashes[j] ^ executable[i]) * 1099511628211ull;
+ for (uint64_t i = 0; i < desc->id.len; i++)
+ hashes[j] = (hashes[j] ^ (uint8_t)desc->id.ptr[i]) * 1099511628211ull;
+ }
+ memcpy(&t->identity, hashes, sizeof(t->identity));
+ WNDCLASSEXW cls = {0};
+ cls.cbSize = sizeof(cls);
+ cls.lpfnWndProc = trayProc;
+ cls.hInstance = GetModuleHandleW(NULL);
+ cls.lpszClassName = tray_class;
+ tray_restart = RegisterWindowMessageW(L"TaskbarCreated");
+ if ((!RegisterClassExW(&cls) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) ||
+ !CreateWindowExW(
+ WS_EX_TOOLWINDOW,
+ tray_class,
+ L"",
+ WS_POPUP,
+ 0,
+ 0,
+ 0,
+ 0,
+ NULL,
+ NULL,
+ cls.hInstance,
+ t
+ )) {
+ profileFree(t);
+ profileFree(tooltip);
+ DestroyIcon(icon);
+ return UHDK_STATUS_OS_ERROR;
+ }
+ z_object_set_native(handle, t);
+ }
+ if (t->tracking)
+ EndMenu();
+ if (t->icon)
+ DestroyIcon(t->icon);
+ t->icon = icon;
+ size_t length = wcslen(tooltip);
+ if (length > 127)
+ length = 127;
+ if (length && tooltip[length - 1] >= 0xd800 && tooltip[length - 1] <= 0xdbff)
+ length--;
+ memcpy(t->tooltip, tooltip, length * sizeof(WCHAR));
+ t->tooltip[length] = 0;
+ profileFree(tooltip);
+ traySync(t);
+ return UHDK_STATUS_OK;
+}
+static void destroyTray(void *native) {
+ Tray *t = native;
+ t->destroyed = TRUE;
+ if (t->tracking)
+ EndMenu();
+ NOTIFYICONDATAW data = trayData(t);
+ if (t->added)
+ Shell_NotifyIconW(NIM_DELETE, &data);
+ SetWindowLongPtrW(t->window, GWLP_USERDATA, 0);
+ DestroyWindow(t->window);
+ trayRelease(t);
+}