/* * moonmix: browser tab names. * * Host side: Chrome native messaging on stdin, and one published file per * host in $XDG_RUNTIME_DIR/moonmix (private, gone at logout). * Mixer side: watching that directory, and the titles Chromium-family * browsers publish over MPRIS. * * Everything runs on the GLib default main context (shared with WirePlumber * and GTK). MoonBit gets one callback with the kind of event. */ #include #include #include #include #include #include #include #include "moonbit.h" enum { MM_TABS_MESSAGE = 1, MM_TABS_EOF = 2, MM_TABS_FILES = 3, MM_TABS_MEDIA = 4, }; /* Native messaging allows far more; a list of tabs never needs it. */ #define MAX_MESSAGE (1024 * 1024) typedef void (*mm_tcall_t)(void *closure, int32_t kind); static mm_tcall_t g_call; static void *g_closure; static void emit(int32_t kind) { if (g_call) { moonbit_incref(g_closure); g_call(g_closure, kind); } } MOONBIT_FFI_EXPORT void mm_tabs_set_handler(mm_tcall_t call, void *closure) { if (g_closure) moonbit_decref(g_closure); g_call = call; g_closure = closure; } static moonbit_bytes_t to_bytes(const char *s, size_t n) { moonbit_bytes_t b = moonbit_make_bytes((int32_t)n, 0); if (n) memcpy(b, s, n); return b; } MOONBIT_FFI_EXPORT int64_t mm_tabs_now_ms(void) { return g_get_monotonic_time() / 1000; } MOONBIT_FFI_EXPORT int32_t mm_tabs_getppid(void) { return getppid(); } /* ---- native messaging --------------------------------------------------- */ static GByteArray *g_in; static GString *g_message; static gboolean end_of_input(void) { emit(MM_TABS_EOF); return G_SOURCE_REMOVE; } static gboolean on_stdin(gint fd, GIOCondition cond, gpointer d) { (void)cond; (void)d; guint8 buf[65536]; ssize_t n = read(fd, buf, sizeof buf); if (n < 0 && (errno == EINTR || errno == EAGAIN)) return G_SOURCE_CONTINUE; if (n <= 0) return end_of_input(); g_byte_array_append(g_in, buf, (guint)n); while (g_in->len >= 4) { guint32 len; /* native byte order, per the protocol */ memcpy(&len, g_in->data, 4); if (len > MAX_MESSAGE) return end_of_input(); if (g_in->len < 4 + len) break; g_string_truncate(g_message, 0); g_string_append_len(g_message, (const char *)g_in->data + 4, len); g_byte_array_remove_range(g_in, 0, 4 + len); emit(MM_TABS_MESSAGE); } return G_SOURCE_CONTINUE; } static gboolean on_term(gpointer d) { (void)d; return end_of_input(); } MOONBIT_FFI_EXPORT void mm_tabs_listen(void) { g_in = g_byte_array_new(); g_message = g_string_new(NULL); g_unix_fd_add(STDIN_FILENO, G_IO_IN | G_IO_HUP | G_IO_ERR, on_stdin, NULL); g_unix_signal_add(SIGTERM, on_term, NULL); g_unix_signal_add(SIGINT, on_term, NULL); } MOONBIT_FFI_EXPORT moonbit_bytes_t mm_tabs_message(void) { return to_bytes(g_message->str, g_message->len); } /* ---- published files ---------------------------------------------------- */ static char *tabs_dir(void) { const char *dir = g_getenv("MOONMIX_TABS_DIR"); if (dir && *dir) return g_strdup(dir); /* No fallback to a shared directory: titles are private. */ dir = g_getenv("XDG_RUNTIME_DIR"); return dir && *dir ? g_build_filename(dir, "moonmix", NULL) : NULL; } static char *own_file(const char *dir) { char name[32]; g_snprintf(name, sizeof name, "%d.json", (int)getpid()); return g_build_filename(dir, name, NULL); } MOONBIT_FFI_EXPORT int32_t mm_tabs_publish(moonbit_bytes_t text) { g_autofree char *dir = tabs_dir(); if (!dir || g_mkdir_with_parents(dir, 0700) != 0) return -1; g_autofree char *path = own_file(dir); return g_file_set_contents_full(path, (const char *)text, -1, G_FILE_SET_CONTENTS_CONSISTENT, 0600, NULL) ? 0 : -1; } MOONBIT_FFI_EXPORT void mm_tabs_unpublish(void) { g_autofree char *dir = tabs_dir(); if (dir) { g_autofree char *path = own_file(dir); g_unlink(path); } } /* Remove files whose host was killed before it could. */ MOONBIT_FFI_EXPORT void mm_tabs_prune(void) { g_autofree char *dir = tabs_dir(); g_autoptr(GDir) d = dir ? g_dir_open(dir, 0, NULL) : NULL; const char *name; while (d && (name = g_dir_read_name(d))) { char *end; long pid = strtol(name, &end, 10); if (pid <= 0 || strcmp(end, ".json") != 0) continue; g_autofree char *proc = g_strdup_printf("/proc/%ld", pid); if (!g_file_test(proc, G_FILE_TEST_EXISTS)) { g_autofree char *path = g_build_filename(dir, name, NULL); g_unlink(path); } } } /* Every published file (each is one line of JSON), newline separated. */ MOONBIT_FFI_EXPORT moonbit_bytes_t mm_tabs_read(void) { g_autofree char *dir = tabs_dir(); g_autoptr(GDir) d = dir ? g_dir_open(dir, 0, NULL) : NULL; g_autoptr(GString) out = g_string_new(NULL); const char *name; while (d && (name = g_dir_read_name(d))) { if (!g_str_has_suffix(name, ".json")) continue; g_autofree char *path = g_build_filename(dir, name, NULL); g_autofree char *text = NULL; gsize len; if (g_file_get_contents(path, &text, &len, NULL) && len <= MAX_MESSAGE) { g_string_append_len(out, text, (gssize)len); g_string_append_c(out, '\n'); } } return to_bytes(out->str, out->len); } static void on_dir_changed(GFileMonitor *m, GFile *f, GFile *other, GFileMonitorEvent ev, gpointer d) { (void)m; (void)f; (void)other; (void)ev; (void)d; emit(MM_TABS_FILES); } MOONBIT_FFI_EXPORT void mm_tabs_watch(void) { static GFileMonitor *monitor; g_autofree char *dir = tabs_dir(); if (monitor || !dir) return; /* May fail on the container's read-only mount, where it already exists. */ g_mkdir_with_parents(dir, 0700); g_autoptr(GFile) file = g_file_new_for_path(dir); monitor = g_file_monitor_directory(file, G_FILE_MONITOR_WATCH_MOVES, NULL, NULL); if (monitor) g_signal_connect(monitor, "changed", G_CALLBACK(on_dir_changed), NULL); } /* ---- MPRIS -------------------------------------------------------------- */ #define MPRIS "org.mpris.MediaPlayer2" #define MPRIS_CHROMIUM MPRIS ".chromium.instance" static GDBusConnection *g_bus; static GHashTable *g_titles; /* browser pid -> char *title, while playing */ static guint g_rescan; typedef struct { GHashTable *titles; int pending; } Scan; static void scan_done(Scan *scan) { if (--scan->pending > 0) return; if (g_titles) g_hash_table_unref(g_titles); g_titles = scan->titles; g_free(scan); emit(MM_TABS_MEDIA); } typedef struct { Scan *scan; int pid; } Query; static void on_player(GObject *src, GAsyncResult *res, gpointer d) { Query *q = d; g_autoptr(GVariant) ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src), res, NULL); if (ret) { g_autoptr(GVariant) props = g_variant_get_child_value(ret, 0); g_autoptr(GVariant) meta = g_variant_lookup_value(props, "Metadata", G_VARIANT_TYPE_VARDICT); const char *status = NULL, *title = NULL; if (g_variant_lookup(props, "PlaybackStatus", "&s", &status) && strcmp(status, "Playing") == 0 && meta && g_variant_lookup(meta, "xesam:title", "&s", &title) && *title) g_hash_table_insert(q->scan->titles, GINT_TO_POINTER(q->pid), g_strdelimit(g_strdup(title), "\t\r\n", ' ')); } scan_done(q->scan); g_free(q); } static void on_names(GObject *src, GAsyncResult *res, gpointer d) { (void)d; g_autoptr(GVariant) ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src), res, NULL); if (!ret) return; Scan *scan = g_new0(Scan, 1); scan->titles = g_hash_table_new_full(NULL, NULL, NULL, g_free); scan->pending = 1; g_autoptr(GVariantIter) it = NULL; const char *name; g_variant_get(ret, "(as)", &it); while (g_variant_iter_next(it, "&s", &name)) { if (!g_str_has_prefix(name, MPRIS_CHROMIUM)) continue; int pid = atoi(name + strlen(MPRIS_CHROMIUM)); if (pid <= 0) continue; Query *q = g_new0(Query, 1); q->scan = scan; q->pid = pid; scan->pending++; g_dbus_connection_call( G_DBUS_CONNECTION(src), name, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties", "GetAll", g_variant_new("(s)", MPRIS ".Player"), G_VARIANT_TYPE("(a{sv})"), G_DBUS_CALL_FLAGS_NO_AUTO_START, 2000, NULL, on_player, q); } scan_done(scan); } static gboolean rescan(gpointer d) { (void)d; g_rescan = 0; g_dbus_connection_call(g_bus, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListNames", NULL, G_VARIANT_TYPE("(as)"), G_DBUS_CALL_FLAGS_NO_AUTO_START, 2000, NULL, on_names, NULL); return G_SOURCE_REMOVE; } static void on_mpris_signal(GDBusConnection *c, const char *sender, const char *path, const char *iface, const char *signal, GVariant *params, gpointer d) { (void)c; (void)sender; (void)path; (void)iface; (void)signal; (void)params; (void)d; if (!g_rescan) g_rescan = g_timeout_add(100, rescan, NULL); } MOONBIT_FFI_EXPORT void mm_tabs_watch_media(void) { if (g_bus) return; g_bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL); if (!g_bus) return; g_dbus_connection_signal_subscribe( g_bus, "org.freedesktop.DBus", "org.freedesktop.DBus", "NameOwnerChanged", "/org/freedesktop/DBus", MPRIS, G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE, on_mpris_signal, NULL, NULL); g_dbus_connection_signal_subscribe( g_bus, NULL, "org.freedesktop.DBus.Properties", "PropertiesChanged", "/org/mpris/MediaPlayer2", MPRIS ".Player", G_DBUS_SIGNAL_FLAGS_NONE, on_mpris_signal, NULL, NULL); rescan(NULL); } /* "pid\ttitle\n" for every browser that is playing. */ MOONBIT_FFI_EXPORT moonbit_bytes_t mm_tabs_media(void) { g_autoptr(GString) out = g_string_new(NULL); GHashTableIter it; gpointer pid, title; if (g_titles) { g_hash_table_iter_init(&it, g_titles); while (g_hash_table_iter_next(&it, &pid, &title)) g_string_append_printf(out, "%d\t%s\n", GPOINTER_TO_INT(pid), (char *)title); } return to_bytes(out->str, out->len); }