// 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 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(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 onOpen; // What the service answered (the headless mode logs it). std::function 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(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(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> p(static_cast*>(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(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 byConversation; std::unordered_map byId; std::unordered_set inFlight; // conversations with a Notify on its way std::unordered_set closeWhenShown; // closed while their Notify was on its way std::unordered_map waiting; // the latest text that came meanwhile }; }