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).
194 lines
9.8 KiB
C++
194 lines
9.8 KiB
C++
// 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
|
|
};
|
|
}
|