imsd-messages/interfaces/ImsdMessages.Bus-Notifier.cppm
Jorijn van der Graaf 20e687452f
Ui, main: the new-conversation screen and the long-press sheets
The + opens a screen with a number field (its placeholder "Number", a
parameter of the compose field now) and Start; the number becomes a
conversation key through Number's ConversationKey, as an sms: link's
does (E.164 through the country code, a short code as digits), anything
else is refused in place. A long press on a conversation row offers to
delete the conversation, on a message to copy its text to the clipboard
or delete it; only those two have one: App tells the recogniser before
each press whether what it lands on has a long press (GestureDetector's
longPress), and without one a press held as long — on a button, a field,
a sheet's row — stays a tap at its release, so a slow finger presses the
button all the same. A sheet draws on the overlay layer over a scrim and
pushes its regions last, so they win the hit test, and the wheel scrolls
nothing under it; Escape, the back arrow and a tap outside dismiss it.
Deleting a conversation also closes its notification and drops its
draft; the + keeps the draft of the conversation it leaves, as Back
does, and so does a view that closes because its last message was
deleted. The deletes go through Sync (Erase, EraseConversation: the
commit before, which keeps a deleted text deleted). The number field's
box is drawn by its screen, as the send bar's is by the bar: the shared
field drawing paints no background of its own. Opening a conversation,
from a notification or a link, leaves the new-conversation screen and
any sheet, and the + leaves any sheet. A key whose press changed the
screen acts once: held, its repeats are not the new screen's — Enter,
which started the conversation, would type line breaks into its field,
and Escape would go on back, from a sheet through the conversation and
its draft. A sheet that asks to delete a conversation goes when a text
arrives for it: a yes would delete that text unread. A press on the
conversation's row opens no such sheet either while the row it aimed at
had not shown the text — the regions are a frame's: the press that is
down when the text arrives, and one that comes down before the next
frame is drawn, have no long press; a release before the long-press time
is still the row's tap, while the row stays under the finger.

--new and --bench-sheet put either on screen for the bench
(--bench-sheet conversation or message, each on the screen a long press
opens it over: another value is refused, and one that finds nothing to
press says so in the log), and are window flags as --screenshot is.

Tested: the screens and the sheets by the bench (--new, --bench-sheet)
and the phone step's screenshots; the deletes' logic with the commit
before, in tests/Store and tests/Sync; the press without a long press in
tests/Gesture (the timer gives no long press and a move within the slop
nothing; the release is the tap, however late; a slide off the control
is a drag); a deleted conversation's draft dropped, in tests/Edit. The
press on a row a text arrived for has no bench: none holds a finger on a
row.
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 or deleted: 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
};
}