diff --git a/CHANGELOG.md b/CHANGELOG.md index 58f2e2d..ff851de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to cloofy. The format follows [Keep a Changelog](https://kee - **Your terminal's colors.** Settings has Colors now. **Terminal** takes your terminal's background and text, with the shades in between mixed from them, so cloofy looks at home in a purple Ptyxis on Ubuntu or any other theme. **Auto** stays as before: Omarchy's theme there, cloofy's own dark colors elsewhere, which **cloofy** keeps everywhere. - **Your own colors.** Any of cloofy's colors in `~/.config/cloofy/theme.toml`, such as `bg = "#2b0a3d"`, go over the others. cloofy follows the file as you edit it. +- **Notifications on Linux in every terminal.** Song notifications come from the desktop, with the cover, in terminals without notifications of their own, like Alacritty, foot, Konsole or GNOME Terminal: from GNOME, KDE Plasma or a notification daemon like mako or dunst. On Hyprland they always come from the desktop, as on Omarchy, and a click on one brings cloofy to the front. Over SSH they stay with the terminal. ### Changed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ed32124..e66eef6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,7 +25,7 @@ Some tests need a program and skip themselves without it. CI has them all and se | Needs | Tests | In CI | |---|---|---| | mpv | YouTube Music's player | `CLOOFY_REQUIRE_MPV=1` | -| a D-Bus session bus (Linux) | the media controls over MPRIS | `CLOOFY_REQUIRE_DBUS=1`, under `dbus-run-session` | +| a D-Bus session bus (Linux) | the media controls over MPRIS, the desktop's notifications | `CLOOFY_REQUIRE_DBUS=1`, under `dbus-run-session` | Tests that go online are `#[ignore = "online"]`. Run them with: diff --git a/README.md b/README.md index 7bb6746..e5c0fe8 100644 --- a/README.md +++ b/README.md @@ -243,7 +243,7 @@ cloofy draws with its own dark colors, or with Omarchy's theme. With Colors set Power saving stops animations and redraws less often. Unless set otherwise, it turns on by itself with Low Power Mode on macOS and the Power Saver profile on Linux. -Inside tmux, notifications need `set -g focus-events on` and `set -g allow-passthrough all` in `~/.tmux.conf`. With `credentials = "keychain"`, cloofy moves its sign-ins into the macOS Keychain on the next start; macOS asks once after each update, because release builds aren't signed yet. +Inside tmux, notifications need `set -g focus-events on`, and the terminal's own also `set -g allow-passthrough all`, in `~/.tmux.conf`. With `credentials = "keychain"`, cloofy moves its sign-ins into the macOS Keychain on the next start; macOS asks once after each update, because release builds aren't signed yet. cloofy keeps its sign-ins (unless they are in the Keychain) and its session in `~/.local/share/cloofy`, and its caches and log in `~/.cache/cloofy`. @@ -265,10 +265,11 @@ On [Omarchy](https://omarchy.org), cloofy takes its colors from the theme and fo | --- | --- | --- | --- | | Ghostty, kitty, WezTerm | Real images | Built in | Yes | | iTerm2 | Real images | With a Nerd Font | Yes | -| foot, Windows Terminal, Konsole, VS Code, xterm, mlterm | Real images | With a Nerd Font | No | -| Others | Real images with Sixel, else blocks | With a Nerd Font | No | +| foot, Konsole, VS Code, xterm, mlterm | Real images | With a Nerd Font | On Linux | +| Windows Terminal | Real images | With a Nerd Font | No | +| Others | Real images with Sixel, else blocks | With a Nerd Font | On Linux | -Every terminal needs true color. Without a Nerd Font, pick text icons in Settings. VS Code shows images once `terminal.integrated.enableImages` is on, xterm when started with `-ti 340`, and Windows Terminal from version 1.22. Inside tmux, covers are real images in Ghostty and kitty and blocks elsewhere, because tmux keeps only a few Sixel images at a time. On Omarchy, notifications come from the desktop in every terminal. +Every terminal needs true color. Without a Nerd Font, pick text icons in Settings. VS Code shows images once `terminal.integrated.enableImages` is on, xterm when started with `-ti 340`, and Windows Terminal from version 1.22. Inside tmux, covers are real images in Ghostty and kitty and blocks elsewhere, because tmux keeps only a few Sixel images at a time. On Linux, terminals without notifications of their own get them from the desktop, with the cover, and on Hyprland and Omarchy every terminal does. ## FAQ diff --git a/crates/cloofy-os/src/linux/notifications.rs b/crates/cloofy-os/src/linux/notifications.rs index 24f2181..7e4aa36 100644 --- a/crates/cloofy-os/src/linux/notifications.rs +++ b/crates/cloofy-os/src/linux/notifications.rs @@ -1,5 +1,6 @@ //! Desktop notifications sent to the desktop's notification server itself, rather than through -//! the terminal: that way they can carry the cover, which Omarchy's notifications show. +//! the terminal: that way they carry the cover, and they also work in terminals without +//! notifications of their own. use std::{ collections::HashMap, @@ -11,7 +12,7 @@ use std::{ }; use futures::StreamExt; -use zbus::{Connection, Proxy, Variant}; +use zbus::{Connection, Proxy, Variant, fdo, names::WellKnownName}; use super::{bus, media}; @@ -31,14 +32,24 @@ struct Shown { id: u32, image: Option, written: u64, + /// Whether the server reads markup in the body, once asked. + markup: Option, +} + +/// Whether a click on a notification brings cloofy's window to the front: on Hyprland. +pub fn click_raises() -> bool { + media::can_raise() } impl Notifications { - /// `None` without a session bus. + /// `None` without a session bus, or without a notification server on it. pub fn new() -> Option { - let connection = bus::run(bus::session())?; + let connection = bus::run(async { + let connection = bus::session().await?; + has_server(&connection).await.then_some(connection) + })?; let shown = Arc::default(); - if media::can_raise() { + if click_raises() { bus::spawn(raise_on_click(connection.clone(), Arc::downgrade(&shown))); } Some(Self { connection, shown }) @@ -48,13 +59,23 @@ impl Notifications { /// the notification shown before. pub fn show(&self, title: &str, body: &str, image: Option>) { let (connection, shown) = (self.connection.clone(), self.shown.clone()); - let (title, body) = (title.to_owned(), escape(body)); + let (title, body) = (title.to_owned(), body.to_owned()); bus::spawn(async move { + let markup = shown.lock().unwrap_or_else(PoisonError::into_inner).markup; + let markup = match markup { + Some(markup) => markup, + None => { + let markup = takes_markup(&connection).await; + shown.lock().unwrap_or_else(PoisonError::into_inner).markup = Some(markup); + markup + } + }; + let body = if markup { escape(&body) } else { body }; let (replaces, image) = { let mut shown = shown.lock().unwrap_or_else(PoisonError::into_inner); (shown.id, image.and_then(|image| shown.write(&image))) }; - let arguments = notify_arguments(replaces, &title, &body, image.as_deref()); + let arguments = notify_arguments(replaces, &title, &body, image.as_deref(), click_raises()); let reply = connection.call_method(Some(SERVER), PATH, Some(SERVER), "Notify", &arguments).await; match reply.and_then(|reply| reply.body().deserialize::()) { Ok(id) => shown.lock().unwrap_or_else(PoisonError::into_inner).id = id, @@ -76,8 +97,15 @@ impl Drop for Notifications { type NotifyArguments<'a> = (&'a str, u32, &'a str, &'a str, &'a str, &'a [&'a str], HashMap<&'a str, Variant<'a>>, i32); /// What `Notify` takes: app, the notification it replaces, icon, title, body, actions, hints -/// and how long it shows (the server's choice). -fn notify_arguments<'a>(replaces: u32, title: &'a str, body: &'a str, image: Option<&Path>) -> NotifyArguments<'a> { +/// and how long it shows (the server's choice). `clickable` where a click brings cloofy to the +/// front. +fn notify_arguments<'a>( + replaces: u32, + title: &'a str, + body: &'a str, + image: Option<&Path>, + clickable: bool, +) -> NotifyArguments<'a> { let mut hints = HashMap::from([ ("desktop-entry", Variant::from("cloofy")), ("omarchy-glyph", Variant::from(GLYPH)), @@ -89,10 +117,37 @@ fn notify_arguments<'a>(replaces: u32, title: &'a str, body: &'a str, image: Opt } // The action a click on the notification takes; it shows no button. A slice, since a fixed // array would go over the bus as a structure, which `Notify` doesn't take. - let actions: &[&str] = &["default", "Show cloofy"]; + let actions: &[&str] = if clickable { &["default", "Show cloofy"] } else { &[] }; ("cloofy", replaces, "cloofy", title, body, actions, hints, -1) } +/// Whether a notification server runs or the bus starts one when asked: without, notifications +/// would go nowhere, as on a desktop without one or a server reached over SSH. +async fn has_server(connection: &Connection) -> bool { + let found = async { + let bus = fdo::DBusProxy::new(connection).await?; + if bus.name_has_owner(WellKnownName::from_static_str_unchecked(SERVER).into()).await? { + return Ok(true); + } + let startable = bus.list_activatable_names().await?; + Ok::<_, fdo::Error>(startable.iter().any(|name| name.as_str() == SERVER)) + }; + found.await.inspect_err(|err| tracing::debug!("notification server: {err}")).unwrap_or(false) +} + +/// Whether the server reads markup in the body; asked only once there is something to show, as +/// asking starts a server that isn't running yet. +async fn takes_markup(connection: &Connection) -> bool { + let reply = connection.call_method(Some(SERVER), PATH, Some(SERVER), "GetCapabilities", &()).await; + match reply.and_then(|reply| reply.body().deserialize::>()) { + Ok(capabilities) => capabilities.iter().any(|capability| capability == "body-markup"), + Err(err) => { + tracing::debug!("notification server's capabilities: {err}"); + false + } + } +} + /// Brings cloofy's window to the front when the notification on screen is clicked, for as long /// as there are notifications. async fn raise_on_click(connection: Connection, shown: Weak>) { @@ -135,7 +190,7 @@ impl Shown { } } -/// The body may hold markup, so text that looks like it is escaped. +/// For servers that read markup in the body, text that looks like it is escaped. fn escape(text: &str) -> String { text.replace('&', "&").replace('<', "<").replace('>', ">") } @@ -148,10 +203,14 @@ mod tests { #[test] fn calls_notify_with_its_signature() { - let arguments = notify_arguments(3, "Strobe", "deadmau5", Some(Path::new("/run/cover.jpg"))); + let arguments = notify_arguments(3, "Strobe", "deadmau5", Some(Path::new("/run/cover.jpg")), true); assert_eq!(arguments.signature().to_string(), "(susssasa{sv}i)"); assert_eq!(arguments.1, 3, "replaces the one before"); + assert_eq!(arguments.5, ["default", "Show cloofy"]); assert_eq!(arguments.6["image-path"], Variant::from("file:///run/cover.jpg")); + let arguments = notify_arguments(0, "Strobe", "deadmau5", None, false); + assert!(arguments.5.is_empty(), "no click to offer where it does nothing"); + assert_eq!(arguments.signature().to_string(), "(susssasa{sv}i)"); } #[test] diff --git a/crates/cloofy-os/tests/notifications.rs b/crates/cloofy-os/tests/notifications.rs new file mode 100644 index 0000000..6b4309a --- /dev/null +++ b/crates/cloofy-os/tests/notifications.rs @@ -0,0 +1,118 @@ +//! Song notifications on a real session bus, as the desktop's notification server gets them. CI +//! runs this under `dbus-run-session` with `CLOOFY_REQUIRE_DBUS=1`; elsewhere it passes without +//! looking, also on a desktop whose own server holds the name. +#![cfg(target_os = "linux")] + +use std::{ + collections::HashMap, + future::Future, + sync::{Arc, Mutex}, + time::{Duration, Instant}, +}; + +use cloofy_os::notifications::Notifications; +use zbus::{Connection, OwnedVariant, fdo, interface, names::WellKnownName}; + +const SERVER: &str = "org.freedesktop.Notifications"; +const PATH: &str = "/org/freedesktop/Notifications"; + +/// What a notification server got: title, body and the cover's path. +type Shown = Arc)>>>; + +/// A notification server, with markup in the body or without. +struct Server { + markup: bool, + shown: Shown, +} + +#[interface(name = "org.freedesktop.Notifications")] +impl Server { + fn get_capabilities(&self) -> Vec<&'static str> { + if self.markup { vec!["body", "body-markup", "actions"] } else { vec!["body", "actions"] } + } + + #[allow(clippy::too_many_arguments)] + fn notify( + &self, + _app: String, + _replaces: u32, + _icon: String, + title: String, + body: String, + _actions: Vec, + hints: HashMap, + _timeout: i32, + ) -> u32 { + let image = hints.get("image-path").and_then(|path| String::try_from(path.try_clone().ok()?).ok()); + let mut shown = self.shown.lock().unwrap(); + shown.push((title, body, image)); + shown.len() as u32 + } + + fn get_server_information(&self) -> (&str, &str, &str, &str) { + ("fake", "cloofy", "1", "1.2") + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn shows_songs_on_the_desktop_s_server_with_the_cover() { + if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_none() { + assert!(std::env::var_os("CLOOFY_REQUIRE_DBUS").is_none(), "no session bus"); + return eprintln!("no session bus, skipped"); + } + let bus = fdo::DBusProxy::new(&Connection::session().await.unwrap()).await.unwrap(); + let name = || WellKnownName::from_static_str_unchecked(SERVER).into(); + if bus.name_has_owner(name()).await.unwrap() { + assert!(std::env::var_os("CLOOFY_REQUIRE_DBUS").is_none(), "a server runs already"); + return eprintln!("the desktop's notification server runs, skipped"); + } + let startable = bus.list_activatable_names().await.unwrap(); + if !startable.iter().any(|name| name.as_str() == SERVER) { + assert!(Notifications::new().is_none(), "nowhere to show them without a server"); + } + + let shown = Shown::default(); + let server = serve(true, shown.clone()).await; + let notifications = Notifications::new().expect("a server to show them"); + let cover = b"\xff\xd8\xffjpeg".as_slice(); + notifications.show("Strobe", "deadmau5 · & more", Some(cover.into())); + let (title, body, image) = + eventually("the notification", || async { shown.lock().unwrap().first().cloned() }).await; + assert_eq!(title, "Strobe"); + assert_eq!(body, "deadmau5 · <live> & more", "escaped for a server that reads markup"); + let image = url::Url::parse(&image.expect("the cover")).unwrap().to_file_path().unwrap(); + assert_eq!(std::fs::read(&image).unwrap(), cover); + drop(notifications); + assert!(!image.exists(), "the cover goes with cloofy"); + server.release_name(SERVER).await.unwrap(); + + let plain = Shown::default(); + let _server = serve(false, plain.clone()).await; + let notifications = Notifications::new().expect("a server to show them"); + notifications.show("Strobe", "deadmau5 · & more", None); + let (_, body, image) = eventually("the notification", || async { plain.lock().unwrap().first().cloned() }).await; + assert_eq!(body, "deadmau5 · & more", "as it is for a server that shows text as it is"); + assert_eq!(image, None::); +} + +/// A notification server on the session bus, until the connection goes. +async fn serve(markup: bool, shown: Shown) -> Connection { + zbus::connection::Builder::session() + .serve_at(PATH, Server { markup, shown }) + .name(SERVER) + .build() + .await + .expect("the notification server's name") +} + +/// Asks until `check` has an answer, for at most five seconds. +async fn eventually>>(what: &str, mut check: impl FnMut() -> F) -> T { + let started = Instant::now(); + loop { + if let Some(found) = check().await { + return found; + } + assert!(started.elapsed() < Duration::from_secs(5), "{what} never came"); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} diff --git a/crates/cloofy-tui/src/notify.rs b/crates/cloofy-tui/src/notify.rs index d5ada80..2619f89 100644 --- a/crates/cloofy-tui/src/notify.rs +++ b/crates/cloofy-tui/src/notify.rs @@ -1,7 +1,8 @@ //! Desktop notifications for new tracks while cloofy's window is in the background. They go //! through the terminal's own escape sequence, so they need no permission of their own and a -//! click leads back to the terminal. Under Omarchy they go to the desktop directly instead, -//! which shows the cover with them. +//! click leads back to the terminal. On Linux they go to the desktop directly in terminals +//! without notifications of their own, and on Hyprland in all of them: the desktop shows the +//! cover with them, and there a click brings cloofy's window to the front. use std::{sync::Arc, time::Duration}; @@ -38,37 +39,28 @@ enum Channel { /// Inside tmux, which passes the sequence on only when wrapped. tmux: bool, }, - /// The desktop's notification server, under Omarchy: its notifications show the cover, and - /// a click on one brings cloofy's window to the front. + /// The desktop's notification server: its notifications show the cover, and on Hyprland a + /// click on one brings cloofy's window to the front. #[cfg(target_os = "linux")] Desktop(cloofy_os::notifications::Notifications), } impl Notifier { - /// `None` in terminals without notifications, unless Omarchy shows them. + /// The terminal's notifications, or the desktop's on Linux where they do better. `None` + /// without either. pub fn detect() -> Option { + let terminal = Protocol::detect().map(|protocol| Channel::Terminal { protocol, tmux: set("TMUX") }); + // A click on the terminal's notification brings its window to the front, which only + // Hyprland lets cloofy do for the desktop's. Over SSH the desktop's session bus belongs + // to another computer, whose screen nobody is looking at. #[cfg(target_os = "linux")] - if crate::omarchy::state_dir().is_some() + if (terminal.is_none() || cloofy_os::notifications::click_raises()) + && !set("SSH_CONNECTION") && let Some(desktop) = cloofy_os::notifications::Notifications::new() { return Some(Self::new(Channel::Desktop(desktop))); } - let var = |name| std::env::var(name).unwrap_or_default(); - let set = |name| std::env::var_os(name).is_some(); - let protocol = if set("KITTY_WINDOW_ID") || var("TERM").contains("kitty") { - Protocol::Kitty - } else if set("GHOSTTY_RESOURCES_DIR") || set("WEZTERM_PANE") { - Protocol::Rxvt - } else if set("ITERM_SESSION_ID") { - Protocol::ITerm - } else { - match var("TERM_PROGRAM").as_str() { - "ghostty" | "WezTerm" => Protocol::Rxvt, - "iTerm.app" => Protocol::ITerm, - _ => return None, - } - }; - Some(Self::new(Channel::Terminal { protocol, tmux: set("TMUX") })) + terminal.map(Self::new) } fn new(channel: Channel) -> Self { @@ -124,6 +116,30 @@ impl Notifier { } } +impl Protocol { + /// The terminal's, from what it sets in the environment. + fn detect() -> Option { + let var = |name| std::env::var(name).unwrap_or_default(); + if set("KITTY_WINDOW_ID") || var("TERM").contains("kitty") { + Some(Self::Kitty) + } else if set("GHOSTTY_RESOURCES_DIR") || set("WEZTERM_PANE") { + Some(Self::Rxvt) + } else if set("ITERM_SESSION_ID") { + Some(Self::ITerm) + } else { + match var("TERM_PROGRAM").as_str() { + "ghostty" | "WezTerm" => Some(Self::Rxvt), + "iTerm.app" => Some(Self::ITerm), + _ => None, + } + } + } +} + +fn set(name: &str) -> bool { + std::env::var_os(name).is_some() +} + fn sequence(protocol: Protocol, tmux: bool, title: &str, body: &str) -> String { let (title, body) = (clean(title), clean(body)); let sequence = match protocol { diff --git a/website/src/content/docs/docs/settings.md b/website/src/content/docs/docs/settings.md index 6b26f97..895f0df 100644 --- a/website/src/content/docs/docs/settings.md +++ b/website/src/content/docs/docs/settings.md @@ -54,7 +54,7 @@ Power saving stops animations and redraws less often. Unless set otherwise, it t ## Notifications -Each new track shows a desktop notification while cloofy's window is in the background, in kitty, Ghostty, WezTerm and iTerm2. Inside tmux, notifications need `set -g focus-events on` and `set -g allow-passthrough all` in `~/.tmux.conf`. On Omarchy they come from the desktop, with the cover, in every terminal. +Each new track shows a desktop notification while cloofy's window is in the background. kitty, Ghostty, WezTerm and iTerm2 show them themselves. On Linux, every other terminal gets them from the desktop, with the cover: from GNOME, KDE Plasma or a notification daemon like mako or dunst. On Hyprland, [Omarchy](/docs/omarchy/) included, they always come from the desktop, and a click on one brings cloofy to the front. Inside tmux, notifications need `set -g focus-events on`, and the terminal's own also `set -g allow-passthrough all`, in `~/.tmux.conf`. ## Keychain diff --git a/website/src/content/docs/docs/terminals.md b/website/src/content/docs/docs/terminals.md index cbc5fc9..bab6dcf 100644 --- a/website/src/content/docs/docs/terminals.md +++ b/website/src/content/docs/docs/terminals.md @@ -7,8 +7,9 @@ description: Which terminals show cover art as real images, icons and notificati | --- | --- | --- | --- | | Ghostty, kitty, WezTerm | Real images | Built in | Yes | | iTerm2 | Real images | With a Nerd Font | Yes | -| foot, Windows Terminal, Konsole, VS Code, xterm, mlterm | Real images | With a Nerd Font | No | -| Others | Real images with Sixel, else blocks | With a Nerd Font | No | +| foot, Konsole, VS Code, xterm, mlterm | Real images | With a Nerd Font | On Linux | +| Windows Terminal | Real images | With a Nerd Font | No | +| Others | Real images with Sixel, else blocks | With a Nerd Font | On Linux | Every terminal needs true color. Without a Nerd Font, pick text icons in [Settings](/docs/settings/). @@ -22,8 +23,8 @@ cloofy draws covers through the Kitty graphics protocol, Sixel or the iTerm2 pro ## tmux -Inside tmux, covers are real images in Ghostty and kitty and blocks elsewhere, because tmux keeps only a few Sixel images at a time. Notifications need `set -g focus-events on` and `set -g allow-passthrough all` in `~/.tmux.conf`. +Inside tmux, covers are real images in Ghostty and kitty and blocks elsewhere, because tmux keeps only a few Sixel images at a time. Notifications need `set -g focus-events on`, and the terminal's own also `set -g allow-passthrough all`, in `~/.tmux.conf`. -## Omarchy +## Notifications -On [Omarchy](/docs/omarchy/), notifications come from the desktop in every terminal, with the cover. +kitty, Ghostty, WezTerm and iTerm2 show notifications themselves, and a click on one brings their window to the front. On Linux, every other terminal gets them from the desktop instead, with the cover: from GNOME, KDE Plasma or a notification daemon like mako or dunst. On Hyprland, [Omarchy](/docs/omarchy/) included, they always come from the desktop, in every terminal, and a click on one brings cloofy to the front. Over SSH, only terminals with notifications of their own show them.