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:
parent
f70e9dc35b
commit
dcf1aecafd
10 changed files with 930 additions and 31 deletions
|
|
@ -70,6 +70,7 @@ export namespace ImsdMessages {
|
|||
virtual void OnReceived(const ReceivedMessage& message) = 0;
|
||||
virtual void OnStateChanged(std::string_view id, std::string_view state, std::string_view reason) = 0;
|
||||
virtual void OnRegistrationChanged(bool registered) = 0;
|
||||
virtual void OnFault(std::string_view what) {} // a callback threw (a read, an allocation; the store catches its writes): logged, not fatal
|
||||
};
|
||||
|
||||
// What Sync tells the UI and the notifier. A call can come from inside
|
||||
|
|
@ -494,6 +495,8 @@ export namespace ImsdMessages {
|
|||
for (const auto& [id, r] : waiting) Import(r, true);
|
||||
}
|
||||
|
||||
void OnFault(std::string_view what) override { listener.OnLog(std::format("a bus callback failed: {}", what)); }
|
||||
|
||||
void DeleteStored(const std::string& id) {
|
||||
if (deleting.contains(id) || undeletable.contains(id)) return;
|
||||
deleting.insert(id);
|
||||
|
|
|
|||
|
|
@ -1,10 +1,226 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// lint-disable-file no-char-pointer
|
||||
/*
|
||||
ImsdMessages.Bus:Client — the GDBus client of net.catcrafts.IMS1.Messaging,
|
||||
the Sync logic's transport. Every call is asynchronous and answers on the
|
||||
GLib main loop; the signals and the name watch feed ImsdEvents (Sync), the
|
||||
watch's appeared callback being where Sync subscribes. One connection:
|
||||
the system bus, or the session bus for `imsd --session`.
|
||||
*/
|
||||
module;
|
||||
#include <gio/gio.h>
|
||||
export module ImsdMessages.Bus:Client;
|
||||
import std;
|
||||
import ImsdMessages;
|
||||
import :Variant;
|
||||
|
||||
namespace ImsdMessages::Bus {
|
||||
constexpr const char* imsdName = "net.catcrafts.IMS1";
|
||||
constexpr const char* imsdPath = "/net/catcrafts/IMS1";
|
||||
constexpr const char* imsdIface = "net.catcrafts.IMS1";
|
||||
constexpr const char* messagingIface = "net.catcrafts.IMS1.Messaging";
|
||||
constexpr gint callTimeoutMs = 10000;
|
||||
// Subscribe, List and Delete sit behind imsd's polkit gate, which allows
|
||||
// interaction: a rule that prompts gets two minutes.
|
||||
constexpr gint gatedTimeoutMs = 120000;
|
||||
// Send sits behind the gate too, and has no bound of the client's
|
||||
// (GDBus: G_MAXINT): imsd waits on a prompt without one and sends the
|
||||
// text once the prompt lets the call through, so a Send given up on
|
||||
// here would be failed by Sync and be sent all the same. The call ends
|
||||
// with imsd's answer, or with the bus's when imsd leaves it.
|
||||
constexpr gint sendTimeoutMs = G_MAXINT;
|
||||
}
|
||||
|
||||
export namespace ImsdMessages::Bus {
|
||||
class ImsdClient : public ImsdTransport {
|
||||
public:
|
||||
explicit ImsdClient(GDBusConnection* conn) : conn(conn) {}
|
||||
~ImsdClient() override { Stop(); }
|
||||
ImsdClient(const ImsdClient&) = delete;
|
||||
ImsdClient& operator=(const ImsdClient&) = delete;
|
||||
|
||||
// Installs the signal subscriptions and the name watch.
|
||||
void Start(ImsdEvents& e) {
|
||||
events = &e;
|
||||
messagingSub = g_dbus_connection_signal_subscribe(conn, imsdName, messagingIface, nullptr, imsdPath, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, OnMessagingSignal, this, nullptr);
|
||||
baseSub = g_dbus_connection_signal_subscribe(conn, imsdName, imsdIface, "RegistrationChanged", imsdPath, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, OnBaseSignal, this, nullptr);
|
||||
watch = g_bus_watch_name_on_connection(conn, imsdName, G_BUS_NAME_WATCHER_FLAGS_NONE, OnAppeared, OnVanished, this, nullptr);
|
||||
}
|
||||
|
||||
void Stop() {
|
||||
if (watch) g_bus_unwatch_name(watch);
|
||||
if (messagingSub) g_dbus_connection_signal_unsubscribe(conn, messagingSub);
|
||||
if (baseSub) g_dbus_connection_signal_unsubscribe(conn, baseSub);
|
||||
watch = 0;
|
||||
messagingSub = 0;
|
||||
baseSub = 0;
|
||||
events = nullptr;
|
||||
}
|
||||
|
||||
void Subscribe(Done done) override {
|
||||
Call("Subscribe", nullptr, nullptr, [done = std::move(done)](GVariant*, GError* err) {
|
||||
done(err ? std::optional<BusError>(ErrorFrom(err)) : std::nullopt);
|
||||
});
|
||||
}
|
||||
|
||||
// The Messaging status, the subscriber's own number in it (`ppi`, as
|
||||
// the frozen interface gives it: imsd reads both from one snapshot,
|
||||
// so one call never lacks a number it has).
|
||||
void GetStatus(std::function<void(StatusResult)> done) override {
|
||||
Call("GetStatus", nullptr, G_VARIANT_TYPE("(a{sv})"), [done = std::move(done)](GVariant* reply, GError* err) {
|
||||
if (err) {
|
||||
done(std::unexpected(ErrorFrom(err)));
|
||||
return;
|
||||
}
|
||||
GVariant* dict = g_variant_get_child_value(reply, 0);
|
||||
Status s = StatusFromVariant(dict);
|
||||
g_variant_unref(dict);
|
||||
done(std::move(s));
|
||||
});
|
||||
}
|
||||
|
||||
void List(std::function<void(ListResult)> done) override {
|
||||
Call("List", nullptr, G_VARIANT_TYPE("(a(sa{sv}))"), [done = std::move(done)](GVariant* reply, GError* err) {
|
||||
if (err) {
|
||||
done(std::unexpected(ErrorFrom(err)));
|
||||
return;
|
||||
}
|
||||
std::vector<ReceivedMessage> out;
|
||||
GVariant* array = g_variant_get_child_value(reply, 0);
|
||||
GVariantIter it;
|
||||
g_variant_iter_init(&it, array);
|
||||
while (GVariant* item = g_variant_iter_next_value(&it)) {
|
||||
const gchar* id = nullptr;
|
||||
GVariant* dict = nullptr;
|
||||
g_variant_get(item, "(&s@a{sv})", &id, &dict);
|
||||
out.push_back(ReceivedFromVariant(id ? id : "", dict));
|
||||
g_variant_unref(dict);
|
||||
g_variant_unref(item);
|
||||
}
|
||||
g_variant_unref(array);
|
||||
done(std::move(out));
|
||||
});
|
||||
}
|
||||
|
||||
void Delete(std::string id, Done done) override {
|
||||
Call("Delete", g_variant_new("(s)", id.c_str()), nullptr, [done = std::move(done)](GVariant*, GError* err) {
|
||||
done(err ? std::optional<BusError>(ErrorFrom(err)) : std::nullopt);
|
||||
});
|
||||
}
|
||||
|
||||
void Send(std::string number, std::string text, bool statusReport, std::function<void(SendResult)> done) override {
|
||||
Call("Send", g_variant_new("(ss@a{sv})", number.c_str(), text.c_str(), SendOptions(statusReport)), G_VARIANT_TYPE("(s)"), [done = std::move(done)](GVariant* reply, GError* err) {
|
||||
if (err) {
|
||||
done(std::unexpected(ErrorFrom(err)));
|
||||
return;
|
||||
}
|
||||
const gchar* id = nullptr;
|
||||
g_variant_get(reply, "(&s)", &id);
|
||||
done(std::string(id ? id : ""));
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
// One pending call's continuation: exactly one of reply and err is
|
||||
// set; both are freed by OnCallDone after it ran.
|
||||
using Reply = std::function<void(GVariant* reply, GError* err)>;
|
||||
struct Pending { // one call's continuation and the client that hears a throw out of it
|
||||
Reply reply;
|
||||
ImsdClient* client;
|
||||
};
|
||||
|
||||
// A call on the Messaging interface; the client hears a throw out of
|
||||
// the reply as a fault (OnCallDone).
|
||||
void Call(const char* method, GVariant* params, const GVariantType* replyType, Reply reply) {
|
||||
const std::string_view name = method;
|
||||
const bool gated = name != "GetStatus";
|
||||
g_dbus_connection_call(conn, imsdName, imsdPath, messagingIface, method, params, replyType, gated ? G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION : G_DBUS_CALL_FLAGS_NONE, name == "Send" ? sendTimeoutMs : gated ? gatedTimeoutMs : callTimeoutMs, nullptr, OnCallDone, new Pending{ std::move(reply), this });
|
||||
}
|
||||
|
||||
// Every reply passes here, inside GLib's dispatch, which no try
|
||||
// encloses: a throw out of the continuation (a read, an allocation;
|
||||
// the store catches its writes) is the events' fault, not the end
|
||||
// of the process.
|
||||
static void OnCallDone(GObject* source, GAsyncResult* result, gpointer data) {
|
||||
std::unique_ptr<Pending> pending(static_cast<Pending*>(data));
|
||||
GError* err = nullptr;
|
||||
GVariant* value = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &err);
|
||||
try {
|
||||
pending->reply(value, err);
|
||||
} catch (const std::exception& e) {
|
||||
if (pending->client->events) pending->client->events->OnFault(e.what());
|
||||
}
|
||||
if (value) g_variant_unref(value);
|
||||
if (err) g_error_free(err);
|
||||
}
|
||||
|
||||
// The signal handlers run inside GLib's dispatch, which no try
|
||||
// encloses: a throw out of them is handed to the events as a fault
|
||||
// and the process goes on.
|
||||
static void OnMessagingSignal(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* signal, GVariant* params, gpointer data) {
|
||||
ImsdClient& self = *static_cast<ImsdClient*>(data);
|
||||
if (!self.events) return;
|
||||
try {
|
||||
const std::string_view name = signal;
|
||||
if (name == "Received") {
|
||||
const gchar* id = nullptr;
|
||||
GVariant* dict = nullptr;
|
||||
g_variant_get(params, "(&s@a{sv})", &id, &dict);
|
||||
const ReceivedMessage m = ReceivedFromVariant(id ? id : "", dict);
|
||||
g_variant_unref(dict);
|
||||
self.events->OnReceived(m);
|
||||
} else if (name == "StateChanged") {
|
||||
const gchar* id = nullptr;
|
||||
const gchar* state = nullptr;
|
||||
const gchar* reason = nullptr;
|
||||
g_variant_get(params, "(&s&s&s)", &id, &state, &reason);
|
||||
self.events->OnStateChanged(id ? id : "", state ? state : "", reason ? reason : "");
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
self.events->OnFault(e.what());
|
||||
}
|
||||
}
|
||||
|
||||
static void OnBaseSignal(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar*, GVariant* params, gpointer data) {
|
||||
ImsdClient& self = *static_cast<ImsdClient*>(data);
|
||||
if (!self.events) return;
|
||||
gboolean registered = FALSE;
|
||||
g_variant_get(params, "(b)", ®istered);
|
||||
try {
|
||||
self.events->OnRegistrationChanged(registered == TRUE);
|
||||
} catch (const std::exception& e) {
|
||||
self.events->OnFault(e.what());
|
||||
}
|
||||
}
|
||||
|
||||
// The name watch's callbacks, guarded as the replies and the signal
|
||||
// handlers are.
|
||||
static void OnAppeared(GDBusConnection*, const gchar*, const gchar*, gpointer data) {
|
||||
ImsdClient& self = *static_cast<ImsdClient*>(data);
|
||||
if (!self.events) return;
|
||||
try {
|
||||
self.events->OnImsdAppeared();
|
||||
} catch (const std::exception& e) {
|
||||
self.events->OnFault(e.what());
|
||||
}
|
||||
}
|
||||
|
||||
static void OnVanished(GDBusConnection*, const gchar*, gpointer data) {
|
||||
ImsdClient& self = *static_cast<ImsdClient*>(data);
|
||||
if (!self.events) return;
|
||||
try {
|
||||
self.events->OnImsdVanished();
|
||||
} catch (const std::exception& e) {
|
||||
self.events->OnFault(e.what());
|
||||
}
|
||||
}
|
||||
|
||||
GDBusConnection* conn;
|
||||
ImsdEvents* events = nullptr;
|
||||
guint messagingSub = 0;
|
||||
guint baseSub = 0;
|
||||
guint watch = 0;
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,194 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// lint-disable-file no-char-pointer
|
||||
/*
|
||||
ImsdMessages.Bus:Notifier — one desktop notification per conversation
|
||||
through org.freedesktop.Notifications on the session bus, replaced in
|
||||
place as more texts arrive; its default action asks the app to open that
|
||||
conversation. Without a session bus the notifier is off.
|
||||
*/
|
||||
module;
|
||||
#include <gio/gio.h>
|
||||
export module ImsdMessages.Bus:Notifier;
|
||||
import std;
|
||||
import ImsdMessages;
|
||||
import :Instance;
|
||||
|
||||
namespace ImsdMessages::Bus {
|
||||
constexpr const char* notifyName = "org.freedesktop.Notifications";
|
||||
constexpr const char* notifyPath = "/org/freedesktop/Notifications";
|
||||
// The longest preview, in code points.
|
||||
constexpr std::size_t previewCodepoints = 140;
|
||||
|
||||
// The first line with text on it, at most previewCodepoints long, "…"
|
||||
// when cut (exported for its test).
|
||||
export std::string Preview(std::string_view text) {
|
||||
while (!text.empty() && (text.front() == '\n' || text.front() == '\r' || text.front() == ' ' || text.front() == '\t')) text.remove_prefix(1); // the first line with text on it
|
||||
std::size_t i = 0;
|
||||
std::size_t count = 0;
|
||||
while (i < text.size() && count < previewCodepoints) {
|
||||
const std::size_t at = i;
|
||||
if (DecodeUtf8(text, i) == '\n') return std::format("{}\u2026", text.substr(0, at));
|
||||
++count;
|
||||
}
|
||||
if (i >= text.size()) return std::string(text);
|
||||
return std::format("{}\u2026", text.substr(0, i));
|
||||
}
|
||||
}
|
||||
|
||||
export namespace ImsdMessages::Bus {
|
||||
// The text as a server that renders the body as markup must get it
|
||||
// (g_markup_escape_text: & < > " ' as entities).
|
||||
std::string MarkupEscaped(std::string_view text) {
|
||||
gchar* escaped = g_markup_escape_text(text.data(), static_cast<gssize>(text.size()));
|
||||
std::string out(escaped);
|
||||
g_free(escaped);
|
||||
return out;
|
||||
}
|
||||
|
||||
class Notifier {
|
||||
public:
|
||||
explicit Notifier(GDBusConnection* session) : conn(session) {
|
||||
if (conn) sub = g_dbus_connection_signal_subscribe(conn, notifyName, notifyName, nullptr, notifyPath, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, OnSignal, this, nullptr);
|
||||
// Whether the server renders the body as markup (Plasma and GNOME
|
||||
// do), asked once; until it answers the body is escaped. The
|
||||
// cancellable outlives this object for a reply that comes after
|
||||
// it: the destructor cancels and clears the pointer the reply
|
||||
// would follow.
|
||||
if (conn) {
|
||||
capabilities = g_cancellable_new();
|
||||
g_object_set_data(G_OBJECT(capabilities), "notifier", this);
|
||||
g_dbus_connection_call(conn, notifyName, notifyPath, notifyName, "GetCapabilities", nullptr, G_VARIANT_TYPE("(as)"), G_DBUS_CALL_FLAGS_NONE, 5000, capabilities, OnCapabilities, g_object_ref(capabilities));
|
||||
}
|
||||
}
|
||||
~Notifier() {
|
||||
if (conn && sub) g_dbus_connection_signal_unsubscribe(conn, sub);
|
||||
if (capabilities) {
|
||||
g_object_set_data(G_OBJECT(capabilities), "notifier", nullptr);
|
||||
g_cancellable_cancel(capabilities);
|
||||
g_object_unref(capabilities);
|
||||
}
|
||||
}
|
||||
Notifier(const Notifier&) = delete;
|
||||
Notifier& operator=(const Notifier&) = delete;
|
||||
|
||||
// The user tapped the notification of a conversation.
|
||||
std::function<void(const std::string& conversation)> onOpen;
|
||||
// What the service answered (the headless mode logs it).
|
||||
std::function<void(std::string_view)> onLog;
|
||||
|
||||
bool Enabled() const noexcept { return conn != nullptr; }
|
||||
|
||||
void Notify(const Message& m) {
|
||||
if (!conn) return;
|
||||
// One Notify at a time per conversation: the id to replace comes
|
||||
// with the answer, so a text that arrives before it waits for it
|
||||
// and then replaces what the first one showed.
|
||||
if (inFlight.contains(m.conversation)) {
|
||||
waiting.insert_or_assign(m.conversation, m);
|
||||
return;
|
||||
}
|
||||
inFlight.insert(m.conversation);
|
||||
const guint32 replaces = byConversation.contains(m.conversation) ? byConversation[m.conversation] : 0;
|
||||
GVariantBuilder actions;
|
||||
g_variant_builder_init(&actions, G_VARIANT_TYPE("as"));
|
||||
g_variant_builder_add(&actions, "s", "default");
|
||||
g_variant_builder_add(&actions, "s", "Open");
|
||||
GVariantBuilder hints;
|
||||
g_variant_builder_init(&hints, G_VARIANT_TYPE("a{sv}"));
|
||||
g_variant_builder_add(&hints, "{sv}", "desktop-entry", g_variant_new_string(std::string(appId).c_str()));
|
||||
g_variant_builder_add(&hints, "{sv}", "category", g_variant_new_string("im.received"));
|
||||
g_variant_builder_add(&hints, "{sv}", "urgency", g_variant_new_byte(1));
|
||||
const std::string summary = DisplayNumber(m.conversation);
|
||||
const std::string body = bodyMarkup ? MarkupEscaped(Preview(m.text)) : Preview(m.text);
|
||||
// GDBus's default timeout (25 s): a server still coming up at login
|
||||
// answers late, and an answer that misses the timeout would leave a
|
||||
// notification the app cannot route.
|
||||
g_dbus_connection_call(conn, notifyName, notifyPath, notifyName, "Notify", g_variant_new("(susssasa{sv}i)", "imsd-messages", replaces, std::string(appId).c_str(), summary.c_str(), body.c_str(), &actions, &hints, -1), G_VARIANT_TYPE("(u)"), G_DBUS_CALL_FLAGS_NONE, -1, nullptr, OnNotified, new std::pair<Notifier*, std::string>(this, m.conversation));
|
||||
}
|
||||
|
||||
private:
|
||||
static void OnCapabilities(GObject* source, GAsyncResult* result, gpointer data) {
|
||||
GCancellable* cancellable = G_CANCELLABLE(data);
|
||||
Notifier* self = static_cast<Notifier*>(g_object_get_data(G_OBJECT(cancellable), "notifier"));
|
||||
GError* err = nullptr;
|
||||
GVariant* reply = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &err);
|
||||
if (err) {
|
||||
g_error_free(err); // the default stands
|
||||
} else {
|
||||
GVariantIter* names = nullptr;
|
||||
g_variant_get(reply, "(as)", &names);
|
||||
const gchar* name = nullptr;
|
||||
bool markup = false;
|
||||
while (g_variant_iter_loop(names, "&s", &name)) markup = markup || std::string_view(name) == "body-markup";
|
||||
g_variant_iter_free(names);
|
||||
g_variant_unref(reply);
|
||||
if (self) self->bodyMarkup = markup;
|
||||
}
|
||||
g_object_unref(cancellable);
|
||||
}
|
||||
|
||||
static void OnNotified(GObject* source, GAsyncResult* result, gpointer data) {
|
||||
std::unique_ptr<std::pair<Notifier*, std::string>> p(static_cast<std::pair<Notifier*, std::string>*>(data));
|
||||
GError* err = nullptr;
|
||||
GVariant* reply = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &err);
|
||||
Notifier& self = *p->first;
|
||||
if (err) {
|
||||
if (self.onLog) self.onLog(std::format("Notify for {} failed: {}", p->second, err->message));
|
||||
g_error_free(err);
|
||||
} else {
|
||||
guint32 id = 0;
|
||||
g_variant_get(reply, "(u)", &id);
|
||||
g_variant_unref(reply);
|
||||
self.byConversation[p->second] = id;
|
||||
self.byId[id] = p->second;
|
||||
if (self.onLog) self.onLog(std::format("notification {} shown for {}", id, p->second));
|
||||
}
|
||||
self.inFlight.erase(p->second);
|
||||
// A text that came while this one was on its way replaces it.
|
||||
if (const auto w = self.waiting.find(p->second); w != self.waiting.end()) {
|
||||
const Message next = w->second;
|
||||
self.waiting.erase(w);
|
||||
self.Notify(next);
|
||||
}
|
||||
}
|
||||
|
||||
static void OnSignal(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* signal, GVariant* params, gpointer data) {
|
||||
Notifier& self = *static_cast<Notifier*>(data);
|
||||
const std::string_view name = signal;
|
||||
if (name == "ActionInvoked") {
|
||||
guint32 id = 0;
|
||||
const gchar* action = nullptr;
|
||||
g_variant_get(params, "(u&s)", &id, &action);
|
||||
const auto it = self.byId.find(id);
|
||||
if (it != self.byId.end() && self.onOpen && action && std::string_view(action) == "default") {
|
||||
// The open runs inside GLib's dispatch, which no try encloses:
|
||||
// a throw is logged, not the process's end.
|
||||
try {
|
||||
self.onOpen(it->second);
|
||||
} catch (const std::exception& e) {
|
||||
g_warning("imsd-messages: the notification's open threw: %s", e.what());
|
||||
}
|
||||
}
|
||||
} else if (name == "NotificationClosed") {
|
||||
guint32 id = 0;
|
||||
guint32 reason = 0;
|
||||
g_variant_get(params, "(uu)", &id, &reason);
|
||||
const auto it = self.byId.find(id);
|
||||
if (it == self.byId.end()) return;
|
||||
self.byConversation.erase(it->second);
|
||||
self.byId.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
GDBusConnection* conn;
|
||||
guint sub = 0;
|
||||
GCancellable* capabilities = nullptr; // the GetCapabilities call; its qdata "notifier" points here while this object lives
|
||||
bool bodyMarkup = true; // the server renders the body as markup (so until it says otherwise)
|
||||
std::unordered_map<std::string, guint32> byConversation;
|
||||
std::unordered_map<guint32, std::string> byId;
|
||||
std::unordered_set<std::string> inFlight; // conversations with a Notify on its way
|
||||
std::unordered_map<std::string, Message> waiting; // the latest text that came meanwhile
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,130 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// lint-disable-file no-char-pointer
|
||||
/*
|
||||
ImsdMessages.Bus:Variant — imsd's dictionaries and errors as the core's
|
||||
types. The keys and types are those imsd writes (AGENTS.md §8.4: the
|
||||
Received dictionary of its SmsVariant, GetStatus's): a key that is
|
||||
missing or of another type reads as its default.
|
||||
*/
|
||||
module;
|
||||
#include <gio/gio.h>
|
||||
export module ImsdMessages.Bus:Variant;
|
||||
import std;
|
||||
import ImsdMessages;
|
||||
|
||||
namespace ImsdMessages::Bus {
|
||||
std::string LookupString(GVariant* dict, const char* key) {
|
||||
GVariant* v = g_variant_lookup_value(dict, key, G_VARIANT_TYPE_STRING);
|
||||
if (!v) return "";
|
||||
std::string s = g_variant_get_string(v, nullptr);
|
||||
g_variant_unref(v);
|
||||
return s;
|
||||
}
|
||||
|
||||
template <class T>
|
||||
T LookupScalar(GVariant* dict, const char* key, const GVariantType* type, T (*get)(GVariant*), T fallback) {
|
||||
GVariant* v = g_variant_lookup_value(dict, key, type);
|
||||
if (!v) return fallback;
|
||||
const T x = get(v);
|
||||
g_variant_unref(v);
|
||||
return x;
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> LookupBytes(GVariant* dict, const char* key) {
|
||||
GVariant* v = g_variant_lookup_value(dict, key, G_VARIANT_TYPE_BYTESTRING);
|
||||
if (!v) return {};
|
||||
gsize n = 0;
|
||||
const guint8* p = static_cast<const guint8*>(g_variant_get_fixed_array(v, &n, 1));
|
||||
std::vector<std::uint8_t> out(p, p + n);
|
||||
g_variant_unref(v);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::optional<std::uint32_t> LookupOptionalUint32(GVariant* dict, const char* key) {
|
||||
GVariant* v = g_variant_lookup_value(dict, key, G_VARIANT_TYPE_UINT32);
|
||||
if (!v) return std::nullopt;
|
||||
const std::uint32_t x = g_variant_get_uint32(v);
|
||||
g_variant_unref(v);
|
||||
return x;
|
||||
}
|
||||
}
|
||||
|
||||
export namespace ImsdMessages::Bus {
|
||||
// The GLib the bus layer is built against, for --version.
|
||||
// The GLib the bus layer runs on, for --version.
|
||||
inline const std::string glibVersion = std::format("{}.{}.{}", glib_major_version, glib_minor_version, glib_micro_version);
|
||||
|
||||
// The number of a tel: URI (the status's `ppi`, a Received's `to`);
|
||||
// "" for none or another kind of URI.
|
||||
std::string TelNumber(std::string_view uri) { return uri.starts_with("tel:") ? std::string(uri.substr(4)) : ""; }
|
||||
|
||||
// The a{sv} of a Received signal or a List entry.
|
||||
ReceivedMessage ReceivedFromVariant(std::string_view id, GVariant* dict) {
|
||||
ReceivedMessage m;
|
||||
m.imsdId = std::string(id);
|
||||
m.from = LookupString(dict, "from");
|
||||
m.text = LookupString(dict, "text");
|
||||
m.timestamp = LookupString(dict, "timestamp");
|
||||
m.received = LookupScalar<gint64>(dict, "received", G_VARIANT_TYPE_INT64, g_variant_get_int64, 0);
|
||||
m.sc = LookupString(dict, "sc");
|
||||
m.to = TelNumber(LookupString(dict, "to"));
|
||||
m.simOperator = LookupString(dict, "operator");
|
||||
m.smsClass = LookupScalar<gint32>(dict, "class", G_VARIANT_TYPE_INT32, g_variant_get_int32, -1);
|
||||
m.pid = LookupScalar<guint8>(dict, "pid", G_VARIANT_TYPE_BYTE, g_variant_get_byte, 0);
|
||||
m.dcs = LookupScalar<guint8>(dict, "dcs", G_VARIANT_TYPE_BYTE, g_variant_get_byte, 0);
|
||||
m.segments = LookupScalar<gint32>(dict, "segments", G_VARIANT_TYPE_INT32, g_variant_get_int32, 1);
|
||||
m.messageWaiting = LookupScalar<gboolean>(dict, "message-waiting", G_VARIANT_TYPE_BOOLEAN, g_variant_get_boolean, FALSE) == TRUE;
|
||||
m.portDst = LookupOptionalUint32(dict, "port-dst");
|
||||
m.portSrc = LookupOptionalUint32(dict, "port-src");
|
||||
m.data = LookupBytes(dict, "data");
|
||||
m.pdu = LookupBytes(dict, "pdu");
|
||||
return m;
|
||||
}
|
||||
|
||||
// The a{sv} of GetStatus.
|
||||
Status StatusFromVariant(GVariant* dict) {
|
||||
Status s;
|
||||
s.enabled = LookupScalar<gboolean>(dict, "enabled", G_VARIANT_TYPE_BOOLEAN, g_variant_get_boolean, FALSE) == TRUE;
|
||||
s.smsc = LookupString(dict, "smsc");
|
||||
s.ownNumber = TelNumber(LookupString(dict, "ppi")); // the frozen interface's `ppi`, in this answer too
|
||||
s.simOperator = LookupString(dict, "operator");
|
||||
s.registered = LookupScalar<gboolean>(dict, "registered", G_VARIANT_TYPE_BOOLEAN, g_variant_get_boolean, FALSE) == TRUE;
|
||||
s.subscribers = LookupScalar<guint32>(dict, "subscribers", G_VARIANT_TYPE_UINT32, g_variant_get_uint32, 0);
|
||||
return s;
|
||||
}
|
||||
|
||||
// A GError as the core's BusError; the remote error's name is read off
|
||||
// GDBus's mapping and stripped from the text. The caller frees err.
|
||||
BusError ErrorFrom(GError* err) {
|
||||
BusError e;
|
||||
if (!err) return e;
|
||||
if (err->domain == G_DBUS_ERROR) {
|
||||
switch (err->code) {
|
||||
case G_DBUS_ERROR_ACCESS_DENIED: e.kind = BusError::Kind::AccessDenied; break;
|
||||
case G_DBUS_ERROR_NOT_SUPPORTED: e.kind = BusError::Kind::NotSupported; break;
|
||||
case G_DBUS_ERROR_FILE_NOT_FOUND: e.kind = BusError::Kind::NotFound; break;
|
||||
case G_DBUS_ERROR_INVALID_ARGS: e.kind = BusError::Kind::InvalidArgs; break;
|
||||
case G_DBUS_ERROR_SERVICE_UNKNOWN:
|
||||
case G_DBUS_ERROR_NAME_HAS_NO_OWNER: e.kind = BusError::Kind::NoOwner; break;
|
||||
case G_DBUS_ERROR_NO_REPLY:
|
||||
case G_DBUS_ERROR_TIMEOUT:
|
||||
case G_DBUS_ERROR_TIMED_OUT: e.kind = BusError::Kind::Timeout; break;
|
||||
default: e.kind = BusError::Kind::Other; break;
|
||||
}
|
||||
} else if (g_error_matches(err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
|
||||
e.kind = BusError::Kind::Timeout;
|
||||
}
|
||||
g_dbus_error_strip_remote_error(err);
|
||||
e.message = err->message ? err->message : "";
|
||||
return e;
|
||||
}
|
||||
|
||||
// Send's options dictionary (floating).
|
||||
GVariant* SendOptions(bool statusReport) {
|
||||
GVariantBuilder b;
|
||||
g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}"));
|
||||
g_variant_builder_add(&b, "{sv}", "status-report", g_variant_new_boolean(statusReport ? TRUE : FALSE));
|
||||
return g_variant_builder_end(&b);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@
|
|||
|
||||
/*
|
||||
ImsdMessages.Bus — the GLib side of imsd-messages: the GDBus client of
|
||||
net.catcrafts.IMS1.Messaging on the system bus, the decoding of its
|
||||
imsd's /net/catcrafts/IMS1 on the system bus (the Messaging interface, and
|
||||
the frozen interface's registration signal), the decoding of its
|
||||
dictionaries, the desktop notifications, and the app's own session-bus name.
|
||||
No window: the executable wires this to the UI.
|
||||
*/
|
||||
|
|
|
|||
Loading…
Reference in a new issue