// 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 export module ImsdMessages.Bus:Instance; import std; 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( )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 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 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 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 activate; std::function uris)> open; std::function 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(&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(data); const std::string_view name = method; std::vector 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; }; }