From 40b54c22d0ae0933a9e21f291f4135a07c04a878 Mon Sep 17 00:00:00 2001 From: Francesco Gruosso <64712227+FrancescoCoding@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:19:43 +0000 Subject: [PATCH 1/4] Add a power action for when a download finishes Right-click a process and pick "When download finishes..." to shut down, sleep or hibernate the PC once its download has gone quiet. The watch only arms after the process has downloaded above a threshold for 10 seconds in a row, so an idle process or a stray burst cannot trigger it. The download counts as finished when the rate then stays below the threshold for a set time. A 60 second countdown with a Cancel button runs before the action, and traffic picking up again cancels it too. The watch is never saved, so it cannot fire on a later run. Marked experimental: a connection outage longer than the quiet time still looks like a finished download. Closes #21 --- Cargo.toml | 2 +- README.md | 3 + src/finish_watch.rs | 443 ++++++++++++++++++++++++++++++++++++++++++++ src/gui.rs | 357 +++++++++++++++++++++++++++++++++++ src/main.rs | 1 + 5 files changed, 805 insertions(+), 1 deletion(-) create mode 100644 src/finish_watch.rs diff --git a/Cargo.toml b/Cargo.toml index eb1dd4c..d014cff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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..a273c91 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 download finishes..." to + shut down, sleep or hibernate the PC once its download has 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..bd9f4a9 --- /dev/null +++ b/src/finish_watch.rs @@ -0,0 +1,443 @@ +//! "When download finishes": watch one process and run a power action once +//! its download has gone quiet. +//! +//! [`FinishWatch`] is a small state machine fed one download rate per +//! snapshot (about once a second) with the time passed in, so it can be +//! tested without waiting: +//! +//! 1. `Waiting`: nothing happens until the process has downloaded 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. `Downloading`: 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 `Downloading`; staying quiet for the configured +//! time starts the countdown. +//! 4. `Countdown`: the last chance to cancel. Traffic picking up again also +//! cancels it. When it runs out 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 the cancel window stays up before the action runs. +pub const COUNTDOWN: Duration = Duration::from_secs(60); + +/// Keep `shutdown.exe` from flashing a console window. +const CREATE_NO_WINDOW: u32 = 0x0800_0000; + +/// What to do once the download 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 countdown: "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 { + /// Download rates below this, in bytes per second, count as quiet. + pub threshold: u64, + /// How long the rate must stay quiet before the countdown starts. + pub quiet: Duration, + pub action: PowerAction, + /// Shutdown only: close apps that would otherwise hold the shutdown up. + pub force: bool, +} + +/// 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, + }, + Downloading, + Quiet { + since: Instant, + }, + Countdown { + until: 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 }, + } + } + + /// Feed the download rate from one snapshot. A process missing from the + /// snapshot (it exited, as launchers often do when done) counts as zero. + pub fn sample(&mut self, down_rate: u64, now: Instant) -> Event { + let busy = down_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::Downloading + } else { + Phase::Waiting { seen: seen + 1 } + }; + } + Phase::Downloading => { + if !busy { + self.phase = Phase::Quiet { since: now }; + } + } + Phase::Quiet { since } => { + if busy { + self.phase = Phase::Downloading; + } else if now.duration_since(since) >= self.config.quiet { + self.phase = Phase::Countdown { + until: now + COUNTDOWN, + }; + return Event::CountdownStarted; + } + } + Phase::Countdown { .. } => { + if busy { + self.phase = Phase::Downloading; + } + } + } + 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 { until } if now >= until => 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 { until } => { + 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 { .. } => "waiting for the download to start".to_string(), + Phase::Downloading => "downloading".to_string(), + Phase::Quiet { since } => format!( + "quiet for {} of {}", + clock(now.duration_since(since)), + clock(self.config.quiet) + ), + Phase::Countdown { .. } => format!( + "{} in {} s", + self.config.action.progressive().to_lowercase(), + self.countdown_left(now).unwrap_or(0) + ), + } + } +} + +/// `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!("download 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 { + 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 `Downloading`. + fn armed(now: &mut Instant) -> FinishWatch { + let mut w = watch(); + feed(&mut w, now, BUSY, ARM_SAMPLES); + assert_eq!(w.phase, Phase::Downloading); + 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::Downloading); + feed(&mut w, &mut now, THRESHOLD - 1, 1); + assert!(matches!(w.phase, Phase::Quiet { .. })); + } + + #[test] + fn quiet_for_the_whole_window_starts_the_countdown_then_fires() { + let mut now = Instant::now(); + let mut w = armed(&mut now); + // The first quiet sample starts the clock; the window is not over yet. + let events = feed(&mut w, &mut now, 0, QUIET.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); + feed(&mut w, &mut now, 0, QUIET.as_secs() as u32 - 5); + feed(&mut w, &mut now, BUSY, 1); + assert_eq!(w.phase, Phase::Downloading); + // The quiet clock starts from scratch after the dip. + let events = feed(&mut w, &mut now, 0, QUIET.as_secs() as u32); + 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::Downloading); + assert_eq!(w.tick(now + COUNTDOWN), Event::None); + assert_eq!(w.countdown_left(now), None); + } + + #[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 for 1:05 of 5:00"); + feed(&mut w, &mut now, 0, QUIET.as_secs() as u32 - 65); + assert_eq!(w.status(now), "shutting down in 60 s"); + assert_eq!( + w.status(now + Duration::from_millis(1500)), + "shutting down in 59 s" + ); + } +} diff --git a/src/gui.rs b/src/gui.rs index fd99083..aac2564 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}; 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,21 @@ struct LimitModal { error: Option, } +/// State for the "When download finishes" window. +struct FinishModal { + exe_path: String, + name: String, + action: PowerAction, + /// Rate below which the download 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 +326,12 @@ pub struct ThrottleApp { focus_filter: bool, limit_modal: Option, + finish_modal: Option, + /// The running "When download 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 +417,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 +1663,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 +1710,20 @@ impl ThrottleApp { ui.close(); } ui.separator(); + if self + .finish_watch + .as_ref() + .is_some_and(|w| w.exe_path == key) + { + if ui.button("Cancel power action").clicked() { + self.finish_watch = None; + ui.close(); + } + } else if ui.button("When download 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 +1742,277 @@ impl ThrottleApp { }); } + fn open_finish_modal(&mut self, key: &str, name: &str) { + self.finish_modal = Some(FinishModal { + exe_path: key.to_string(), + name: name.to_string(), + action: PowerAction::Shutdown, + threshold: "100".to_string(), + unit: RateUnit::KBps, + quiet_mins: 5, + force: false, + error: None, + }); + } + + /// The "When download 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 download 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 download.", + ); + }); + 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| { + for a in PowerAction::ALL { + ui.selectable_value(&mut modal.action, a, a.label()); + } + }); + }); + ui.horizontal(|ui| { + ui.label("Finished when download 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| { + 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 downloaded above that rate for \ + {} seconds. Before the action runs you get a {} second countdown to \ + cancel it.", + finish_watch::ARM_SAMPLES, + finish_watch::COUNTDOWN.as_secs() + )) + .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| { + if ui.button("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; + self.finish_watch = Some(FinishWatch::new( + modal.exe_path, + modal.name, + finish_watch::Config { + threshold, + quiet: Duration::from_secs(u64::from(modal.quiet_mins) * 60), + action: modal.action, + force: modal.force, + }, + )); + return; // done, modal closes + } + + self.finish_modal = Some(modal); + } + + /// A banner while a "When download 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; + 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 downloading: {}", + watch.config.action.label(), + watch.name, + 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 + )); + cancel = ui.button("Cancel").clicked(); + }); + }); + if dismiss { + self.finish_error = None; + } + if cancel { + self.finish_watch = None; + } + } + + /// The last chance to cancel: a centred window for the whole countdown. + fn draw_finish_countdown(&mut self, ctx: &egui::Context) { + let now = Instant::now(); + let Some(watch) = &self.finish_watch else { + return; + }; + let Some(left) = watch.countdown_left(now) else { + return; + }; + let mut cancel = false; + egui::Window::new("Download finished") + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]) + .show(ctx, |ui| { + ui.vertical_centered(|ui| { + ui.add_space(6.0); + ui.label(format!("{} has stopped downloading.", watch.name)); + ui.add_space(4.0); + ui.heading( + egui::RichText::new(format!( + "{} in {left} s", + watch.config.action.progressive() + )) + .color(self.accents.block), + ); + ui.add_space(8.0); + if ui.button("Cancel").clicked() { + cancel = true; + } + ui.add_space(4.0); + }); + }); + 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; @@ -1816,7 +2127,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| p.down_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 +2150,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 download finishes. + // The countdown brings it 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 +2270,13 @@ 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_finish_countdown(&ctx); self.draw_about(&ctx); self.draw_customise_window(&ctx); self.draw_import_error(&ctx); @@ -2000,6 +2340,23 @@ 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 +} + /// 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; From 3cec68ad8a93415113575894c0792fef331b99dc Mon Sep 17 00:00:00 2001 From: Francesco Gruosso <64712227+FrancescoCoding@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:19:45 +0000 Subject: [PATCH 2/4] Bump version to 0.2.3 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 d014cff..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" From cc6dfef9a35b6b577f59e4642f1e3e97c60d72d3 Mon Sep 17 00:00:00 2001 From: Francesco Gruosso <64712227+FrancescoCoding@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:32:11 +0000 Subject: [PATCH 3/4] Watch uploads too when waiting for a transfer to finish The dialog gains a Watch choice: download, upload, or both. Both waits until the two directions are quiet together, which suits sync and backup clients. The menu entry is now "When transfer finishes...". The banner shows the time left until the countdown starts while the transfer is quiet, in place of the elapsed time. Refs #21 --- README.md | 6 +- src/finish_watch.rs | 137 +++++++++++++++++++++++++++++++++----------- src/gui.rs | 55 ++++++++++++------ 3 files changed, 147 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index a273c91..a679094 100644 --- a/README.md +++ b/README.md @@ -37,9 +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 download finishes..." to - shut down, sleep or hibernate the PC once its download has gone quiet, with - a countdown to cancel. +- 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 index bd9f4a9..93a727c 100644 --- a/src/finish_watch.rs +++ b/src/finish_watch.rs @@ -1,17 +1,17 @@ -//! "When download finishes": watch one process and run a power action once -//! its download has gone quiet. +//! "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 download rate per -//! snapshot (about once a second) with the time passed in, so it can be -//! tested without waiting: +//! [`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 process has downloaded at or above -//! the threshold for [`ARM_SAMPLES`] samples in a row. An idle process can +//! 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. `Downloading`: armed. The first sample below the threshold starts the +//! 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 `Downloading`; staying quiet for the configured +//! above it goes back to `Active`; staying quiet for the configured //! time starts the countdown. //! 4. `Countdown`: the last chance to cancel. Traffic picking up again also //! cancels it. When it runs out the watch reports [`Event::Fire`]. @@ -30,7 +30,56 @@ pub const COUNTDOWN: Duration = Duration::from_secs(60); /// Keep `shutdown.exe` from flashing a console window. const CREATE_NO_WINDOW: u32 = 0x0800_0000; -/// What to do once the download has finished. +/// 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, @@ -67,7 +116,8 @@ impl PowerAction { /// The user's choices from the dialog. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Config { - /// Download rates below this, in bytes per second, count as quiet. + 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 countdown starts. pub quiet: Duration, @@ -83,7 +133,7 @@ pub enum Phase { Waiting { seen: u32, }, - Downloading, + Active, Quiet { since: Instant, }, @@ -123,28 +173,29 @@ impl FinishWatch { } } - /// Feed the download rate from one snapshot. A process missing from the - /// snapshot (it exited, as launchers often do when done) counts as zero. - pub fn sample(&mut self, down_rate: u64, now: Instant) -> Event { - let busy = down_rate >= self.config.threshold; + /// 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::Downloading + Phase::Active } else { Phase::Waiting { seen: seen + 1 } }; } - Phase::Downloading => { + Phase::Active => { if !busy { self.phase = Phase::Quiet { since: now }; } } Phase::Quiet { since } => { if busy { - self.phase = Phase::Downloading; + self.phase = Phase::Active; } else if now.duration_since(since) >= self.config.quiet { self.phase = Phase::Countdown { until: now + COUNTDOWN, @@ -154,7 +205,7 @@ impl FinishWatch { } Phase::Countdown { .. } => { if busy { - self.phase = Phase::Downloading; + self.phase = Phase::Active; } } } @@ -183,12 +234,13 @@ impl FinishWatch { /// One line on where the watch is, for the banner. pub fn status(&self, now: Instant) -> String { match self.phase { - Phase::Waiting { .. } => "waiting for the download to start".to_string(), - Phase::Downloading => "downloading".to_string(), + Phase::Waiting { .. } => { + format!("waiting for the {} to start", self.config.transfer.noun()) + } + Phase::Active => self.config.transfer.gerund().to_string(), Phase::Quiet { since } => format!( - "quiet for {} of {}", - clock(now.duration_since(since)), - clock(self.config.quiet) + "quiet, countdown starts in {}", + clock(self.config.quiet.saturating_sub(now.duration_since(since))) ), Phase::Countdown { .. } => format!( "{} in {} s", @@ -209,7 +261,7 @@ fn clock(d: Duration) -> String { /// 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!("download finished: running {action:?} (force: {force})"); + tracing::info!("transfer finished: running {action:?} (force: {force})"); match action { PowerAction::Shutdown => { // `/t 0`: our own countdown has already run. A delay above zero @@ -311,6 +363,7 @@ mod tests { r"c:\games\launcher.exe".to_string(), "launcher.exe".to_string(), Config { + transfer: Transfer::Download, threshold: THRESHOLD, quiet: QUIET, action: PowerAction::Shutdown, @@ -333,11 +386,11 @@ mod tests { events } - /// A watch that has armed and is in `Downloading`. + /// 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::Downloading); + assert_eq!(w.phase, Phase::Active); w } @@ -368,7 +421,7 @@ mod tests { let mut w = watch(); let mut now = Instant::now(); feed(&mut w, &mut now, THRESHOLD, ARM_SAMPLES); - assert_eq!(w.phase, Phase::Downloading); + assert_eq!(w.phase, Phase::Active); feed(&mut w, &mut now, THRESHOLD - 1, 1); assert!(matches!(w.phase, Phase::Quiet { .. })); } @@ -398,7 +451,7 @@ mod tests { let mut w = armed(&mut now); feed(&mut w, &mut now, 0, QUIET.as_secs() as u32 - 5); feed(&mut w, &mut now, BUSY, 1); - assert_eq!(w.phase, Phase::Downloading); + assert_eq!(w.phase, Phase::Active); // The quiet clock starts from scratch after the dip. let events = feed(&mut w, &mut now, 0, QUIET.as_secs() as u32); assert!(events.is_empty()); @@ -419,11 +472,31 @@ mod tests { 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::Downloading); + assert_eq!(w.phase, Phase::Active); assert_eq!(w.tick(now + COUNTDOWN), Event::None); assert_eq!(w.countdown_left(now), None); } + #[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(); @@ -432,7 +505,7 @@ mod tests { 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 for 1:05 of 5:00"); + assert_eq!(w.status(now), "quiet, countdown starts in 3:55"); feed(&mut w, &mut now, 0, QUIET.as_secs() as u32 - 65); assert_eq!(w.status(now), "shutting down in 60 s"); assert_eq!( diff --git a/src/gui.rs b/src/gui.rs index aac2564..37069cf 100644 --- a/src/gui.rs +++ b/src/gui.rs @@ -16,7 +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}; +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}; @@ -292,12 +292,13 @@ struct LimitModal { error: Option, } -/// State for the "When download finishes" window. +/// State for the "When transfer finishes" window. struct FinishModal { exe_path: String, name: String, action: PowerAction, - /// Rate below which the download counts as finished, as typed. + transfer: Transfer, + /// Rate below which the transfer counts as finished, as typed. threshold: String, unit: RateUnit, /// Minutes the rate must stay below the threshold. @@ -327,7 +328,7 @@ pub struct ThrottleApp { limit_modal: Option, finish_modal: Option, - /// The running "When download finishes" watch. Never persisted: it is a + /// 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. @@ -1719,7 +1720,7 @@ impl ThrottleApp { self.finish_watch = None; ui.close(); } - } else if ui.button("When download finishes\u{2026}").clicked() { + } else if ui.button("When transfer finishes\u{2026}").clicked() { self.open_finish_modal(key, name); ui.close(); } @@ -1747,6 +1748,7 @@ impl ThrottleApp { 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, @@ -1755,7 +1757,7 @@ impl ThrottleApp { }); } - /// The "When download finishes" window: pick the action and what counts + /// 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 { @@ -1766,7 +1768,7 @@ impl ThrottleApp { let mut start = false; let mut cancel = false; - egui::Window::new("When download finishes") + egui::Window::new("When transfer finishes") .collapsible(false) .resizable(false) .open(&mut open) @@ -1776,7 +1778,7 @@ impl ThrottleApp { 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 download.", + finished transfer.", ); }); ui.add_space(4.0); @@ -1791,7 +1793,22 @@ impl ThrottleApp { }); }); ui.horizontal(|ui| { - ui.label("Finished when download stays below"); + ui.label("Watch"); + egui::ComboBox::from_id_salt("finish-transfer") + .selected_text(modal.transfer.label()) + .show_ui(ui, |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) @@ -1833,7 +1850,7 @@ impl ThrottleApp { ui.add_space(4.0); ui.label( egui::RichText::new(format!( - "Watching starts once the process has downloaded above that rate for \ + "Watching starts once the process has stayed above that rate for \ {} seconds. Before the action runs you get a {} second countdown to \ cancel it.", finish_watch::ARM_SAMPLES, @@ -1890,6 +1907,7 @@ impl ThrottleApp { modal.exe_path, modal.name, finish_watch::Config { + transfer: modal.transfer, threshold, quiet: Duration::from_secs(u64::from(modal.quiet_mins) * 60), action: modal.action, @@ -1902,7 +1920,7 @@ impl ThrottleApp { self.finish_modal = Some(modal); } - /// A banner while a "When download finishes" watch runs (or its action + /// 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() { @@ -1925,9 +1943,10 @@ impl ThrottleApp { return; }; let text = egui::RichText::new(format!( - "{} when {} finishes downloading: {}", + "{} when {} finishes {}: {}", watch.config.action.label(), watch.name, + watch.config.transfer.gerund(), watch.status(now) )) .strong(); @@ -1963,14 +1982,18 @@ impl ThrottleApp { return; }; let mut cancel = false; - egui::Window::new("Download finished") + egui::Window::new("Transfer finished") .collapsible(false) .resizable(false) .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]) .show(ctx, |ui| { ui.vertical_centered(|ui| { ui.add_space(6.0); - ui.label(format!("{} has stopped downloading.", watch.name)); + ui.label(format!( + "{} has stopped {}.", + watch.name, + watch.config.transfer.gerund() + )); ui.add_space(4.0); ui.heading( egui::RichText::new(format!( @@ -2135,7 +2158,7 @@ impl eframe::App for ThrottleApp { let rate = snap .processes .get(&watch.exe_path) - .map_or(0, |p| p.down_rate); + .map_or(0, |p| watch.config.transfer.rate(p.down_rate, p.up_rate)); countdown_started |= watch.sample(rate, now) == finish_watch::Event::CountdownStarted; } @@ -2151,7 +2174,7 @@ impl eframe::App for ThrottleApp { } // The watch runs here, not in `ui`, because the window is usually - // hidden to the tray by the time an overnight download finishes. + // hidden to the tray by the time an overnight transfer finishes. // The countdown brings it back so the Cancel button can be reached. if countdown_started { self.start_hidden = None; From 152fdf8813010c708ab9a7be9922a26d1a33aa18 Mon Sep 17 00:00:00 2001 From: Francesco Gruosso <64712227+FrancescoCoding@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:23:02 +0000 Subject: [PATCH 4/4] Simplify the transfer watch to one timer, and make it editable The quiet time is now the whole wait: the action runs when it is up, with no countdown added on top and no separate countdown window. The banner counts the time down, and the app window still comes back for the last minute so Cancel is within reach. A running watch can be edited from the banner or the right-click menu. Changing it keeps its progress unless the watched direction changes. Dropdown rows no longer shift by a pixel when hovered. Refs #21 --- src/finish_watch.rs | 124 ++++++++++++++++++++++++++++++---------- src/gui.rs | 134 ++++++++++++++++++++++++-------------------- 2 files changed, 166 insertions(+), 92 deletions(-) diff --git a/src/finish_watch.rs b/src/finish_watch.rs index 93a727c..436d97c 100644 --- a/src/finish_watch.rs +++ b/src/finish_watch.rs @@ -11,10 +11,11 @@ //! 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`; staying quiet for the configured -//! time starts the countdown. -//! 4. `Countdown`: the last chance to cancel. Traffic picking up again also -//! cancels it. When it runs out the watch reports [`Event::Fire`]. +//! 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. @@ -24,7 +25,7 @@ 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 the cancel window stays up before the action runs. +/// 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. @@ -103,7 +104,7 @@ impl PowerAction { } } - /// Progressive form for the countdown: "Shutting down". + /// Progressive form for the banner: "Shutting down". pub fn progressive(self) -> &'static str { match self { PowerAction::Shutdown => "Shutting down", @@ -119,13 +120,22 @@ 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 countdown starts. + /// 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 { @@ -137,8 +147,9 @@ pub enum Phase { Quiet { since: Instant, }, + /// Still counted from when the rate went quiet. Countdown { - until: Instant, + since: Instant, }, } @@ -173,6 +184,18 @@ impl FinishWatch { } } + /// 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. @@ -196,10 +219,8 @@ impl FinishWatch { Phase::Quiet { since } => { if busy { self.phase = Phase::Active; - } else if now.duration_since(since) >= self.config.quiet { - self.phase = Phase::Countdown { - until: now + COUNTDOWN, - }; + } else if now.duration_since(since) + self.config.countdown() >= self.config.quiet { + self.phase = Phase::Countdown { since }; return Event::CountdownStarted; } } @@ -216,7 +237,7 @@ impl FinishWatch { /// deadline must not wait for the next snapshot. pub fn tick(&self, now: Instant) -> Event { match self.phase { - Phase::Countdown { until } if now >= until => Event::Fire, + Phase::Countdown { since } if now >= since + self.config.quiet => Event::Fire, _ => Event::None, } } @@ -224,7 +245,8 @@ impl FinishWatch { /// Seconds left on the countdown, or `None` outside it. pub fn countdown_left(&self, now: Instant) -> Option { match self.phase { - Phase::Countdown { until } => { + Phase::Countdown { since } => { + let until = since + self.config.quiet; Some(until.saturating_duration_since(now).as_secs_f64().ceil() as u64) } _ => None, @@ -238,14 +260,12 @@ impl FinishWatch { format!("waiting for the {} to start", self.config.transfer.noun()) } Phase::Active => self.config.transfer.gerund().to_string(), - Phase::Quiet { since } => format!( - "quiet, countdown starts in {}", - clock(self.config.quiet.saturating_sub(now.duration_since(since))) - ), - Phase::Countdown { .. } => format!( - "{} in {} s", + // 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(), - self.countdown_left(now).unwrap_or(0) + clock(self.config.quiet.saturating_sub(now.duration_since(since))) ), } } @@ -427,11 +447,12 @@ mod tests { } #[test] - fn quiet_for_the_whole_window_starts_the_countdown_then_fires() { + 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 window is not over yet. - let events = feed(&mut w, &mut now, 0, QUIET.as_secs() as u32); + // 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); @@ -449,11 +470,12 @@ mod tests { fn a_dip_shorter_than_the_window_is_ignored() { let mut now = Instant::now(); let mut w = armed(&mut now); - feed(&mut w, &mut now, 0, QUIET.as_secs() as u32 - 5); + 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, QUIET.as_secs() as u32); + let events = feed(&mut w, &mut now, 0, before_countdown); assert!(events.is_empty()); } @@ -477,6 +499,43 @@ mod tests { 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); @@ -505,12 +564,17 @@ mod tests { 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, countdown starts in 3:55"); - feed(&mut w, &mut now, 0, QUIET.as_secs() as u32 - 65); - assert_eq!(w.status(now), "shutting down in 60 s"); + 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)), - "shutting down in 59 s" + "quiet, shutting down in 0:58" ); } } diff --git a/src/gui.rs b/src/gui.rs index 37069cf..64c127d 100644 --- a/src/gui.rs +++ b/src/gui.rs @@ -1716,6 +1716,10 @@ impl ThrottleApp { .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(); @@ -1743,8 +1747,10 @@ 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) { - self.finish_modal = Some(FinishModal { + let mut modal = FinishModal { exe_path: key.to_string(), name: name.to_string(), action: PowerAction::Shutdown, @@ -1754,7 +1760,22 @@ impl ThrottleApp { 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 @@ -1787,6 +1808,7 @@ impl ThrottleApp { 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()); } @@ -1797,6 +1819,7 @@ impl ThrottleApp { 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()); } @@ -1826,6 +1849,7 @@ impl ThrottleApp { 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()); } @@ -1851,10 +1875,9 @@ impl ThrottleApp { ui.label( egui::RichText::new(format!( "Watching starts once the process has stayed above that rate for \ - {} seconds. Before the action runs you get a {} second countdown to \ - cancel it.", - finish_watch::ARM_SAMPLES, - finish_watch::COUNTDOWN.as_secs() + {} 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(), @@ -1875,7 +1898,14 @@ impl ThrottleApp { } ui.add_space(4.0); ui.horizontal(|ui| { - if ui.button("Start").clicked() { + 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() { @@ -1903,17 +1933,19 @@ impl ThrottleApp { return; }; self.finish_error = None; - self.finish_watch = Some(FinishWatch::new( - modal.exe_path, - modal.name, - finish_watch::Config { - transfer: modal.transfer, - threshold, - quiet: Duration::from_secs(u64::from(modal.quiet_mins) * 60), - action: modal.action, - force: modal.force, - }, - )); + 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 } @@ -1929,6 +1961,7 @@ impl ThrottleApp { 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 { @@ -1961,9 +1994,14 @@ impl ThrottleApp { 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; } @@ -1972,48 +2010,6 @@ impl ThrottleApp { } } - /// The last chance to cancel: a centred window for the whole countdown. - fn draw_finish_countdown(&mut self, ctx: &egui::Context) { - let now = Instant::now(); - let Some(watch) = &self.finish_watch else { - return; - }; - let Some(left) = watch.countdown_left(now) else { - return; - }; - let mut cancel = false; - egui::Window::new("Transfer finished") - .collapsible(false) - .resizable(false) - .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]) - .show(ctx, |ui| { - ui.vertical_centered(|ui| { - ui.add_space(6.0); - ui.label(format!( - "{} has stopped {}.", - watch.name, - watch.config.transfer.gerund() - )); - ui.add_space(4.0); - ui.heading( - egui::RichText::new(format!( - "{} in {left} s", - watch.config.action.progressive() - )) - .color(self.accents.block), - ); - ui.add_space(8.0); - if ui.button("Cancel").clicked() { - cancel = true; - } - ui.add_space(4.0); - }); - }); - 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. @@ -2086,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()); } @@ -2175,7 +2172,7 @@ impl eframe::App for ThrottleApp { // The watch runs here, not in `ui`, because the window is usually // hidden to the tray by the time an overnight transfer finishes. - // The countdown brings it back so the Cancel button can be reached. + // Near the end it comes back so the Cancel button can be reached. if countdown_started { self.start_hidden = None; self.show_window(ctx); @@ -2299,7 +2296,6 @@ impl eframe::App for ThrottleApp { self.draw_table(ui, &snap); self.draw_limit_modal(&ctx); self.draw_finish_modal(&ctx); - self.draw_finish_countdown(&ctx); self.draw_about(&ctx); self.draw_customise_window(&ctx); self.draw_import_error(&ctx); @@ -2380,6 +2376,20 @@ fn pill(ui: &mut egui::Ui, text: &str) -> egui::Response { .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 {