#Calling Methods and Signals
Building D-Bus method calls by hand is tedious. You have to allocate a message, append destination headers, assign serials, encode parameters with proper alignment, send the packet, wait for the reply, match the serial, and decode the return value.
Goose wraps all of this behind the Proxy struct.
#Creating a Proxy
A Proxy binds your connection to a remote destination, object path, and interface:
/// A local representation of a remote D-Bus object.
pub const Proxy = struct {
conn: *Connection,
dest: [:0]const u8,
path: [:0]const u8,
interface: [:0]const u8,
/// Creates a new Proxy for a remote object.
/// `dest`: The well-known name or unique name of the destination connection.
/// `path`: The object path on the destination.
/// `interface`: The default interface to use for method calls.
pub fn init(conn: *Connection, dest: [:0]const u8, path: [:0]const u8, interface: [:0]const u8) Proxy {
return .{
.conn = conn,
.dest = dest,
.path = path,
.interface = interface,
};
}
/// Performs a low-level method call on a specific interface.
pub fn rawCall(self: Proxy, iface: [:0]const u8, method: [:0]const u8, args: anytype) !MethodResult {
var encoder = try BodyEncoder.encode(self.conn.__allocator, args);
defer encoder.deinit();
const reply = try self.conn.methodCall(
self.dest,
self.path,
iface,
method,
encoder.signature(),
encoder.body(),
);
if (reply.isError()) {
const err_name = reply.getErrorName() orelse "UnknownError";
var decoder = BodyDecoder.fromMessage(self.conn.__allocator, reply);
const err_msg = decoder.decode(GStr) catch GStr.new("(no error message)");
std.debug.print("[goose] DBus Error: {s}: {s}\n", .{ err_name, err_msg.s });
self.conn.freeMessage(@constCast(&reply));
return error.RemoteError;
}
return MethodResult{
.msg = reply,
.conn = self.conn,
.arena = std.heap.ArenaAllocator.init(self.conn.__allocator),
};
}
/// Invokes a method on the remote object using the default interface.
/// `args` can be a single value or a tuple of values.
/// Returns a MethodResult owning the reply message.
pub fn call(self: Proxy, method: [:0]const u8, args: anytype) !MethodResult {
return self.rawCall(self.interface, method, args);
}
/// Helper to get a property value.
/// T must be a union (Variant) that can hold the expected property type.
/// D-Bus Get returns a Variant ('v').
/// The returned value is allocated using the connection's allocator if it contains strings or slices.
pub fn getProperty(self: Proxy, comptime T: type, name: [:0]const u8) !T {
var result = try self.rawCall("org.freedesktop.DBus.Properties", "Get", .{ GStr.new(self.interface), GStr.new(name) });
defer result.deinit();
var dec = BodyDecoder.fromMessage(self.conn.__allocator, result.msg);
return try dec.decodeAlloc(T);
}
/// Helper to set a property value.
/// `value` must be a union (Variant) representing the new value.
pub fn setProperty(self: Proxy, name: [:0]const u8, value: anytype) !void {
var result = try self.rawCall("org.freedesktop.DBus.Properties", "Set", .{ GStr.new(self.interface), GStr.new(name), value });
result.deinit();
}
/// Subscribes to a D-Bus signal on this proxy's interface and registers a typed callback.
/// `SignalArgs` must be a tuple representing the signal's argument types (e.g. `@Tuple(&[_]type{ GStr, u32 })`).
pub fn connectSignal(
self: Proxy,
comptime SignalArgs: type,
member: [:0]const u8,
ctx: anytype,
comptime callback: fn (@TypeOf(ctx), SignalArgs) void,
) !void {
const match = try std.fmt.allocPrintSentinel(self.conn.__allocator, "type='signal',interface='{s}',member='{s}'", .{ self.interface, member }, 0);
defer self.conn.__allocator.free(match);
try self.conn.addMatch(match);
const Wrapper = struct {
fn handle(raw_ctx: ?*anyopaque, msg: core.Message) void {
const typed_ctx: @TypeOf(ctx) = @ptrCast(@alignCast(raw_ctx));
var arena = std.heap.ArenaAllocator.init(msg.allocator orelse return);
defer arena.deinit();
var dec = BodyDecoder.fromMessage(arena.allocator(), msg);
const args = dec.decode(SignalArgs) catch return;
callback(typed_ctx, args);
}
};
try self.conn.registerSignalHandler(
self.interface,
member,
Wrapper.handle,
@ptrCast(@alignCast(@constCast(ctx))),
);
}
};Initializing a proxy doesn't send any traffic over the network; it's just a local handle:
const proxy = goose.proxy;
const notif = proxy.Proxy.init(
&conn,
"org.freedesktop.Notifications", // Destination bus name
"/org/freedesktop/Notifications", // Object path
"org.freedesktop.Notifications", // Default interface
);
#Invoking Methods
To invoke a remote method, call proxy.call(). Arguments are passed as an anonymous tuple:
var result = try notif.call("GetServerInformation", .{});
defer result.deinit();
#Decoding the Response
The returned MethodResult owns the raw D-Bus reply packet:
/// Result of a D-Bus method call.
/// Owns the reply message and provides methods to decode its body.
pub const MethodResult = struct {
msg: core.Message,
conn: *Connection,
arena: std.heap.ArenaAllocator,
/// Releases resources associated with the result message.
pub fn deinit(self: *MethodResult) void {
self.conn.freeMessage(&self.msg);
self.arena.deinit();
}
/// Returns a BodyDecoder to read the result body.
/// Note: The decoder's lifetime is tied to the result.
pub fn reader(self: *MethodResult) BodyDecoder {
return BodyDecoder.fromMessage(self.arena.allocator(), self.msg);
}
/// Convenience method to decode a single value of type T from the reply body.
/// Note: The MethodResult must still be explicitly deinitialized after use
/// if T borrows memory (like strings or slices) from the message body.
pub fn expect(self: *MethodResult, comptime T: type) !T {
var dec = self.reader();
return try dec.decode(T);
}
/// Convenience method to decode and deep-copy a value of type T from the reply body.
/// The memory is allocated using the connection's allocator and outlives the MethodResult.
pub fn expectAlloc(self: *MethodResult, comptime T: type) !T {
var dec = BodyDecoder.fromMessage(self.conn.__allocator, self.msg);
return try dec.decodeAlloc(T);
}
};You have two ways to read the data:
#1. Borrowed Reads (`result.expect(T)`)
Decodes values directly referencing the message payload. This is fast and performs zero heap allocations for strings or slices:
const ServerInfo = struct {
name: GStr,
vendor: GStr,
version: GStr,
spec_version: GStr,
};
const info = try result.expect(ServerInfo);
std.debug.print("Running {s} version {s}\n", .{ info.name.s, info.version.s });
Note: Because info.name.s points directly into the reply buffer, you cannot use it after calling result.deinit().
#2. Owned Deep-Copies (`result.expectAlloc(T)`)
If you need the data to outlive the method result, use expectAlloc:
const owned_string = try result.expectAlloc(GStr);
// owned_string.s is allocated via conn.__allocator and remains valid after result.deinit()
#Remote Error Handling
If the remote service returns a D-Bus error packet, call() prints the diagnostic error name and returns error.RemoteError:
var result = notif.call("NonExistentMethod", .{}) catch |err| {
if (err == error.RemoteError) {
std.debug.print("The remote service returned an error!\n", .{});
}
return err;
};
defer result.deinit();
#Reading and Writing Properties
Services expose properties through org.freedesktop.DBus.Properties. You can read and write them directly through helper methods on the proxy:
// Read a property
const VariantType = goose.core.value.Value.Variant(MyPropsUnion);
const current_volume = try notif.getProperty(VariantType, "Volume");
// Write a property
try notif.setProperty("Volume", @as(u32, 90));
#Subscribing to Signals
D-Bus signals are broadcast events emitted when state changes or events occur. When you call p.connectSignal(), Goose automatically registers the appropriate D-Bus match rule (AddMatch) with the broker and routes incoming signal frames straight to your typed callback.
#Signal Callback Recipe
- Define a callback function taking a context pointer and an argument tuple:
const Counter = struct { received: u32 = 0 };
fn onNotificationClosed(ctx: *Counter, args: @Tuple(&[_]type{ u32, u32 })) void {
const id = args[0];
const reason = args[1];
ctx.received += 1;
std.debug.print("Notification {d} closed with reason {d}\n", .{ id, reason });
}
- Register the callback on the proxy:
var counter = Counter{};
try notif.connectSignal(
@Tuple(&[_]type{ u32, u32 }),
"NotificationClosed",
&counter,
onNotificationClosed,
);
#Practical Example: Sending a Desktop Notification
Here is a complete, standalone program that sends a real notification to your desktop environment:
const std = @import("std");
const goose = @import("goose");
const GStr = goose.core.value.GStr;
const GVariant = core.value.GVariant;
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
const io = init.io;
var conn = try goose.Connection.init(allocator, .Session, io, init.environ_map);
defer conn.close();
const notif = goose.proxy.Proxy.init(
&conn,
"org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
"org.freedesktop.Notifications",
);
// Prepare Notify arguments
const empty_actions = [_]GStr{};
const empty_hints = std.StringHashMap(GVariant).init(allocator);
const args = .{
GStr.new("Goose"), // app_name
@as(u32, 0), // replaces_id
GStr.new("dialog-information"), // app_icon
GStr.new("Honk!"), // summary
GStr.new("Pure Zig D-Bus in action."), // body
empty_actions[0..], // actions
empty_hints, // hints
@as(i32, 4000), // expire_timeout (ms)
};
var reply = try notif.call("Notify", args);
defer reply.deinit();
const notification_id = try reply.expect(u32);
std.debug.print("Notification sent! ID: {d}\n", .{notification_id});
}