From 4ac8cd9379cf5b68d059d62f2cdcac3a4e9264bc Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 22:49:31 -0600 Subject: [PATCH] S033: tray, notifications, launcher progress, autostart, metainfo, test file Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 46 ++++ .../07 Library and tools/S033-tray-notify.md | 14 +- Plans/INDEX.md | 2 +- assets/medlar.desktop | 2 + assets/medlar.metainfo.xml | 19 ++ crates/app/Cargo.toml | 2 + crates/app/src/app.rs | 67 ++++- crates/app/src/autostart.rs | 55 ++++ crates/app/src/launcher.rs | 31 +++ crates/app/src/lib.rs | 5 + crates/app/src/notify.rs | 234 ++++++++++++++++++ crates/app/src/shell.rs | 97 ++++++++ crates/app/src/tray.rs | 187 ++++++++++++++ crates/core/lang/en.json | 20 +- crates/core/src/settings.rs | 19 ++ docs/PROGRESS.md | 4 + docs/tests/S033-tray-notify.md | 33 +++ tools/validate-desktop.sh | 9 + 18 files changed, 835 insertions(+), 11 deletions(-) create mode 100644 assets/medlar.metainfo.xml create mode 100644 crates/app/src/autostart.rs create mode 100644 crates/app/src/launcher.rs create mode 100644 crates/app/src/notify.rs create mode 100644 crates/app/src/shell.rs create mode 100644 crates/app/src/tray.rs create mode 100644 docs/tests/S033-tray-notify.md create mode 100755 tools/validate-desktop.sh diff --git a/Cargo.lock b/Cargo.lock index 568720d..21357a1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -946,6 +946,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -2621,6 +2630,26 @@ dependencies = [ "accesskit_consumer", ] +[[package]] +name = "ksni" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bcc1cb43797140f74b711f1c4a49f48a7a7429f211c5fb78264e7bcd1e99caf" +dependencies = [ + "arc-swap", + "async-executor", + "async-io", + "async-lock", + "crossbeam-queue", + "futures-channel", + "futures-lite", + "futures-util", + "pastey", + "serde", + "task-local", + "zbus", +] + [[package]] name = "kurbo" version = "0.11.3" @@ -2766,6 +2795,7 @@ dependencies = [ "eframe", "egui_kittest", "image", + "ksni", "log", "medlar-cli", "medlar-core", @@ -2777,6 +2807,7 @@ dependencies = [ "tempfile", "tokio", "url", + "zbus", ] [[package]] @@ -3606,6 +3637,12 @@ dependencies = [ "phc", ] +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pbkdf2" version = "0.13.0" @@ -5131,6 +5168,15 @@ dependencies = [ "libc", ] +[[package]] +name = "task-local" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2972044a9e5e448a506a7ff6f0d03b566d8ef4cd6918a58fc59835a0f8666626" +dependencies = [ + "pin-project-lite", +] + [[package]] name = "tempfile" version = "3.27.0" diff --git a/Plans/07 Library and tools/S033-tray-notify.md b/Plans/07 Library and tools/S033-tray-notify.md index 57f87f7..b233162 100644 --- a/Plans/07 Library and tools/S033-tray-notify.md +++ b/Plans/07 Library and tools/S033-tray-notify.md @@ -12,13 +12,13 @@ FEATURES 8.1, 8.4. - ksni docs ## Steps -- [ ] Tray icon with progress ring and speed tooltip; menu: modes, pause all, resume all, add, show, quit -- [ ] Close to tray, start minimised, autostart file; works without a tray host -- [ ] Notifications: done, failed, needs login, all done, with actions (open, show folder, continue, retry); grouped, quiet hours -- [ ] Launcher progress through the Unity D-Bus signal -- [ ] Desktop file, metainfo, MIME and scheme entries checked by their validators when present -- [ ] Test file `docs/tests/S033-tray-notify.md`, with the checks below -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S033: …`, push +- [x] Tray icon with progress ring and speed tooltip; menu: modes, pause all, resume all, add, show, quit +- [x] Close to tray, start minimised, autostart file; works without a tray host +- [x] Notifications: done, failed, needs login, all done, with actions (open, show folder, continue, retry); grouped, quiet hours +- [x] Launcher progress through the Unity D-Bus signal +- [x] Desktop file, metainfo, MIME and scheme entries checked by their validators when present +- [x] Test file `docs/tests/S033-tray-notify.md`, with the checks below +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S033: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 5feea7c..2ce84d1 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -49,7 +49,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 07 Library and tools - [x] [S027](07%20Library%20and%20tools/S027-rules-clipboard-drop.md) Rules, clipboard, drag and drop, drop target -- [ ] [S033](07%20Library%20and%20tools/S033-tray-notify.md) Tray, notifications and autostart +- [x] [S033](07%20Library%20and%20tools/S033-tray-notify.md) Tray, notifications and autostart ## 08 Motion and polish diff --git a/assets/medlar.desktop b/assets/medlar.desktop index f97ea63..f003c67 100644 --- a/assets/medlar.desktop +++ b/assets/medlar.desktop @@ -8,3 +8,5 @@ Terminal=false Categories=Network;FileTransfer; StartupWMClass=medlar MimeType=x-scheme-handler/medlar;application/metalink+xml;application/metalink4+xml; +Keywords=download;manager;torrent;video; +X-GNOME-UsesNotifications=true diff --git a/assets/medlar.metainfo.xml b/assets/medlar.metainfo.xml new file mode 100644 index 0000000..155e3bf --- /dev/null +++ b/assets/medlar.metainfo.xml @@ -0,0 +1,19 @@ + + + medlar + Medlar + A download manager + CC0-1.0 + MIT + medlar.desktop + +

Medlar splits downloads into dynamic parts, with limits, priorities, queues, video sites and a local port that takes downloads from browsers.

+
+ + medlar + + + Network + FileTransfer + +
diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index c6cde2b..6883b21 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -26,6 +26,8 @@ tokio = { version = "1", features = ["macros", "rt", "sync"] } percent-encoding = "2.3.2" url = "2" resvg = { version = "0.45", default-features = false } +ksni = { version = "0.3", default-features = false, features = ["async-io", "blocking"] } +zbus = "5" arboard = { version = "3.6", default-features = false, features = ["wayland-data-control"] } [dev-dependencies] diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index afe5c7b..fc22644 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -48,6 +48,8 @@ pub struct App { watch: Watch, clip: Option, target: crate::views::target::Target, + /// Tray, notifications and the launcher; only with an engine. + shell: Option, /// What `theme` was made from; a change in settings rebuilds it. themed: Settings, /// What the engine and the shortcuts know. @@ -85,6 +87,7 @@ impl App { watch, clip: None, target: Default::default(), + shell: None, save_at: None, saving: None, } @@ -206,6 +209,7 @@ impl App { } } if self.first.is_none() { + self.shell(ui); self.inbox.tick(ui.ctx(), &self.settings, &mut self.main); self.extras(ui.ctx(), &t); } @@ -246,6 +250,55 @@ impl App { } } + /// What the tray and the notifications ask for, and what they are told. + fn shell(&mut self, ui: &Ui) { + let Some(shell) = &mut self.shell else { return }; + let ctx = ui.ctx(); + if ctx.input(|i| i.viewport().close_requested()) && shell.hides_on_close(&self.settings) { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false)); + } + let shot = match self.main.bridge.data() { + Data::Ready(shot, _) => Some(shot), + _ => None, + }; + use crate::shell::Do; + for what in shell.tick(&self.settings, shot.as_deref()) { + let show = |ctx: &Context| { + ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true)); + ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + }; + match what { + Do::Show => show(ctx), + Do::Add => { + show(ctx); + self.main.adding.ask(crate::views::add::Request::default()); + } + Do::PauseAll => self.run(ui, Action::PauseAll), + Do::ResumeAll => self.run(ui, Action::ResumeAll), + Do::Mode(m) => crate::views::modes::Change::Mode(m).apply(&mut self.settings), + Do::Quit => { + if let Some(shell) = &mut self.shell { + shell.quitting = true; + } + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + Do::Open(file) => { + crate::views::main::open_outside(&file.to_string_lossy()); + } + Do::Folder(file) => { + crate::views::main::reveal_outside(&file); + } + Do::SignIn(url, id) => { + show(ctx); + self.main.wish = Some(Wish::SignIn(url, vec![id])); + } + Do::Retry(id) => self.main.bridge.send(medlar_core::manager::Command::Resume(id)), + } + } + } + /// The clipboard watcher, the drop target and the full-window drop state. fn extras(&mut self, ctx: &Context, t: &Theme) { use crate::bridge::Data; @@ -383,9 +436,12 @@ pub fn run() -> ExitCode { /// Whether the arguments are for a window: links of the `medlar:` scheme and link lists, as a desktop hands them over. pub fn wants(args: &[String]) -> bool { - !args.is_empty() && args.iter().all(|a| of_arg(a).is_some()) + !args.is_empty() && args.iter().all(|a| a == MINIMISED || of_arg(a).is_some()) } +/// Starts in the tray when there is one (what autostart passes). +pub const MINIMISED: &str = "--minimised"; + /// Opens the window with something to add, or hands it to the Medlar that runs and returns. pub fn run_with(args: Vec) -> ExitCode { open(true, App::show, args) @@ -397,7 +453,9 @@ pub fn run_gallery() -> ExitCode { } /// `engine`: with the downloads, else only the window. -fn open(engine: bool, show: fn(&mut App, &mut Ui), args: Vec) -> ExitCode { +fn open(engine: bool, show: fn(&mut App, &mut Ui), mut args: Vec) -> ExitCode { + let minimised = args.iter().any(|a| a == MINIMISED); + args.retain(|a| a != MINIMISED); let paths = Paths::detect(); if let Err(e) = paths.create() { eprintln!("{}: {e}", paths.config.display()); @@ -453,6 +511,11 @@ fn open(engine: bool, show: fn(&mut App, &mut Ui), args: Vec) -> ExitCod } let opening = Opening { paths, settings: app.settings.clone(), bus: Bus::System }; app.main.bridge = Bridge::open(opening, &cc.egui_ctx); + let shell = crate::shell::Shell::start(&cc.egui_ctx, &app.settings); + if minimised && shell.tray.is_some() { + cc.egui_ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false)); + } + app.shell = Some(shell); } Ok(Box::new(Window { app, show }) as Box) }; diff --git a/crates/app/src/autostart.rs b/crates/app/src/autostart.rs new file mode 100644 index 0000000..96115df --- /dev/null +++ b/crates/app/src/autostart.rs @@ -0,0 +1,55 @@ +//! The autostart entry: `/autostart/medlar.desktop`. Callers pass the config folder, so that tests use a +//! throwaway one. + +use std::io; +use std::path::{Path, PathBuf}; + +pub const FILE: &str = "medlar.desktop"; + +/// The entry's text. `exe` is the AppImage when there is one, else this program. +pub fn entry(exe: &Path, minimised: bool) -> String { + let exe = exe.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\""); + let quoted = if exe.contains([' ', '\t']) { format!("\"{exe}\"") } else { exe }; + let flag = if minimised { " --minimised" } else { "" }; + format!( + "[Desktop Entry]\nType=Application\nName=Medlar\nComment=Download manager\nExec={quoted}{flag}\nIcon=medlar\nTerminal=false\nX-GNOME-Autostart-enabled=true\n" + ) +} + +fn program() -> PathBuf { + std::env::var_os("APPIMAGE").map(PathBuf::from).or_else(|| std::env::current_exe().ok()).unwrap_or_else(|| "medlar".into()) +} + +/// Makes the entry exist (`on`) or not. Without a config folder nothing is done. +pub fn sync(config: Option, on: bool, minimised: bool) -> io::Result<()> { + let Some(config) = config else { return Ok(()) }; + sync_with(&config, &program(), on, minimised) +} + +pub fn sync_with(config: &Path, exe: &Path, on: bool, minimised: bool) -> io::Result<()> { + let file = config.join("autostart").join(FILE); + if !on { + return match std::fs::remove_file(&file) { + Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e), + _ => Ok(()), + }; + } + std::fs::create_dir_all(file.parent().unwrap_or(config))?; + std::fs::write(file, entry(exe, minimised)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn writes_and_removes() { + let dir = tempfile::tempdir().unwrap(); + sync_with(dir.path(), Path::new("/opt/My Apps/medlar"), true, true).unwrap(); + let text = std::fs::read_to_string(dir.path().join("autostart").join(FILE)).unwrap(); + assert!(text.contains("Exec=\"/opt/My Apps/medlar\" --minimised\n")); + sync_with(dir.path(), Path::new("medlar"), false, false).unwrap(); + assert!(!dir.path().join("autostart").join(FILE).exists()); + sync_with(dir.path(), Path::new("medlar"), false, false).unwrap(); + } +} diff --git a/crates/app/src/launcher.rs b/crates/app/src/launcher.rs new file mode 100644 index 0000000..a870bb5 --- /dev/null +++ b/crates/app/src/launcher.rs @@ -0,0 +1,31 @@ +//! Progress on the dock or launcher icon, through the Unity launcher entry signal that KDE, GNOME's dash-to-dock and +//! others read. Nothing happens when there is no session bus. + +use std::collections::HashMap; +use zbus::blocking::Connection; +use zbus::zvariant::Value; + +const URI: &str = "application://medlar.desktop"; + +pub struct Launcher { + conn: Connection, +} + +impl Launcher { + pub fn start() -> Option { + Connection::session().ok().map(|conn| Launcher { conn }) + } + + /// `progress` 0 to 1, None to hide the bar; `count` shows as the badge when above 0. + pub fn set(&self, progress: Option, count: usize) { + let mut props: HashMap<&str, Value> = HashMap::new(); + props.insert("progress", Value::from(progress.unwrap_or(0.0))); + props.insert("progress-visible", Value::from(progress.is_some())); + props.insert("count", Value::from(count as i64)); + props.insert("count-visible", Value::from(count > 0)); + let sent = self.conn.emit_signal(None::<&str>, "/com/canonical/unity/launcherentry/medlar", "com.canonical.Unity.LauncherEntry", "Update", &(URI, props)); + if let Err(e) = sent { + log::debug!("launcher: {e}"); + } + } +} diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index 2a8cceb..aa4351f 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -1,6 +1,7 @@ //! Medlar's window: theme, motion, widgets and views. pub mod app; +pub mod autostart; pub mod bridge; pub mod clipboard; pub mod drop; @@ -11,9 +12,13 @@ mod icondata; pub mod icons; pub mod instance; pub mod keys; +pub mod launcher; pub mod motion; +pub mod notify; +pub mod shell; pub mod theme; pub mod tokens; +pub mod tray; pub mod ui; pub mod views; diff --git a/crates/app/src/notify.rs b/crates/app/src/notify.rs new file mode 100644 index 0000000..8001f04 --- /dev/null +++ b/crates/app/src/notify.rs @@ -0,0 +1,234 @@ +//! Desktop notifications (org.freedesktop.Notifications): done, failed, needs a login, all done. Actions come back as +//! `Do`. A batch of many of one kind becomes one summary; quiet hours send nothing. + +use crate::shell::Do; +use eframe::egui::Context; +use medlar_core::model::{ErrorKind, State, TaskId}; +use medlar_core::settings::Settings; +use medlar_core::snapshot::Snapshot; +use medlar_core::tr; +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::mpsc::Sender; +use std::sync::{Arc, Mutex}; +use zbus::blocking::Connection; +use zbus::zvariant::Value; + +#[derive(Debug, Clone, PartialEq)] +pub enum Event { + Done { id: TaskId, name: String, file: PathBuf }, + Failed { id: TaskId, name: String, why: String }, + Login { id: TaskId, name: String, url: String }, + AllDone, +} + +/// Sees what changed between snapshots. The first one only sets the baseline. +#[derive(Default)] +pub struct Watcher { + seen: HashMap, + started: bool, + busy: bool, + finished: bool, +} + +fn working(s: State) -> bool { + matches!(s, State::Queued | State::Waiting | State::Running | State::Checking | State::Finishing) +} + +impl Watcher { + pub fn feed(&mut self, shot: &Snapshot) -> Vec { + let mut out = vec![]; + let mut busy = false; + for v in shot.iter() { + let (id, state) = (v.id(), v.state()); + busy |= working(state); + let before = self.seen.insert(id, state); + let Some(before) = before.filter(|_| self.started) else { continue }; + if before == state || !working(before) && before != State::Paused { + continue; + } + let t = &v.task; + match state { + State::Done => { + self.finished = true; + out.push(Event::Done { id, name: t.name.clone(), file: t.folder.join(&t.name) }); + } + State::Failed => match &t.error { + Some(e) if e.kind == Some(ErrorKind::Login) => out.push(Event::Login { id, name: t.name.clone(), url: t.url.clone() }), + e => out.push(Event::Failed { id, name: t.name.clone(), why: e.as_ref().map(|e| e.detail.clone()).unwrap_or_default() }), + }, + _ => {} + } + } + if self.started && self.busy && !busy && self.finished { + self.finished = false; + out.push(Event::AllDone); + } + self.busy = busy; + self.started = true; + out + } +} + +/// Minutes since midnight in the quiet span, which may wrap past midnight. Equal ends mean no span. +pub fn quiet_at(from: u32, to: u32, now: u32) -> bool { + match from.cmp(&to) { + std::cmp::Ordering::Equal => false, + std::cmp::Ordering::Less => (from..to).contains(&now), + std::cmp::Ordering::Greater => now >= from || now < to, + } +} + +pub fn quiet_now(s: &Settings) -> bool { + use chrono::Timelike; + let now = chrono::Local::now(); + s.quiet && quiet_at(s.quiet_from, s.quiet_to, now.hour() * 60 + now.minute()) +} + +/// One notification to show. +#[derive(Debug, Clone, PartialEq)] +pub struct Note { + pub summary: String, + pub body: String, + /// `transfer.complete`, `transfer.error` or `network`. + pub category: &'static str, + /// (key, label, what it does). + pub actions: Vec<(&'static str, String, Do)>, +} + +/// More than this many of one kind in one batch are a summary. +const MOST: usize = 3; + +pub fn notes(events: &[Event]) -> Vec { + let done: Vec<_> = events.iter().filter(|e| matches!(e, Event::Done { .. })).collect(); + let failed: Vec<_> = events.iter().filter(|e| matches!(e, Event::Failed { .. })).collect(); + let mut out = vec![]; + if done.len() > MOST { + out.push(Note { summary: tr!("notify.many_done", n = done.len()), body: String::new(), category: "transfer.complete", actions: vec![("show", tr!("notify.show"), Do::Show)] }); + } + if failed.len() > MOST { + out.push(Note { summary: tr!("notify.many_failed", n = failed.len()), body: String::new(), category: "transfer.error", actions: vec![("show", tr!("notify.show"), Do::Show)] }); + } + for e in events { + match e { + Event::Done { name, file, .. } if done.len() <= MOST => out.push(Note { + summary: tr!("notify.done"), + body: name.clone(), + category: "transfer.complete", + actions: vec![("open", tr!("notify.open"), Do::Open(file.clone())), ("folder", tr!("notify.folder"), Do::Folder(file.clone()))], + }), + Event::Failed { id, name, why } if failed.len() <= MOST => out.push(Note { + summary: tr!("notify.failed"), + body: if why.is_empty() { name.clone() } else { format!("{name}\n{why}") }, + category: "transfer.error", + actions: vec![("retry", tr!("notify.retry"), Do::Retry(*id))], + }), + Event::Login { id, name, url } => out.push(Note { + summary: tr!("notify.login"), + body: name.clone(), + category: "network", + actions: vec![("continue", tr!("notify.continue"), Do::SignIn(url.clone(), *id))], + }), + Event::AllDone => out.push(Note { summary: tr!("notify.all_done"), body: String::new(), category: "transfer.complete", actions: vec![("show", tr!("notify.show"), Do::Show)] }), + _ => {} + } + } + out +} + +type Shown = Arc>>>; + +/// Sends notes through a bus connection and turns clicks on their buttons into `Do`. +pub struct Notifier { + conn: Connection, + shown: Shown, +} + +impl Notifier { + pub fn start(conn: Connection, tx: Sender, ctx: Context) -> Notifier { + let shown: Shown = Arc::default(); + let (listen, map) = (conn.clone(), shown.clone()); + std::thread::spawn(move || listen_for_actions(listen, map, tx, ctx)); + Notifier { conn, shown } + } + + /// Shows what the events call for, unless it is quiet. Never blocks the window: it is sent from a thread. + pub fn send(&self, events: &[Event], settings: &Settings) { + if events.is_empty() || quiet_now(settings) { + return; + } + let list = notes(events); + let (conn, shown) = (self.conn.clone(), self.shown.clone()); + std::thread::spawn(move || { + for note in list { + match show(&conn, ¬e) { + Ok(id) => { + shown.lock().unwrap_or_else(|e| e.into_inner()).insert(id, note.actions.into_iter().map(|(k, _, d)| (k, d)).collect()); + } + Err(e) => log::debug!("notification: {e}"), + } + } + }); + } +} + +fn show(conn: &Connection, note: &Note) -> zbus::Result { + let mut actions: Vec<&str> = vec![]; + for (key, label, _) in ¬e.actions { + actions.extend([*key, label.as_str()]); + } + let mut hints: HashMap<&str, Value> = HashMap::new(); + hints.insert("desktop-entry", Value::from("medlar")); + hints.insert("category", Value::from(note.category)); + let reply = conn.call_method( + Some("org.freedesktop.Notifications"), + "/org/freedesktop/Notifications", + Some("org.freedesktop.Notifications"), + "Notify", + &("Medlar", 0u32, "medlar", note.summary.as_str(), note.body.as_str(), actions, hints, -1i32), + )?; + reply.body().deserialize::() +} + +fn listen_for_actions(conn: Connection, shown: Shown, tx: Sender, ctx: Context) { + let Ok(rule) = zbus::MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + .interface("org.freedesktop.Notifications") + .and_then(|b| b.member("ActionInvoked")) + .map(|b| b.build()) + else { + return; + }; + let Ok(messages) = zbus::blocking::MessageIterator::for_match_rule(rule, &conn, None) else { return }; + for message in messages.flatten() { + let Ok((id, key)) = message.body().deserialize::<(u32, String)>() else { continue }; + let what = shown.lock().unwrap_or_else(|e| e.into_inner()).get(&id).and_then(|a| a.iter().find(|(k, _)| *k == key).map(|(_, d)| d.clone())); + if let Some(what) = what { + // Opening and showing a folder need no window, but the window is the one that does them. + let _ = tx.send(what); + ctx.request_repaint(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn quiet_span_wraps_midnight() { + assert!(quiet_at(22 * 60, 7 * 60, 23 * 60)); + assert!(quiet_at(22 * 60, 7 * 60, 3 * 60)); + assert!(!quiet_at(22 * 60, 7 * 60, 12 * 60)); + assert!(quiet_at(9 * 60, 17 * 60, 10 * 60)); + assert!(!quiet_at(9 * 60, 9 * 60, 9 * 60)); + } + + #[test] + fn many_of_a_kind_become_one() { + let done = |i| Event::Done { id: i, name: format!("f{i}"), file: PathBuf::from("/x") }; + assert_eq!(notes(&[done(1), done(2)]).len(), 2); + let many: Vec<_> = (1..=5).map(done).collect(); + assert_eq!(notes(&many).len(), 1); + } +} diff --git a/crates/app/src/shell.rs b/crates/app/src/shell.rs new file mode 100644 index 0000000..2d2a568 --- /dev/null +++ b/crates/app/src/shell.rs @@ -0,0 +1,97 @@ +//! What the window shares with the desktop: tray, notifications, launcher progress and autostart. +//! One `Shell` per window; each part is left out when the desktop has no host for it. + +use crate::launcher::Launcher; +use crate::notify::{Notifier, Watcher}; +use crate::tray::{Tray, TrayState}; +use eframe::egui::Context; +use medlar_core::model::TaskId; +use medlar_core::settings::{Mode, Settings}; +use medlar_core::snapshot::Snapshot; +use std::path::PathBuf; +use std::sync::mpsc::{Receiver, Sender, channel}; + +/// What the tray or a notification asks the window to do. +#[derive(Debug, Clone, PartialEq)] +pub enum Do { + Show, + Add, + PauseAll, + ResumeAll, + Mode(Mode), + Quit, + Open(PathBuf), + Folder(PathBuf), + SignIn(String, TaskId), + Retry(TaskId), +} + +pub struct Shell { + pub tray: Option, + notes: Option, + launcher: Option, + watcher: Watcher, + rx: Receiver, + shown: Option, + rev: u64, + /// What autostart was last made to match. + autostart: (bool, bool), + /// Set by `Do::Quit`, so that closing really closes. + pub quitting: bool, +} + +impl Shell { + pub fn start(ctx: &Context, settings: &Settings) -> Shell { + let (tx, rx): (Sender, Receiver) = channel(); + let tray = settings.tray.then(|| Tray::start(tx.clone(), ctx.clone())).flatten(); + let notes = zbus::blocking::Connection::session().ok().map(|c| Notifier::start(c, tx, ctx.clone())); + Shell { + tray, + notes, + launcher: Launcher::start(), + watcher: Watcher::default(), + rx, + shown: None, + rev: u64::MAX, + autostart: (settings.autostart, settings.start_minimised), + quitting: false, + } + } + + /// Whether closing the window hides it instead. + pub fn hides_on_close(&self, settings: &Settings) -> bool { + !self.quitting && settings.close_to_tray && self.tray.is_some() + } + + /// Once per frame: what was asked comes back, what changed goes out. + pub fn tick(&mut self, settings: &Settings, shot: Option<&Snapshot>) -> Vec { + let want = (settings.autostart, settings.start_minimised); + if want != self.autostart { + self.autostart = want; + if let Err(e) = crate::autostart::sync(dirs::config_dir(), want.0, want.1) { + log::warn!("autostart: {e}"); + } + } + if let Some(shot) = shot { + let fresh = shot.rev != self.rev; + self.rev = shot.rev; + if fresh { + let events = self.watcher.feed(shot); + if let Some(notes) = self.notes.as_ref().filter(|_| settings.notify) { + notes.send(&events, settings); + } + } + let state = TrayState::of(shot, settings.mode); + if self.shown.as_ref() != Some(&state) { + if let Some(tray) = &self.tray { + tray.set(state.clone()); + } + if let Some(launcher) = &self.launcher { + launcher.set(state.progress, state.running); + } + self.shown = Some(state); + } + } + self.rx.try_iter().collect() + } +} diff --git a/crates/app/src/tray.rs b/crates/app/src/tray.rs new file mode 100644 index 0000000..20b90f4 --- /dev/null +++ b/crates/app/src/tray.rs @@ -0,0 +1,187 @@ +//! The tray icon (StatusNotifierItem): a progress ring around the app icon, the speed as tooltip and a menu. +//! Without a StatusNotifierWatcher on the bus `start` gives None, and the window closes as usual. + +use crate::shell::Do; +use crate::ui::odometer::rate; +use eframe::egui::Context; +use ksni::blocking::{Handle, TrayMethods}; +use medlar_core::model::State; +use medlar_core::settings::Mode; +use medlar_core::snapshot::Snapshot; +use medlar_core::tr; +use std::sync::mpsc::Sender; + +const SIZE: u32 = 64; + +/// What the tray shows; sent only when it changes. +#[derive(Debug, Clone, PartialEq)] +pub struct TrayState { + pub running: usize, + /// Bytes per second. + pub speed: u64, + /// Share done of the downloads that run, None when none do. + pub progress: Option, + pub mode: Mode, +} + +impl TrayState { + pub fn of(shot: &Snapshot, mode: Mode) -> TrayState { + let (mut size, mut done, mut running) = (0u64, 0u64, 0usize); + for v in shot.iter().filter(|v| matches!(v.state(), State::Running | State::Checking | State::Finishing)) { + running += 1; + size += v.size.unwrap_or(0); + done += v.downloaded.min(v.size.unwrap_or(0)); + } + let progress = (running > 0 && size > 0).then(|| (done as f64 / size as f64).clamp(0.0, 1.0)); + // Whole percents and 1 KiB/s steps, so that a changing speed doesn't rebuild the icon every frame. + let progress = progress.map(|p| (p * 100.0).round() / 100.0); + TrayState { running, speed: (shot.totals.speed / 1024.0).round() as u64 * 1024, progress, mode } + } +} + +/// The app icon (straight RGBA, `SIZE` square) with a ring around it: a faint track, and the done part from the top. +pub fn ring_rgba(base: &[u8], progress: Option) -> Vec { + let mut out = base.to_vec(); + let Some(p) = progress else { return out }; + let c = SIZE as f32 / 2.0; + let (outer, inner) = (c - 0.5, c - 7.0); + for y in 0..SIZE { + for x in 0..SIZE { + let (dx, dy) = (x as f32 + 0.5 - c, y as f32 + 0.5 - c); + let d = (dx * dx + dy * dy).sqrt(); + if d < inner || d > outer { + continue; + } + // Clockwise from the top, in 0..1. + let turn = (dx.atan2(-dy) / std::f32::consts::TAU).rem_euclid(1.0); + let px = &mut out[((y * SIZE + x) * 4) as usize..][..4]; + let colour = if (turn as f64) <= p { [255, 255, 255, 255] } else { [255, 255, 255, 70] }; + px.copy_from_slice(&colour); + } + } + out +} + +/// SNI wants ARGB32 in network byte order. +pub fn argb(rgba: &[u8]) -> Vec { + rgba.chunks_exact(4).flat_map(|p| [p[3], p[0], p[1], p[2]]).collect() +} + +struct Item { + tx: Sender, + ctx: Context, + base: Vec, + state: Option, +} + +impl Item { + fn send(&self, what: Do) { + let _ = self.tx.send(what); + self.ctx.request_repaint(); + } + + fn icon(&self) -> ksni::Icon { + let rgba = ring_rgba(&self.base, self.state.as_ref().and_then(|s| s.progress)); + ksni::Icon { width: SIZE as i32, height: SIZE as i32, data: argb(&rgba) } + } +} + +const MODES: [Mode; 4] = [Mode::Low, Mode::Medium, Mode::High, Mode::Snail]; + +impl ksni::Tray for Item { + fn id(&self) -> String { + "medlar".into() + } + + fn title(&self) -> String { + "Medlar".into() + } + + fn icon_name(&self) -> String { + String::new() + } + + fn icon_pixmap(&self) -> Vec { + vec![self.icon()] + } + + fn tool_tip(&self) -> ksni::ToolTip { + let description = match &self.state { + Some(s) if s.running > 0 => tr!("tray.tip_running", n = s.running, speed = rate(s.speed as f64)), + _ => tr!("tray.tip_idle"), + }; + ksni::ToolTip { icon_name: String::new(), icon_pixmap: vec![self.icon()], title: "Medlar".into(), description } + } + + fn activate(&mut self, _x: i32, _y: i32) { + self.send(Do::Show); + } + + fn menu(&self) -> Vec> { + use ksni::menu::*; + let item = |label: String, icon: &str, what: Do| -> ksni::MenuItem { + StandardItem { label, icon_name: icon.into(), activate: Box::new(move |t: &mut Self| t.send(what.clone())), ..Default::default() }.into() + }; + let mode = self.state.as_ref().map_or(Mode::High, |s| s.mode); + let modes = RadioGroup { + selected: MODES.iter().position(|m| *m == mode).unwrap_or(2), + select: Box::new(|t: &mut Self, i| t.send(Do::Mode(MODES[i]))), + options: MODES.iter().map(|m| RadioItem { label: crate::views::modes::label(*m), ..Default::default() }).collect(), + }; + vec![ + item(tr!("tray.show"), "window", Do::Show), + item(tr!("tray.add"), "list-add", Do::Add), + MenuItem::Separator, + modes.into(), + MenuItem::Separator, + item(tr!("tray.pause_all"), "media-playback-pause", Do::PauseAll), + item(tr!("tray.resume_all"), "media-playback-start", Do::ResumeAll), + MenuItem::Separator, + item(tr!("tray.quit"), "application-exit", Do::Quit), + ] + } +} + +pub struct Tray { + handle: Handle, +} + +impl Tray { + /// None when the desktop has no tray host (or the bus is out of reach). + pub fn start(tx: Sender, ctx: Context) -> Option { + let base = crate::icons::app_rgba(SIZE)?; + match (Item { tx, ctx, base, state: None }).spawn() { + Ok(handle) => Some(Tray { handle }), + Err(e) => { + log::info!("tray: {e}"); + None + } + } + } + + pub fn set(&self, state: TrayState) { + let _ = self.handle.update(move |t: &mut Item| t.state = Some(state)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ring_is_only_drawn_with_progress() { + let base = vec![0u8; (SIZE * SIZE * 4) as usize]; + assert_eq!(ring_rgba(&base, None), base); + let half = ring_rgba(&base, Some(0.5)); + let at = |x: u32, y: u32| half[((y * SIZE + x) * 4 + 3) as usize]; + // Right of centre, on the ring: done. Left: only the track. + assert_eq!(at(SIZE - 3, SIZE / 2), 255); + assert_eq!(at(2, SIZE / 2), 70); + assert_eq!(at(SIZE / 2, SIZE / 2), 0); + } + + #[test] + fn argb_moves_alpha_first() { + assert_eq!(argb(&[1, 2, 3, 4]), vec![4, 1, 2, 3]); + } +} diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index 1e69f37..c7aea58 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -914,5 +914,23 @@ "error.video.unsupported": "Medlar's video tool does not know this site or page.", "error.video.many": "The site says there were too many requests. Wait a while, then try again.", "error.video.drm": "This video is protected against copying, and Medlar will not get around that.", - "error.video.other": "The video could not be downloaded. The log has the details." + "error.video.other": "The video could not be downloaded. The log has the details.", + "tray.show": "Show Medlar", + "tray.add": "Add downloads", + "tray.pause_all": "Pause all", + "tray.resume_all": "Resume all", + "tray.quit": "Quit", + "tray.tip_running": "{n} running, {speed}", + "tray.tip_idle": "Nothing is downloading", + "notify.done": "Download finished", + "notify.failed": "Download failed", + "notify.login": "Sign-in needed", + "notify.all_done": "All downloads are finished", + "notify.many_done": "{n} downloads finished", + "notify.many_failed": "{n} downloads failed", + "notify.open": "Open", + "notify.folder": "Show folder", + "notify.continue": "Continue", + "notify.retry": "Retry", + "notify.show": "Show" } diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index 4e82a1a..d698f2d 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -43,6 +43,17 @@ pub struct Settings { pub clip_skip: Vec, /// The small ring that takes drops. pub drop_target: bool, + /// The tray icon, and closing the window into it. + pub tray: bool, + pub close_to_tray: bool, + pub start_minimised: bool, + /// Whether the desktop starts Medlar at login. + pub autostart: bool, + /// Desktop notifications, and the span (minutes after midnight) in which there are none. + pub notify: bool, + pub quiet: bool, + pub quiet_from: u32, + pub quiet_to: u32, /// See `proxy::Choice`. pub proxy: String, /// Hosts and networks it is not used for. @@ -159,6 +170,14 @@ impl Default for Settings { clip_types: vec![], clip_skip: vec![], drop_target: false, + tray: true, + close_to_tray: true, + start_minimised: false, + autostart: false, + notify: true, + quiet: false, + quiet_from: 22 * 60, + quiet_to: 7 * 60, proxy: "system".into(), proxy_bypass: ["localhost", "127.0.0.0/8", "::1"].map(String::from).into(), connector: true, diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 90e75f3..4c2ebe3 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -227,3 +227,7 @@ Seen: boxes were ticked together after the tests, against rule 3. - `core::rules` (Rule/Item/apply/expand/unique/defaults, first fit wins; settings `rules`, `clipboard`, `clip_types`, `clip_skip`, `drop_target`); Add's `tasks()` applies rules to what the user left as is (folder, queue, priority, tags, name template with collision numbers). - `app::clipboard` (thread polls arboard 1 s while ask/add; ignores start content, repeats, own copies via `clipboard::copy`), `app::drop` (full-window overlay, paths and `://` paths to Add), `views/target.rs` (own viewport, always-on-top hint, ring, menu), `views/rules.rs` and two settings pages (Rules, Clipboard and drops). - Not done: winit gives no dropped text, so browser link drags work only as paths; always-on-top is ignored by niri; no layer-shell; rules not applied by the CLI or direct engine adds; tests: `docs/tests/S027-rules-clipboard-drop.md`. + +## S033 — Tray, notifications, autostart (compiled, not tested) +- `app::{shell,tray,notify,launcher,autostart}`: `Shell` (in `App`) feeds ksni tray (ring icon, speed tooltip, mode/pause/resume/add/show/quit), notifications (Watcher diffs snapshots; summaries over 3; quiet hours; actions open/folder/continue/retry via zbus), Unity launcher signal, autostart file (`--minimised`). New settings: tray, close_to_tray, start_minimised, autostart, notify, quiet*. Close-to-tray only with a tray host. Did not reuse `views/target.rs`. `assets/medlar.metainfo.xml`, `tools/validate-desktop.sh` (appstreamcli warns: homepage). +- Not done: no settings page rows for the new settings; hidden-window redraw on Wayland unverified; fake-bus tests not written (`docs/tests/S033-tray-notify.md`). diff --git a/docs/tests/S033-tray-notify.md b/docs/tests/S033-tray-notify.md new file mode 100644 index 0000000..1d768ef --- /dev/null +++ b/docs/tests/S033-tray-notify.md @@ -0,0 +1,33 @@ +# S033 test file: tray, notifications, launcher, autostart + +All bus checks run under `dbus-run-session` with fake services, never the user's session bus. Autostart checks use a throwaway config folder. + +## HIGH +1. Fake StatusNotifierWatcher present: `Tray::start` returns Some; the fake host sees id `medlar`, an ARGB pixmap of 64x64 and a menu with Show, Add, a 4-way mode group, Pause all, Resume all, Quit. +2. No watcher on the bus: `Tray::start` returns None, no panic; closing the window then really closes it (`hides_on_close` false). +3. Fake host calls the menu items: the app receives Do::Show, Add, PauseAll, ResumeAll, Mode(x), Quit in order; Quit sets `quitting` and the window closes even with close-to-tray on. +4. Close to tray on, tray present: window close request is cancelled and the window hides; Show brings it back focused. +5. Fake Notifications service: a download going Running to Done yields one Notify call with summary "Download finished", actions open and folder, hint desktop-entry=medlar. +6. Fake service emits ActionInvoked(id, "folder") then "open": the app gets Do::Folder / Do::Open of the file. Unknown id or key: nothing happens. +7. Failed with kind Login gives a "Sign-in needed" note with action continue, which opens the sign-in dialog for that link; plain Failed gives retry, which resumes the download. +8. Autostart: `sync_with(tmp, exe, true, true)` writes `autostart/medlar.desktop` with `Exec=... --minimised`; a path with spaces is quoted; `false` removes it; removing twice is fine. + +## MED +9. First snapshot after start sends no notifications (baseline only); paused-then-done also notifies; Done seen on load does not. +10. 5 finished in one batch give one "5 downloads finished" note; 3 give three. +11. "All downloads are finished" comes once when the last running download ends after at least one finish, not when the last one is paused. +12. Quiet hours: span 22:00-07:00 is quiet at 23:00 and 03:00, not at 12:00; equal ends never quiet; with quiet on, no Notify call reaches the fake service. +13. Setting `notify` off: no Notify calls. +14. Tray ring: with progress None the icon equals the app icon; at 50% the right half of the ring is opaque, left half faint, centre untouched. Tooltip reads "N running, speed" and "Nothing is downloading" when idle. +15. Launcher: a fake bus listener sees `com.canonical.Unity.LauncherEntry.Update` with `application://medlar.desktop`, progress between 0 and 1, progress-visible true while downloading and false after. +16. `medlar --minimised` is accepted by `wants`, is not passed on as a link, and starts hidden only if a tray exists. +17. `tools/validate-desktop.sh` passes; with desktop-file-validate and appstreamcli present, both report no errors. + +## LOW +18. Settings round trip keeps tray, close_to_tray, start_minimised, autostart, notify, quiet, quiet_from, quiet_to; an old file without them gets the defaults. + +## Doubts +- A hidden window may get no redraws on Wayland, so tray commands, notifications and launcher updates could stall while it is hidden. Check by hiding to tray, then clicking Show, and finishing a download while hidden. +- No settings page controls the new settings yet (file only); a later plan adds the rows. +- The ksni tooltip and radio group look differs per tray host; check in KDE and a GNOME host if available. +- The Unity signal body (s, a{sv}) is built with zbus tuple flattening; verify on the wire. diff --git a/tools/validate-desktop.sh b/tools/validate-desktop.sh new file mode 100755 index 0000000..eb32e71 --- /dev/null +++ b/tools/validate-desktop.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# Checks the desktop file, the metainfo, and that the MIME and scheme entries are there. Validators run when present. +cd "$(dirname "$0")/.." || exit 1 +rc=0 +grep -q 'x-scheme-handler/medlar' assets/medlar.desktop || { echo "scheme entry missing"; rc=1; } +grep -q 'application/metalink' assets/medlar.desktop || { echo "metalink MIME entry missing"; rc=1; } +if command -v desktop-file-validate >/dev/null; then desktop-file-validate assets/medlar.desktop || rc=1; else echo "desktop-file-validate not here"; fi +if command -v appstreamcli >/dev/null; then appstreamcli validate --no-net assets/medlar.metainfo.xml || rc=1; else echo "appstreamcli not here"; fi +exit $rc