diff --git a/Cargo.lock b/Cargo.lock index 2768d2e..7074a44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3465,7 +3465,7 @@ dependencies = [ [[package]] name = "throttle" -version = "0.2.2" +version = "0.2.3" dependencies = [ "anyhow", "crossbeam-channel", diff --git a/Cargo.toml b/Cargo.toml index eb1dd4c..9b65d76 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "throttle" -version = "0.2.2" +version = "0.2.3" edition = "2024" description = "A free, open-source per-process bandwidth monitor and limiter for Windows" repository = "https://github.com/FrancescoCoding/Throttle" @@ -22,7 +22,7 @@ tray-icon = { version = "0.26.1", default-features = false } ureq = "3" windivert = "0.6.0" windivert-sys = "0.10.0" -windows = { version = "0.62.2", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security", "Win32_System_Threading", "Win32_System_ProcessStatus", "Win32_System_Registry","Win32_UI_WindowsAndMessaging"] } +windows = { version = "0.62.2", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security", "Win32_System_Threading", "Win32_System_Power","Win32_System_ProcessStatus", "Win32_System_Registry","Win32_UI_WindowsAndMessaging"] } zip = { version = "2", default-features = false, features = ["deflate"] } [build-dependencies] diff --git a/README.md b/README.md index ff9590f..a679094 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,9 @@ https://github.com/user-attachments/assets/9413bec4-a48a-41c2-9e75-7e6207d80d4f - Right-click any process to set a download limit, set an upload limit, block, unblock, or remove its rule. - Rate editor uses a number field plus a unit dropdown (B/s, KB/s, MB/s, GB/s). +- Experimental: right-click a process and pick "When transfer finishes..." to + shut down, sleep or hibernate the PC once its download, upload or both have + gone quiet, with a countdown to cancel. - System tray icon, with optional minimise to tray, close to tray, start minimised, and launch at Windows startup (Settings menu). Startup uses a Task Scheduler logon task, since Windows skips Run-key entries that need diff --git a/src/finish_watch.rs b/src/finish_watch.rs new file mode 100644 index 0000000..436d97c --- /dev/null +++ b/src/finish_watch.rs @@ -0,0 +1,580 @@ +//! "When transfer finishes": watch one process and run a power action once +//! its download, its upload or both have gone quiet. +//! +//! [`FinishWatch`] is a small state machine fed one rate per snapshot (about +//! once a second) with the time passed in, so it can be tested without +//! waiting. Which rate that is comes from [`Transfer::rate`]: +//! +//! 1. `Waiting`: nothing happens until the rate has been at or above the +//! threshold for [`ARM_SAMPLES`] samples in a row. An idle process can +//! therefore never trigger the action, and neither can a stray burst. +//! 2. `Active`: armed. The first sample below the threshold starts the +//! quiet clock. +//! 3. `Quiet`: the rate has stayed below the threshold. Any sample at or +//! above it goes back to `Active`. +//! 4. `Countdown`: the end of the quiet time (see [`Config::countdown`]), +//! when the app window comes back so the watch can still be cancelled. +//! Traffic picking up again also cancels it. +//! When the configured time is up the watch reports [`Event::Fire`]. +//! +//! The watch is never persisted: it is a one shot for this run of the app. + +use std::os::windows::process::CommandExt; +use std::time::{Duration, Instant}; + +/// Samples in a row at or above the threshold before the watch is armed. +pub const ARM_SAMPLES: u32 = 10; + +/// How long before the action the app window comes back on screen. +pub const COUNTDOWN: Duration = Duration::from_secs(60); + +/// Keep `shutdown.exe` from flashing a console window. +const CREATE_NO_WINDOW: u32 = 0x0800_0000; + +/// Which direction of a process's traffic the watch follows. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Transfer { + Download, + Upload, + /// Finished only once download and upload are quiet together. + Both, +} + +impl Transfer { + pub const ALL: [Transfer; 3] = [Transfer::Download, Transfer::Upload, Transfer::Both]; + + pub fn label(self) -> &'static str { + match self { + Transfer::Download => "Download", + Transfer::Upload => "Upload", + Transfer::Both => "Download and upload", + } + } + + /// "the download", as in "waiting for the download to start". + pub fn noun(self) -> &'static str { + match self { + Transfer::Download => "download", + Transfer::Upload => "upload", + Transfer::Both => "transfer", + } + } + + /// "downloading", as in "finishes downloading". + pub fn gerund(self) -> &'static str { + match self { + Transfer::Download => "downloading", + Transfer::Upload => "uploading", + Transfer::Both => "transferring", + } + } + + /// The rate to feed the watch from a process's two rates. For `Both` it + /// is the larger one, so either direction keeps the watch active. + pub fn rate(self, down: u64, up: u64) -> u64 { + match self { + Transfer::Download => down, + Transfer::Upload => up, + Transfer::Both => down.max(up), + } + } +} + +/// What to do once the transfer has finished. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PowerAction { + Shutdown, + Sleep, + Hibernate, +} + +impl PowerAction { + pub const ALL: [PowerAction; 3] = [ + PowerAction::Shutdown, + PowerAction::Sleep, + PowerAction::Hibernate, + ]; + + /// Imperative label for the dropdown and the banner: "Shut down". + pub fn label(self) -> &'static str { + match self { + PowerAction::Shutdown => "Shut down", + PowerAction::Sleep => "Sleep", + PowerAction::Hibernate => "Hibernate", + } + } + + /// Progressive form for the banner: "Shutting down". + pub fn progressive(self) -> &'static str { + match self { + PowerAction::Shutdown => "Shutting down", + PowerAction::Sleep => "Going to sleep", + PowerAction::Hibernate => "Hibernating", + } + } +} + +/// The user's choices from the dialog. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Config { + pub transfer: Transfer, + /// Rates below this, in bytes per second, count as quiet. + pub threshold: u64, + /// How long the rate must stay quiet before the action runs. The + /// countdown is the end of this time, not added to it. + pub quiet: Duration, + pub action: PowerAction, + /// Shutdown only: close apps that would otherwise hold the shutdown up. + pub force: bool, +} + +impl Config { + /// Length of the countdown: [`COUNTDOWN`], or half the quiet time + /// when that is shorter, so a short quiet time is not all countdown. + pub fn countdown(&self) -> Duration { + COUNTDOWN.min(self.quiet / 2) + } +} + +/// Where the watch is. See the module docs for the transitions. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Phase { + /// Not armed yet; `seen` busy samples in a row so far. + Waiting { + seen: u32, + }, + Active, + Quiet { + since: Instant, + }, + /// Still counted from when the rate went quiet. + Countdown { + since: Instant, + }, +} + +/// What a sample or a tick changed, for the caller to act on. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Event { + None, + /// The countdown just started: bring the window up so it can be cancelled. + CountdownStarted, + /// The countdown ran out: run the action now. + Fire, +} + +/// A running watch on one process. +#[derive(Debug, Clone)] +pub struct FinishWatch { + /// Lowercase executable path, the key of the process in a snapshot. + pub exe_path: String, + /// File name for display. + pub name: String, + pub config: Config, + pub phase: Phase, +} + +impl FinishWatch { + pub fn new(exe_path: String, name: String, config: Config) -> Self { + Self { + exe_path, + name, + config, + phase: Phase::Waiting { seen: 0 }, + } + } + + /// Apply new choices from the dialog to a running watch. Progress is + /// kept unless a different direction is now watched; a countdown is + /// judged again on the next sample, since the quiet time may have grown. + pub fn reconfigure(&mut self, config: Config) { + if config.transfer != self.config.transfer { + self.phase = Phase::Waiting { seen: 0 }; + } else if let Phase::Countdown { since } = self.phase { + self.phase = Phase::Quiet { since }; + } + self.config = config; + } + + /// Feed the rate from one snapshot (see [`Transfer::rate`]). A process + /// missing from the snapshot (it exited, as launchers often do when + /// done) counts as zero. + pub fn sample(&mut self, rate: u64, now: Instant) -> Event { + let busy = rate >= self.config.threshold; + match self.phase { + Phase::Waiting { seen } => { + self.phase = if !busy { + Phase::Waiting { seen: 0 } + } else if seen + 1 >= ARM_SAMPLES { + Phase::Active + } else { + Phase::Waiting { seen: seen + 1 } + }; + } + Phase::Active => { + if !busy { + self.phase = Phase::Quiet { since: now }; + } + } + Phase::Quiet { since } => { + if busy { + self.phase = Phase::Active; + } else if now.duration_since(since) + self.config.countdown() >= self.config.quiet { + self.phase = Phase::Countdown { since }; + return Event::CountdownStarted; + } + } + Phase::Countdown { .. } => { + if busy { + self.phase = Phase::Active; + } + } + } + Event::None + } + + /// Check the countdown against the clock. Called every frame, since the + /// deadline must not wait for the next snapshot. + pub fn tick(&self, now: Instant) -> Event { + match self.phase { + Phase::Countdown { since } if now >= since + self.config.quiet => Event::Fire, + _ => Event::None, + } + } + + /// Seconds left on the countdown, or `None` outside it. + pub fn countdown_left(&self, now: Instant) -> Option { + match self.phase { + Phase::Countdown { since } => { + let until = since + self.config.quiet; + Some(until.saturating_duration_since(now).as_secs_f64().ceil() as u64) + } + _ => None, + } + } + + /// One line on where the watch is, for the banner. + pub fn status(&self, now: Instant) -> String { + match self.phase { + Phase::Waiting { .. } => { + format!("waiting for the {} to start", self.config.transfer.noun()) + } + Phase::Active => self.config.transfer.gerund().to_string(), + // One timer for the whole quiet time: the countdown is only + // when the window comes back, not a second clock. + Phase::Quiet { since } | Phase::Countdown { since } => format!( + "quiet, {} in {}", + self.config.action.progressive().to_lowercase(), + clock(self.config.quiet.saturating_sub(now.duration_since(since))) + ), + } + } +} + +/// `m:ss` for the banner. +fn clock(d: Duration) -> String { + let secs = d.as_secs(); + format!("{}:{:02}", secs / 60, secs % 60) +} + +/// Run the power action. Shutdown and hibernate go through `shutdown.exe`; +/// sleep has no command line of its own, so it uses the power API from a +/// thread, because that call only returns when the machine wakes up again. +pub fn run(action: PowerAction, force: bool) -> Result<(), String> { + tracing::info!("transfer finished: running {action:?} (force: {force})"); + match action { + PowerAction::Shutdown => { + // `/t 0`: our own countdown has already run. A delay above zero + // would also imply `/f`, which is the user's choice to make. + let mut args = vec!["/s", "/t", "0"]; + if force { + args.push("/f"); + } + shutdown_exe(&args) + } + PowerAction::Hibernate => shutdown_exe(&["/h"]), + PowerAction::Sleep => { + std::thread::spawn(|| { + if let Err(e) = sleep() { + tracing::error!("sleep failed: {e}"); + } + }); + Ok(()) + } + } +} + +fn shutdown_exe(args: &[&str]) -> Result<(), String> { + let out = std::process::Command::new("shutdown") + .args(args) + .creation_flags(CREATE_NO_WINDOW) + .output() + .map_err(|e| format!("could not run shutdown.exe: {e}"))?; + if out.status.success() { + Ok(()) + } else { + let message = String::from_utf8_lossy(&out.stderr).trim().to_string(); + Err(if message.is_empty() { + format!("shutdown.exe failed ({})", out.status) + } else { + message + }) + } +} + +/// Suspend to RAM. The call needs the shutdown privilege, which an elevated +/// token holds but leaves switched off, so it is enabled first. +fn sleep() -> Result<(), String> { + use windows::Win32::Foundation::{CloseHandle, HANDLE, LUID}; + use windows::Win32::Security::{ + AdjustTokenPrivileges, LUID_AND_ATTRIBUTES, LookupPrivilegeValueW, SE_PRIVILEGE_ENABLED, + SE_SHUTDOWN_NAME, TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES, TOKEN_QUERY, + }; + use windows::Win32::System::Power::SetSuspendState; + use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + + // SAFETY: plain Win32 calls on this process's own token; every pointer + // is to a local that outlives its call, and the token handle is closed. + unsafe { + let mut token = HANDLE::default(); + OpenProcessToken( + GetCurrentProcess(), + TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, + &mut token, + ) + .map_err(|e| format!("could not open the process token: {e}"))?; + let mut luid = LUID::default(); + let enabled = LookupPrivilegeValueW(None, SE_SHUTDOWN_NAME, &mut luid).and_then(|()| { + let privileges = TOKEN_PRIVILEGES { + PrivilegeCount: 1, + Privileges: [LUID_AND_ATTRIBUTES { + Luid: luid, + Attributes: SE_PRIVILEGE_ENABLED, + }], + }; + AdjustTokenPrivileges(token, false, Some(&privileges), 0, None, None) + }); + let _ = CloseHandle(token); + // Not fatal: the suspend call below reports the failure that matters. + if let Err(e) = enabled { + tracing::warn!("could not enable the shutdown privilege: {e}"); + } + if SetSuspendState(false, false, false) { + Ok(()) + } else { + Err(format!( + "SetSuspendState failed: {}", + std::io::Error::last_os_error() + )) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const THRESHOLD: u64 = 100 * 1024; + const BUSY: u64 = 5 * 1024 * 1024; + const QUIET: Duration = Duration::from_secs(300); + + fn watch() -> FinishWatch { + FinishWatch::new( + r"c:\games\launcher.exe".to_string(), + "launcher.exe".to_string(), + Config { + transfer: Transfer::Download, + threshold: THRESHOLD, + quiet: QUIET, + action: PowerAction::Shutdown, + force: false, + }, + ) + } + + /// Feed `count` samples of `rate`, one second apart, starting at `*now`. + /// Returns the events that were not `None`. + fn feed(w: &mut FinishWatch, now: &mut Instant, rate: u64, count: u32) -> Vec { + let mut events = Vec::new(); + for _ in 0..count { + *now += Duration::from_secs(1); + let e = w.sample(rate, *now); + if e != Event::None { + events.push(e); + } + } + events + } + + /// A watch that has armed and is in `Active`. + fn armed(now: &mut Instant) -> FinishWatch { + let mut w = watch(); + feed(&mut w, now, BUSY, ARM_SAMPLES); + assert_eq!(w.phase, Phase::Active); + w + } + + #[test] + fn an_idle_process_never_arms() { + let mut w = watch(); + let mut now = Instant::now(); + let events = feed(&mut w, &mut now, 0, 3600); + assert!(events.is_empty()); + assert_eq!(w.phase, Phase::Waiting { seen: 0 }); + assert_eq!(w.tick(now), Event::None); + } + + #[test] + fn a_short_burst_does_not_arm() { + let mut w = watch(); + let mut now = Instant::now(); + feed(&mut w, &mut now, BUSY, ARM_SAMPLES - 1); + feed(&mut w, &mut now, 0, 1); + assert_eq!(w.phase, Phase::Waiting { seen: 0 }); + // The run must be unbroken: the count starts over. + feed(&mut w, &mut now, BUSY, ARM_SAMPLES - 1); + assert!(matches!(w.phase, Phase::Waiting { .. })); + } + + #[test] + fn the_threshold_itself_counts_as_downloading() { + let mut w = watch(); + let mut now = Instant::now(); + feed(&mut w, &mut now, THRESHOLD, ARM_SAMPLES); + assert_eq!(w.phase, Phase::Active); + feed(&mut w, &mut now, THRESHOLD - 1, 1); + assert!(matches!(w.phase, Phase::Quiet { .. })); + } + + #[test] + fn the_countdown_is_the_end_of_the_quiet_time_then_fires() { + let mut now = Instant::now(); + let mut w = armed(&mut now); + // The first quiet sample starts the clock; the countdown is the last + // minute of the five, so four minutes pass first. + let events = feed(&mut w, &mut now, 0, (QUIET - COUNTDOWN).as_secs() as u32); + assert!(events.is_empty()); + assert!(matches!(w.phase, Phase::Quiet { .. })); + let events = feed(&mut w, &mut now, 0, 1); + assert_eq!(events, vec![Event::CountdownStarted]); + assert_eq!(w.countdown_left(now), Some(COUNTDOWN.as_secs())); + + assert_eq!( + w.tick(now + COUNTDOWN - Duration::from_millis(1)), + Event::None + ); + assert_eq!(w.tick(now + COUNTDOWN), Event::Fire); + } + + #[test] + fn a_dip_shorter_than_the_window_is_ignored() { + let mut now = Instant::now(); + let mut w = armed(&mut now); + let before_countdown = (QUIET - COUNTDOWN).as_secs() as u32; + feed(&mut w, &mut now, 0, before_countdown - 5); + feed(&mut w, &mut now, BUSY, 1); + assert_eq!(w.phase, Phase::Active); + // The quiet clock starts from scratch after the dip. + let events = feed(&mut w, &mut now, 0, before_countdown); + assert!(events.is_empty()); + } + + #[test] + fn background_chatter_below_the_threshold_still_counts_as_quiet() { + let mut now = Instant::now(); + let mut w = armed(&mut now); + let events = feed(&mut w, &mut now, THRESHOLD / 2, QUIET.as_secs() as u32 + 1); + assert_eq!(events, vec![Event::CountdownStarted]); + } + + #[test] + fn traffic_during_the_countdown_cancels_it() { + let mut now = Instant::now(); + let mut w = armed(&mut now); + feed(&mut w, &mut now, 0, QUIET.as_secs() as u32 + 1); + assert!(matches!(w.phase, Phase::Countdown { .. })); + feed(&mut w, &mut now, BUSY, 1); + assert_eq!(w.phase, Phase::Active); + assert_eq!(w.tick(now + COUNTDOWN), Event::None); + assert_eq!(w.countdown_left(now), None); + } + + #[test] + fn a_short_quiet_time_is_half_countdown() { + let mut w = watch(); + w.config.quiet = Duration::from_secs(60); + assert_eq!(w.config.countdown(), Duration::from_secs(30)); + let mut now = Instant::now(); + feed(&mut w, &mut now, BUSY, ARM_SAMPLES); + let events = feed(&mut w, &mut now, 0, 30); + assert!(events.is_empty()); + let events = feed(&mut w, &mut now, 0, 1); + assert_eq!(events, vec![Event::CountdownStarted]); + assert_eq!(w.countdown_left(now), Some(30)); + assert_eq!(w.tick(now + Duration::from_secs(30)), Event::Fire); + } + + #[test] + fn reconfiguring_keeps_progress_and_rejudges_a_countdown() { + let mut now = Instant::now(); + let mut w = armed(&mut now); + feed(&mut w, &mut now, 0, QUIET.as_secs() as u32); + assert!(matches!(w.phase, Phase::Countdown { .. })); + + // A longer quiet time: back to quiet, with the clock kept. + let mut longer = w.config; + longer.quiet = QUIET * 2; + w.reconfigure(longer); + assert!(matches!(w.phase, Phase::Quiet { .. })); + assert!(feed(&mut w, &mut now, 0, 1).is_empty()); + assert_eq!(w.status(now), "quiet, shutting down in 5:00"); + + // Watching another direction starts over. + let mut upload = w.config; + upload.transfer = Transfer::Upload; + w.reconfigure(upload); + assert_eq!(w.phase, Phase::Waiting { seen: 0 }); + } + + #[test] + fn the_transfer_picks_which_rate_is_watched() { + assert_eq!(Transfer::Download.rate(5, 9), 5); + assert_eq!(Transfer::Upload.rate(5, 9), 9); + // Either direction keeps a watch on both active. + assert_eq!(Transfer::Both.rate(5, 9), 9); + assert_eq!(Transfer::Both.rate(9, 5), 9); + assert_eq!(Transfer::Both.rate(0, 0), 0); + } + + #[test] + fn status_names_the_watched_direction() { + let mut w = watch(); + w.config.transfer = Transfer::Upload; + let mut now = Instant::now(); + assert_eq!(w.status(now), "waiting for the upload to start"); + feed(&mut w, &mut now, BUSY, ARM_SAMPLES); + assert_eq!(w.status(now), "uploading"); + } + + #[test] + fn status_reads_well_in_every_phase() { + let mut now = Instant::now(); + let mut w = watch(); + assert_eq!(w.status(now), "waiting for the download to start"); + feed(&mut w, &mut now, BUSY, ARM_SAMPLES); + assert_eq!(w.status(now), "downloading"); + feed(&mut w, &mut now, 0, 66); + assert_eq!(w.status(now), "quiet, shutting down in 3:55"); + feed( + &mut w, + &mut now, + 0, + (QUIET - COUNTDOWN).as_secs() as u32 - 65, + ); + assert_eq!(w.status(now), "quiet, shutting down in 1:00"); + assert_eq!( + w.status(now + Duration::from_millis(1500)), + "quiet, shutting down in 0:58" + ); + } +} diff --git a/src/gui.rs b/src/gui.rs index fd99083..64c127d 100644 --- a/src/gui.rs +++ b/src/gui.rs @@ -16,6 +16,7 @@ use crate::tray::{self, TrayAction, TrayRule}; use crate::backend::rules; use crate::backend::synthetic::{is_shapable, is_system}; +use crate::finish_watch::{self, FinishWatch, PowerAction, Transfer}; use crate::settings::{self, Settings, SortColumn, View}; use crate::types::{Command, ProcessStats, Rule, Snapshot}; use crate::units::{GB, KB, MB, humanize_bytes, humanize_rate, settle}; @@ -291,6 +292,22 @@ struct LimitModal { error: Option, } +/// State for the "When transfer finishes" window. +struct FinishModal { + exe_path: String, + name: String, + action: PowerAction, + transfer: Transfer, + /// Rate below which the transfer counts as finished, as typed. + threshold: String, + unit: RateUnit, + /// Minutes the rate must stay below the threshold. + quiet_mins: u32, + /// Shutdown only: close apps that would hold the shutdown up. + force: bool, + error: Option, +} + // --------------------------------------------------------------------------- // The app // --------------------------------------------------------------------------- @@ -310,6 +327,12 @@ pub struct ThrottleApp { focus_filter: bool, limit_modal: Option, + finish_modal: Option, + /// The running "When transfer finishes" watch. Never persisted: it is a + /// one shot for this run, so it cannot fire by surprise on a later one. + finish_watch: Option, + /// Why the power action failed; shown in the banner until dismissed. + finish_error: Option, about_open: bool, shutdown_sent: bool, @@ -395,6 +418,9 @@ impl ThrottleApp { filter: String::new(), focus_filter: false, limit_modal: None, + finish_modal: None, + finish_watch: None, + finish_error: None, about_open: false, shutdown_sent: false, settings, @@ -1638,6 +1664,7 @@ impl ThrottleApp { fn row_context_menu(&mut self, resp: &egui::Response, key: &str, name: &str) { resp.context_menu(|ui| { + ui.spacing_mut().button_padding.x += 6.0; // The "Unknown" row is not a process but the traffic we failed to // attribute, so it gets no rule actions. if !is_shapable(key) { @@ -1684,6 +1711,24 @@ impl ThrottleApp { ui.close(); } ui.separator(); + if self + .finish_watch + .as_ref() + .is_some_and(|w| w.exe_path == key) + { + if ui.button("Edit power action\u{2026}").clicked() { + self.open_finish_modal(key, name); + ui.close(); + } + if ui.button("Cancel power action").clicked() { + self.finish_watch = None; + ui.close(); + } + } else if ui.button("When transfer finishes\u{2026}").clicked() { + self.open_finish_modal(key, name); + ui.close(); + } + ui.separator(); if let Some(rule) = self.last_snapshot.rules.get(key) { let (label, disable) = if rule.disabled { ("Enable rule", false) @@ -1702,6 +1747,291 @@ impl ThrottleApp { }); } + /// Open the dialog for `key`, filled in from the watch already running + /// on that process if there is one. + fn open_finish_modal(&mut self, key: &str, name: &str) { + let mut modal = FinishModal { + exe_path: key.to_string(), + name: name.to_string(), + action: PowerAction::Shutdown, + transfer: Transfer::Download, + threshold: "100".to_string(), + unit: RateUnit::KBps, + quiet_mins: 5, + force: false, + error: None, + }; + if let Some(watch) = self.finish_watch.as_ref().filter(|w| w.exe_path == key) { + let config = &watch.config; + let (value, unit) = RateUnit::decompose(config.threshold); + let value = format!("{value:.2}"); + modal.threshold = value + .trim_end_matches('0') + .trim_end_matches('.') + .to_string(); + modal.unit = unit; + modal.action = config.action; + modal.transfer = config.transfer; + modal.quiet_mins = (config.quiet.as_secs() / 60) as u32; + modal.force = config.force; + } + self.finish_modal = Some(modal); + } + + /// The "When transfer finishes" window: pick the action and what counts + /// as finished, then start the watch. + fn draw_finish_modal(&mut self, ctx: &egui::Context) { + let Some(mut modal) = self.finish_modal.take() else { + return; + }; + + let mut open = true; + let mut start = false; + let mut cancel = false; + + egui::Window::new("When transfer finishes") + .collapsible(false) + .resizable(false) + .open(&mut open) + .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]) + .show(ctx, |ui| { + ui.horizontal(|ui| { + ui.label(format!("Process: {}", modal.name)); + pill(ui, "Experimental").on_hover_text( + "New and lightly tested. A long connection outage can look like a \ + finished transfer.", + ); + }); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.label("Action"); + egui::ComboBox::from_id_salt("finish-action") + .selected_text(modal.action.label()) + .show_ui(ui, |ui| { + steady_rows(ui); + for a in PowerAction::ALL { + ui.selectable_value(&mut modal.action, a, a.label()); + } + }); + }); + ui.horizontal(|ui| { + ui.label("Watch"); + egui::ComboBox::from_id_salt("finish-transfer") + .selected_text(modal.transfer.label()) + .show_ui(ui, |ui| { + steady_rows(ui); + for t in Transfer::ALL { + ui.selectable_value(&mut modal.transfer, t, t.label()); + } + }) + .response + .on_hover_text( + "Upload never goes quiet for a client that keeps seeding, so the \ + action would never run.", + ); + }); + ui.horizontal(|ui| { + ui.label("Finished when it stays below"); + let spacing = ui.spacing(); + let button_height = spacing.interact_size.y.max( + ui.text_style_height(&egui::TextStyle::Button) + + 2.0 * spacing.button_padding.y, + ); + let resp = ui.add( + egui::TextEdit::singleline(&mut modal.threshold) + .desired_width(60.0) + .min_size(egui::vec2(0.0, button_height)) + .vertical_align(egui::Align::Center), + ); + if resp.changed() { + modal.threshold = numeric_input(&modal.threshold); + } + egui::ComboBox::from_id_salt("finish-unit") + .selected_text(modal.unit.label()) + .show_ui(ui, |ui| { + steady_rows(ui); + for u in RateUnit::ALL { + ui.selectable_value(&mut modal.unit, u, u.label()); + } + }); + }); + ui.horizontal(|ui| { + ui.label("for"); + ui.add(egui::DragValue::new(&mut modal.quiet_mins).range(1..=240)); + ui.label(if modal.quiet_mins == 1 { + "minute" + } else { + "minutes" + }); + }); + if modal.action == PowerAction::Shutdown { + ui.checkbox(&mut modal.force, "Force apps to close") + .on_hover_text( + "Without this, an app with unsaved work can hold the shutdown up. \ + With it, that work is lost.", + ); + } + ui.add_space(4.0); + ui.label( + egui::RichText::new(format!( + "Watching starts once the process has stayed above that rate for \ + {} seconds. The bar at the top shows the time left and a Cancel \ + button, and Throttle comes back on screen near the end.", + finish_watch::ARM_SAMPLES + )) + .weak() + .small(), + ); + if let Some(other) = self + .finish_watch + .as_ref() + .filter(|w| w.exe_path != modal.exe_path) + { + ui.label( + egui::RichText::new(format!("Replaces the watch on {}.", other.name)) + .weak() + .small(), + ); + } + if let Some(err) = &modal.error { + ui.colored_label(self.accents.block, err); + } + ui.add_space(4.0); + ui.horizontal(|ui| { + let editing = self + .finish_watch + .as_ref() + .is_some_and(|w| w.exe_path == modal.exe_path); + if ui + .button(if editing { "Update" } else { "Start" }) + .clicked() + { + start = true; + } + if ui.button("Cancel").clicked() { + cancel = true; + } + }); + }); + + if cancel || !open { + return; // modal dropped + } + + if start { + let typed = modal.threshold.trim().replace(',', "."); + let threshold = typed + .parse::() + .ok() + .filter(|v| v.is_finite()) + .map(|v| (v * modal.unit.multiplier()) as u64) + // Zero would make every sample count as downloading. + .filter(|&bps| bps > 0); + let Some(threshold) = threshold else { + modal.error = Some("Enter a rate above zero, e.g. 100".to_string()); + self.finish_modal = Some(modal); + return; + }; + self.finish_error = None; + let config = finish_watch::Config { + transfer: modal.transfer, + threshold, + quiet: Duration::from_secs(u64::from(modal.quiet_mins) * 60), + action: modal.action, + force: modal.force, + }; + match &mut self.finish_watch { + Some(watch) if watch.exe_path == modal.exe_path => watch.reconfigure(config), + _ => { + self.finish_watch = Some(FinishWatch::new(modal.exe_path, modal.name, config)); + } + } + return; // done, modal closes + } + + self.finish_modal = Some(modal); + } + + /// A banner while a "When transfer finishes" watch runs (or its action + /// failed): what it waits for, where it is, and a way to cancel it. + fn draw_finish_banner(&mut self, ui: &mut egui::Ui) { + if self.finish_watch.is_none() && self.finish_error.is_none() { + return; + } + let now = Instant::now(); + let mut cancel = false; + let mut dismiss = false; + let mut edit = false; + egui::Panel::top("finish_banner").show(ui, |ui| { + ui.horizontal(|ui| { + if let Some(e) = &self.finish_error { + ui.label( + egui::RichText::new(format!("Power action failed: {e}")) + .color(self.accents.block), + ); + dismiss = ui.button("Dismiss").clicked(); + return; + } + let Some(watch) = &self.finish_watch else { + return; + }; + let text = egui::RichText::new(format!( + "{} when {} finishes {}: {}", + watch.config.action.label(), + watch.name, + watch.config.transfer.gerund(), + watch.status(now) + )) + .strong(); + let counting = watch.countdown_left(now).is_some(); + ui.label(if counting { + text.color(self.accents.block) + } else { + text + }); + ui.weak(format!( + "(below {} for {} min)", + humanize_rate(watch.config.threshold), + watch.config.quiet.as_secs() / 60 + )); + edit = ui.button("Edit").clicked(); + cancel = ui.button("Cancel").clicked(); + }); + }); + if edit && let Some(watch) = &self.finish_watch { + let (key, name) = (watch.exe_path.clone(), watch.name.clone()); + self.open_finish_modal(&key, &name); + } + if dismiss { + self.finish_error = None; + } + if cancel { + self.finish_watch = None; + } + } + + /// The countdown ran out: run the action. A shutdown also quits Throttle + /// the normal way, so the rules are saved; after sleep or hibernate the + /// app simply carries on with the watch gone. + fn fire_finish_watch(&mut self, ctx: &egui::Context) { + let Some(watch) = self.finish_watch.take() else { + return; + }; + match finish_watch::run(watch.config.action, watch.config.force) { + Ok(()) => { + if watch.config.action == PowerAction::Shutdown { + self.send_shutdown(); + self.exit(ctx); + } + } + Err(e) => { + tracing::error!("power action failed: {e}"); + self.finish_error = Some(e); + self.show_window(ctx); + } + } + } + fn draw_limit_modal(&mut self, ctx: &egui::Context) { let Some(mut modal) = self.limit_modal.take() else { return; @@ -1752,6 +2082,7 @@ impl ThrottleApp { egui::ComboBox::from_id_salt("rate-unit") .selected_text(modal.unit.label()) .show_ui(ui, |ui| { + steady_rows(ui); for u in RateUnit::ALL { ui.selectable_value(&mut modal.unit, u, u.label()); } @@ -1816,7 +2147,18 @@ impl eframe::App for ThrottleApp { let incoming: Vec = self.snapshot_rx.try_iter().collect(); let keep = self.settings.view.history_secs.max(1); let mut fresh = false; + let now = Instant::now(); + let mut countdown_started = false; for snap in incoming { + // A process missing from the snapshot has exited: that is quiet. + if let Some(watch) = &mut self.finish_watch { + let rate = snap + .processes + .get(&watch.exe_path) + .map_or(0, |p| watch.config.transfer.rate(p.down_rate, p.up_rate)); + countdown_started |= + watch.sample(rate, now) == finish_watch::Event::CountdownStarted; + } self.total_down_hist.push(snap.total_down_rate as f64); self.total_up_hist.push(snap.total_up_rate as f64); trim_front(&mut self.total_down_hist, keep); @@ -1828,6 +2170,21 @@ impl eframe::App for ThrottleApp { self.refresh_tray(ctx); } + // The watch runs here, not in `ui`, because the window is usually + // hidden to the tray by the time an overnight transfer finishes. + // Near the end it comes back so the Cancel button can be reached. + if countdown_started { + self.start_hidden = None; + self.show_window(ctx); + } + if self + .finish_watch + .as_ref() + .is_some_and(|w| w.tick(now) == finish_watch::Event::Fire) + { + self.fire_finish_watch(ctx); + } + // The window exists by the first frame; only a non default level is // sent, so the stock window is left alone. if self.first_frame { @@ -1933,10 +2290,12 @@ impl eframe::App for ThrottleApp { self.draw_menu_bar(ui); self.draw_update_banner(ui); + self.draw_finish_banner(ui); self.draw_top_panel(ui, &snap); self.draw_detail_panel(ui, &snap); self.draw_table(ui, &snap); self.draw_limit_modal(&ctx); + self.draw_finish_modal(&ctx); self.draw_about(&ctx); self.draw_customise_window(&ctx); self.draw_import_error(&ctx); @@ -2000,6 +2359,37 @@ fn draw_swatch(ui: &mut egui::Ui, palette: &theme::Palette) { } } +/// A small rounded tag in the theme's warning colour, for marking a +/// feature as experimental. +fn pill(ui: &mut egui::Ui, text: &str) -> egui::Response { + let colour = ui.visuals().warn_fg_color; + egui::Frame::new() + .fill(colour.gamma_multiply(0.15)) + .stroke(egui::Stroke::new(1.0, colour)) + .corner_radius(255) + .inner_margin(egui::Margin::symmetric(8, 1)) + .show(ui, |ui| { + ui.add( + egui::Label::new(egui::RichText::new(text).small().color(colour)).selectable(false), + ); + }) + .response +} + +/// Dropdown rows are unframed until hovered, and a hovered frame is larger +/// by its stroke. Dropping the stroke, as menus do, keeps the rows still. +fn steady_rows(ui: &mut egui::Ui) { + let widgets = &mut ui.visuals_mut().widgets; + for state in [ + &mut widgets.inactive, + &mut widgets.hovered, + &mut widgets.active, + &mut widgets.open, + ] { + state.bg_stroke = egui::Stroke::NONE; + } +} + /// Drop the oldest samples so at most `keep` remain. fn trim_front(hist: &mut Vec, keep: usize) { if hist.len() > keep { diff --git a/src/main.rs b/src/main.rs index 3bfa6c3..491a74a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,6 +13,7 @@ mod appearance; mod autostart; mod backend; +mod finish_watch; mod gui; mod icon; mod plot;