187 lines
6.3 KiB
Rust
187 lines
6.3 KiB
Rust
//! 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]);
|
|
}
|
|
}
|