S033: tray, notifications, launcher progress, autostart, metainfo, test file
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
parent
8e00dcd6cc
commit
4ac8cd9379
10 changed files with 835 additions and 11 deletions
|
|
@ -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]
|
||||
|
|
|
|||
|
|
@ -48,6 +48,8 @@ pub struct App {
|
|||
watch: Watch,
|
||||
clip: Option<crate::clipboard::Watch>,
|
||||
target: crate::views::target::Target,
|
||||
/// Tray, notifications and the launcher; only with an engine.
|
||||
shell: Option<crate::shell::Shell>,
|
||||
/// 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<String>) -> 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<String>) -> ExitCode {
|
||||
fn open(engine: bool, show: fn(&mut App, &mut Ui), mut args: Vec<String>) -> 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<String>) -> 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<dyn eframe::App>)
|
||||
};
|
||||
|
|
|
|||
55
crates/app/src/autostart.rs
Normal file
55
crates/app/src/autostart.rs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
//! The autostart entry: `<config>/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<PathBuf>, 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();
|
||||
}
|
||||
}
|
||||
31
crates/app/src/launcher.rs
Normal file
31
crates/app/src/launcher.rs
Normal file
|
|
@ -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<Launcher> {
|
||||
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<f64>, 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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
||||
|
|
|
|||
234
crates/app/src/notify.rs
Normal file
234
crates/app/src/notify.rs
Normal file
|
|
@ -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<TaskId, State>,
|
||||
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<Event> {
|
||||
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<Note> {
|
||||
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<Mutex<HashMap<u32, Vec<(&'static str, Do)>>>>;
|
||||
|
||||
/// 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<Do>, 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<u32> {
|
||||
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::<u32>()
|
||||
}
|
||||
|
||||
fn listen_for_actions(conn: Connection, shown: Shown, tx: Sender<Do>, 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);
|
||||
}
|
||||
}
|
||||
97
crates/app/src/shell.rs
Normal file
97
crates/app/src/shell.rs
Normal file
|
|
@ -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<Tray>,
|
||||
notes: Option<Notifier>,
|
||||
launcher: Option<Launcher>,
|
||||
watcher: Watcher,
|
||||
rx: Receiver<Do>,
|
||||
shown: Option<TrayState>,
|
||||
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<Do>, Receiver<Do>) = 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<Do> {
|
||||
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()
|
||||
}
|
||||
}
|
||||
187
crates/app/src/tray.rs
Normal file
187
crates/app/src/tray.rs
Normal file
|
|
@ -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<f64>,
|
||||
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<f64>) -> Vec<u8> {
|
||||
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<u8> {
|
||||
rgba.chunks_exact(4).flat_map(|p| [p[3], p[0], p[1], p[2]]).collect()
|
||||
}
|
||||
|
||||
struct Item {
|
||||
tx: Sender<Do>,
|
||||
ctx: Context,
|
||||
base: Vec<u8>,
|
||||
state: Option<TrayState>,
|
||||
}
|
||||
|
||||
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<ksni::Icon> {
|
||||
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<ksni::MenuItem<Self>> {
|
||||
use ksni::menu::*;
|
||||
let item = |label: String, icon: &str, what: Do| -> ksni::MenuItem<Self> {
|
||||
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<Item>,
|
||||
}
|
||||
|
||||
impl Tray {
|
||||
/// None when the desktop has no tray host (or the bus is out of reach).
|
||||
pub fn start(tx: Sender<Do>, ctx: Context) -> Option<Tray> {
|
||||
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]);
|
||||
}
|
||||
}
|
||||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,6 +43,17 @@ pub struct Settings {
|
|||
pub clip_skip: Vec<String>,
|
||||
/// 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,
|
||||
|
|
|
|||
Loading…
Reference in a new issue