diff --git a/AGENTS.md b/AGENTS.md index 394df46..ac275dd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ and §7.9 (Messaging) and §8.1 (the frozen one). |---|---| | `project.cpp` | The build description for Crafter.Build: four products (below) and the tests. | | `interfaces/ImsdMessages*.cppm` | `imsd-messages-core`: std + Crafter.DB, no GLib, no window — numbers, time, the model, word wrap, gestures, the message field's editing, the store, the sync logic. | -| `interfaces/ImsdMessages.Bus*.cppm` | `imsd-messages-bus`: GLib/GDBus — imsd's dictionaries, the client, notifications, the app's own bus name, the desktop portal's appearance settings. | +| `interfaces/ImsdMessages.Bus*.cppm` | `imsd-messages-bus`: GLib/GDBus — imsd's dictionaries, the client, notifications, the app's own bus name, the desktop portal (appearance, background). | | `interfaces/ImsdMessages.Ui*.cppm` | `imsd-messages-ui`: the window on Crafter.Graphics, driven from the GLib main loop. | | `implementations/main.cpp` | The executable `imsd-messages`. | | `tests//main.cpp` | One test per directory, declared in `project.cpp`. | diff --git a/implementations/main.cpp b/implementations/main.cpp index 9fd7874..237d628 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -430,6 +430,14 @@ int main(int argc, char** argv) { notifier.onOpen = [&app](const std::string& conversation) { app->Open(conversation); }; Log(std::format("{} {}; database {}; imsd on the {} bus; notifications {}; assets {}", version, o.send ? "sending one text" : o.daemon ? "resident" : "starting", dataDir.string(), o.session ? "session" : "system", notifier.Enabled() ? "on" : "off", AssetDir().string())); client.Start(sync); + // Inside its flatpak the app asks to run on with the window closed and + // to be started hidden at login; the errand and the smoke test do not. + std::optional background; + if (session && !o.send && !o.headless && Bus::InOwnFlatpak()) { + background.emplace(session, "To receive texts and show them while the window is closed", std::vector{ "imsd-messages", "--daemon" }); + background->onLog = Log; + background->Start(); + } if (o.uri) { // The link's conversation opens at once, keyed with the country code // known now — at a start --country's, else the number's own — and diff --git a/interfaces/ImsdMessages.Bus-Background.cppm b/interfaces/ImsdMessages.Bus-Background.cppm new file mode 100644 index 0000000..32e5b6a --- /dev/null +++ b/interfaces/ImsdMessages.Bus-Background.cppm @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: GPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// lint-disable-file no-char-pointer +/* +ImsdMessages.Bus:Background — inside its own flatpak, the app asks the +desktop portal's Background interface to keep running with the window +closed and to be started at login as `imsd-messages --daemon`, so texts +are imported and notified with no window open. The portal keeps the +answer and writes the login entry again at each request it grants, so a +deleted entry comes back while the background permission allows it. +Outside its own flatpak nothing is asked. +*/ +module; +#include +export module ImsdMessages.Bus:Background; +import std; +import :Instance; + +namespace ImsdMessages::Bus { + constexpr const char* desktopPortal = "org.freedesktop.portal.Desktop"; + constexpr const char* desktopPortalPath = "/org/freedesktop/portal/desktop"; + constexpr const char* backgroundIface = "org.freedesktop.portal.Background"; + constexpr const char* requestIface = "org.freedesktop.portal.Request"; +} + +export namespace ImsdMessages::Bus { + // Where the portal puts the Request of a call made with `token`: under + // the caller's unique name, the ':' dropped and every '.' a '_'. + std::string PortalRequestPath(std::string_view uniqueName, std::string_view token) { + std::string sender; + for (const char c : uniqueName) { + if (c == ':') continue; + sender.push_back(c == '.' ? '_' : c); + } + return std::format("{}/request/{}/{}", desktopPortalPath, sender, token); + } + + // RequestBackground's options: autostart with `commandline`, not through + // D-Bus activation. + GVariant* BackgroundOptions(std::string_view token, std::string_view reason, std::span commandline) { + GVariantBuilder cmd; + g_variant_builder_init(&cmd, G_VARIANT_TYPE("as")); + for (const std::string& arg : commandline) g_variant_builder_add(&cmd, "s", arg.c_str()); + GVariantBuilder options; + g_variant_builder_init(&options, G_VARIANT_TYPE("a{sv}")); + g_variant_builder_add(&options, "{sv}", "handle_token", g_variant_new_string(std::string(token).c_str())); + g_variant_builder_add(&options, "{sv}", "reason", g_variant_new_string(std::string(reason).c_str())); + g_variant_builder_add(&options, "{sv}", "autostart", g_variant_new_boolean(TRUE)); + g_variant_builder_add(&options, "{sv}", "commandline", g_variant_builder_end(&cmd)); + g_variant_builder_add(&options, "{sv}", "dbus-activatable", g_variant_new_boolean(FALSE)); + return g_variant_builder_end(&options); + } + + // This process is the app's own flatpak: flatpak sets FLATPAK_ID. + bool InOwnFlatpak() { + const gchar* id = g_getenv("FLATPAK_ID"); + return id && std::string_view(id) == appId; + } + + class BackgroundRequest { + public: + BackgroundRequest(GDBusConnection* session, std::string reason, std::vector commandline) : conn(session), reason(std::move(reason)), commandline(std::move(commandline)) {} + ~BackgroundRequest() { + if (conn && sub) g_dbus_connection_signal_unsubscribe(conn, sub); + } + BackgroundRequest(const BackgroundRequest&) = delete; + BackgroundRequest& operator=(const BackgroundRequest&) = delete; + + // What the portal answered, one line. + std::function onLog; + + void Start() { + if (!conn) return; + const gchar* unique = g_dbus_connection_get_unique_name(conn); + if (!unique) return; + const std::string token = std::format("imsd_messages_{}", g_random_int()); + // Subscribed before the call: the answer may come before the + // call returns the request's path. + Watch(PortalRequestPath(unique, token)); + g_dbus_connection_call(conn, desktopPortal, desktopPortalPath, backgroundIface, "RequestBackground", g_variant_new("(s@a{sv})", "", BackgroundOptions(token, reason, commandline)), G_VARIANT_TYPE("(o)"), G_DBUS_CALL_FLAGS_NONE, -1, nullptr, OnCalled, this); + } + + private: + void Watch(const std::string& requestPath) { + if (sub) g_dbus_connection_signal_unsubscribe(conn, sub); + path = requestPath; + sub = g_dbus_connection_signal_subscribe(conn, desktopPortal, requestIface, "Response", path.c_str(), nullptr, G_DBUS_SIGNAL_FLAGS_NONE, OnResponse, this, nullptr); + } + + void Log(std::string_view line) { + if (onLog) onLog(line); + } + + static void OnCalled(GObject* source, GAsyncResult* result, gpointer data) { + BackgroundRequest& self = *static_cast(data); + GError* err = nullptr; + GVariant* reply = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &err); + if (err) { + self.Log(std::format("autostart: the desktop portal did not take the request ({})", err->message)); + g_error_free(err); + if (self.sub) g_dbus_connection_signal_unsubscribe(self.conn, self.sub); + self.sub = 0; + return; + } + const gchar* handle = nullptr; + g_variant_get(reply, "(&o)", &handle); + // A portal older than handle_token picks its own path. + if (handle && self.path != handle) self.Watch(handle); + g_variant_unref(reply); + } + + static void OnResponse(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar*, GVariant* params, gpointer data) { + BackgroundRequest& self = *static_cast(data); + guint32 response = 2; + GVariant* results = nullptr; + g_variant_get(params, "(u@a{sv})", &response, &results); + gboolean background = FALSE; + gboolean autostart = FALSE; + if (results) { + g_variant_lookup(results, "background", "b", &background); + g_variant_lookup(results, "autostart", "b", &autostart); + g_variant_unref(results); + } + if (response == 0) self.Log(std::format("autostart: running in the background {}, starting at login {}", background ? "allowed" : "refused", autostart ? "on" : "off")); + else self.Log(response == 1 ? "autostart: the desktop portal refused the request" : "autostart: the request ended without an answer"); + g_dbus_connection_signal_unsubscribe(self.conn, self.sub); + self.sub = 0; + } + + GDBusConnection* conn; + std::string reason; + std::vector commandline; + std::string path; + guint sub = 0; + }; +} diff --git a/interfaces/ImsdMessages.Bus.cppm b/interfaces/ImsdMessages.Bus.cppm index 9083426..b9c5d81 100644 --- a/interfaces/ImsdMessages.Bus.cppm +++ b/interfaces/ImsdMessages.Bus.cppm @@ -6,7 +6,7 @@ ImsdMessages.Bus — the GLib side of imsd-messages: the GDBus client of 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, the app's own session-bus name and -the desktop portal's appearance settings. No window: the executable wires +the desktop portal (appearance, background). No window: the executable wires this to the UI. */ export module ImsdMessages.Bus; @@ -15,3 +15,4 @@ export import :Client; export import :Notifier; export import :Instance; export import :Appearance; +export import :Background; diff --git a/project.cpp b/project.cpp index 278a19d..87fb040 100644 --- a/project.cpp +++ b/project.cpp @@ -112,7 +112,7 @@ extern "C" Configuration CrafterBuildProject(std::span a // imsd-messages-bus — the GLib side: imsd's dictionaries, the GDBus client // of net.catcrafts.IMS1.Messaging, the desktop notifications, the app's - // own session-bus name and the desktop portal's appearance settings. No + // own session-bus name and the desktop portal (appearance, background). No // window. static auto Bus = std::make_unique(); Bus->path = "./"; @@ -122,12 +122,13 @@ extern "C" Configuration CrafterBuildProject(std::span a Bus->type = ConfigurationType::LibraryStatic; Bus->dependencies = { Core.get() }; { - std::array ifaces = { + std::array ifaces = { "interfaces/ImsdMessages.Bus", "interfaces/ImsdMessages.Bus-Variant", "interfaces/ImsdMessages.Bus-Client", "interfaces/ImsdMessages.Bus-Notifier", "interfaces/ImsdMessages.Bus-Appearance", + "interfaces/ImsdMessages.Bus-Background", "interfaces/ImsdMessages.Bus-Instance", }; std::array impls = {}; @@ -184,11 +185,16 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("Sync").Dependencies({ Core.get() }); cfg.AddTest("Gesture").Dependencies({ Core.get() }); cfg.AddTest("Edit").Dependencies({ Core.get() }); - // The bus library's decoding test includes GLib's headers: the library's - // compile flags (its link flags come with the library). - TestBuilder decode = cfg.AddTest("Decode"); - decode.Dependencies({ Core.get(), Bus.get() }); - for (const std::string& flag : gio.compile) decode.CompileFlag(flag); + // The bus library's tests include GLib's headers: the library's compile + // flags (its link flags come with the library). Decode names the core's + // types too; Portal imports the bus library alone. + const auto busTest = [&](std::string_view name, std::vector deps) { + TestBuilder test = cfg.AddTest(std::string(name)); + test.Dependencies(std::move(deps)); + for (const std::string& flag : gio.compile) test.CompileFlag(flag); + }; + busTest("Decode", { Core.get(), Bus.get() }); + busTest("Portal", { Bus.get() }); LintRules::AddRules(cfg); return cfg; diff --git a/tests/Portal/main.cpp b/tests/Portal/main.cpp new file mode 100644 index 0000000..1c704f8 --- /dev/null +++ b/tests/Portal/main.cpp @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// lint-disable-file no-char-pointer +// The desktop portal's side of the bus layer: where a request's answer +// arrives, and the options the Background request carries. +#include + +import std; +import ImsdMessages.Bus; +using namespace ImsdMessages; + +namespace { + +std::int32_t failures = 0; + +void Check(bool ok, std::string_view what) { + std::println("{} {}", ok ? "PASS" : "FAIL", what); + if (!ok) ++failures; +} + +std::string LookupString(GVariant* dict, const char* key) { + const gchar* value = nullptr; + return g_variant_lookup(dict, key, "&s", &value) && value ? std::string(value) : std::string(""); +} + +std::optional LookupBool(GVariant* dict, const char* key) { + gboolean value = FALSE; + if (!g_variant_lookup(dict, key, "b", &value)) return std::nullopt; + return value != FALSE; +} + +} + +int main() { + Check(Bus::PortalRequestPath(":1.42", "imsd_messages_7") == "/org/freedesktop/portal/desktop/request/1_42/imsd_messages_7", "a unique name loses its ':' and its '.' becomes '_'"); + Check(Bus::PortalRequestPath(":1.2345", "t") == "/org/freedesktop/portal/desktop/request/1_2345/t", "every digit of the connection number stays"); + + const std::vector commandline = { "imsd-messages", "--daemon" }; + GVariant* options = g_variant_ref_sink(Bus::BackgroundOptions("tok", "to receive texts", commandline)); + Check(g_variant_is_of_type(options, G_VARIANT_TYPE("a{sv}")), "the options are an a{sv}"); + Check(LookupString(options, "handle_token") == "tok", "handle_token is the token"); + Check(LookupString(options, "reason") == "to receive texts", "reason is passed through"); + Check(LookupBool(options, "autostart") == true, "autostart is asked for"); + Check(LookupBool(options, "dbus-activatable") == false, "the autostart entry runs the command line, not D-Bus activation"); + GVariant* cmd = g_variant_lookup_value(options, "commandline", G_VARIANT_TYPE("as")); + std::vector got; + if (cmd) { + gsize n = 0; + const gchar** strv = g_variant_get_strv(cmd, &n); + for (gsize i = 0; i < n; ++i) got.emplace_back(strv[i]); + g_free(static_cast(strv)); + g_variant_unref(cmd); + } + Check(got == commandline, "commandline is the daemon's argv, in order"); + g_variant_unref(options); + + if (failures) std::println("{} check(s) failed", failures); + return failures ? 1 : 0; +}