Bus: the GDBus client, imsd's dictionaries, the notifier and the owned name

The GLib side of the app. Variant reads imsd's Received dictionary by
key and type as its SmsVariant writes it (`to`, the number the text
arrived for, a tel: URI read like the status's `ppi`; `operator`, the
SIM it arrived under), the GetStatus one with the subscriber's own
number and the SIM's operator in it (`ppi`, a tel: URI as the frozen
interface gives it; `operator`), and maps a GError to the core's error
kinds off GDBus's own mapping. Client is the Sync logic's transport:
asynchronous calls with their continuations as user data — every reply
guarded where it is delivered (OnCallDone), as are the signal handlers
and the name watch's callbacks: a throw is a fault the events hear, not
the end of the process — the calls behind imsd's polkit gate allow
interaction: Subscribe, List and Delete wait two minutes; Send has no
bound of the client's, since imsd sends the text once its prompt lets
the call through, however late, and a Send given up on would be failed
by Sync and be sent all the same; GetStatus ten seconds — (one call: the
Messaging status carries the own number, imsd reading both from one
snapshot; AGENTS.md §1 names both interfaces), the Messaging and
RegistrationChanged signals, and a watch on net.catcrafts.IMS1 whose
appeared callback is where Sync subscribes. Notifier shows one desktop
notification per conversation and replaces it as more texts arrive: one
Notify at a time per conversation, since the id to replace comes with
the answer; its default action asks the app for that conversation; the
body is escaped when the server renders markup (GetCapabilities, asked
once; Plasma and GNOME do), so a text's '<' or '&' shows as typed.
Instance owns net.catcrafts.ImsdMessages and serves
org.freedesktop.Application there, the Desktop Entry Specification's
interface of a running application: Activate, Open and ActivateAction,
each with its platform data — sent empty and not read: nothing in the
app can use an activation token yet — and one action, quit, any other
refused (the object registered before the name is asked for, so a launch
that forwards the moment the name is granted finds it; Own tells a name
another instance holds from a request that failed or was refused, and
keeps the error's words); it forwards a call to the owner. project.cpp
computes the gio flags once for the bus library, the executable and the
Decode test.

Tested: tests/Decode (every key of imsd's Received dictionary, one with
ten of them, GetStatus, the own number, the SIM's operator, the error
kinds, the markup escape, the parameters of the instance's three calls).
This commit is contained in:
Jorijn van der Graaf 2026-10-17 23:45:29 +02:00
commit dcf1aecafd
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
10 changed files with 930 additions and 31 deletions

View file

@ -1,10 +1,210 @@
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// lint-disable-file no-char-pointer
/*
ImsdMessages.Bus:Instance — one app per session: Own() takes
net.catcrafts.ImsdMessages on the session bus — and tells a name another
instance holds from a request that failed or was refused — and serves
org.freedesktop.Application there, the Desktop Entry Specification's
interface of a running application — Activate, Open and ActivateAction,
each with its platform data — whose one action is "quit"; the Forward
calls make one of them on the owner. The platform data (a launch's
activation token) is sent empty and not read: nothing in the app can use
a token yet.
*/
module;
#include <gio/gio.h>
export module ImsdMessages.Bus:Instance;
import std;
export namespace ImsdMessages::Bus {
namespace ImsdMessages::Bus {
// The specification's object path: the application id, its dots as slashes.
constexpr const char* ownPath = "/net/catcrafts/ImsdMessages";
constexpr const char* ownIface = "org.freedesktop.Application";
constexpr const char* introspection = R"xml(
<node>
<interface name="org.freedesktop.Application">
<method name="Activate">
<arg type="a{sv}" name="platform_data" direction="in"/>
</method>
<method name="Open">
<arg type="as" name="uris" direction="in"/>
<arg type="a{sv}" name="platform_data" direction="in"/>
</method>
<method name="ActivateAction">
<arg type="s" name="action_name" direction="in"/>
<arg type="av" name="parameter" direction="in"/>
<arg type="a{sv}" name="platform_data" direction="in"/>
</method>
</interface>
</node>)xml";
// org.freedesktop.DBus.RequestName
constexpr guint32 flagDoNotQueue = 4;
constexpr guint32 replyPrimaryOwner = 1;
constexpr guint32 replyAlreadyOwner = 4;
}
export namespace ImsdMessages::Bus {
inline constexpr std::string_view appId = "net.catcrafts.ImsdMessages";
inline constexpr std::string_view quitAction = "quit";
// The parameters of the three calls (floating), their platform data
// empty, and what the instance reads out of them.
GVariant* ActivateParameters() { return g_variant_new("(a{sv})", nullptr); }
GVariant* OpenParameters(std::span<const std::string> uris) {
GVariantBuilder list;
g_variant_builder_init(&list, G_VARIANT_TYPE("as"));
for (const std::string& uri : uris) g_variant_builder_add(&list, "s", uri.c_str());
return g_variant_new("(asa{sv})", &list, nullptr);
}
GVariant* ActionParameters(std::string_view action) { return g_variant_new("(sava{sv})", std::string(action).c_str(), nullptr, nullptr); }
std::vector<std::string> OpenUris(GVariant* params) {
GVariant* list = g_variant_get_child_value(params, 0);
gsize n = 0;
const gchar** strings = g_variant_get_strv(list, &n); // the array is ours, its strings the variant's
std::vector<std::string> uris(strings, strings + n);
g_free(strings);
g_variant_unref(list);
return uris;
}
std::string ActionName(GVariant* params) {
const gchar* name = nullptr;
g_variant_get_child(params, 0, "&s", &name);
return name;
}
class Instance {
public:
struct Handlers {
std::function<void()> activate;
std::function<void(std::vector<std::string> uris)> open;
std::function<void()> quit;
};
Instance(GDBusConnection* session, Handlers handlers) : conn(session), handlers(std::move(handlers)) {}
~Instance() {
if (conn && registration) g_dbus_connection_unregister_object(conn, registration);
if (node) g_dbus_node_info_unref(node);
}
Instance(const Instance&) = delete;
Instance& operator=(const Instance&) = delete;
// What became of the name: ours; another instance's; or neither
// shown — the bus gave an error to the request or no answer in its
// five seconds, or the connection took no object (Failure has the
// error's words).
enum class Owning : std::uint8_t { Owned, Taken, Failed };
// Becomes the owner and serves the object.
Owning Own() {
if (!conn) {
failure = "no session bus";
return Owning::Failed;
}
// The object before the name (GLib's own order for an owned
// name): a launch that forwards the moment the bus grants the
// name finds the object there. Without the name the object is
// reachable by this connection's unique name alone.
GError* err = nullptr;
node = g_dbus_node_info_new_for_xml(introspection, nullptr);
static const GDBusInterfaceVTable vtable = { OnMethod, nullptr, nullptr, {} };
registration = g_dbus_connection_register_object(conn, ownPath, node->interfaces[0], &vtable, this, nullptr, &err);
if (err) return Fail(err);
GVariant* reply = g_dbus_connection_call_sync(conn, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName", g_variant_new("(su)", std::string(appId).c_str(), flagDoNotQueue), G_VARIANT_TYPE("(u)"), G_DBUS_CALL_FLAGS_NONE, 5000, nullptr, &err);
if (err) {
Unregister();
return Fail(err);
}
guint32 result = 0;
g_variant_get(reply, "(u)", &result);
g_variant_unref(reply);
// Asked not to queue, the bus answers that the name is ours or
// that it exists.
if (result != replyPrimaryOwner && result != replyAlreadyOwner) {
Unregister();
return Owning::Taken;
}
return Owning::Owned;
}
// Why Own failed: the error's message, the bus's or GLib's.
const std::string& Failure() const noexcept { return failure; }
// Ask the running instance: for its window, for a link's
// conversation, to exit. False when none answered, or when it
// knows no such action.
static bool ForwardActivate(GDBusConnection* session) { return Call(session, "Activate", ActivateParameters()); }
static bool ForwardOpen(GDBusConnection* session, const std::string& uri) { return Call(session, "Open", OpenParameters(std::span<const std::string>(&uri, 1))); }
static bool ForwardQuit(GDBusConnection* session) { return Call(session, "ActivateAction", ActionParameters(quitAction)); }
private:
static bool Call(GDBusConnection* session, const char* method, GVariant* params) {
if (!session) {
g_variant_unref(g_variant_ref_sink(params));
return false;
}
GError* err = nullptr;
GVariant* reply = g_dbus_connection_call_sync(session, std::string(appId).c_str(), ownPath, ownIface, method, params, nullptr, G_DBUS_CALL_FLAGS_NONE, 5000, nullptr, &err);
if (err) {
g_error_free(err);
return false;
}
g_variant_unref(reply);
return true;
}
Owning Fail(GError* err) {
failure = err->message;
g_error_free(err);
return Owning::Failed;
}
// The object goes when the name was not ours to take.
void Unregister() {
if (registration) g_dbus_connection_unregister_object(conn, registration);
registration = 0;
}
// GDBus has checked the call against the interface above: the
// method is one of the three, its parameters of its signature.
static void OnMethod(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* method, GVariant* params, GDBusMethodInvocation* inv, gpointer data) {
Instance& self = *static_cast<Instance*>(data);
const std::string_view name = method;
std::vector<std::string> uris;
if (name == "Open") uris = OpenUris(params);
if (name == "ActivateAction" && ActionName(params) != quitAction) {
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.InvalidArgs", "no such action");
return;
}
// The reply first: the caller (a forwarding launch, waiting 5 s)
// asked for the instance to act, not to have acted — a first
// Show creates the window, which can outlast its wait. A
// handler that throws is the instance's fault to log, not the
// process's end (GLib's dispatch encloses no try).
g_dbus_method_invocation_return_value(inv, nullptr);
try {
if (name == "Activate") {
if (self.handlers.activate) self.handlers.activate();
} else if (name == "Open") {
if (self.handlers.open) self.handlers.open(std::move(uris));
} else {
if (self.handlers.quit) self.handlers.quit();
}
} catch (const std::exception& e) {
g_warning("imsd-messages: the %s handler threw: %s", method, e.what());
}
}
GDBusConnection* conn;
Handlers handlers;
GDBusNodeInfo* node = nullptr;
guint registration = 0;
std::string failure;
};
}