imsd-messages/interfaces/ImsdMessages.Bus-Notifier.cppm
Jorijn van der Graaf dd1108da58
main: show the window; --screenshot and --quit-after
The executable shows the window at start unless --daemon (which
--headless and --send imply), on Activate and Open from a second launch
or a notification (of the URIs an Open carries, its first sms: link),
and on an sms: link, which opens the conversation of its first recipient
at once (Number's SmsUriRecipient: the scheme in any case, the fields
after '?' dropped, percent-escapes decoded; then ConversationKey with
the country code known at that moment — --country's, else the one imsd's
status gave once it is in, else what the number itself carries — which
takes NormalizeNumber's result as a phone number — E.164, or digits: a
short code, a national number no country code completed — and nothing
else), or just the window when it names no phone number; the
conversation remembers the address as dialled and the plan of the SIM it
was typed under, and that SIM's statuses move its key (Number's
AfterStatus, one step, applied in App::Status: another SIM's status —
another operator's, or without operators another own number's code,
Number's SameSim — changes nothing, so a SIM change leaves the key and
the plan the address was typed under; the same SIM's fills in what the
plan lacks, and the key follows from its digits to the centre's stand-in
and from any key to the own number's code once the plan has it, never
from one stand-in's key to another's and not while the code is lost, the
conversation it moves to shown at its latest message — and only while
nothing is stored under the key: a text stored before the code arrived
keeps the conversation on the key its rows carry). The shell forwards
Sync's events to the window and the notifier closes a conversation's
notification when it is opened (one closed while its Notify is on its
way goes when the answer comes). --screenshot renders one frame outside
the compositor's pacing 2.5 s after start — 600 ms later where it has to
make the window first — and saves it as a PNG before quitting, or ends
with exit 1 when no frame was captured — with a line when no window
could render it or another instance is running (a flag that acts on the
window finds none there: the run forwards nothing), and without one when
the run ended before the capture (the display gone, a close that quits);
a PNG the library cannot write is not noticed at this commit, and a
capture that throws ends the process — the verification path for a
machine without eyes, which must not depend on a desktop that repaints —
and --quit-after ends a bench on its own clock (a number of seconds its
timer can take: anything else is refused); a --send errand ended by
anything but its final state — that clock — exits 2, as it does on a
signal, its end latched before the loop stops; --screenshot beside
--send or --quit is refused, neither having a window. The window is torn
down in order before the bus client stops, and when the compositor's
connection breaks the process ends, so the next launch starts afresh. A
window the library cannot make (no display, no Vulkan driver) is logged
by Ui's Show and the start ends with exit 1, as a start without its
database does; a resident instance logs it and runs on without one, and
a later Activate or Open logs the same at once, the device's set-up
running only once.

Tested: tests/Number, the sms: links (a query, an escape, a list, the
scheme in capitals, no number), the keys of typed addresses, SameSim
(the same operator, another operator of one country, a status without
its operator, nothing known, own numbers' codes without operators) and
AfterStatus through the statuses a typed address meets: the stand-in
completing its digits while the plan learns the operator; another
stand-in, a lost code and another operator's status — its own number's
code the stand-in's or not — changing nothing; rows keeping the key
while the plan learns the code; the own number's code moving the
stand-in's key, at once or once nothing is stored; a key the own
number's code made, and its plan, staying under another SIM and under
its own SIM's stand-in; an own code that makes the stand-in's key; a
short code; --country before the operator; no operators; no address; an
international address, under another SIM and under its own; and the
address as dialled making the key the address as typed made.
2026-11-18 01:12:27 +01:00

216 lines
11 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 close or 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));
}
// The conversation was opened: its notification goes.
void Close(const std::string& conversation) {
if (!conn) return;
waiting.erase(conversation);
// A Notify still on its way has no id yet: closed when it comes.
if (inFlight.contains(conversation)) closeWhenShown.insert(conversation);
const auto it = byConversation.find(conversation);
if (it == byConversation.end()) return;
g_dbus_connection_call(conn, notifyName, notifyPath, notifyName, "CloseNotification", g_variant_new("(u)", it->second), nullptr, G_DBUS_CALL_FLAGS_NONE, 5000, nullptr, nullptr, nullptr);
byId.erase(it->second);
byConversation.erase(it);
}
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));
if (self.closeWhenShown.contains(p->second)) {
// Closed while it was on its way: it goes now; a text that
// arrived meanwhile still gets its own below.
g_dbus_connection_call(self.conn, notifyName, notifyPath, notifyName, "CloseNotification", g_variant_new("(u)", id), nullptr, G_DBUS_CALL_FLAGS_NONE, 5000, nullptr, nullptr, nullptr);
self.byId.erase(id);
self.byConversation.erase(p->second);
}
}
self.closeWhenShown.erase(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_set<std::string> closeWhenShown; // closed while their Notify was on its way
std::unordered_map<std::string, Message> waiting; // the latest text that came meanwhile
};
}