S046: readable speed, one-bar setting, snail button and 8 kB cap

This commit is contained in:
astar76 2026-11-26 12:44:21 -06:00
commit 6f06b10792
13 changed files with 254 additions and 8 deletions

View file

@ -69,6 +69,7 @@ impl App {
let theme = Theme::build(&settings, desktop);
theme.apply(ctx, settings.motion);
keys::set(&settings);
crate::ui::wave::set_one_bar(settings.bar == medlar_core::settings::BarStyle::One);
let watch = Watch::start(sources.clone(), ctx);
App {
themed: settings.clone(),
@ -110,6 +111,7 @@ impl App {
let now = ctx.input(|i| i.time);
if self.applied != self.settings {
keys::set(&self.settings);
crate::ui::wave::set_one_bar(self.settings.bar == medlar_core::settings::BarStyle::One);
self.main.bridge.apply(&self.settings);
if let Some(paths) = self.paths.as_ref().filter(|_| self.applied.language != self.settings.language) {
strings::set(Catalogue::load(&paths.languages(), &self.settings.language).0);
@ -203,6 +205,12 @@ impl App {
}
None => {
self.main.show(ui, &t, &self.settings);
let window = ui.ctx().content_rect();
let at = egui::pos2(window.right() - crate::tokens::space::L, window.bottom() - self.main.floor() - crate::tokens::space::L);
let on = self.settings.mode == medlar_core::settings::Mode::Snail;
if crate::ui::snail::button(ui.ctx(), &t, at, on, &keys::label(Action::Snail)) {
self.run(ui, Action::Snail);
}
if let Some(change) = self.main.change.take() {
change.apply(&mut self.settings);
}

View file

@ -11,5 +11,6 @@ pub mod widgets;
pub mod graph;
pub mod odometer;
pub mod parts;
pub mod snail;
pub mod shape;
pub mod wave;

View file

@ -96,9 +96,50 @@ pub fn odometer(ui: &Ui, id: Id, pos: Pos2, words: &str, font: FontId, color: Co
Rect::from_min_max(pos2(pos.x, top), pos2(x, top + height))
}
/// A live speed that can be read: the average of the last `WINDOW` seconds, kept on show for `HOLD` seconds before it
/// changes, and not changed at all for what its digits don't show. Big jumps (start, stop, pause) pass at once.
#[derive(Clone, Default)]
pub struct Calm {
seen: std::collections::VecDeque<(f64, f64)>,
shown: f64,
since: f64,
}
pub const HOLD: f64 = 1.0;
const WINDOW: f64 = 2.0;
impl Calm {
/// `raw` is the speed measured at `now` (seconds); gives back what to show.
pub fn feed(&mut self, now: f64, raw: f64) -> f64 {
let raw = if raw.is_finite() { raw.max(0.0) } else { 0.0 };
self.seen.push_back((now, raw));
while self.seen.front().is_some_and(|(at, _)| *at < now - WINDOW) {
self.seen.pop_front();
}
let jump = raw == 0.0 || self.shown == 0.0 || raw > self.shown * 3.0 || raw < self.shown / 3.0;
if jump {
self.seen.clear();
self.seen.push_back((now, raw));
(self.shown, self.since) = (raw, now);
} else if now - self.since >= HOLD {
let mean = self.seen.iter().map(|(_, v)| v).sum::<f64>() / self.seen.len() as f64;
if scaled(mean) != scaled(self.shown) {
(self.shown, self.since) = (mean, now);
}
}
self.shown
}
}
/// The big speed number with its unit. Returns where it ended up.
pub fn speed(ui: &Ui, t: &Theme, id: Id, pos: Pos2, bytes_per_second: f64) -> Rect {
use crate::{fonts, tokens::{space, text}};
let now = ui.input(|i| i.time);
let bytes_per_second = ui.data_mut(|d| d.get_temp_mut_or_default::<Calm>(id.with("calm")).feed(now, bytes_per_second));
if bytes_per_second > 0.0 {
// The hold ends by itself; idle draws nothing.
ui.ctx().request_repaint_after_secs(HOLD as f32);
}
let all = rate(bytes_per_second);
let number = scaled(bytes_per_second).0;
let (before, after) = all.split_once(&number).unwrap_or(("", &all));
@ -117,6 +158,29 @@ mod tests {
assert_eq!([f64::NAN, -4.0, 2_000.0].map(rate), ["0 B/s", "0 B/s", "2.0 kB/s"]);
}
#[test]
fn a_noisy_speed_changes_at_most_once_per_hold() {
let mut calm = Calm::default();
let mut seed = 12345_u64;
let (mut last, mut changes) = (f64::NAN, 0);
// 20 seconds at 20 samples a second around 480 kB/s, plus or minus a third.
for i in 0..400 {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
let noise = ((seed >> 33) % 1000) as f64 / 1000.0 - 0.5;
let shown = calm.feed(i as f64 * 0.05, 480_000.0 * (1.0 + noise * 0.66));
if shown != last {
changes += 1;
last = shown;
}
}
assert!(changes <= 21, "{changes} changes in 20 s");
let mut calm = Calm::default();
assert_eq!([calm.feed(0.0, 0.0), calm.feed(0.1, 500_000.0), calm.feed(0.2, 0.0)], [0.0, 500_000.0, 0.0], "start and stop pass at once");
let mut calm = Calm::default();
calm.feed(0.0, 488_300.0);
assert_eq!(calm.feed(2.0, 488_340.0), 488_300.0, "below the shown precision nothing rolls");
}
#[test]
fn digits_take_the_short_way() {
assert_eq!([nearest(9.0, 0.0), nearest(0.0, 9.0), nearest(12.0, 1.0), nearest(3.0, 5.0)], [10.0, -1.0, 11.0, 5.0]);

108
crates/app/src/ui/snail.rs Normal file
View file

@ -0,0 +1,108 @@
//! The snail button at the window's corner: snail mode on or off, with a small snail drawn as a vector shape.
use super::widgets::{cr, feel, tip};
use crate::motion;
use crate::theme::{Theme, alpha};
use crate::tokens::{self, elevation};
use eframe::egui::accesskit::Role;
use eframe::egui::{Area, Color32, Context, Id, Order, Painter, Pos2, Rect, Sense, Shape, Stroke, WidgetInfo, vec2};
use medlar_core::settings::Motion;
use medlar_core::tr;
/// Frames per second of the crawl: it is cheap, and it is the only loop that runs while nothing else moves.
const FPS: f32 = 15.0;
/// A round button with its bottom right corner at `at`. True when it was clicked.
#[allow(deprecated)]
pub fn button(ctx: &Context, t: &Theme, at: Pos2, on: bool, keys: &str) -> bool {
let side = tokens::size::LARGE;
let rect = Rect::from_min_max(at - vec2(side, side), at);
let id = Id::new("snail button");
let name = tr!("snail.button");
let mut clicked = false;
Area::new(id).order(Order::Middle).fixed_pos(rect.min).constrain(false).fade_in(false).sense(Sense::hover()).show(ctx, |ui| {
let r = ui.interact(rect, id.with("hit"), Sense::click());
r.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, on, &name));
let f = feel(&r, true);
let (fill, ink) = if on { (t.secondary_container, t.on_secondary_container) } else { (t.high, t.on_variant) };
let p = ui.painter();
p.add(elevation::floating(t.dark).as_shape(rect, cr(side / 2.0)));
p.circle_filled(rect.center(), side / 2.0 - f.press.max(0.0) * 2.0, fill);
if f.tint > 0.0 {
p.circle_filled(rect.center(), side / 2.0, alpha(ink, f.tint));
}
// Reduced motion is a small sway, off is still; nothing moves while it is off.
let amount = match motion::level() {
Motion::Off => 0.0,
Motion::Reduced => 0.35,
_ => 1.0,
};
let phase = if on && amount > 0.0 {
ctx.request_repaint_after_secs(1.0 / FPS);
ctx.input(|i| i.time) as f32
} else {
0.0
};
draw(p, rect.center(), side * 0.5, ink, on, phase, amount);
tip(&r, t, &name, keys);
clicked = r.clicked();
});
clicked
}
/// The snail in a square of `size`, facing right. `phase` in seconds moves the stretch of its body and the sway of its shell.
pub fn draw(p: &Painter, center: Pos2, size: f32, ink: Color32, filled: bool, phase: f32, amount: f32) {
let u = size / 2.0;
let wave = (phase * 2.4).sin() * amount;
let stroke = Stroke::new((size / 14.0).max(1.5), ink);
// The foot stretches and shrinks a little.
let tail = center + vec2(-0.9 * u - 0.08 * u * wave, 0.62 * u);
let neck = center + vec2(0.55 * u + 0.1 * u * wave, 0.62 * u);
p.line_segment([tail, neck], stroke);
// The head and its feelers.
let head = neck + vec2(0.1 * u, -0.28 * u);
p.line_segment([neck, head], stroke);
let sway = 0.12 * u * wave;
for dx in [0.0, 0.3] {
let base = head + vec2(0.04 * u + dx * u * 0.5, -0.04 * u);
p.line_segment([base, base + vec2(0.1 * u + sway, -0.3 * u)], Stroke::new(stroke.width * 0.7, ink));
}
p.circle_filled(head, 0.17 * u, ink);
// The shell: a disc (filled when on) with a spiral, turned a little by the sway.
let shell = center + vec2(-0.2 * u, -0.05 * u);
let r = 0.62 * u;
if filled {
p.circle_filled(shell, r, alpha(ink, 0.28));
}
p.circle_stroke(shell, r, stroke);
let turn = 0.15 * wave;
let points: Vec<Pos2> = (0..=36)
.map(|i| {
let a = i as f32 / 36.0 * 3.2 * std::f32::consts::PI;
let radius = r * 0.9 * (a / (3.2 * std::f32::consts::PI));
shell + vec2((a + turn).cos(), (a + turn).sin()) * radius
})
.collect();
p.add(Shape::line(points, Stroke::new(stroke.width * 0.8, ink)));
}
#[cfg(test)]
mod tests {
use super::*;
use eframe::egui::{RawInput, ViewportId};
#[test]
fn off_asks_for_no_frames_and_on_asks_for_a_slow_loop() {
let t = Theme::build(&medlar_core::settings::Settings::default(), crate::desktop::Desktop::default());
use eframe::egui::pos2;;
for (on, repaints) in [(false, false), (true, true)] {
let ctx = Context::default();
let mut out = ctx.run_ui(RawInput::default(), |ui| {
button(ui.ctx(), &t, pos2(300.0, 300.0), on, "Ctrl+Shift+S");
});
out.textures_delta.clear();
let after = out.viewport_output[&ViewportId::ROOT].repaint_delay;
assert_eq!(after < std::time::Duration::from_secs(1), repaints, "on={on}: {after:?}");
}
}
}

View file

@ -293,6 +293,17 @@ impl Ink {
}
}
static ONE_BAR: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Follows the setting: one continuous bar, or one per part.
pub fn set_one_bar(one: bool) {
ONE_BAR.store(one, std::sync::atomic::Ordering::Relaxed);
}
pub fn one_bar() -> bool {
ONE_BAR.load(std::sync::atomic::Ordering::Relaxed)
}
/// What a bar shows. `parts` are the file's ranges in order; bytes between them count as missing.
#[derive(Clone, Copy, Default)]
pub struct Bar<'a> {

View file

@ -257,7 +257,7 @@ fn state_ink(t: &Theme, v: &TaskView) -> Color32 {
fn bar(ui: &Ui, t: &Theme, rect: Rect, v: &TaskView) {
let parts: Vec<Part> = v.parts.iter().map(|p| Part { start: p.start, end: p.end, done: p.done }).collect();
let whole = [Part { start: 0, end: v.size, done: v.downloaded }];
let parts = if parts.is_empty() { &whole[..] } else { &parts[..] };
let parts = if parts.is_empty() || wave::one_bar() { &whole[..] } else { &parts[..] };
let b = Bar { look: Look::from(v.state()), size: v.size, parts, speed: v.speed, checked: v.checked };
let rect = Rect::from_center_size(rect.center(), vec2(rect.width(), wave::HEIGHT));
wave::bar(ui, t, id(v.id()).with("bar"), rect, &b);

View file

@ -278,7 +278,7 @@ impl Main {
}
/// How much at the bottom the toolbar takes.
fn floor(&self) -> f32 {
pub fn floor(&self) -> f32 {
if self.list.selected.is_empty() { 0.0 } else { bar::TOOLBAR - space::L }
}
@ -367,7 +367,8 @@ impl Main {
}
fn list_in(&mut self, ui: &mut Ui, t: &Theme, rest: Rect, lists: &Arc<Lists>, orders: &mut Vec<Order>) {
let below = if self.list.selected.is_empty() { space::L } else { bar::TOOLBAR };
// Room for the snail button that floats at the corner.
let below = if self.list.selected.is_empty() { size::LARGE + space::XL } else { bar::TOOLBAR + size::LARGE };
// The scroll bar stands in the margin, so rows end where everything else does.
orders.extend(self.list.show(ui, t, rest.with_max_x(rest.right() + space::M), lists, below));
orders.extend(bar::selected(ui, t, rest, &mut self.list));

View file

@ -5,7 +5,7 @@ use super::{Cx, View, backup, look, network, sites};
use crate::keys::{self, Action};
use crate::ui::dialog;
use eframe::egui::Ui;
use medlar_core::settings::{Appearance, Contrast, Mode, Motion, Scheme, Settings};
use medlar_core::settings::{Appearance, BarStyle, Contrast, Mode, Motion, Scheme, Settings};
use medlar_core::strings::{self, Catalogue};
use medlar_core::tr;
use std::ops::RangeInclusive;
@ -169,6 +169,7 @@ const MODES: [Mode; 4] = [Mode::Low, Mode::Medium, Mode::High, Mode::Snail];
const APPEARANCES: [Appearance; 4] = [Appearance::Auto, Appearance::Light, Appearance::Dark, Appearance::Amoled];
const SCHEMES: [Scheme; 4] = [Scheme::Tonal, Scheme::Vibrant, Scheme::Expressive, Scheme::Mono];
const CONTRASTS: [Contrast; 3] = [Contrast::Standard, Contrast::Medium, Contrast::High];
const BARS: [BarStyle; 2] = [BarStyle::Parts, BarStyle::One];
const MOTIONS: [Motion; 4] = [Motion::Off, Motion::Reduced, Motion::Normal, Motion::Expressive];
fn at<T: PartialEq>(all: &[T], one: T) -> usize {
@ -261,6 +262,13 @@ static ROWS: &[Row] = &[
&["motion"],
Kind::Choice { options: &["off", "reduced", "normal", "expressive"], get: |s| at(&MOTIONS, s.motion), set: |s, i| s.motion = MOTIONS[i] },
),
row(
Page::Look,
"motion",
"bar",
&["progress", "bar", "parts"],
Kind::Choice { options: &["parts", "one"], get: |s| at(&BARS, s.bar), set: |s, i| s.bar = BARS[i] },
),
row(
Page::Look,
"language",

View file

@ -26,6 +26,7 @@ const OPEN: [f32; 2] = [SMALL + space::XXL + space::XL + space::XS, SMALL + 3.0
#[derive(Default)]
pub struct Target {
menu: bool,
calm: crate::ui::odometer::Calm,
}
enum Do {
@ -58,6 +59,10 @@ impl Target {
let mut act = None;
let mut dropped = vec![];
let menu = &mut self.menu;
let calm = self.calm.feed(ctx.input(|i| i.time), speed);
if calm > 0.0 {
ctx.request_repaint_after_secs(crate::ui::odometer::HOLD as f32);
}
ctx.show_viewport_immediate(ViewportId::from_hash_of("drop target"), builder, |ui, class| {
if class != ViewportClass::Immediate && class != ViewportClass::Root {
// Embedded in the main window: nothing to show on its own.
@ -70,7 +75,7 @@ impl Target {
let look = if speed > 0.0 { Look::Running } else { Look::Waiting };
wave::ring(ui, t, salt("target ring"), ring, look, None, speed);
let p = ui.painter();
p.text(pos2(full.center().x, ring.bottom() + space::S), Align2::CENTER_TOP, rate(speed), fonts::med(text::LABEL), t.on_surface);
p.text(pos2(full.center().x, ring.bottom() + space::S), Align2::CENTER_TOP, rate(calm), fonts::med(text::LABEL), t.on_surface);
let r = ui.interact(ring, salt("target hit"), Sense::click_and_drag());
if r.drag_started() {
ui.ctx().send_viewport_cmd(ViewportCommand::StartDrag);

View file

@ -44,6 +44,8 @@ const SCENES: &[Scene] = &[("window", App::show), ("tokens", |app, ui| app.frame
("fab", |app, ui| over(app, ui, "fab")),
("toasts", |app, ui| over(app, ui, "toasts")),
("main", |app, ui| main_view(app, ui, |_| {})),
("main-snail", |app, ui| main_view(app, ui, |app| app.settings.mode = medlar_core::settings::Mode::Snail)),
("main-onebar", |app, ui| main_view(app, ui, |app| app.settings.bar = medlar_core::settings::BarStyle::One)),
("main-cards", |app, ui| main_view(app, ui, |app| app.main.list.form = Form::Cards)),
("main-selected", |app, ui| main_view(app, ui, |app| app.main.list.selected = [2, 4, 9].into())),
("main-filtered", |app, ui| main_view(app, ui, |app| app.main.list.query.filter.kind = Some(medlar_app::ui::shape::Kind::Archive))),

View file

@ -604,6 +604,11 @@
"set.motion.reduced": "Reduced",
"set.motion.normal": "Normal",
"set.motion.expressive": "Full",
"set.bar": "Progress bar",
"set.bar.why": "One bar for the whole file, or one for each part that is downloading.",
"set.bar.parts": "One per part",
"set.bar.one": "One bar",
"snail.button": "Snail mode",
"set.language": "Language",
"set.language.why": "More appear when their files are in Medlar's languages folder.",
"set.language.auto": "Same as the desktop",

View file

@ -74,6 +74,7 @@ pub struct Settings {
pub scheme: Scheme,
pub contrast: Contrast,
pub motion: Motion,
pub bar: BarStyle,
/// The user's own, by action; empty for none. What isn't here has its usual one.
pub shortcuts: BTreeMap<String, String>,
/// Keys of newer versions.
@ -129,6 +130,22 @@ pub enum Contrast {
High,
}
/// Snail mode: 8 kB/s (the app counts in thousands).
pub const SNAIL_SPEED: u64 = 8000;
/// What snail mode was before 0.1.1; a stored value that is still this one moves to the new one.
const OLD_SNAIL_SPEED: u64 = 32 * 1024;
/// How the wavy progress bar shows a download.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BarStyle {
/// One bar per part.
#[default]
Parts,
/// One continuous bar for the whole file.
One,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Motion {
@ -160,7 +177,7 @@ impl Default for Settings {
low: Limits::new(256 * 1024, 2, 8, 4, 4),
medium: Limits::new(1024 * 1024, 3, 24, 8, 8),
high: Limits::default(),
snail: Limits::new(32 * 1024, 1, 1, 1, 1),
snail: Limits::new(SNAIL_SPEED, 1, 1, 1, 1),
mode_grid: vec![],
tries: 10,
auto_resume: true,
@ -192,6 +209,7 @@ impl Default for Settings {
scheme: Scheme::Tonal,
contrast: Contrast::Standard,
motion: Motion::Expressive,
bar: BarStyle::Parts,
shortcuts: BTreeMap::new(),
unknown: Map::new(),
}
@ -248,7 +266,10 @@ impl Settings {
}
}
});
let settings = serde_json::from_value(Value::Object(map)).expect("every key was checked");
let mut settings: Settings = serde_json::from_value(Value::Object(map)).expect("every key was checked");
if settings.snail.speed == OLD_SNAIL_SPEED {
settings.snail.speed = SNAIL_SPEED;
}
if keys.is_empty() {
return (settings, None);
}
@ -362,6 +383,18 @@ mod tests {
(dir, path)
}
#[test]
fn snail_moves_to_8_kb_unless_changed() {
assert_eq!(Settings::default().snail.speed, 8000);
let (_d, path) = file(r#"{"snail": {"speed": 32768, "max_active": 1, "max_connections": 1, "parts_per_download": 1, "connections_per_host": 1}}"#);
assert_eq!(Settings::load(&path).0.snail.speed, 8000);
let (_d, path) = file(r#"{"snail": {"speed": 20000, "max_active": 1, "max_connections": 1, "parts_per_download": 1, "connections_per_host": 1}, "bar": "one"}"#);
let s = Settings::load(&path).0;
assert_eq!((s.snail.speed, s.bar), (20000, BarStyle::One));
let (_d, path) = file("{}");
assert_eq!(Settings::load(&path).0.bar, BarStyle::Parts);
}
#[test]
fn missing_file_gives_defaults() {
assert_eq!(Settings::load(Path::new("/nonexistent/settings.json")), (Settings::default(), None));

View file

@ -373,7 +373,7 @@ async fn slow_is_even_and_stays_connected() {
async fn modes_change_live_without_reconnecting() {
let _alone = ALONE.lock().await;
let mut settings = Settings::default();
for (mode, speed) in [(Mode::Low, 100 * KB), (Mode::Medium, MB), (Mode::High, 3 * MB), (Mode::Snail, 32 * KB)] {
for (mode, speed) in [(Mode::Low, 100 * KB), (Mode::Medium, MB), (Mode::High, 3 * MB), (Mode::Snail, 8 * KB)] {
*settings.limits_of(mode) = Limits { speed, parts_per_download: 2, ..LIMITS };
}
let b = Bench::new(settings.limits()).await;