Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand All @@ -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

Expand Down
83 changes: 71 additions & 12 deletions crates/cloofy-os/src/linux/notifications.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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};

Expand All @@ -31,14 +32,24 @@ struct Shown {
id: u32,
image: Option<PathBuf>,
written: u64,
/// Whether the server reads markup in the body, once asked.
markup: Option<bool>,
}

/// 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<Self> {
let connection = bus::run(bus::session())?;
let connection = bus::run(async {
let connection = bus::session().await?;
has_server(&connection).await.then_some(connection)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
})?;
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 })
Expand All @@ -48,13 +59,23 @@ impl Notifications {
/// the notification shown before.
pub fn show(&self, title: &str, body: &str, image: Option<Arc<[u8]>>) {
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::<u32>()) {
Ok(id) => shown.lock().unwrap_or_else(PoisonError::into_inner).id = id,
Expand All @@ -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)),
Expand All @@ -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::<Vec<String>>()) {
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<Mutex<Shown>>) {
Expand Down Expand Up @@ -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('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}
Expand All @@ -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]
Expand Down
118 changes: 118 additions & 0 deletions crates/cloofy-os/tests/notifications.rs
Original file line number Diff line number Diff line change
@@ -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<Mutex<Vec<(String, String, Option<String>)>>>;

/// 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<String>,
hints: HashMap<String, OwnedVariant>,
_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 · <live> & 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 · &lt;live&gt; &amp; 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 · <live> & more", None);
let (_, body, image) = eventually("the notification", || async { plain.lock().unwrap().first().cloned() }).await;
assert_eq!(body, "deadmau5 · <live> & more", "as it is for a server that shows text as it is");
assert_eq!(image, None::<String>);
}

/// 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<T, F: Future<Output = Option<T>>>(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;
}
}
Loading
Loading