Linux + iPhone Continuity / iMessage / SMS
feat: notification improvements: icons, history
Zack Barteldacf205d4439
diff --git a/src/core/include/tether/bluetooth/ancs/notifications.hpp b/src/core/include/tether/bluetooth/ancs/notifications.hppindex e31f25b..32f9b5d 100644--- a/src/core/include/tether/bluetooth/ancs/notifications.hpp+++ b/src/core/include/tether/bluetooth/ancs/notifications.hpp@@ -75,6 +75,10 @@ namespace tether::bluetooth::ancs {// ANCS copy is kept for correlation but must never raise a second popup.bool should_show_desktop_popup(const Notification& notification);+ // Freedesktop icon names to try for a notification, best first: the app's+ // own logo, then something generic for its category.+ std::vector<std::string> icon_candidates(const Notification& notification);+nlohmann::json to_json(const Notification& notification);} // namespace tether::bluetooth::ancsdiff --git a/src/core/src/bluetooth/ancs/notifications.cpp b/src/core/src/bluetooth/ancs/notifications.cppindex 6d6112d..5c61e12 100644--- a/src/core/src/bluetooth/ancs/notifications.cpp+++ b/src/core/src/bluetooth/ancs/notifications.cpp@@ -2,11 +2,45 @@#include <algorithm>#include <cctype>+#include <map>namespace tether::bluetooth::ancs {namespace {constexpr size_t MAX_RETAINED = 200;++ // Generic stand-ins for an app whose own logo is unknown or absent from+ // the theme. Two per category, because Breeze and Adwaita disagree on+ // several of these names and only one of them has to land.+ std::vector<const char*> category_icons(CategoryId category) {+ switch (category) {+ case CategoryId::IncomingCall:+ return {"call-start", "call-incoming"};+ case CategoryId::MissedCall:+ return {"call-stop", "call-missed"};+ case CategoryId::Voicemail:+ return {"media-playback-start", "audio-input-microphone"};+ case CategoryId::Social:+ return {"internet-chat", "im-user"};+ case CategoryId::Schedule:+ return {"office-calendar", "x-office-calendar"};+ case CategoryId::Email:+ return {"mail-unread", "mail-message-new"};+ case CategoryId::News:+ return {"application-rss+xml", "internet-news-reader"};+ case CategoryId::HealthAndFitness:+ return {"applications-health", "preferences-desktop-personal"};+ case CategoryId::BusinessAndFinance:+ return {"wallet-open", "office-chart-line"};+ case CategoryId::Location:+ return {"mark-location", "find-location"};+ case CategoryId::Entertainment:+ return {"applications-multimedia", "multimedia-player"};+ case CategoryId::Other:+ break;+ }+ return {"phone-symbolic", "phone"};+ }} // namespaceDecision NotificationRegistry::classify(const SourceEvent& event, bool initial) const {@@ -87,6 +121,60 @@ namespace tether::bluetooth::ancs {return !notification.silent;}+ std::vector<std::string> icon_candidates(const Notification& notification) {+ std::vector<std::string> out;++ // Brand logos, named the way icon themes that carry them do (Papirus is+ // the common one; Breeze and Adwaita ship none of these, which is why+ // the category names below have to stand on their own).+ static const std::map<std::string, const char*> by_app_id{+ {"com.amazon.Amazon", "amazon"},+ {"com.apple.MobileAddressBook", "x-office-address-book"},+ {"com.apple.MobileSMS", "internet-chat"},+ {"com.apple.Music", "multimedia-player"},+ {"com.apple.facetime", "camera-web"},+ {"com.apple.mobilecal", "office-calendar"},+ {"com.apple.mobilemail", "mail-unread"},+ {"com.apple.mobilenotes", "accessories-text-editor"},+ {"com.apple.mobilephone", "call-start"},+ {"com.apple.mobileslideshow", "multimedia-photo-viewer"},+ {"com.apple.news", "application-rss+xml"},+ {"com.apple.podcasts", "podcasts"},+ {"com.apple.reminders", "view-task"},+ {"com.atebits.Tweetie2", "twitter"},+ {"com.burbn.instagram", "instagram"},+ {"com.facebook.Facebook", "facebook"},+ {"com.facebook.Messenger", "messenger"},+ {"com.github.stormbreaker.prod", "github"},+ {"com.google.Gmail", "gmail"},+ {"com.google.Maps", "google-maps"},+ {"com.google.ios.youtube", "youtube"},+ {"com.hammerandchisel.discord", "discord"},+ {"com.linkedin.LinkedIn", "linkedin"},+ {"com.microsoft.Office.Outlook", "ms-outlook"},+ {"com.reddit.Reddit", "reddit"},+ {"com.spotify.client", "spotify"},+ {"com.tinyspeck.chatlyio", "slack"},+ {"com.toyopagroup.picaboo", "snapchat"},+ {"com.ubercab.UberClient", "uber"},+ {"com.zhiliaoapp.musically", "tiktok"},+ {"net.whatsapp.WhatsApp", "whatsapp"},+ {"org.telegram.messenger", "telegram"},+ {"org.whispersystems.signal", "signal-desktop"},+ {"ph.telegra.Telegraph", "telegram"},+ {"us.zoom.videomeetings", "zoom"},+ };++ if (auto found = by_app_id.find(notification.app_id); found != by_app_id.end())+ out.emplace_back(found->second);++ for (const char* name : category_icons(notification.category))+ out.emplace_back(name);++ out.emplace_back("tether");+ return out;+ }+nlohmann::json to_json(const Notification& notification) {return {{"uid", notification.uid},diff --git a/src/daemon/main.cpp b/src/daemon/main.cppindex d14ecde..f19c538 100644--- a/src/daemon/main.cpp+++ b/src/daemon/main.cpp@@ -141,7 +141,12 @@ int main(int argc, char** argv) {}if (who.empty())who = message.peer_name.empty() ? message.peer_address : message.peer_name;- notifier.notify(who.empty() ? "iPhone" : who, message.body);+ tether::bluetooth::ancs::Notification as_notification;+ as_notification.app_id = tether::bluetooth::ancs::APP_ID_MESSAGES;+ notifier.notify({"Messages",+ who.empty() ? "iPhone" : who,+ message.body,+ tether::bluetooth::ancs::icon_candidates(as_notification)});});if (bluez.start()) {tether::bluetooth::g_bluez = &bluez;@@ -190,7 +195,10 @@ int main(int argc, char** argv) {const std::string title = notification.title.empty() ? notification.app_name : notification.title;// Some apps put the whole notification in the subtitle and leave the message empty.const std::string body = notification.body.empty() ? notification.subtitle : notification.body;- notifier.notify(title.empty() ? "iPhone" : title, body);+ notifier.notify({notification.app_name,+ title.empty() ? "iPhone" : title,+ body,+ tether::bluetooth::ancs::icon_candidates(notification)});},[](uint32_t uid) {nlohmann::json event;diff --git a/src/daemon/notification.cpp b/src/daemon/notification.cppindex 45bf950..d28169e 100644--- a/src/daemon/notification.cpp+++ b/src/daemon/notification.cpp@@ -4,18 +4,95 @@#include <glib.h>#include <libnotify/notify.h>+#include <mutex>#include <string>#include <tether/log.hpp>#include <thread>+#include <unordered_set>namespace tether {namespace {+ constexpr const char* DESKTOP_ENTRY = "tether-gtk";+struct NotificationRequest {std::filesystem::path path;};+ // Every icon name installed by any theme on this machine.+ // scanned once and cached for the life of the process.+ const std::unordered_set<std::string>& installed_icons() {+ static const std::unordered_set<std::string> names = [] {+ std::unordered_set<std::string> found;+ std::vector<std::filesystem::path> roots;++ const char* home = std::getenv("HOME");+ if (const char* data_home = std::getenv("XDG_DATA_HOME"); data_home && *data_home)+ roots.emplace_back(std::filesystem::path(data_home) / "icons");+ else if (home)+ roots.emplace_back(std::filesystem::path(home) / ".local/share/icons");+ if (home)+ roots.emplace_back(std::filesystem::path(home) / ".icons");++ const char* data_dirs = std::getenv("XDG_DATA_DIRS");+ std::string dirs = data_dirs && *data_dirs ? data_dirs : "/usr/local/share:/usr/share";+ for (size_t start = 0; start <= dirs.size();) {+ const size_t end = dirs.find(':', start);+ const std::string dir = dirs.substr(start, end - start);+ if (!dir.empty())+ roots.emplace_back(std::filesystem::path(dir) / "icons");+ if (end == std::string::npos)+ break;+ start = end + 1;+ }+ roots.emplace_back("/usr/share/pixmaps");++ std::error_code ec;+ for (const auto& root : roots) {+ auto it = std::filesystem::recursive_directory_iterator(+ root, std::filesystem::directory_options::skip_permission_denied, ec);+ if (ec) {+ ec.clear();+ continue;+ }+ for (const auto& entry : it) {+ const auto ext = entry.path().extension();+ if (ext == ".png" || ext == ".svg" || ext == ".xpm")+ found.insert(entry.path().stem().string());+ }+ }+ debug::log(INFO, "Found {} icon names across the installed themes", found.size());+ return found;+ }();+ return names;+ }++ // The first candidate this machine can actually draw. Handing the server+ // a name no theme has leaves the popup with no icon at all, which is+ // worse than a generic one.+ std::string resolve_icon(const std::vector<std::string>& candidates) {+ const auto& installed = installed_icons();+ for (const auto& name : candidates) {+ if (installed.count(name))+ return name;+ }+ return {};+ }++ // Identifies the sending application to the notification server. Without+ // this KDE shows the popup and then forgets it.+ void set_identity(NotifyNotification* notification, const std::string& app_name) {+ notify_notification_set_hint(notification, "desktop-entry", g_variant_new_string(DESKTOP_ENTRY));+ if (!app_name.empty()) {+ // Keeps history and configuration grouped under Tether while the+ // header names the iPhone app the notification came from.+ notify_notification_set_hint(+ notification, "x-kde-display-appname", g_variant_new_string(app_name.c_str()));+ }+ notify_notification_set_hint(notification, "x-kde-origin-name", g_variant_new_string("iPhone"));+ }+struct NotificationActionData {std::string uri;};@@ -72,7 +149,7 @@ namespace tether {NotifyNotification* notification =notify_notification_new("File arrived", file.filename().c_str(), "document-save");- notify_notification_set_hint(notification, "desktop-entry", g_variant_new_string("tether"));+ set_identity(notification, "");notify_notification_set_hint(notification, "resident", g_variant_new_boolean(TRUE));notify_notification_set_timeout(notification, 15000);@@ -101,6 +178,28 @@ namespace tether {return G_SOURCE_REMOVE;}+ gboolean show_spec_on_main(gpointer user_data) {+ std::unique_ptr<NotificationSpec> spec(static_cast<NotificationSpec*>(user_data));++ const std::string icon = resolve_icon(spec->icons);+ NotifyNotification* notification =+ notify_notification_new(spec->summary.c_str(),+ spec->body.empty() ? nullptr : spec->body.c_str(),+ icon.empty() ? nullptr : icon.c_str());+ if (!notification)+ return G_SOURCE_REMOVE;++ set_identity(notification, spec->app_name);++ GError* error = nullptr;+ if (!notify_notification_show(notification, &error)) {+ debug::log(ERR, "Failed to show notification: {}", error ? error->message : "unknown");+ g_clear_error(&error);+ }+ g_object_unref(notification);+ return G_SOURCE_REMOVE;+ }+} // namespacestruct DesktopNotifier::Impl {@@ -140,7 +239,7 @@ namespace tether {return true;}- if (!notify_init("tetherd")) {+ if (!notify_init("Tether")) {debug::log(ERR, "Failed to initialize libnotify");return false;}@@ -149,6 +248,9 @@ namespace tether {impl_->loop = g_main_loop_new(impl_->context, FALSE);impl_->thread = std::thread([ctx = impl_->context, loop = impl_->loop]() {g_main_context_push_thread_default(ctx);+ // Walking the icon themes takes long enough to be worth doing before+ // the first notification rather than during it.+ installed_icons();g_main_loop_run(loop);g_main_context_pop_thread_default(ctx);});@@ -156,23 +258,15 @@ namespace tether {return true;}- void DesktopNotifier::notify(const std::string& summary, const std::string& body) {+ void DesktopNotifier::notify(const NotificationSpec& spec) {if (!impl_ || !impl_->initialized) {return;}- NotifyNotification* notification =- notify_notification_new(summary.c_str(), body.empty() ? nullptr : body.c_str(), "phone-symbolic");- if (!notification) {- return;- }-- GError* error = nullptr;- if (!notify_notification_show(notification, &error)) {- debug::log(ERR, "Failed to show notification: {}", error ? error->message : "unknown");- g_clear_error(&error);- }- g_object_unref(notification);+ // Bluetooth delivers on its own thread; libnotify's proxy belongs to the+ // notifier's loop.+ auto* copy = new NotificationSpec(spec);+ g_main_context_invoke_full(impl_->context, G_PRIORITY_DEFAULT, show_spec_on_main, copy, nullptr);}void DesktopNotifier::notify_file_arrived(const std::filesystem::path& path) {diff --git a/src/daemon/notification.hpp b/src/daemon/notification.hppindex bae89d3..654936c 100644--- a/src/daemon/notification.hpp+++ b/src/daemon/notification.hpp@@ -3,9 +3,20 @@#include <filesystem>#include <memory>#include <string>+#include <vector>namespace tether {+ // A mirrored notification as the desktop should present it.+ struct NotificationSpec {+ // The originating iPhone app. Shown as the popup's application name+ std::string app_name;+ std::string summary;+ std::string body;+ // Freedesktop icon names, best first.+ std::vector<std::string> icons;+ };+class DesktopNotifier {public:DesktopNotifier();@@ -18,7 +29,7 @@ namespace tether {void notify_file_arrived(const std::filesystem::path& path);// A plain notification with no actions.- void notify(const std::string& summary, const std::string& body);+ void notify(const NotificationSpec& spec);private:struct Impl;diff --git a/src/gtk/notifications_view.cpp b/src/gtk/notifications_view.cppindex 94daf9e..2c33c98 100644--- a/src/gtk/notifications_view.cpp+++ b/src/gtk/notifications_view.cpp@@ -4,6 +4,7 @@#include <ctime>#include <string>+#include <tether/bluetooth/ancs/notifications.hpp>namespace tether::ui {@@ -36,6 +37,22 @@ namespace tether::ui {daemon_send(j);}+ // Same per-app icon the desktop popup uses, narrowed to what this+ // theme has.+ GtkWidget* app_icon(const nlohmann::json& notification) {+ bluetooth::ancs::Notification resolved;+ resolved.app_id = notification.value("app_id", "");+ resolved.category = static_cast<bluetooth::ancs::CategoryId>(notification.value("category", 0));++ GtkIconTheme* theme = gtk_icon_theme_get_default();+ for (const auto& name : bluetooth::ancs::icon_candidates(resolved)) {+ if (gtk_icon_theme_has_icon(theme, name.c_str()))+ return gtk_image_new_from_icon_name(name.c_str(), GTK_ICON_SIZE_LARGE_TOOLBAR);+ }+ return gtk_image_new_from_icon_name("preferences-system-notifications-symbolic",+ GTK_ICON_SIZE_LARGE_TOOLBAR);+ }+GtkWidget* build_row(const nlohmann::json& notification) {const std::string app = notification.value("app_name", notification.value("app_id", ""));const std::string title = notification.value("title", "");@@ -50,6 +67,7 @@ namespace tether::ui {gtk_container_set_border_width(GTK_CONTAINER(box), 10);GtkWidget* header = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8);+ gtk_box_pack_start(GTK_BOX(header), app_icon(notification), FALSE, FALSE, 0);GtkWidget* app_label = gtk_label_new(nullptr);gtk_label_set_markup(GTK_LABEL(app_label), ("<b>" + escape_markup(app) + "</b>").c_str());gtk_label_set_xalign(GTK_LABEL(app_label), 0.0);diff --git a/src/gtk/tether-gtk.desktop.in b/src/gtk/tether-gtk.desktop.inindex 0e2e9de..34fab75 100644--- a/src/gtk/tether-gtk.desktop.in+++ b/src/gtk/tether-gtk.desktop.in@@ -3,7 +3,7 @@ Name=TetherGenericName=Device SynchronizationComment=Pair devices and synchronize clipboard across the networkExec=tether-gtk-Icon=@CMAKE_INSTALL_FULL_DATADIR@/icons/hicolor/1024x1024/apps/tether.png+Icon=tetherTerminal=falseType=ApplicationCategories=Network;Utility;diff --git a/test/test_ancs_notifications.cpp b/test/test_ancs_notifications.cppindex 9af4f99..53d22a9 100644--- a/test/test_ancs_notifications.cpp+++ b/test/test_ancs_notifications.cpp@@ -1,3 +1,4 @@+#include <algorithm>#include <gtest/gtest.h>#include <tether/bluetooth/ancs/notifications.hpp>#include <tether/bluetooth/config.hpp>@@ -25,6 +26,32 @@ TEST(AncsAppName, DerivesTheLastBundleComponent) {EXPECT_EQ(derive_app_name(""), "");}+TEST(AncsIcons, PrefersTheAppOverItsCategory) {+ Notification n = make(1, "com.burbn.instagram");+ n.category = CategoryId::Social;+ const auto icons = icon_candidates(n);+ ASSERT_FALSE(icons.empty());+ EXPECT_EQ(icons.front(), "instagram");+ EXPECT_NE(std::find(icons.begin(), icons.end(), "internet-chat"), icons.end())+ << "the category icon stands in for themes without brand logos";+}++TEST(AncsIcons, FallsBackToTheCategoryForAnUnknownApp) {+ Notification n = make(2, "com.example.unheardof");+ n.category = CategoryId::Email;+ EXPECT_EQ(icon_candidates(n).front(), "mail-unread");+}++TEST(AncsIcons, AlwaysEndsWithAnIconThatShipsWithTether) {+ for (uint8_t category = 0; category <= static_cast<uint8_t>(CategoryId::Entertainment); ++category) {+ Notification n = make(3, "");+ n.category = static_cast<CategoryId>(category);+ const auto icons = icon_candidates(n);+ ASSERT_FALSE(icons.empty()) << "category " << int(category);+ EXPECT_EQ(icons.back(), "tether") << "category " << int(category);+ }+}+TEST(AncsRegistry, RenameAppTouchesOnlyThatApp) {NotificationRegistry registry;registry.store(make(1, "com.burbn.instagram"));