diff --git a/AGENTS.md b/AGENTS.md index 884c489..7156716 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,12 +11,16 @@ right and this file has a bug — fix it in the same change. ## 1. What imsd-messages is An SMS app for Linux phones (postmarketOS on the Fairphone 6 first; Plasma -Mobile and Phosh) whose only transport is imsd's D-Bus interface -`net.catcrafts.IMS1.Messaging` (system bus, object `/net/catcrafts/IMS1`). -imsd receives texts over IMS and keeps each one under `/var/lib/imsd/sms/` -until the app deletes it; the app subscribes to imsd's signals, imports the -stored messages into its own database and deletes imsd's copy. The interface -is documented in imsd's AGENTS.md §8.4 and §7.9. +Mobile and Phosh) whose transport is imsd's D-Bus object `/net/catcrafts/IMS1` +on the system bus: its `net.catcrafts.IMS1.Messaging` interface carries the +texts, the subscriber's own number and the SIM's operator (`GetStatus`'s +`ppi` and `operator`), and the frozen `net.catcrafts.IMS1` interface gives +the registration changes. imsd receives texts over IMS and keeps each one +it could store under `/var/lib/imsd/sms/` until the app deletes it; the app +subscribes to +imsd's signals, imports the stored messages into its own database and +deletes imsd's copy. The interfaces are documented in imsd's AGENTS.md §8.4 +and §7.9 (Messaging) and §8.1 (the frozen one). ## 2. Repository layout diff --git a/README.md b/README.md index e5ce224..de502bb 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ The SMS app for [imsd](https://forgejo.catcrafts.net/Catcrafts/imsd) on Linux phones. imsd 2.0.0 carries texts over IMS and keeps them until a messaging app takes them; this is that app. It speaks imsd's -`net.catcrafts.IMS1.Messaging` D-Bus interface and nothing else: no -ModemManager, no modem. +`net.catcrafts.IMS1.Messaging` D-Bus interface: no ModemManager, no +modem. Nothing to install yet. The flatpak will come from the Catcrafts remote: diff --git a/interfaces/ImsdMessages-Sync.cppm b/interfaces/ImsdMessages-Sync.cppm index cb45e57..c257367 100644 --- a/interfaces/ImsdMessages-Sync.cppm +++ b/interfaces/ImsdMessages-Sync.cppm @@ -70,6 +70,7 @@ export namespace ImsdMessages { virtual void OnReceived(const ReceivedMessage& message) = 0; virtual void OnStateChanged(std::string_view id, std::string_view state, std::string_view reason) = 0; virtual void OnRegistrationChanged(bool registered) = 0; + virtual void OnFault(std::string_view what) {} // a callback threw (a read, an allocation; the store catches its writes): logged, not fatal }; // What Sync tells the UI and the notifier. A call can come from inside @@ -494,6 +495,8 @@ export namespace ImsdMessages { for (const auto& [id, r] : waiting) Import(r, true); } + void OnFault(std::string_view what) override { listener.OnLog(std::format("a bus callback failed: {}", what)); } + void DeleteStored(const std::string& id) { if (deleting.contains(id) || undeletable.contains(id)) return; deleting.insert(id); diff --git a/interfaces/ImsdMessages.Bus-Client.cppm b/interfaces/ImsdMessages.Bus-Client.cppm index 1349840..b4ee0da 100644 --- a/interfaces/ImsdMessages.Bus-Client.cppm +++ b/interfaces/ImsdMessages.Bus-Client.cppm @@ -1,10 +1,226 @@ // SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® +// lint-disable-file no-char-pointer +/* +ImsdMessages.Bus:Client — the GDBus client of net.catcrafts.IMS1.Messaging, +the Sync logic's transport. Every call is asynchronous and answers on the +GLib main loop; the signals and the name watch feed ImsdEvents (Sync), the +watch's appeared callback being where Sync subscribes. One connection: +the system bus, or the session bus for `imsd --session`. +*/ module; #include export module ImsdMessages.Bus:Client; import std; +import ImsdMessages; +import :Variant; + +namespace ImsdMessages::Bus { + constexpr const char* imsdName = "net.catcrafts.IMS1"; + constexpr const char* imsdPath = "/net/catcrafts/IMS1"; + constexpr const char* imsdIface = "net.catcrafts.IMS1"; + constexpr const char* messagingIface = "net.catcrafts.IMS1.Messaging"; + constexpr gint callTimeoutMs = 10000; + // Subscribe, List and Delete sit behind imsd's polkit gate, which allows + // interaction: a rule that prompts gets two minutes. + constexpr gint gatedTimeoutMs = 120000; + // Send sits behind the gate too, and has no bound of the client's + // (GDBus: G_MAXINT): imsd waits on a prompt without one and sends the + // text once the prompt lets the call through, so a Send given up on + // here would be failed by Sync and be sent all the same. The call ends + // with imsd's answer, or with the bus's when imsd leaves it. + constexpr gint sendTimeoutMs = G_MAXINT; +} export namespace ImsdMessages::Bus { + class ImsdClient : public ImsdTransport { + public: + explicit ImsdClient(GDBusConnection* conn) : conn(conn) {} + ~ImsdClient() override { Stop(); } + ImsdClient(const ImsdClient&) = delete; + ImsdClient& operator=(const ImsdClient&) = delete; + + // Installs the signal subscriptions and the name watch. + void Start(ImsdEvents& e) { + events = &e; + messagingSub = g_dbus_connection_signal_subscribe(conn, imsdName, messagingIface, nullptr, imsdPath, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, OnMessagingSignal, this, nullptr); + baseSub = g_dbus_connection_signal_subscribe(conn, imsdName, imsdIface, "RegistrationChanged", imsdPath, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, OnBaseSignal, this, nullptr); + watch = g_bus_watch_name_on_connection(conn, imsdName, G_BUS_NAME_WATCHER_FLAGS_NONE, OnAppeared, OnVanished, this, nullptr); + } + + void Stop() { + if (watch) g_bus_unwatch_name(watch); + if (messagingSub) g_dbus_connection_signal_unsubscribe(conn, messagingSub); + if (baseSub) g_dbus_connection_signal_unsubscribe(conn, baseSub); + watch = 0; + messagingSub = 0; + baseSub = 0; + events = nullptr; + } + + void Subscribe(Done done) override { + Call("Subscribe", nullptr, nullptr, [done = std::move(done)](GVariant*, GError* err) { + done(err ? std::optional(ErrorFrom(err)) : std::nullopt); + }); + } + + // The Messaging status, the subscriber's own number in it (`ppi`, as + // the frozen interface gives it: imsd reads both from one snapshot, + // so one call never lacks a number it has). + void GetStatus(std::function done) override { + Call("GetStatus", nullptr, G_VARIANT_TYPE("(a{sv})"), [done = std::move(done)](GVariant* reply, GError* err) { + if (err) { + done(std::unexpected(ErrorFrom(err))); + return; + } + GVariant* dict = g_variant_get_child_value(reply, 0); + Status s = StatusFromVariant(dict); + g_variant_unref(dict); + done(std::move(s)); + }); + } + + void List(std::function done) override { + Call("List", nullptr, G_VARIANT_TYPE("(a(sa{sv}))"), [done = std::move(done)](GVariant* reply, GError* err) { + if (err) { + done(std::unexpected(ErrorFrom(err))); + return; + } + std::vector out; + GVariant* array = g_variant_get_child_value(reply, 0); + GVariantIter it; + g_variant_iter_init(&it, array); + while (GVariant* item = g_variant_iter_next_value(&it)) { + const gchar* id = nullptr; + GVariant* dict = nullptr; + g_variant_get(item, "(&s@a{sv})", &id, &dict); + out.push_back(ReceivedFromVariant(id ? id : "", dict)); + g_variant_unref(dict); + g_variant_unref(item); + } + g_variant_unref(array); + done(std::move(out)); + }); + } + + void Delete(std::string id, Done done) override { + Call("Delete", g_variant_new("(s)", id.c_str()), nullptr, [done = std::move(done)](GVariant*, GError* err) { + done(err ? std::optional(ErrorFrom(err)) : std::nullopt); + }); + } + + void Send(std::string number, std::string text, bool statusReport, std::function done) override { + Call("Send", g_variant_new("(ss@a{sv})", number.c_str(), text.c_str(), SendOptions(statusReport)), G_VARIANT_TYPE("(s)"), [done = std::move(done)](GVariant* reply, GError* err) { + if (err) { + done(std::unexpected(ErrorFrom(err))); + return; + } + const gchar* id = nullptr; + g_variant_get(reply, "(&s)", &id); + done(std::string(id ? id : "")); + }); + } + + private: + // One pending call's continuation: exactly one of reply and err is + // set; both are freed by OnCallDone after it ran. + using Reply = std::function; + struct Pending { // one call's continuation and the client that hears a throw out of it + Reply reply; + ImsdClient* client; + }; + + // A call on the Messaging interface; the client hears a throw out of + // the reply as a fault (OnCallDone). + void Call(const char* method, GVariant* params, const GVariantType* replyType, Reply reply) { + const std::string_view name = method; + const bool gated = name != "GetStatus"; + g_dbus_connection_call(conn, imsdName, imsdPath, messagingIface, method, params, replyType, gated ? G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION : G_DBUS_CALL_FLAGS_NONE, name == "Send" ? sendTimeoutMs : gated ? gatedTimeoutMs : callTimeoutMs, nullptr, OnCallDone, new Pending{ std::move(reply), this }); + } + + // Every reply passes here, inside GLib's dispatch, which no try + // encloses: a throw out of the continuation (a read, an allocation; + // the store catches its writes) is the events' fault, not the end + // of the process. + static void OnCallDone(GObject* source, GAsyncResult* result, gpointer data) { + std::unique_ptr pending(static_cast(data)); + GError* err = nullptr; + GVariant* value = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &err); + try { + pending->reply(value, err); + } catch (const std::exception& e) { + if (pending->client->events) pending->client->events->OnFault(e.what()); + } + if (value) g_variant_unref(value); + if (err) g_error_free(err); + } + + // The signal handlers run inside GLib's dispatch, which no try + // encloses: a throw out of them is handed to the events as a fault + // and the process goes on. + static void OnMessagingSignal(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* signal, GVariant* params, gpointer data) { + ImsdClient& self = *static_cast(data); + if (!self.events) return; + try { + const std::string_view name = signal; + if (name == "Received") { + const gchar* id = nullptr; + GVariant* dict = nullptr; + g_variant_get(params, "(&s@a{sv})", &id, &dict); + const ReceivedMessage m = ReceivedFromVariant(id ? id : "", dict); + g_variant_unref(dict); + self.events->OnReceived(m); + } else if (name == "StateChanged") { + const gchar* id = nullptr; + const gchar* state = nullptr; + const gchar* reason = nullptr; + g_variant_get(params, "(&s&s&s)", &id, &state, &reason); + self.events->OnStateChanged(id ? id : "", state ? state : "", reason ? reason : ""); + } + } catch (const std::exception& e) { + self.events->OnFault(e.what()); + } + } + + static void OnBaseSignal(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar*, GVariant* params, gpointer data) { + ImsdClient& self = *static_cast(data); + if (!self.events) return; + gboolean registered = FALSE; + g_variant_get(params, "(b)", ®istered); + try { + self.events->OnRegistrationChanged(registered == TRUE); + } catch (const std::exception& e) { + self.events->OnFault(e.what()); + } + } + + // The name watch's callbacks, guarded as the replies and the signal + // handlers are. + static void OnAppeared(GDBusConnection*, const gchar*, const gchar*, gpointer data) { + ImsdClient& self = *static_cast(data); + if (!self.events) return; + try { + self.events->OnImsdAppeared(); + } catch (const std::exception& e) { + self.events->OnFault(e.what()); + } + } + + static void OnVanished(GDBusConnection*, const gchar*, gpointer data) { + ImsdClient& self = *static_cast(data); + if (!self.events) return; + try { + self.events->OnImsdVanished(); + } catch (const std::exception& e) { + self.events->OnFault(e.what()); + } + } + + GDBusConnection* conn; + ImsdEvents* events = nullptr; + guint messagingSub = 0; + guint baseSub = 0; + guint watch = 0; + }; } diff --git a/interfaces/ImsdMessages.Bus-Instance.cppm b/interfaces/ImsdMessages.Bus-Instance.cppm index 7fc751b..4706ad1 100644 --- a/interfaces/ImsdMessages.Bus-Instance.cppm +++ b/interfaces/ImsdMessages.Bus-Instance.cppm @@ -1,10 +1,210 @@ // SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® +// lint-disable-file no-char-pointer +/* +ImsdMessages.Bus:Instance — one app per session: Own() takes +net.catcrafts.ImsdMessages on the session bus — and tells a name another +instance holds from a request that failed or was refused — 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 — whose one action is "quit"; the Forward +calls make one of them on the owner. The platform data (a launch's +activation token) is sent empty and not read: nothing in the app can use +a token yet. +*/ module; #include export module ImsdMessages.Bus:Instance; import std; -export namespace ImsdMessages::Bus { +namespace ImsdMessages::Bus { + // The specification's object path: the application id, its dots as slashes. + constexpr const char* ownPath = "/net/catcrafts/ImsdMessages"; + constexpr const char* ownIface = "org.freedesktop.Application"; + constexpr const char* introspection = R"xml( + + + + + + + + + + + + + + + +)xml"; + + // org.freedesktop.DBus.RequestName + constexpr guint32 flagDoNotQueue = 4; + constexpr guint32 replyPrimaryOwner = 1; + constexpr guint32 replyAlreadyOwner = 4; +} + +export namespace ImsdMessages::Bus { + inline constexpr std::string_view appId = "net.catcrafts.ImsdMessages"; + inline constexpr std::string_view quitAction = "quit"; + + // The parameters of the three calls (floating), their platform data + // empty, and what the instance reads out of them. + GVariant* ActivateParameters() { return g_variant_new("(a{sv})", nullptr); } + + GVariant* OpenParameters(std::span uris) { + GVariantBuilder list; + g_variant_builder_init(&list, G_VARIANT_TYPE("as")); + for (const std::string& uri : uris) g_variant_builder_add(&list, "s", uri.c_str()); + return g_variant_new("(asa{sv})", &list, nullptr); + } + + GVariant* ActionParameters(std::string_view action) { return g_variant_new("(sava{sv})", std::string(action).c_str(), nullptr, nullptr); } + + std::vector OpenUris(GVariant* params) { + GVariant* list = g_variant_get_child_value(params, 0); + gsize n = 0; + const gchar** strings = g_variant_get_strv(list, &n); // the array is ours, its strings the variant's + std::vector uris(strings, strings + n); + g_free(strings); + g_variant_unref(list); + return uris; + } + + std::string ActionName(GVariant* params) { + const gchar* name = nullptr; + g_variant_get_child(params, 0, "&s", &name); + return name; + } + + class Instance { + public: + struct Handlers { + std::function activate; + std::function uris)> open; + std::function quit; + }; + + Instance(GDBusConnection* session, Handlers handlers) : conn(session), handlers(std::move(handlers)) {} + ~Instance() { + if (conn && registration) g_dbus_connection_unregister_object(conn, registration); + if (node) g_dbus_node_info_unref(node); + } + Instance(const Instance&) = delete; + Instance& operator=(const Instance&) = delete; + + // What became of the name: ours; another instance's; or neither + // shown — the bus gave an error to the request or no answer in its + // five seconds, or the connection took no object (Failure has the + // error's words). + enum class Owning : std::uint8_t { Owned, Taken, Failed }; + + // Becomes the owner and serves the object. + Owning Own() { + if (!conn) { + failure = "no session bus"; + return Owning::Failed; + } + // The object before the name (GLib's own order for an owned + // name): a launch that forwards the moment the bus grants the + // name finds the object there. Without the name the object is + // reachable by this connection's unique name alone. + GError* err = nullptr; + node = g_dbus_node_info_new_for_xml(introspection, nullptr); + static const GDBusInterfaceVTable vtable = { OnMethod, nullptr, nullptr, {} }; + registration = g_dbus_connection_register_object(conn, ownPath, node->interfaces[0], &vtable, this, nullptr, &err); + if (err) return Fail(err); + GVariant* reply = g_dbus_connection_call_sync(conn, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName", g_variant_new("(su)", std::string(appId).c_str(), flagDoNotQueue), G_VARIANT_TYPE("(u)"), G_DBUS_CALL_FLAGS_NONE, 5000, nullptr, &err); + if (err) { + Unregister(); + return Fail(err); + } + guint32 result = 0; + g_variant_get(reply, "(u)", &result); + g_variant_unref(reply); + // Asked not to queue, the bus answers that the name is ours or + // that it exists. + if (result != replyPrimaryOwner && result != replyAlreadyOwner) { + Unregister(); + return Owning::Taken; + } + return Owning::Owned; + } + + // Why Own failed: the error's message, the bus's or GLib's. + const std::string& Failure() const noexcept { return failure; } + + // Ask the running instance: for its window, for a link's + // conversation, to exit. False when none answered, or when it + // knows no such action. + static bool ForwardActivate(GDBusConnection* session) { return Call(session, "Activate", ActivateParameters()); } + static bool ForwardOpen(GDBusConnection* session, const std::string& uri) { return Call(session, "Open", OpenParameters(std::span(&uri, 1))); } + static bool ForwardQuit(GDBusConnection* session) { return Call(session, "ActivateAction", ActionParameters(quitAction)); } + + private: + static bool Call(GDBusConnection* session, const char* method, GVariant* params) { + if (!session) { + g_variant_unref(g_variant_ref_sink(params)); + return false; + } + GError* err = nullptr; + GVariant* reply = g_dbus_connection_call_sync(session, std::string(appId).c_str(), ownPath, ownIface, method, params, nullptr, G_DBUS_CALL_FLAGS_NONE, 5000, nullptr, &err); + if (err) { + g_error_free(err); + return false; + } + g_variant_unref(reply); + return true; + } + + Owning Fail(GError* err) { + failure = err->message; + g_error_free(err); + return Owning::Failed; + } + + // The object goes when the name was not ours to take. + void Unregister() { + if (registration) g_dbus_connection_unregister_object(conn, registration); + registration = 0; + } + + // GDBus has checked the call against the interface above: the + // method is one of the three, its parameters of its signature. + static void OnMethod(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* method, GVariant* params, GDBusMethodInvocation* inv, gpointer data) { + Instance& self = *static_cast(data); + const std::string_view name = method; + std::vector uris; + if (name == "Open") uris = OpenUris(params); + if (name == "ActivateAction" && ActionName(params) != quitAction) { + g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.InvalidArgs", "no such action"); + return; + } + // The reply first: the caller (a forwarding launch, waiting 5 s) + // asked for the instance to act, not to have acted — a first + // Show creates the window, which can outlast its wait. A + // handler that throws is the instance's fault to log, not the + // process's end (GLib's dispatch encloses no try). + g_dbus_method_invocation_return_value(inv, nullptr); + try { + if (name == "Activate") { + if (self.handlers.activate) self.handlers.activate(); + } else if (name == "Open") { + if (self.handlers.open) self.handlers.open(std::move(uris)); + } else { + if (self.handlers.quit) self.handlers.quit(); + } + } catch (const std::exception& e) { + g_warning("imsd-messages: the %s handler threw: %s", method, e.what()); + } + } + + GDBusConnection* conn; + Handlers handlers; + GDBusNodeInfo* node = nullptr; + guint registration = 0; + std::string failure; + }; } diff --git a/interfaces/ImsdMessages.Bus-Notifier.cppm b/interfaces/ImsdMessages.Bus-Notifier.cppm index 43595da..d1aa244 100644 --- a/interfaces/ImsdMessages.Bus-Notifier.cppm +++ b/interfaces/ImsdMessages.Bus-Notifier.cppm @@ -1,10 +1,194 @@ // 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 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)); + } + + 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)); + } + 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_map waiting; // the latest text that came meanwhile + }; } diff --git a/interfaces/ImsdMessages.Bus-Variant.cppm b/interfaces/ImsdMessages.Bus-Variant.cppm index 5cf3642..0478903 100644 --- a/interfaces/ImsdMessages.Bus-Variant.cppm +++ b/interfaces/ImsdMessages.Bus-Variant.cppm @@ -1,12 +1,130 @@ // SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® +// lint-disable-file no-char-pointer +/* +ImsdMessages.Bus:Variant — imsd's dictionaries and errors as the core's +types. The keys and types are those imsd writes (AGENTS.md §8.4: the +Received dictionary of its SmsVariant, GetStatus's): a key that is +missing or of another type reads as its default. +*/ module; #include export module ImsdMessages.Bus:Variant; import std; +import ImsdMessages; + +namespace ImsdMessages::Bus { + std::string LookupString(GVariant* dict, const char* key) { + GVariant* v = g_variant_lookup_value(dict, key, G_VARIANT_TYPE_STRING); + if (!v) return ""; + std::string s = g_variant_get_string(v, nullptr); + g_variant_unref(v); + return s; + } + + template + T LookupScalar(GVariant* dict, const char* key, const GVariantType* type, T (*get)(GVariant*), T fallback) { + GVariant* v = g_variant_lookup_value(dict, key, type); + if (!v) return fallback; + const T x = get(v); + g_variant_unref(v); + return x; + } + + std::vector LookupBytes(GVariant* dict, const char* key) { + GVariant* v = g_variant_lookup_value(dict, key, G_VARIANT_TYPE_BYTESTRING); + if (!v) return {}; + gsize n = 0; + const guint8* p = static_cast(g_variant_get_fixed_array(v, &n, 1)); + std::vector out(p, p + n); + g_variant_unref(v); + return out; + } + + std::optional LookupOptionalUint32(GVariant* dict, const char* key) { + GVariant* v = g_variant_lookup_value(dict, key, G_VARIANT_TYPE_UINT32); + if (!v) return std::nullopt; + const std::uint32_t x = g_variant_get_uint32(v); + g_variant_unref(v); + return x; + } +} export namespace ImsdMessages::Bus { - // The GLib the bus layer is built against, for --version. + // The GLib the bus layer runs on, for --version. inline const std::string glibVersion = std::format("{}.{}.{}", glib_major_version, glib_minor_version, glib_micro_version); + + // The number of a tel: URI (the status's `ppi`, a Received's `to`); + // "" for none or another kind of URI. + std::string TelNumber(std::string_view uri) { return uri.starts_with("tel:") ? std::string(uri.substr(4)) : ""; } + + // The a{sv} of a Received signal or a List entry. + ReceivedMessage ReceivedFromVariant(std::string_view id, GVariant* dict) { + ReceivedMessage m; + m.imsdId = std::string(id); + m.from = LookupString(dict, "from"); + m.text = LookupString(dict, "text"); + m.timestamp = LookupString(dict, "timestamp"); + m.received = LookupScalar(dict, "received", G_VARIANT_TYPE_INT64, g_variant_get_int64, 0); + m.sc = LookupString(dict, "sc"); + m.to = TelNumber(LookupString(dict, "to")); + m.simOperator = LookupString(dict, "operator"); + m.smsClass = LookupScalar(dict, "class", G_VARIANT_TYPE_INT32, g_variant_get_int32, -1); + m.pid = LookupScalar(dict, "pid", G_VARIANT_TYPE_BYTE, g_variant_get_byte, 0); + m.dcs = LookupScalar(dict, "dcs", G_VARIANT_TYPE_BYTE, g_variant_get_byte, 0); + m.segments = LookupScalar(dict, "segments", G_VARIANT_TYPE_INT32, g_variant_get_int32, 1); + m.messageWaiting = LookupScalar(dict, "message-waiting", G_VARIANT_TYPE_BOOLEAN, g_variant_get_boolean, FALSE) == TRUE; + m.portDst = LookupOptionalUint32(dict, "port-dst"); + m.portSrc = LookupOptionalUint32(dict, "port-src"); + m.data = LookupBytes(dict, "data"); + m.pdu = LookupBytes(dict, "pdu"); + return m; + } + + // The a{sv} of GetStatus. + Status StatusFromVariant(GVariant* dict) { + Status s; + s.enabled = LookupScalar(dict, "enabled", G_VARIANT_TYPE_BOOLEAN, g_variant_get_boolean, FALSE) == TRUE; + s.smsc = LookupString(dict, "smsc"); + s.ownNumber = TelNumber(LookupString(dict, "ppi")); // the frozen interface's `ppi`, in this answer too + s.simOperator = LookupString(dict, "operator"); + s.registered = LookupScalar(dict, "registered", G_VARIANT_TYPE_BOOLEAN, g_variant_get_boolean, FALSE) == TRUE; + s.subscribers = LookupScalar(dict, "subscribers", G_VARIANT_TYPE_UINT32, g_variant_get_uint32, 0); + return s; + } + + // A GError as the core's BusError; the remote error's name is read off + // GDBus's mapping and stripped from the text. The caller frees err. + BusError ErrorFrom(GError* err) { + BusError e; + if (!err) return e; + if (err->domain == G_DBUS_ERROR) { + switch (err->code) { + case G_DBUS_ERROR_ACCESS_DENIED: e.kind = BusError::Kind::AccessDenied; break; + case G_DBUS_ERROR_NOT_SUPPORTED: e.kind = BusError::Kind::NotSupported; break; + case G_DBUS_ERROR_FILE_NOT_FOUND: e.kind = BusError::Kind::NotFound; break; + case G_DBUS_ERROR_INVALID_ARGS: e.kind = BusError::Kind::InvalidArgs; break; + case G_DBUS_ERROR_SERVICE_UNKNOWN: + case G_DBUS_ERROR_NAME_HAS_NO_OWNER: e.kind = BusError::Kind::NoOwner; break; + case G_DBUS_ERROR_NO_REPLY: + case G_DBUS_ERROR_TIMEOUT: + case G_DBUS_ERROR_TIMED_OUT: e.kind = BusError::Kind::Timeout; break; + default: e.kind = BusError::Kind::Other; break; + } + } else if (g_error_matches(err, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) { + e.kind = BusError::Kind::Timeout; + } + g_dbus_error_strip_remote_error(err); + e.message = err->message ? err->message : ""; + return e; + } + + // Send's options dictionary (floating). + GVariant* SendOptions(bool statusReport) { + GVariantBuilder b; + g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}")); + g_variant_builder_add(&b, "{sv}", "status-report", g_variant_new_boolean(statusReport ? TRUE : FALSE)); + return g_variant_builder_end(&b); + } } diff --git a/interfaces/ImsdMessages.Bus.cppm b/interfaces/ImsdMessages.Bus.cppm index b900cca..6152411 100644 --- a/interfaces/ImsdMessages.Bus.cppm +++ b/interfaces/ImsdMessages.Bus.cppm @@ -3,7 +3,8 @@ /* ImsdMessages.Bus — the GLib side of imsd-messages: the GDBus client of -net.catcrafts.IMS1.Messaging on the system bus, the decoding of its +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, and the app's own session-bus name. No window: the executable wires this to the UI. */ diff --git a/project.cpp b/project.cpp index f5dea32..fd87997 100644 --- a/project.cpp +++ b/project.cpp @@ -30,32 +30,40 @@ static std::vector PkgConfig(std::string_view args) { // GDBus (gio-2.0) — bus layer for the two daemons; chosen over sd-bus because // the platform stack (ModemManager, libqmi for the future direct-AKA port) is -// GLib, so they want a GMainLoop regardless. -static void ApplyGioFlags(Configuration& cfg) { +// GLib, so they want a GMainLoop regardless. (imsd's reasoning; the same +// layer here.) Computed once, for each target that takes them. +struct GioFlags { + std::vector compile; + std::vector link; +}; + +static GioFlags ComputeGioFlags(const Configuration& cfg) { + GioFlags f; if (!cfg.sysroot.empty()) { // cross build (e.g. --target=aarch64-alpine-linux-musl // --sysroot=): the host's // pkg-config would answer for the wrong architecture. glib's // include layout is stable across distros; the `-I=` form makes // clang resolve the paths inside the sysroot. - cfg.compileFlags.push_back("-I=/usr/include/glib-2.0"); - cfg.compileFlags.push_back("-I=/usr/lib/glib-2.0/include"); - for (const char* l : { "-lgio-2.0", "-lgobject-2.0", "-lglib-2.0" }) - cfg.linkFlags.push_back(l); - } else { - // native build: ask pkg-config. Only -I/-D flags pass through: - // pkg-config also emits -pthread, which would config-mismatch the - // shared prebuilt std.pcm (and pthread lives in libc on every - // platform we target). - for (std::string& f : PkgConfig("--cflags gio-2.0")) - if (f.starts_with("-I") || f.starts_with("-D")) cfg.compileFlags.push_back(std::move(f)); - std::vector libs; - for (std::string& f : PkgConfig("--libs gio-2.0")) - if (f.starts_with("-l") || f.starts_with("-L")) libs.push_back(std::move(f)); - if (libs.empty()) libs = { "-lgio-2.0", "-lgobject-2.0", "-lglib-2.0" }; - for (std::string& f : libs) - cfg.linkFlags.push_back(std::move(f)); + f.compile = { "-I=/usr/include/glib-2.0", "-I=/usr/lib/glib-2.0/include" }; + f.link = { "-lgio-2.0", "-lgobject-2.0", "-lglib-2.0" }; + return f; } + // native build: ask pkg-config. Only -I/-D flags pass through: + // pkg-config also emits -pthread, which would config-mismatch the + // shared prebuilt std.pcm (and pthread lives in libc on every + // platform we target). + for (std::string& flag : PkgConfig("--cflags gio-2.0")) + if (flag.starts_with("-I") || flag.starts_with("-D")) f.compile.push_back(std::move(flag)); + for (std::string& flag : PkgConfig("--libs gio-2.0")) + if (flag.starts_with("-l") || flag.starts_with("-L")) f.link.push_back(std::move(flag)); + if (f.link.empty()) f.link = { "-lgio-2.0", "-lgobject-2.0", "-lglib-2.0" }; + return f; +} + +static void ApplyGioFlags(Configuration& cfg, const GioFlags& f) { + for (const std::string& flag : f.compile) cfg.compileFlags.push_back(flag); + for (const std::string& flag : f.link) cfg.linkFlags.push_back(flag); } extern "C" Configuration CrafterBuildProject(std::span args) { @@ -115,7 +123,8 @@ extern "C" Configuration CrafterBuildProject(std::span a std::array impls = {}; Bus->GetInterfacesAndImplementations(ifaces, impls); } - ApplyGioFlags(*Bus); + const GioFlags gio = ComputeGioFlags(*Bus); + ApplyGioFlags(*Bus, gio); // imsd-messages — the executable: the command line, the window and the // wiring between the bus layer and the UI. @@ -131,7 +140,7 @@ extern "C" Configuration CrafterBuildProject(std::span a std::array impls = { "implementations/main" }; cfg.GetInterfacesAndImplementations(ifaces, impls); } - ApplyGioFlags(cfg); + ApplyGioFlags(cfg, gio); cfg.AddTest("Number").Dependencies({ Core.get() }); cfg.AddTest("Time").Dependencies({ Core.get() }); @@ -139,6 +148,11 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("Model").Dependencies({ Core.get() }); cfg.AddTest("Store").Dependencies({ Core.get(), db }); cfg.AddTest("Sync").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); LintRules::AddRules(cfg); return cfg; diff --git a/tests/Decode/main.cpp b/tests/Decode/main.cpp new file mode 100644 index 0000000..1451415 --- /dev/null +++ b/tests/Decode/main.cpp @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: GPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// lint-disable-file no-char-pointer +// The bus layer's decoding: a Received dictionary with every key imsd's +// SmsVariant writes, one with ten of them and a duplicate key of another +// type, a GetStatus dictionary, and GErrors as the core's BusError kinds. +#include + +import std; +import ImsdMessages; +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; +} + +GVariant* FullDict() { + const std::vector data = { 1, 2, 3 }; + const std::vector pdu = { 4, 11, 145 }; + GVariantBuilder b; + g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}")); + g_variant_builder_add(&b, "{sv}", "from", g_variant_new_string("+31621308050")); + g_variant_builder_add(&b, "{sv}", "text", g_variant_new_string("Tëst")); + g_variant_builder_add(&b, "{sv}", "timestamp", g_variant_new_string("2026-10-17T00:41:40+02:00")); + g_variant_builder_add(&b, "{sv}", "received", g_variant_new_int64(1792192661)); + g_variant_builder_add(&b, "{sv}", "sc", g_variant_new_string("+31624000000")); + g_variant_builder_add(&b, "{sv}", "to", g_variant_new_string("tel:+31612345678")); + g_variant_builder_add(&b, "{sv}", "operator", g_variant_new_string("20408")); + g_variant_builder_add(&b, "{sv}", "class", g_variant_new_int32(0)); + g_variant_builder_add(&b, "{sv}", "pid", g_variant_new_byte(0x41)); + g_variant_builder_add(&b, "{sv}", "dcs", g_variant_new_byte(0x04)); + g_variant_builder_add(&b, "{sv}", "segments", g_variant_new_int32(2)); + g_variant_builder_add(&b, "{sv}", "message-waiting", g_variant_new_boolean(TRUE)); + g_variant_builder_add(&b, "{sv}", "port-dst", g_variant_new_uint32(2948)); + g_variant_builder_add(&b, "{sv}", "port-src", g_variant_new_uint32(9200)); + g_variant_builder_add(&b, "{sv}", "data", g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, data.data(), data.size(), 1)); + g_variant_builder_add(&b, "{sv}", "pdu", g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, pdu.data(), pdu.size(), 1)); + return g_variant_ref_sink(g_variant_builder_end(&b)); +} + +GVariant* PlainDict() { + GVariantBuilder b; + g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}")); + g_variant_builder_add(&b, "{sv}", "from", g_variant_new_string("KPN")); + g_variant_builder_add(&b, "{sv}", "text", g_variant_new_string("Welkom")); + g_variant_builder_add(&b, "{sv}", "timestamp", g_variant_new_string("2026-10-17T00:48:32+02:00")); + g_variant_builder_add(&b, "{sv}", "received", g_variant_new_int64(1792192662)); + g_variant_builder_add(&b, "{sv}", "sc", g_variant_new_string("+31624000000")); + g_variant_builder_add(&b, "{sv}", "class", g_variant_new_int32(-1)); + g_variant_builder_add(&b, "{sv}", "pid", g_variant_new_byte(0)); + g_variant_builder_add(&b, "{sv}", "dcs", g_variant_new_byte(0)); + g_variant_builder_add(&b, "{sv}", "segments", g_variant_new_int32(1)); + g_variant_builder_add(&b, "{sv}", "message-waiting", g_variant_new_boolean(FALSE)); + g_variant_builder_add(&b, "{sv}", "received", g_variant_new_string("not an int64, and after the one that is")); + return g_variant_ref_sink(g_variant_builder_end(&b)); +} + +} + +int main() { + GVariant* full = FullDict(); + const ReceivedMessage m = Bus::ReceivedFromVariant("ims-sms-in-1792192661-1", full); + g_variant_unref(full); + Check(m.imsdId == "ims-sms-in-1792192661-1", "the id"); + Check(m.from == "+31621308050" && m.text == "Tëst" && m.timestamp == "2026-10-17T00:41:40+02:00" && m.sc == "+31624000000", "the strings"); + Check(m.to == "+31612345678", "the number the text arrived for, out of its tel: URI"); + Check(m.simOperator == "20408", "the operator of the SIM it arrived under"); + Check(m.received == 1792192661, "received x"); + Check(m.smsClass == 0 && m.pid == 0x41 && m.dcs == 0x04 && m.segments == 2 && m.messageWaiting, "class, pid, dcs, segments, message-waiting"); + Check(m.portDst == 2948u && m.portSrc == 9200u, "the ports"); + Check(m.data == std::vector{ 1, 2, 3 } && m.pdu == std::vector{ 4, 11, 145 }, "data and pdu"); + + GVariant* plain = PlainDict(); + const ReceivedMessage p = Bus::ReceivedFromVariant("ims-sms-in-1792192662-2", plain); + g_variant_unref(plain); + Check(p.from == "KPN" && p.text == "Welkom" && p.smsClass == -1 && p.segments == 1 && !p.messageWaiting, "a plain text"); + Check(!p.portDst && !p.portSrc && p.data.empty() && p.pdu.empty() && p.to.empty() && p.simOperator.empty(), "absent keys read as absent"); + Check(p.received == 1792192662, "a later duplicate key of another type does not disturb the typed lookup"); + + GVariantBuilder sb; + g_variant_builder_init(&sb, G_VARIANT_TYPE("a{sv}")); + g_variant_builder_add(&sb, "{sv}", "enabled", g_variant_new_boolean(TRUE)); + g_variant_builder_add(&sb, "{sv}", "smsc", g_variant_new_string("+31653131313")); + g_variant_builder_add(&sb, "{sv}", "ppi", g_variant_new_string("tel:+31612345678")); + g_variant_builder_add(&sb, "{sv}", "operator", g_variant_new_string("20408")); + g_variant_builder_add(&sb, "{sv}", "registered", g_variant_new_boolean(TRUE)); + g_variant_builder_add(&sb, "{sv}", "subscribers", g_variant_new_uint32(1)); + GVariant* sd = g_variant_ref_sink(g_variant_builder_end(&sb)); + const Status s = Bus::StatusFromVariant(sd); + g_variant_unref(sd); + Check(s.enabled && s.registered && s.smsc == "+31653131313" && s.ownNumber == "+31612345678" && s.simOperator == "20408" && s.subscribers == 1, "GetStatus, the own number and the SIM's operator in it"); + + for (const auto& [ppi, number, what] : std::array, 3>{ { { "tel:+31612345678", "+31612345678", "the own number is the ppi's tel: URI" }, { "sip:alice@example.org", "", "another kind of URI is no number" }, { nullptr, "", "no ppi, no number" } } }) { + GVariantBuilder pb; + g_variant_builder_init(&pb, G_VARIANT_TYPE("a{sv}")); + g_variant_builder_add(&pb, "{sv}", "registered", g_variant_new_boolean(TRUE)); + if (ppi) g_variant_builder_add(&pb, "{sv}", "ppi", g_variant_new_string(ppi)); + GVariant* pd = g_variant_ref_sink(g_variant_builder_end(&pb)); + Check(Bus::StatusFromVariant(pd).ownNumber == number, what); + Check(Bus::StatusFromVariant(pd).simOperator.empty(), "and no operator from an answer without one"); + g_variant_unref(pd); + } + + GError* denied = g_dbus_error_new_for_dbus_error("org.freedesktop.DBus.Error.AccessDenied", ":1.5 is not authorized for net.catcrafts.IMS1.Messaging"); + const BusError e1 = Bus::ErrorFrom(denied); + g_error_free(denied); + Check(e1.kind == BusError::Kind::AccessDenied && e1.message == ":1.5 is not authorized for net.catcrafts.IMS1.Messaging", "AccessDenied, the remote name stripped from the text"); + GError* missing = g_dbus_error_new_for_dbus_error("org.freedesktop.DBus.Error.FileNotFound", "no such message"); + Check(Bus::ErrorFrom(missing).kind == BusError::Kind::NotFound, "FileNotFound"); + g_error_free(missing); + GError* off = g_dbus_error_new_for_dbus_error("org.freedesktop.DBus.Error.NotSupported", "SMS over IP is off"); + Check(Bus::ErrorFrom(off).kind == BusError::Kind::NotSupported, "NotSupported"); + g_error_free(off); + GError* badId = g_dbus_error_new_for_dbus_error("org.freedesktop.DBus.Error.InvalidArgs", "not an id"); + Check(Bus::ErrorFrom(badId).kind == BusError::Kind::InvalidArgs, "InvalidArgs"); + g_error_free(badId); + GError* nobody = g_error_new_literal(G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN, "The name net.catcrafts.IMS1 was not provided by any .service files"); + Check(Bus::ErrorFrom(nobody).kind == BusError::Kind::NoOwner, "ServiceUnknown is NoOwner"); + g_error_free(nobody); + GError* late = g_error_new_literal(G_IO_ERROR, G_IO_ERROR_TIMED_OUT, "Timeout was reached"); + Check(Bus::ErrorFrom(late).kind == BusError::Kind::Timeout, "a GIO timeout is Timeout"); + g_error_free(late); + GError* other = g_dbus_error_new_for_dbus_error("org.freedesktop.DBus.Error.Failed", "boom"); + Check(Bus::ErrorFrom(other).kind == BusError::Kind::Other && Bus::ErrorFrom(other).message == "boom", "anything else is Other with its text"); + g_error_free(other); + Check(Bus::ErrorFrom(nullptr).kind == BusError::Kind::Other, "no error is a harmless Other"); + + // org.freedesktop.Application's three calls, as a launch forwards them and the instance reads them. + GVariant* activate = g_variant_ref_sink(Bus::ActivateParameters()); + Check(g_variant_is_of_type(activate, G_VARIANT_TYPE("(a{sv})")), "Activate's parameters: the platform data"); + g_variant_unref(activate); + const std::vector links = { "sms:+31612345678", "sms:1234" }; + GVariant* open = g_variant_ref_sink(Bus::OpenParameters(links)); + Check(g_variant_is_of_type(open, G_VARIANT_TYPE("(asa{sv})")) && Bus::OpenUris(open) == links, "Open's parameters: the URIs, in order, and the platform data"); + g_variant_unref(open); + GVariant* none = g_variant_ref_sink(Bus::OpenParameters({})); + Check(Bus::OpenUris(none).empty(), "an Open without a URI reads as none"); + g_variant_unref(none); + GVariant* quit = g_variant_ref_sink(Bus::ActionParameters(Bus::quitAction)); + Check(g_variant_is_of_type(quit, G_VARIANT_TYPE("(sava{sv})")) && Bus::ActionName(quit) == "quit", "ActivateAction's parameters: the action's name, no parameter, the platform data"); + g_variant_unref(quit); + + GVariant* options = g_variant_ref_sink(Bus::SendOptions(true)); + gboolean report = FALSE; + Check(g_variant_lookup(options, "status-report", "b", &report) && report == TRUE, "Send's options carry status-report"); + g_variant_unref(options); + + Check(Bus::Preview("\nYour code: 1234") == "Your code: 1234" && Bus::Preview("\r\n\nhello\nworld") == "hello…" && Bus::Preview(" \t\nYour code: 1234") == "Your code: 1234" && Bus::Preview(" hello") == "hello", "a notification's preview is the first line with text on it: leading line breaks and blanks are skipped"); + Check(Bus::MarkupEscaped("in <5 min & \"more\"") == "in <5 min & "more"", "a notification body is escaped for a server that renders markup"); + + return failures == 0 ? 0 : 1; +}