S014: wavy bars, parts map, shapes, speed graph and rolling digits
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
921d1cc468
commit
13cb409f8f
16 changed files with 2444 additions and 9 deletions
|
|
@ -72,6 +72,7 @@ Never modify: everything outside this folder. `~/Projects/*` is read-only refere
|
|||
| `nice cargo test -j 2` | unit and engine tests | 01 Foundation |
|
||||
| `MEDLAR_SHOTS=dir nice cargo test -j 2 -p medlar --test shots`, then `tools/contact.sh dir` | screenshots light and dark (`SCENE`, `SIZES=WxH,…`, `HOVER=x,y`, `PRESS=1`); add the view to `SCENES` | S003 |
|
||||
| `tools/hidden.sh <outdir> [driver.sh] [WxH]` | the release build in a hidden nested niri with a throwaway home: click, type, grab, cpu | S003 |
|
||||
| `MEDLAR_SEQUENCE=dir nice cargo test -j 2 -p medlar --test visuals sequence`; `cargo run -p medlar --example visuals` | progress widgets frame by frame; live with a scrubber | S014 |
|
||||
| `python3 tools/gen_assets.py icons` | adds icons: put the name in `tools/icons.txt` first | S003 |
|
||||
| `nice cargo build --release -j 2` | release build (never at the same time as the tests) | 01 Foundation |
|
||||
| `nice cargo test -j 2 -p medlar-testserver` / `cargo run -p medlar-testserver -- [--port N] [--tls] [--media] [--proxies]` | local server with faults and proxy stubs; API in the `crates/testserver/src/lib.rs` header | S002 |
|
||||
|
|
|
|||
|
|
@ -13,14 +13,14 @@ The parts of Medlar people will remember, driven by real engine data. FEATURES 9
|
|||
- docs/FEATURES.md §9
|
||||
|
||||
## Steps
|
||||
- [ ] Wavy line progress: amplitude and travel follow speed through springs, round ends, gap and stop mark, flattens when paused; states for waiting, verifying, unknown size, error, done
|
||||
- [ ] Part-aware wave: gaps between parts glide when parts split, hand over or merge
|
||||
- [ ] Wavy ring for compact places and the tray preview; wavy slider for limits
|
||||
- [ ] Parts map: blocks that split, hand over and merge with springs, hover shows range, speed and server; falls back to a density strip for thousands of ranges
|
||||
- [ ] Morphing shapes: loading indicator, one shape per file kind, completion moment (wave settles, shape becomes a tick), interruptible and played once
|
||||
- [ ] Speed graph with filled area, limit line and hover readout; rolling tabular digits for the big number
|
||||
- [ ] Simulated data in the gallery, with a scrubber for speed and part events; cost measured with 200 bars on screen
|
||||
- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S014: …`, push
|
||||
- [x] Wavy line progress: amplitude and travel follow speed through springs, round ends, gap and stop mark, flattens when paused; states for waiting, verifying, unknown size, error, done
|
||||
- [x] Part-aware wave: gaps between parts glide when parts split, hand over or merge
|
||||
- [x] Wavy ring for compact places and the tray preview; wavy slider for limits
|
||||
- [x] Parts map: blocks that split, hand over and merge with springs, hover shows range, speed and server; falls back to a density strip for thousands of ranges
|
||||
- [x] Morphing shapes: loading indicator, one shape per file kind, completion moment (wave settles, shape becomes a tick), interruptible and played once
|
||||
- [x] Speed graph with filled area, limit line and hover readout; rolling tabular digits for the big number
|
||||
- [x] Simulated data in the gallery, with a scrubber for speed and part events; cost measured with 200 bars on screen
|
||||
- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S014: …`, push
|
||||
|
||||
## End criteria
|
||||
- `nice cargo test -j 2 -p medlar --test visuals` green: no NaN, stays in bounds at 0, tiny and 100 %, paused and settled draw no frames
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H
|
|||
## 03 Interface
|
||||
|
||||
- [x] [S013](03%20Interface/S013-controls.md) Controls, dialogs and toasts
|
||||
- [ ] [S014](03%20Interface/S014-wavy-parts-shapes.md) Wavy bars, parts map, shapes and speed graph
|
||||
- [x] [S014](03%20Interface/S014-wavy-parts-shapes.md) Wavy bars, parts map, shapes and speed graph
|
||||
- [ ] [S015](03%20Interface/S015-main-window.md) Main window and list
|
||||
- [ ] [S016](03%20Interface/S016-add-dialog.md) Add dialog, batch and duplicates
|
||||
- [ ] [S017](03%20Interface/S017-details.md) Details panel and file actions
|
||||
|
|
|
|||
27
crates/app/examples/visuals.rs
Normal file
27
crates/app/examples/visuals.rs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
//! The progress widgets in a window, with a scrubber: cargo run -p medlar --example visuals
|
||||
|
||||
#[path = "../tests/visuals/gallery.rs"]
|
||||
mod gallery;
|
||||
|
||||
use eframe::egui::{self, Ui};
|
||||
use medlar_app::app::App;
|
||||
use medlar_app::desktop::Sources;
|
||||
use medlar_core::settings::Settings;
|
||||
|
||||
struct Window(App);
|
||||
|
||||
impl eframe::App for Window {
|
||||
fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) {
|
||||
let half = ui.max_rect().split_left_right_at_fraction(0.5);
|
||||
self.0.frame(ui, |app, ui| {
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(half.0), |ui| gallery::gallery(app, ui));
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(half.1), |ui| gallery::states(app, ui));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
let options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default().with_inner_size([1500.0, 760.0]), ..Default::default() };
|
||||
let make = |cc: &eframe::CreationContext| App::new(&cc.egui_ctx, Settings::default(), Sources::detect());
|
||||
eframe::run_native("medlar-visuals", options, Box::new(move |cc| Ok(Box::new(Window(make(cc))))))
|
||||
}
|
||||
146
crates/app/src/ui/graph.rs
Normal file
146
crates/app/src/ui/graph.rs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
//! Speed over time: filled line, limit, and the value under the pointer.
|
||||
|
||||
use super::odometer::rate;
|
||||
use super::wave::{Ink, with_state};
|
||||
use crate::fonts;
|
||||
use crate::motion::{self, Spring};
|
||||
use crate::theme::{Theme, alpha};
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT};
|
||||
use crate::tokens::{radius, size, space, text};
|
||||
use eframe::egui::{Align2, CornerRadius, Id, Mesh, Pos2, Rect, Response, Sense, Shape, Stroke, Ui, Vec2, pos2, vec2};
|
||||
use medlar_core::settings::Motion;
|
||||
use medlar_core::tr;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
/// Speeds of the last while, one each `STEP` seconds.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct History {
|
||||
samples: VecDeque<f32>,
|
||||
pushed: u64,
|
||||
room: usize,
|
||||
}
|
||||
|
||||
/// Seconds between two samples.
|
||||
pub const STEP: f32 = 1.0;
|
||||
|
||||
impl History {
|
||||
/// Keeps `room` samples; the oldest waits off the left edge.
|
||||
pub fn new(room: usize) -> History {
|
||||
History { samples: VecDeque::with_capacity(room), pushed: 0, room: room.max(3) }
|
||||
}
|
||||
|
||||
pub fn push(&mut self, bytes_per_second: f64) {
|
||||
if self.samples.len() == self.room {
|
||||
self.samples.pop_front();
|
||||
}
|
||||
self.samples.push_back(if bytes_per_second.is_finite() { bytes_per_second.max(0.0) as f32 } else { 0.0 });
|
||||
self.pushed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct GraphState {
|
||||
pushed: u64,
|
||||
/// The newest samples slide in: how far they are still off, in hundredths of a step.
|
||||
slide: Spring,
|
||||
/// Top of the scale, as log2 times 100: it grows and shrinks evenly.
|
||||
top: Spring,
|
||||
}
|
||||
|
||||
impl Default for GraphState {
|
||||
fn default() -> GraphState {
|
||||
GraphState { pushed: 0, slide: Spring::new(0.0), top: Spring::new(0.0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the graph in `rect`. The newest sample is at the right.
|
||||
pub fn graph(ui: &Ui, t: &Theme, id: Id, rect: Rect, history: &History, limit: Option<f64>) -> Response {
|
||||
let resp = ui.interact(rect, id, Sense::hover());
|
||||
if !ui.is_rect_visible(rect) || rect.width() < space::XL || rect.height() < space::XL {
|
||||
return resp;
|
||||
}
|
||||
let p = ui.painter().with_clip_rect(rect);
|
||||
// The area's bottom is its baseline.
|
||||
p.rect_filled(rect, CornerRadius { sw: 0, se: 0, ..CornerRadius::same(radius::M as u8) }, t.low);
|
||||
let limit = limit.filter(|l| l.is_finite() && *l > 0.0).map(|l| l as f32);
|
||||
let peak = history.samples.iter().copied().fold(limit.unwrap_or(0.0), f32::max).max(1.0);
|
||||
let (slide, top) = with_state(ui.ctx(), id, |s: &mut GraphState, seen| {
|
||||
// A little air above the peak.
|
||||
s.top.target = (peak * 1.15).log2() * 100.0;
|
||||
if !seen || history.pushed < s.pushed {
|
||||
s.top.snap(s.top.target);
|
||||
s.slide.snap(0.0);
|
||||
} else if matches!(motion::level(), Motion::Normal | Motion::Expressive) {
|
||||
s.slide.x += ((history.pushed - s.pushed) as f32).min(4.0) * 100.0;
|
||||
}
|
||||
s.pushed = history.pushed;
|
||||
(s.slide.step(EFFECT) / 100.0, (s.top.step(DEFAULT) / 100.0).exp2().max(1.0))
|
||||
});
|
||||
let inner = rect.shrink2(vec2(0.0, size::FOCUS_RING));
|
||||
let step = inner.width() / (history.room - 2) as f32;
|
||||
let x_of = |i: usize| inner.right() - (history.samples.len() - 1 - i) as f32 * step + slide * step;
|
||||
let y_of = |v: f32| inner.bottom() - (v / top).clamp(0.0, 1.0) * inner.height();
|
||||
let points: Vec<Pos2> = history.samples.iter().enumerate().map(|(i, v)| pos2(x_of(i), y_of(*v))).collect();
|
||||
if points.len() > 1 {
|
||||
let mut area = Mesh::default();
|
||||
for (i, q) in points.iter().enumerate() {
|
||||
area.colored_vertex(*q, alpha(t.primary, 0.20));
|
||||
area.colored_vertex(pos2(q.x, rect.bottom()), alpha(t.primary, 0.20));
|
||||
if i > 0 {
|
||||
let k = 2 * i as u32;
|
||||
area.add_triangle(k - 2, k - 1, k);
|
||||
area.add_triangle(k - 1, k + 1, k);
|
||||
}
|
||||
}
|
||||
p.add(Shape::mesh(area));
|
||||
let mut ink = Ink::new(&p);
|
||||
let normal = |i: usize| {
|
||||
let d: Vec2 = points[(i + 1).min(points.len() - 1)] - points[i.saturating_sub(1)];
|
||||
vec2(-d.y, d.x).normalized()
|
||||
};
|
||||
ink.ribbon(points.iter().enumerate().map(|(i, q)| (*q, normal(i))), 1.0, t.primary);
|
||||
ink.paint(&p);
|
||||
}
|
||||
let label = |at: Pos2, align: Align2, words: String| {
|
||||
let galley = p.layout_no_wrap(words, fonts::med(text::LABEL), t.on_surface);
|
||||
let plate = align.anchor_size(at, galley.size() + vec2(space::S, space::XS));
|
||||
let plate = plate.translate(vec2((rect.left() + space::XS - plate.left()).max(0.0) - (plate.right() - rect.right() + space::XS).max(0.0), 0.0));
|
||||
p.rect_filled(plate, radius::XS, t.high);
|
||||
p.galley(plate.min + vec2(space::XS, space::XS / 2.0), galley, t.on_surface);
|
||||
};
|
||||
if let Some(limit) = limit {
|
||||
let y = y_of(limit);
|
||||
p.extend(Shape::dashed_line(&[pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(1.5, t.tertiary), space::S, space::XS));
|
||||
label(pos2(rect.left() + space::S, y + space::XS), Align2::LEFT_TOP, tr!("graph.limit", speed = rate(f64::from(limit))));
|
||||
}
|
||||
let hover = resp.hover_pos().filter(|_| !points.is_empty());
|
||||
if let Some(at) = hover {
|
||||
// The nearest sample.
|
||||
let back = ((inner.right() + slide * step - at.x) / step).round().max(0.0) as usize;
|
||||
if let Some(i) = (points.len() - 1).checked_sub(back) {
|
||||
let q = points[i];
|
||||
p.line_segment([pos2(q.x, rect.top()), pos2(q.x, rect.bottom())], Stroke::new(size::HAIRLINE, t.outline));
|
||||
p.circle(q, space::XS, t.primary, Stroke::new(size::FOCUS_RING, t.low));
|
||||
let ago = (back as f32 * STEP) as u32;
|
||||
let speed = rate(f64::from(history.samples[i]));
|
||||
let words = if ago == 0 { speed } else { tr!("graph.ago", speed = speed, n = ago) };
|
||||
let right = q.x > rect.center().x;
|
||||
label(pos2(q.x + if right { -space::S } else { space::S }, rect.top() + space::S), if right { Align2::RIGHT_TOP } else { Align2::LEFT_TOP }, words);
|
||||
}
|
||||
}
|
||||
resp
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn history_keeps_its_room_and_refuses_nonsense() {
|
||||
let mut h = History::new(3);
|
||||
for v in [1.0, f64::NAN, -2.0, 4.0] {
|
||||
h.push(v);
|
||||
}
|
||||
assert_eq!((h.samples.make_contiguous().to_vec(), h.pushed), (vec![0.0, 0.0, 4.0], 4));
|
||||
}
|
||||
}
|
||||
|
|
@ -6,3 +6,10 @@ pub mod gallery;
|
|||
pub mod menu;
|
||||
pub mod toast;
|
||||
pub mod widgets;
|
||||
|
||||
// Progress, parts, shapes, speed and numbers.
|
||||
pub mod graph;
|
||||
pub mod odometer;
|
||||
pub mod parts;
|
||||
pub mod shape;
|
||||
pub mod wave;
|
||||
|
|
|
|||
124
crates/app/src/ui/odometer.rs
Normal file
124
crates/app/src/ui/odometer.rs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
//! Amounts in words, and the big number whose digits roll.
|
||||
|
||||
use super::wave::finite;
|
||||
use crate::motion::{self, spring, spring_from};
|
||||
use crate::theme::{Theme, alpha};
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT};
|
||||
use eframe::egui::{Align2, Color32, FontId, Id, Pos2, Rect, Ui, pos2, vec2};
|
||||
use medlar_core::settings::Motion;
|
||||
use medlar_core::tr;
|
||||
|
||||
/// Number and unit, in thousands as the rest of the desktop counts: 1.5 and MB.
|
||||
fn scaled(bytes: f64) -> (String, usize) {
|
||||
let mut v = if bytes.is_finite() { bytes.max(0.0) } else { 0.0 };
|
||||
let mut unit = 0;
|
||||
// 999.95 would read as 1000.0.
|
||||
while v >= if unit == 0 { 999.5 } else { 999.95 } && unit < 5 {
|
||||
v /= 1000.0;
|
||||
unit += 1;
|
||||
}
|
||||
(if unit == 0 { format!("{v:.0}") } else { format!("{v:.1}") }, unit)
|
||||
}
|
||||
|
||||
fn with_unit(bytes: f64) -> String {
|
||||
let (n, unit) = scaled(bytes);
|
||||
match unit {
|
||||
0 => tr!("unit.b", n = n),
|
||||
1 => tr!("unit.kb", n = n),
|
||||
2 => tr!("unit.mb", n = n),
|
||||
3 => tr!("unit.gb", n = n),
|
||||
4 => tr!("unit.tb", n = n),
|
||||
_ => tr!("unit.pb", n = n),
|
||||
}
|
||||
}
|
||||
|
||||
/// "1.5 MB".
|
||||
pub fn amount(bytes: u64) -> String {
|
||||
with_unit(bytes as f64)
|
||||
}
|
||||
|
||||
/// "1.5 MB/s".
|
||||
pub fn rate(bytes_per_second: f64) -> String {
|
||||
tr!("unit.rate", amount = with_unit(bytes_per_second))
|
||||
}
|
||||
|
||||
/// The shortest way round from a digit to another: 9 to 0 goes one on, not nine back.
|
||||
fn nearest(from: f32, digit: f32) -> f32 {
|
||||
digit + 10.0 * ((from - digit) / 10.0).round()
|
||||
}
|
||||
|
||||
/// Draws `words` (already in the reader's language) with its left middle at `pos`; its digits roll to new values.
|
||||
/// Returns where it ended up.
|
||||
pub fn odometer(ui: &Ui, id: Id, pos: Pos2, words: &str, font: FontId, color: Color32) -> Rect {
|
||||
let p = ui.painter();
|
||||
let glyph = |c: char| p.layout_no_wrap(c.to_string(), font.clone(), color);
|
||||
let chars: Vec<char> = words.chars().collect();
|
||||
// The ones keep their wheel when a digit joins at the left.
|
||||
let point = chars.iter().position(|c| *c == '.' || *c == ',').unwrap_or_else(|| chars.iter().position(|c| !c.is_ascii_digit()).unwrap_or(chars.len()));
|
||||
let height = glyph('0').size().y;
|
||||
let (mut x, top) = (pos.x, pos.y - height / 2.0);
|
||||
for (i, c) in chars.iter().enumerate() {
|
||||
let galley = glyph(*c);
|
||||
let w = galley.size().x;
|
||||
let slot = Rect::from_min_size(pos2(x, top), vec2(w, height));
|
||||
x += w;
|
||||
let Some(digit) = c.to_digit(10) else {
|
||||
p.galley(slot.min, galley, color);
|
||||
continue;
|
||||
};
|
||||
let key = id.with(i as i64 - point as i64);
|
||||
// Reduced motion still must not lose the number: it changes at once.
|
||||
if matches!(motion::level(), Motion::Off | Motion::Reduced) {
|
||||
motion::forget(key);
|
||||
p.galley(slot.min, galley, color);
|
||||
continue;
|
||||
}
|
||||
let digit = digit as f32;
|
||||
let target_id = key.with("to");
|
||||
let before: f32 = ui.data(|d| d.get_temp(target_id)).unwrap_or(digit);
|
||||
let target = nearest(before, digit);
|
||||
ui.data_mut(|d| d.insert_temp(target_id, target));
|
||||
let at = finite(spring(key, target * 100.0, DEFAULT) / 100.0);
|
||||
let shown = spring_from(key.with("in"), 0.0, 1.0, EFFECT).clamp(0.0, 1.0);
|
||||
if at == target {
|
||||
p.galley(slot.min, galley, alpha(color, shown));
|
||||
continue;
|
||||
}
|
||||
let clip = p.with_clip_rect(slot);
|
||||
for k in [at.floor(), at.floor() + 1.0] {
|
||||
let n = char::from(b'0' + k.rem_euclid(10.0) as u8);
|
||||
let off = k - at;
|
||||
// The wheel turns away at its edges.
|
||||
let fade = (1.0 - off.abs()).clamp(0.0, 1.0).sqrt() * shown;
|
||||
clip.text(slot.center() + vec2(0.0, off * height * 0.8), Align2::CENTER_CENTER, n, font.clone(), alpha(color, fade));
|
||||
}
|
||||
}
|
||||
Rect::from_min_max(pos2(pos.x, top), pos2(x, top + height))
|
||||
}
|
||||
|
||||
/// 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 all = rate(bytes_per_second);
|
||||
let number = scaled(bytes_per_second).0;
|
||||
let (before, after) = all.split_once(&number).unwrap_or(("", &all));
|
||||
let r = odometer(ui, id, pos, &number, fonts::semi(text::DISPLAY), t.on_surface);
|
||||
let baseline = pos2(r.right() + space::S, r.bottom() - space::S);
|
||||
r.union(ui.painter().text(baseline, Align2::LEFT_BOTTOM, format!("{before}{after}").trim(), fonts::med(text::TITLE), t.on_variant))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn amounts_read_well() {
|
||||
assert_eq!([0, 999, 1000, 1_500_000, 999_960, u64::MAX].map(amount), ["0 B", "999 B", "1.0 kB", "1.5 MB", "1.0 MB", "18446.7 PB"]);
|
||||
assert_eq!([f64::NAN, -4.0, 2_000.0].map(rate), ["0 B/s", "0 B/s", "2.0 kB/s"]);
|
||||
}
|
||||
|
||||
#[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]);
|
||||
}
|
||||
}
|
||||
439
crates/app/src/ui/parts.rs
Normal file
439
crates/app/src/ui/parts.rs
Normal file
|
|
@ -0,0 +1,439 @@
|
|||
//! The parts of a file: `Tiles` springs their edges when they split, hand over and merge, the bar and the parts map
|
||||
//! draw it.
|
||||
|
||||
use super::odometer::{amount, rate};
|
||||
use super::wave::{finite, with_state};
|
||||
use crate::fonts;
|
||||
use crate::motion::{Spring, spring};
|
||||
use crate::theme::{Theme, alpha, mix};
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT};
|
||||
use crate::tokens::{radius, space, state, text};
|
||||
use eframe::egui::{self, CornerRadius, Id, Mesh, Rect, Response, Sense, Shape, Ui, pos2};
|
||||
use medlar_core::model::Part;
|
||||
use medlar_core::tr;
|
||||
|
||||
/// A whole file in spring units. Big enough that a spring rests within a pixel.
|
||||
pub(super) const SCALE: f32 = 1000.0;
|
||||
/// More ranges than this, or narrower than `NARROW` each, are drawn as a density strip.
|
||||
const MOST_BLOCKS: usize = 256;
|
||||
const NARROW: f32 = 4.0;
|
||||
/// Width of a column of the density strip.
|
||||
const COLUMN: f32 = 3.0;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Cell {
|
||||
/// Where its part begins; that never changes while the part lives.
|
||||
start: u64,
|
||||
/// Index of its part.
|
||||
part: usize,
|
||||
x: Spring,
|
||||
/// 0 closed, 100 open: the gap before it.
|
||||
gap: Spring,
|
||||
/// What is on disk, from `x` on.
|
||||
len: Spring,
|
||||
leaving: bool,
|
||||
}
|
||||
|
||||
/// Ranges of a file as they move on screen.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Tiles {
|
||||
cells: Vec<Cell>,
|
||||
sorted: Vec<(u64, u64, usize)>,
|
||||
}
|
||||
|
||||
/// One cell of `Tiles`, as shares of the width.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct TileView {
|
||||
pub part: usize,
|
||||
pub left: f32,
|
||||
pub right: f32,
|
||||
pub gap_before: f32,
|
||||
pub gap_after: f32,
|
||||
/// Share of it that is filled.
|
||||
pub filled: f32,
|
||||
pub full: bool,
|
||||
pub first: bool,
|
||||
pub last: bool,
|
||||
}
|
||||
|
||||
fn units(bytes: u64, size: u64) -> f32 {
|
||||
((bytes as f64 / size.max(1) as f64).clamp(0.0, 1.0) * f64::from(SCALE)) as f32
|
||||
}
|
||||
|
||||
impl Tiles {
|
||||
pub fn len(&self) -> usize {
|
||||
self.cells.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.cells.is_empty()
|
||||
}
|
||||
|
||||
/// Takes the file's ranges. `snap` puts everything in its place at once.
|
||||
pub fn follow(&mut self, size: u64, parts: &[Part], snap: bool) {
|
||||
self.sorted.clear();
|
||||
self.sorted.extend(parts.iter().enumerate().map(|(i, p)| (p.start, p.done, i)));
|
||||
if !self.sorted.is_sorted() {
|
||||
self.sorted.sort_unstable();
|
||||
}
|
||||
self.sorted.dedup_by_key(|p| p.0);
|
||||
let snap = snap || self.cells.is_empty();
|
||||
if snap {
|
||||
self.cells.clear();
|
||||
}
|
||||
if self.sorted.is_empty() {
|
||||
// Nothing known about the parts yet: one empty cell.
|
||||
self.sorted.push((0, 0, 0));
|
||||
}
|
||||
let same = self.cells.iter().filter(|c| !c.leaving).map(|c| c.start).eq(self.sorted.iter().map(|p| p.0));
|
||||
if !same {
|
||||
self.rebuild(size, snap);
|
||||
}
|
||||
let n = self.sorted.len();
|
||||
let mut open_before = false;
|
||||
let mut live = self.cells.iter_mut().filter(|c| !c.leaving);
|
||||
for (i, &(start, done, part)) in self.sorted.iter().enumerate() {
|
||||
let Some(c) = live.next() else { break };
|
||||
let end = if i + 1 < n { self.sorted[i + 1].0 } else { size.max(start) };
|
||||
let done = done.min(end - start);
|
||||
c.part = part;
|
||||
c.x.target = if i == 0 { 0.0 } else { units(start, size) };
|
||||
c.len.target = units(done, size);
|
||||
// Two finished stretches become one.
|
||||
c.gap.target = if i > 0 && (open_before || done == 0) { 100.0 } else { 0.0 };
|
||||
open_before = done < end - start;
|
||||
if snap {
|
||||
for s in [&mut c.x, &mut c.gap, &mut c.len] {
|
||||
s.snap(s.target);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Matches cells with the new ranges: kept, moved, new (glides in from the right end of the cell it splits) or leaving.
|
||||
fn rebuild(&mut self, size: u64, snap: bool) {
|
||||
let old = std::mem::take(&mut self.cells);
|
||||
let new = &self.sorted;
|
||||
let kept = |c: &Cell| new.binary_search_by_key(&c.start, |p| p.0).is_ok();
|
||||
let fresh = |&(start, _, part): &(u64, u64, usize)| {
|
||||
let x = if snap { units(start, size) } else { old.iter().find(|c| c.start > start).map_or(SCALE, |c| c.x.x) };
|
||||
Cell { start, part, x: Spring::new(x), gap: Spring::new(0.0), len: Spring::new(0.0), leaving: false }
|
||||
};
|
||||
let mut out: Vec<Cell> = Vec::with_capacity(old.len() + new.len());
|
||||
let (mut i, mut j) = (0, 0);
|
||||
loop {
|
||||
// Between two ranges that stay, those that went and those that came pair up: the same block, moved.
|
||||
let stays = (i..old.len()).find(|&k| kept(&old[k]));
|
||||
let upto = stays.map_or(new.len(), |k| new.partition_point(|p| p.0 < old[k].start));
|
||||
let mut came = new[j..upto].iter();
|
||||
let at = out.len();
|
||||
for c in &old[i..stays.unwrap_or(old.len())] {
|
||||
out.push(match if c.leaving { None } else { came.next() } {
|
||||
Some(p) => Cell { start: p.0, part: p.2, ..c.clone() },
|
||||
None => Cell { leaving: true, ..c.clone() },
|
||||
});
|
||||
}
|
||||
out.extend(came.map(&fresh));
|
||||
out[at..].sort_by_key(|c| c.start);
|
||||
let Some(k) = stays else { break };
|
||||
out.push(Cell { leaving: false, ..old[k].clone() });
|
||||
(i, j) = (k + 1, upto + 1);
|
||||
}
|
||||
self.cells = out;
|
||||
}
|
||||
|
||||
/// One frame on.
|
||||
pub fn step(&mut self) {
|
||||
// End of what the last staying cell will have on disk.
|
||||
let mut head = 0.0;
|
||||
for c in &mut self.cells {
|
||||
if c.leaving {
|
||||
c.gap.target = 0.0;
|
||||
// Swallowed by a finished stretch it fills up; started over, it empties.
|
||||
c.len.target = (head - c.x.x).max(0.0);
|
||||
} else {
|
||||
head = c.x.target + c.len.target;
|
||||
}
|
||||
c.x.step(DEFAULT);
|
||||
c.gap.step(EFFECT);
|
||||
c.len.step(EFFECT);
|
||||
}
|
||||
let mut i = 1;
|
||||
while i < self.cells.len() {
|
||||
let c = &self.cells[i];
|
||||
if c.leaving && c.gap.settled() && c.len.settled() {
|
||||
let end = c.x.x + c.len.x;
|
||||
let before = &mut self.cells[i - 1];
|
||||
if end > before.x.x + before.len.x && before.x.x + before.len.target >= end - 1.0 {
|
||||
before.len.x = end - before.x.x;
|
||||
}
|
||||
self.cells.remove(i);
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
// The first cell can only leave when another takes its place.
|
||||
if self.cells.len() > 1 && self.cells[0].leaving {
|
||||
self.cells.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cells(&self) -> impl Iterator<Item = TileView> + '_ {
|
||||
let mut left = 0.0_f32;
|
||||
let n = self.cells.len();
|
||||
(0..n).map(move |i| {
|
||||
let c = &self.cells[i];
|
||||
let next = self.cells.get(i + 1);
|
||||
let right = next.map_or(SCALE, |c| c.x.x).clamp(left, SCALE);
|
||||
let width = right - left;
|
||||
let len = c.len.x.clamp(0.0, width);
|
||||
let open = |c: &Cell| (c.gap.x / 100.0).clamp(0.0, 1.0);
|
||||
let out = TileView {
|
||||
part: c.part,
|
||||
left: left / SCALE,
|
||||
right: right / SCALE,
|
||||
gap_before: open(c),
|
||||
gap_after: next.map_or(0.0, open),
|
||||
filled: if width > 0.0 { len / width } else { 0.0 },
|
||||
full: len >= width - 0.05,
|
||||
first: i == 0,
|
||||
last: i + 1 == n,
|
||||
};
|
||||
left = right;
|
||||
out
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What the parts map shows of one part.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Block<'a> {
|
||||
pub part: Part,
|
||||
/// Bytes per second now; 0 for a part nobody is filling.
|
||||
pub speed: f64,
|
||||
pub server: Option<&'a str>,
|
||||
pub failed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct MapState {
|
||||
tiles: Tiles,
|
||||
parts: Vec<Part>,
|
||||
}
|
||||
|
||||
/// The parts map in `rect`. Pointing at a block tells its range, speed and server.
|
||||
pub fn map(ui: &Ui, t: &Theme, id: Id, rect: Rect, size: u64, blocks: &[Block]) -> Response {
|
||||
let resp = ui.interact(rect, id, Sense::hover());
|
||||
if !ui.is_rect_visible(rect) || rect.width() < COLUMN {
|
||||
return resp;
|
||||
}
|
||||
let at = resp.hover_pos().map(|p| ((p.x - rect.left()) / rect.width()).clamp(0.0, 1.0));
|
||||
if blocks.len() > MOST_BLOCKS || blocks.len() as f32 * NARROW > rect.width() {
|
||||
return strip(ui, t, rect, size, blocks, resp, at);
|
||||
}
|
||||
let mut hovered = None;
|
||||
with_state(ui.ctx(), id, |s: &mut MapState, seen| {
|
||||
s.parts.clear();
|
||||
s.parts.extend(blocks.iter().map(|b| b.part));
|
||||
s.tiles.follow(size, &s.parts, !seen);
|
||||
s.tiles.step();
|
||||
let gap = space::XS.min(rect.width() * 0.25 / s.tiles.len().max(1) as f32);
|
||||
let p = ui.painter();
|
||||
for c in s.tiles.cells() {
|
||||
let l = rect.left() + c.left * rect.width() + if c.first { 0.0 } else { gap / 2.0 * c.gap_before };
|
||||
let r = rect.left() + c.right * rect.width() - if c.last { 0.0 } else { gap / 2.0 * c.gap_after };
|
||||
if r - l < 0.1 {
|
||||
continue;
|
||||
}
|
||||
let block = blocks.get(c.part);
|
||||
let here = block.is_some() && at.is_some_and(|x| c.left <= x && x < c.right.max(c.left + f32::EPSILON));
|
||||
if here {
|
||||
hovered = block;
|
||||
}
|
||||
let busy = block.is_some_and(|b| b.speed > 0.0 && !c.full);
|
||||
let failed = block.is_some_and(|b| b.failed);
|
||||
let key = block.map(|b| (id, b.part.start));
|
||||
let hot = spring((key, "hot"), if busy { 1.0 } else { 0.0 }, EFFECT);
|
||||
let bad = spring((key, "bad"), if failed { 1.0 } else { 0.0 }, EFFECT);
|
||||
let tint = spring((key, "tint"), if here { state::HOVER } else { 0.0 }, EFFECT);
|
||||
let fill = mix(mix(t.secondary, t.primary, hot), t.error, bad);
|
||||
let track = mix(t.secondary_container, t.error_container, bad);
|
||||
let whole = Rect::from_min_max(pos2(l, rect.top()), pos2(r, rect.bottom()));
|
||||
// A closing gap takes the corners with it.
|
||||
let round = radius::S.min((r - l) / 2.0);
|
||||
let corner = |outer: bool, open: f32| (if outer { round } else { round * open }) as u8;
|
||||
let (w, e) = (corner(c.first, c.gap_before), corner(c.last || r > rect.right() - gap, c.gap_after));
|
||||
let corners = CornerRadius { nw: w, sw: w, ne: e, se: e };
|
||||
if !c.full {
|
||||
p.rect_filled(whole, corners, track);
|
||||
}
|
||||
let head = l + c.filled * (r - l);
|
||||
if head - l > 0.5 {
|
||||
let done = Rect::from_min_max(whole.min, pos2(if c.full { r } else { head }, rect.bottom()));
|
||||
if c.full {
|
||||
p.rect_filled(whole, corners, fill);
|
||||
} else if head - l < round {
|
||||
// Narrower than the corner: cut out of the whole block.
|
||||
p.with_clip_rect(done).rect_filled(whole, corners, fill);
|
||||
} else {
|
||||
p.rect_filled(done, CornerRadius { ne: 0, se: 0, ..corners }, fill);
|
||||
}
|
||||
}
|
||||
if tint > 0.001 {
|
||||
p.rect_filled(whole, corners, alpha(t.on_surface, tint));
|
||||
}
|
||||
}
|
||||
});
|
||||
let Some(b) = hovered else { return resp };
|
||||
let end = b.part.end.unwrap_or(size);
|
||||
let left = end.saturating_sub(b.part.start) > b.part.done;
|
||||
let what = match (left, b.speed > 0.0, b.server) {
|
||||
(false, ..) => tr!("map.done"),
|
||||
(_, true, Some(server)) => tr!("map.from", speed = rate(b.speed), server = server),
|
||||
(_, true, None) => rate(b.speed),
|
||||
_ => tr!("map.still"),
|
||||
};
|
||||
tip(resp, t, &tr!("map.range", from = amount(b.part.start), to = amount(end)), &what)
|
||||
}
|
||||
|
||||
fn tip(resp: Response, t: &Theme, title: &str, line: &str) -> Response {
|
||||
resp.on_hover_ui_at_pointer(|ui| {
|
||||
ui.label(egui::RichText::new(title).font(fonts::med(text::BODY)).color(t.on_surface));
|
||||
ui.label(egui::RichText::new(line).font(fonts::ui(text::LABEL)).color(t.on_variant));
|
||||
})
|
||||
}
|
||||
|
||||
/// How much of each stretch is there, for files in thousands of ranges.
|
||||
fn strip(ui: &Ui, t: &Theme, rect: Rect, size: u64, blocks: &[Block], resp: Response, at: Option<f32>) -> Response {
|
||||
let n = (rect.width() / COLUMN).floor().max(1.0) as usize;
|
||||
let parts: Vec<(Part, bool)> = blocks.iter().map(|b| (b.part, b.speed > 0.0)).collect();
|
||||
let columns = density(size, &parts, n);
|
||||
let w = rect.width() / n as f32;
|
||||
let mut mesh = Mesh::default();
|
||||
for (i, &(share, busy)) in columns.iter().enumerate() {
|
||||
let x = rect.left() + i as f32 * w;
|
||||
let top = rect.bottom() - share * rect.height();
|
||||
mesh.add_colored_rect(Rect::from_min_max(pos2(x, rect.top()), pos2(x + w, top)), t.secondary_container);
|
||||
mesh.add_colored_rect(Rect::from_min_max(pos2(x, top), pos2(x + w, rect.bottom())), if busy { t.primary } else { t.secondary });
|
||||
}
|
||||
ui.painter().add(Shape::mesh(mesh));
|
||||
let Some(at) = at else { return resp };
|
||||
let i = ((at * n as f32) as usize).min(n - 1);
|
||||
let edge = |i: usize| (u128::from(size) * i as u128 / n as u128) as u64;
|
||||
let percent = (columns[i].0 * 100.0).floor();
|
||||
tip(resp, t, &tr!("map.range", from = amount(edge(i)), to = amount(edge(i + 1))), &tr!("map.share", percent = percent))
|
||||
}
|
||||
|
||||
/// Share on disk of each of `n` equal stretches of the file, and whether bytes arrive there.
|
||||
fn density(size: u64, parts: &[(Part, bool)], n: usize) -> Vec<(f32, bool)> {
|
||||
let mut out = vec![(0.0, false); n];
|
||||
if size == 0 || n == 0 {
|
||||
return out;
|
||||
}
|
||||
let per = size as f64 / n as f64;
|
||||
for (p, busy) in parts {
|
||||
let (a, b) = (p.start.min(size) as f64 / per, p.start.saturating_add(p.done).min(size) as f64 / per);
|
||||
let first = (a as usize).min(n - 1);
|
||||
for (i, column) in out.iter_mut().enumerate().take((b.ceil() as usize).min(n)).skip(first) {
|
||||
column.0 += (b.min(i as f64 + 1.0) - a.max(i as f64)).max(0.0) as f32;
|
||||
}
|
||||
out[(b as usize).min(n - 1)].1 |= busy;
|
||||
}
|
||||
for c in &mut out {
|
||||
c.0 = finite(c.0).clamp(0.0, 1.0);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::motion;
|
||||
use medlar_core::settings::Motion;
|
||||
|
||||
fn part(start: u64, end: u64, done: u64) -> Part {
|
||||
Part { start, end: Some(end), done }
|
||||
}
|
||||
|
||||
fn frames(t: &mut Tiles, n: usize) {
|
||||
for _ in 0..n {
|
||||
motion::begin_frame(1.0 / 60.0, Motion::Normal);
|
||||
t.step();
|
||||
}
|
||||
}
|
||||
|
||||
fn lefts(t: &Tiles) -> Vec<f32> {
|
||||
t.cells().map(|c| (c.left * 100.0).round()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_glides_in_from_the_right() {
|
||||
let mut t = Tiles::default();
|
||||
t.follow(1000, &[part(0, 1000, 100)], false);
|
||||
assert_eq!(lefts(&t), [0.0]);
|
||||
t.follow(1000, &[part(0, 550, 100), part(550, 1000, 0)], false);
|
||||
frames(&mut t, 2);
|
||||
let x = t.cells().nth(1).unwrap().left;
|
||||
assert!(x > 0.55 && x < 1.0, "on its way: {x}");
|
||||
frames(&mut t, 120);
|
||||
assert_eq!(lefts(&t), [0.0, 55.0]);
|
||||
assert!(!motion::busy(), "then rests");
|
||||
assert_eq!(t.cells().nth(1).unwrap().gap_before, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hand_over_moves_the_block() {
|
||||
let mut t = Tiles::default();
|
||||
t.follow(1000, &[part(0, 200, 200), part(200, 1000, 10)], false);
|
||||
t.follow(1000, &[part(0, 200, 200), part(600, 1000, 10)], false);
|
||||
assert_eq!(t.len(), 2, "the same block");
|
||||
assert!((t.cells().nth(1).unwrap().left - 0.2).abs() < 1e-3, "still where it was");
|
||||
frames(&mut t, 120);
|
||||
assert_eq!(lefts(&t), [0.0, 60.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finished_neighbours_close_their_gap_and_merge() {
|
||||
let mut t = Tiles::default();
|
||||
t.follow(1000, &[part(0, 500, 400), part(500, 1000, 500)], false);
|
||||
assert_eq!(t.cells().nth(1).unwrap().gap_before, 1.0);
|
||||
t.follow(1000, &[part(0, 500, 500), part(500, 1000, 500)], false);
|
||||
frames(&mut t, 2);
|
||||
let g = t.cells().nth(1).unwrap().gap_before;
|
||||
assert!(g > 0.0 && g < 1.0);
|
||||
t.follow(1000, &[part(0, 1000, 1000)], false);
|
||||
frames(&mut t, 120);
|
||||
let one: Vec<_> = t.cells().collect();
|
||||
assert!(one.len() == 1 && one[0].full && !motion::busy(), "{one:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restart_empties_and_odd_input_stays_in_order() {
|
||||
let mut t = Tiles::default();
|
||||
t.follow(1000, &[part(500, 1000, 300), part(0, 500, 100)], false);
|
||||
assert_eq!(lefts(&t), [0.0, 50.0]);
|
||||
assert_eq!(t.cells().map(|c| c.part).collect::<Vec<_>>(), [1, 0]);
|
||||
t.follow(1000, &[part(0, 1000, 0)], false);
|
||||
frames(&mut t, 180);
|
||||
assert!(t.len() == 1 && t.cells().next().unwrap().filled == 0.0);
|
||||
for (size, parts) in [(0, vec![part(0, 0, 0)]), (10, vec![part(0, 99, 99)]), (10, vec![]), (u64::MAX, vec![part(0, 9, 3), part(9, u64::MAX, 5)])] {
|
||||
t.follow(size, &parts, false);
|
||||
frames(&mut t, 3);
|
||||
let mut last = 0.0;
|
||||
for c in t.cells() {
|
||||
assert!(c.left == last && c.right >= c.left && c.right <= 1.0 && (0.0..=1.0).contains(&c.filled), "{c:?}");
|
||||
last = c.right;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn density_adds_up() {
|
||||
let parts = [(part(0, 250, 250), false), (part(250, 1000, 125), true)];
|
||||
let d = density(1000, &parts, 4);
|
||||
assert_eq!(d, [(1.0, false), (0.5, true), (0.0, false), (0.0, false)]);
|
||||
assert_eq!(density(0, &parts, 3).len(), 3);
|
||||
let many: Vec<_> = (0..5000).map(|i| (part(i * 10, i * 10 + 10, 5), false)).collect();
|
||||
assert!(density(50_000, &many, 100).iter().all(|c| (c.0 - 0.5).abs() < 1e-3));
|
||||
}
|
||||
}
|
||||
357
crates/app/src/ui/shape.rs
Normal file
357
crates/app/src/ui/shape.rs
Normal file
|
|
@ -0,0 +1,357 @@
|
|||
//! Morphing shapes: the loading indicator, one shape per kind of file, and the tick a finished file turns into.
|
||||
|
||||
use super::wave::{Fade, Look, with_state};
|
||||
use crate::icons;
|
||||
use crate::motion::{self, Spring, spring, spring_from};
|
||||
use crate::theme::{Theme, alpha};
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT, SLOW};
|
||||
use eframe::egui::{Color32, Id, Mesh, Painter, Pos2, Rect, Shape, Ui, Vec2, vec2};
|
||||
use medlar_core::settings::Motion;
|
||||
use std::f32::consts::{FRAC_PI_2, PI, TAU};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// Points of an outline. Point `i` and point `N - i` face each other across the shape, so it can be filled in strips
|
||||
/// even where it isn't convex, as the tick and what lies between it and a blob.
|
||||
const N: usize = 96;
|
||||
const HALF: usize = N / 2;
|
||||
|
||||
type Outline = [Vec2; N];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Form {
|
||||
Circle,
|
||||
Square,
|
||||
Pill,
|
||||
Pentagon,
|
||||
Clover,
|
||||
Cookie6,
|
||||
Cookie9,
|
||||
Burst,
|
||||
Tick,
|
||||
}
|
||||
|
||||
impl Form {
|
||||
pub const ALL: [Form; 9] =
|
||||
[Form::Circle, Form::Square, Form::Pill, Form::Pentagon, Form::Clover, Form::Cookie6, Form::Cookie9, Form::Burst, Form::Tick];
|
||||
/// What the loading indicator goes through.
|
||||
const LOADING: [Form; 6] = [Form::Cookie9, Form::Pentagon, Form::Pill, Form::Burst, Form::Cookie6, Form::Clover];
|
||||
|
||||
fn outline(self) -> &'static Outline {
|
||||
static ALL: LazyLock<[Outline; 9]> = LazyLock::new(|| Form::ALL.map(Form::make));
|
||||
&ALL[self as usize]
|
||||
}
|
||||
|
||||
/// Reaches 1 at its furthest point.
|
||||
fn make(self) -> Outline {
|
||||
let round = |r: &dyn Fn(f32) -> f32| -> Outline {
|
||||
let mut out = std::array::from_fn(|i| {
|
||||
let a = i as f32 / N as f32 * TAU;
|
||||
Vec2::angled(a) * r(a)
|
||||
});
|
||||
let most = out.iter().map(|p| p.length()).fold(0.0, f32::max);
|
||||
out.iter_mut().for_each(|p| *p /= most);
|
||||
out
|
||||
};
|
||||
let cookie = |depth: f32, n: f32| round(&|a| 1.0 + depth * (n * a).cos());
|
||||
match self {
|
||||
Form::Circle => round(&|_| 1.0),
|
||||
Form::Square => round(&|a| (a.cos().abs().powf(4.2) + a.sin().abs().powf(4.2)).powf(-1.0 / 4.2)),
|
||||
Form::Pill => round(&|a| ((a.cos() / 0.74).powi(2) + a.sin().powi(2)).powf(-0.5)),
|
||||
Form::Pentagon => round(&|a| {
|
||||
let seg = TAU / 5.0;
|
||||
let edge = (PI / 5.0).cos() / (((a + FRAC_PI_2).rem_euclid(seg)) - PI / 5.0).cos();
|
||||
edge * 0.55 + 0.45 * 0.9
|
||||
}),
|
||||
Form::Clover => cookie(0.13, 4.0),
|
||||
Form::Cookie6 => cookie(0.09, 6.0),
|
||||
Form::Cookie9 => cookie(0.065, 9.0),
|
||||
Form::Burst => cookie(0.1, 8.0),
|
||||
Form::Tick => tick(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tick of even thickness with round ends, from its right tip round below to its left tip and back.
|
||||
fn tick() -> Outline {
|
||||
const CAP: usize = 8;
|
||||
const BEND: usize = 30;
|
||||
let (right, elbow, left) = (vec2(0.66, -0.42), vec2(-0.16, 0.42), vec2(-0.62, -0.03));
|
||||
let half = 0.14;
|
||||
// Along the spine, and to its lower side.
|
||||
let (d1, d2) = ((elbow - right).normalized(), (left - elbow).normalized());
|
||||
let side = |d: Vec2| vec2(d.y, -d.x);
|
||||
let (n1, n2) = (side(d1), side(d2));
|
||||
let bend = (n1 + n2) / (1.0 + n1.dot(n2));
|
||||
std::array::from_fn(|i| {
|
||||
let (j, s) = if i <= HALF { (i, 1.0) } else { (N - i, -1.0) };
|
||||
let cap = |c: Vec2, out: Vec2, n: Vec2, a: f32| c + (out * a.cos() + n * s * a.sin()) * half;
|
||||
let between = |a: Vec2, b: Vec2, k: usize, n: usize| a + (b - a) * (k as f32 / n as f32);
|
||||
if j < CAP {
|
||||
cap(right, -d1, n1, j as f32 / CAP as f32 * FRAC_PI_2)
|
||||
} else if j < BEND {
|
||||
between(right + n1 * half * s, elbow + bend * half * s, j - CAP, BEND - CAP)
|
||||
} else if j < HALF - CAP {
|
||||
between(elbow + bend * half * s, left + n2 * half * s, j - BEND, HALF - CAP - BEND)
|
||||
} else {
|
||||
cap(left, d2, n2, (HALF - j) as f32 / CAP as f32 * FRAC_PI_2)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Fills an outline, scaled by `r` and turned by `turn`.
|
||||
fn fill(p: &Painter, c: Pos2, r: f32, turn: f32, outline: &Outline, color: Color32) {
|
||||
let feather = 0.5 / p.ctx().pixels_per_point().max(0.5);
|
||||
let rot = eframe::egui::emath::Rot2::from_angle(turn);
|
||||
let at = |i: usize| c + rot * outline[i % N] * r;
|
||||
let mut m = Mesh::default();
|
||||
for i in 0..N {
|
||||
let along = at(i + 1) - at(i + N - 1);
|
||||
let out = if along.length_sq() > 1e-6 { vec2(along.y, -along.x).normalized() * feather } else { Vec2::ZERO };
|
||||
m.colored_vertex(at(i) - out, color);
|
||||
m.colored_vertex(at(i) + out, Color32::TRANSPARENT);
|
||||
}
|
||||
let v = |i: usize| 2 * (i % N) as u32;
|
||||
for i in 0..HALF {
|
||||
let (a, b, x, y) = (v(i), v(i + 1), v(N - i), v(N - i - 1));
|
||||
m.add_triangle(a, b, x);
|
||||
m.add_triangle(b, y, x);
|
||||
}
|
||||
for i in 0..N {
|
||||
let (a, b) = (v(i), v(i + 1));
|
||||
m.add_triangle(a, a + 1, b);
|
||||
m.add_triangle(a + 1, b + 1, b);
|
||||
}
|
||||
p.add(Shape::mesh(m));
|
||||
}
|
||||
|
||||
/// An outline on its way to another. A new goal starts from wherever it is.
|
||||
#[derive(Clone)]
|
||||
struct Morph {
|
||||
from: Outline,
|
||||
to: Form,
|
||||
t: Spring,
|
||||
}
|
||||
|
||||
impl Morph {
|
||||
fn new(f: Form) -> Morph {
|
||||
Morph { from: *f.outline(), to: f, t: Spring::new(100.0) }
|
||||
}
|
||||
|
||||
fn now(&self) -> Outline {
|
||||
let to = self.to.outline();
|
||||
if self.t.settled() {
|
||||
return *to;
|
||||
}
|
||||
let k = (self.t.x / 100.0).clamp(0.0, 1.25);
|
||||
std::array::from_fn(|i| self.from[i] + (to[i] - self.from[i]) * k)
|
||||
}
|
||||
|
||||
fn step(&mut self, to: Form, preset: motion::Preset) {
|
||||
if to != self.to {
|
||||
*self = Morph { from: self.now(), to, t: Spring { target: 100.0, ..Spring::new(0.0) } };
|
||||
}
|
||||
self.t.step(preset);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a file is, for its shape and icon.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum Kind {
|
||||
Video,
|
||||
Audio,
|
||||
Picture,
|
||||
Document,
|
||||
Archive,
|
||||
Program,
|
||||
#[default]
|
||||
Other,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
pub const ALL: [Kind; 7] = [Kind::Video, Kind::Audio, Kind::Picture, Kind::Document, Kind::Archive, Kind::Program, Kind::Other];
|
||||
|
||||
pub fn form(self) -> Form {
|
||||
match self {
|
||||
Kind::Video => Form::Square,
|
||||
Kind::Audio => Form::Cookie9,
|
||||
Kind::Picture => Form::Clover,
|
||||
Kind::Document => Form::Pill,
|
||||
Kind::Archive => Form::Cookie6,
|
||||
Kind::Program => Form::Pentagon,
|
||||
Kind::Other => Form::Circle,
|
||||
}
|
||||
}
|
||||
|
||||
fn icon(self, p: &Painter, c: Pos2, size: f32, color: Color32) {
|
||||
match self {
|
||||
Kind::Video => icons::paint(p, c, size, "movie", color),
|
||||
Kind::Audio => icons::paint(p, c, size, "music_note", color),
|
||||
Kind::Picture => icons::paint(p, c, size, "image", color),
|
||||
Kind::Document => icons::paint(p, c, size, "description", color),
|
||||
Kind::Archive => icons::paint(p, c, size, "folder_zip", color),
|
||||
Kind::Program => icons::paint(p, c, size, "package_2", color),
|
||||
Kind::Other => icons::paint(p, c, size, "download", color),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The wave of the bar beside it settles for this long before the shape turns into a tick, in seconds.
|
||||
const SETTLE: f64 = 0.25;
|
||||
/// The tick is gone after this.
|
||||
const HOLD: f64 = 1.6;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct BadgeState {
|
||||
morph: Morph,
|
||||
look: Look,
|
||||
fill: Fade,
|
||||
/// When the file was seen to finish.
|
||||
finished: Option<f64>,
|
||||
}
|
||||
|
||||
impl Default for BadgeState {
|
||||
fn default() -> BadgeState {
|
||||
BadgeState { morph: Morph::new(Form::Circle), look: Look::Waiting, fill: Fade::new(Color32::TRANSPARENT), finished: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// A file's shape with its icon. When `look` turns to `Done` before the reader's eyes, the shape becomes a tick for a
|
||||
/// moment, once; any other change on the way ends that at once.
|
||||
pub fn badge(ui: &Ui, t: &Theme, id: Id, rect: Rect, kind: Kind, look: Look) {
|
||||
let side = rect.width().min(rect.height());
|
||||
if !ui.is_rect_visible(rect) || side < 4.0 {
|
||||
return;
|
||||
}
|
||||
let now = ui.input(|i| i.time);
|
||||
let (outline, color, icon) = with_state(ui.ctx(), id, |s: &mut BadgeState, seen| {
|
||||
// Out of sight it neither plays nor remembers.
|
||||
if !seen && s.finished.is_none_or(|at| now - at > HOLD) {
|
||||
*s = BadgeState { morph: Morph::new(kind.form()), look, fill: Fade::new(t.secondary_container), finished: None };
|
||||
}
|
||||
if look != s.look {
|
||||
s.finished = (look == Look::Done && matches!(s.look, Look::Running | Look::Checking)).then_some(now);
|
||||
s.look = look;
|
||||
}
|
||||
let mut form = kind.form();
|
||||
if let Some(at) = s.finished {
|
||||
let still = matches!(motion::level(), Motion::Off | Motion::Reduced);
|
||||
let (begin, end) = (if still { 0.0 } else { SETTLE }, HOLD);
|
||||
let since = now - at;
|
||||
let next = if since < begin { begin - since } else { end - since };
|
||||
if since >= end {
|
||||
s.finished = None;
|
||||
} else {
|
||||
if since >= begin {
|
||||
form = Form::Tick;
|
||||
}
|
||||
ui.ctx().request_repaint_after_secs(next as f32);
|
||||
}
|
||||
}
|
||||
let done = form == Form::Tick;
|
||||
s.morph.step(form, if done { SLOW } else { DEFAULT });
|
||||
let fill = match look {
|
||||
_ if done => t.success,
|
||||
Look::Failed => t.error_container,
|
||||
_ => t.secondary_container,
|
||||
};
|
||||
(s.morph.now(), s.fill.step(fill), if done { 0.0 } else { 1.0 })
|
||||
});
|
||||
let p = ui.painter();
|
||||
let shown = spring(id.with("icon"), icon, EFFECT).clamp(0.0, 1.0);
|
||||
let grow = spring(id.with("size"), if icon == 0.0 { 1.15 } else { 1.0 }, SLOW).clamp(0.5, 1.4);
|
||||
fill(p, rect.center(), side / 2.0 * grow, 0.0, &outline, color);
|
||||
let on = if look == Look::Failed { t.on_error_container } else { t.on_secondary_container };
|
||||
kind.icon(p, rect.center(), (side / 2.0).round(), alpha(on, shown));
|
||||
}
|
||||
|
||||
/// Waits shorter than this show no loading indicator, in seconds.
|
||||
const PATIENCE: f64 = 0.3;
|
||||
/// Between two shapes.
|
||||
const BEAT: f64 = 0.65;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct LoadState {
|
||||
morph: Morph,
|
||||
since: f64,
|
||||
turn: Spring,
|
||||
}
|
||||
|
||||
impl Default for LoadState {
|
||||
fn default() -> LoadState {
|
||||
LoadState { morph: Morph::new(Form::LOADING[0]), since: 0.0, turn: Spring::new(0.0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The loading indicator. Draw it for as long as something is being waited for.
|
||||
pub fn loading(ui: &Ui, t: &Theme, id: Id, rect: Rect) {
|
||||
if !ui.is_rect_visible(rect) {
|
||||
return;
|
||||
}
|
||||
let now = ui.input(|i| i.time);
|
||||
let drawn = with_state(ui.ctx(), id, |s: &mut LoadState, seen| {
|
||||
if !seen {
|
||||
*s = LoadState { since: now, ..LoadState::default() };
|
||||
motion::forget(id.with("in"));
|
||||
}
|
||||
let waited = now - s.since - PATIENCE;
|
||||
if waited < 0.0 {
|
||||
ui.ctx().request_repaint_after_secs(-waited as f32);
|
||||
return None;
|
||||
}
|
||||
if matches!(motion::level(), Motion::Normal | Motion::Expressive) {
|
||||
let beat = (waited / BEAT) as usize;
|
||||
s.morph.step(Form::LOADING[beat % Form::LOADING.len()], DEFAULT);
|
||||
// Ninths of a turn, so no shape looks the same twice in a row.
|
||||
s.turn.target = beat as f32 * 80.0;
|
||||
s.turn.step(DEFAULT);
|
||||
motion::keep_alive();
|
||||
}
|
||||
Some((s.morph.now(), s.turn.x.to_radians()))
|
||||
});
|
||||
let Some((outline, turn)) = drawn else { return };
|
||||
let shown = spring_from(id.with("in"), 0.0, 1.0, EFFECT).clamp(0.0, 1.0);
|
||||
fill(ui.painter(), rect.center(), rect.width().min(rect.height()) / 2.0, turn, &outline, alpha(t.primary, shown));
|
||||
}
|
||||
|
||||
/// One form at rest, for pictures and buttons.
|
||||
pub fn form(p: &Painter, c: Pos2, r: f32, f: Form, color: Color32) {
|
||||
fill(p, c, r, 0.0, f.outline(), color);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn outlines_fit_and_have_no_gaps() {
|
||||
for f in Form::ALL {
|
||||
let o = f.outline();
|
||||
for i in 0..N {
|
||||
assert!(o[i].length() <= 1.001, "{f:?} {:?}", o[i]);
|
||||
let step = (o[(i + 1) % N] - o[i]).length();
|
||||
assert!(step > 1e-4 && step < 0.25, "{f:?} {i} {step}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_goal_starts_from_where_the_shape_is() {
|
||||
motion::begin_frame(1.0 / 60.0, Motion::Normal);
|
||||
let mut m = Morph::new(Form::Square);
|
||||
for _ in 0..4 {
|
||||
motion::begin_frame(1.0 / 60.0, Motion::Normal);
|
||||
m.step(Form::Tick, SLOW);
|
||||
}
|
||||
let before = m.now();
|
||||
motion::begin_frame(0.001, Motion::Normal);
|
||||
m.step(Form::Circle, SLOW);
|
||||
for (a, b) in before.iter().zip(m.now()) {
|
||||
assert!((*a - b).length() < 0.02);
|
||||
}
|
||||
for _ in 0..240 {
|
||||
motion::begin_frame(1.0 / 60.0, Motion::Normal);
|
||||
m.step(Form::Circle, SLOW);
|
||||
}
|
||||
assert!(!motion::busy() && m.now() == *Form::Circle.outline());
|
||||
}
|
||||
}
|
||||
657
crates/app/src/ui/wave.rs
Normal file
657
crates/app/src/ui/wave.rs
Normal file
|
|
@ -0,0 +1,657 @@
|
|||
//! Wavy progress: the line with part gaps, the ring and the slider. The wave's height and travel follow the speed
|
||||
//! through springs, so it moves only while bytes arrive and lies flat and still otherwise.
|
||||
|
||||
use super::parts::{SCALE, Tiles};
|
||||
use crate::motion::{self, Spring, spring};
|
||||
use crate::theme::{Theme, alpha, mix};
|
||||
use crate::tokens::spring::{EFFECT, FAST, SLOW};
|
||||
use crate::tokens::{size, space, state};
|
||||
use eframe::egui::{self, Color32, CursorIcon, Id, Key, Mesh, Painter, Pos2, Rect, Response, Sense, Shape, Stroke, Ui, Vec2, pos2, vec2};
|
||||
use medlar_core::model::{Part, State};
|
||||
use medlar_core::settings::Motion;
|
||||
use std::f32::consts::{FRAC_PI_2, PI, TAU};
|
||||
|
||||
/// What a bar needs in height.
|
||||
pub const HEIGHT: f32 = 12.0;
|
||||
pub const STROKE: f32 = 4.0;
|
||||
/// Between fill and track, and between parts.
|
||||
const GAP: f32 = 4.0;
|
||||
const AMPLITUDE: f32 = 3.0;
|
||||
const WAVELENGTH: f32 = 32.0;
|
||||
/// Points are this far apart along the wave.
|
||||
const STEP: f32 = 4.0;
|
||||
/// Travel in px/s of the slowest and the fastest transfer.
|
||||
const TRAVEL: (f32, f32) = (20.0, 88.0);
|
||||
/// Steps of a round end.
|
||||
const CAP: u32 = 3;
|
||||
/// More parts than this are drawn as one.
|
||||
const MOST_PARTS: usize = 64;
|
||||
/// Length of the fill when the size is unknown.
|
||||
const UNKNOWN: f32 = 0.32;
|
||||
/// Wavelength on a ring.
|
||||
const RING_WAVELENGTH: f32 = 14.0;
|
||||
|
||||
/// What a progress bar shows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Look {
|
||||
#[default]
|
||||
Waiting,
|
||||
Running,
|
||||
Paused,
|
||||
Checking,
|
||||
Failed,
|
||||
Done,
|
||||
}
|
||||
|
||||
impl From<State> for Look {
|
||||
fn from(s: State) -> Look {
|
||||
match s {
|
||||
State::Queued | State::Waiting | State::Gone => Look::Waiting,
|
||||
State::Running => Look::Running,
|
||||
State::Paused => Look::Paused,
|
||||
State::Checking | State::Finishing => Look::Checking,
|
||||
State::Failed => Look::Failed,
|
||||
State::Done => Look::Done,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Look {
|
||||
fn colour(self, t: &Theme) -> Color32 {
|
||||
match self {
|
||||
Look::Waiting | Look::Paused => t.outline,
|
||||
Look::Running => t.primary,
|
||||
Look::Checking => t.tertiary,
|
||||
Look::Failed => t.error,
|
||||
Look::Done => t.success,
|
||||
}
|
||||
}
|
||||
|
||||
fn track(self, t: &Theme) -> Color32 {
|
||||
match self {
|
||||
Look::Failed => t.error_container,
|
||||
Look::Running => t.secondary_container,
|
||||
// The bytes are all there; what is left to check keeps the colour it had.
|
||||
Look::Checking => t.primary,
|
||||
_ => t.highest,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How lively a transfer is, 0 to 1, for bytes per second. Each doubling adds the same, up to 64 MiB/s.
|
||||
pub fn pace(speed: f64) -> f32 {
|
||||
if speed.is_finite() && speed > 0.0 { ((speed / 4096.0 + 1.0).log2() / 14.0).clamp(0.0, 1.0) as f32 } else { 0.0 }
|
||||
}
|
||||
|
||||
/// `x`, or 0 where it is no number.
|
||||
pub(super) fn finite(x: f32) -> f32 {
|
||||
if x.is_finite() { x } else { 0.0 }
|
||||
}
|
||||
|
||||
/// A colour on its way to another.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Fade {
|
||||
from: Color32,
|
||||
to: Color32,
|
||||
t: Spring,
|
||||
}
|
||||
|
||||
impl Fade {
|
||||
pub fn new(c: Color32) -> Fade {
|
||||
Fade { from: c, to: c, t: Spring::new(1.0) }
|
||||
}
|
||||
|
||||
pub fn step(&mut self, to: Color32) -> Color32 {
|
||||
if to != self.to {
|
||||
*self = Fade { from: self.now(), to, t: Spring { target: 100.0, ..Spring::new(0.0) } };
|
||||
}
|
||||
self.t.step(EFFECT);
|
||||
self.now()
|
||||
}
|
||||
|
||||
fn now(&self) -> Color32 {
|
||||
if self.t.settled() { self.to } else { mix(self.from, self.to, self.t.x / 100.0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Height, travel and phase of one wave.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Drive {
|
||||
/// 0 to 100.
|
||||
amp: Spring,
|
||||
/// px/s.
|
||||
travel: Spring,
|
||||
/// px, within one wavelength.
|
||||
phase: f32,
|
||||
}
|
||||
|
||||
impl Drive {
|
||||
fn new() -> Drive {
|
||||
Drive { amp: Spring::new(0.0), travel: Spring::new(0.0), phase: 0.0 }
|
||||
}
|
||||
|
||||
/// Starts at what `speed` asks for, without a run-up.
|
||||
fn snap(&mut self, speed: f64) {
|
||||
let (amp, travel) = Drive::targets(speed);
|
||||
self.amp.snap(amp);
|
||||
self.travel.snap(travel);
|
||||
}
|
||||
|
||||
fn targets(speed: f64) -> (f32, f32) {
|
||||
let pace = pace(speed);
|
||||
if pace <= 0.0 || matches!(motion::level(), Motion::Off | Motion::Reduced) {
|
||||
return (0.0, 0.0);
|
||||
}
|
||||
(40.0 + 60.0 * pace, TRAVEL.0 + (TRAVEL.1 - TRAVEL.0) * pace)
|
||||
}
|
||||
|
||||
/// One frame on. Returns the height, 0 to 1, and how far the wave moved, in px.
|
||||
fn step(&mut self, speed: f64) -> (f32, f32) {
|
||||
(self.amp.target, self.travel.target) = Drive::targets(speed);
|
||||
let amp = (self.amp.step(SLOW) / 100.0).clamp(0.0, 1.1);
|
||||
let moved = self.travel.step(SLOW).max(0.0) * motion::dt();
|
||||
if moved > 0.0 {
|
||||
self.phase = (self.phase + moved) % WAVELENGTH;
|
||||
motion::keep_alive();
|
||||
}
|
||||
(amp, moved)
|
||||
}
|
||||
}
|
||||
|
||||
/// State a widget keeps between frames. `seen` is false on the first frame, and when it was out of sight for a while.
|
||||
pub(super) fn with_state<T: Clone + Default + Send + Sync + 'static, R>(ctx: &egui::Context, id: Id, f: impl FnOnce(&mut T, bool) -> R) -> R {
|
||||
#[derive(Clone, Default)]
|
||||
struct Kept<T>(T, u64);
|
||||
let mut kept: Option<Kept<T>> = ctx.data_mut(|d| d.remove_temp(id));
|
||||
let frame = ctx.cumulative_pass_nr();
|
||||
let seen = kept.as_ref().is_some_and(|k| k.1 + 1 >= frame);
|
||||
let mut kept = kept.take().unwrap_or_default();
|
||||
let out = f(&mut kept.0, seen);
|
||||
kept.1 = frame;
|
||||
ctx.data_mut(|d| d.insert_temp(id, kept));
|
||||
out
|
||||
}
|
||||
|
||||
/// Draws smooth strokes into a mesh; egui's own paths cost several times as much.
|
||||
pub(super) struct Ink {
|
||||
pub mesh: Mesh,
|
||||
feather: f32,
|
||||
}
|
||||
|
||||
impl Ink {
|
||||
/// With room for `corners`, which saves growing.
|
||||
fn with_room(p: &Painter, corners: usize) -> Ink {
|
||||
let mut ink = Ink::new(p);
|
||||
ink.mesh.reserve_vertices(corners);
|
||||
ink.mesh.reserve_triangles(corners * 3 / 2);
|
||||
ink
|
||||
}
|
||||
|
||||
pub fn new(p: &Painter) -> Ink {
|
||||
Ink { mesh: Mesh::default(), feather: 1.0 / p.ctx().pixels_per_point().max(0.5) }
|
||||
}
|
||||
|
||||
/// Adds what was drawn to the screen.
|
||||
pub fn paint(self, p: &Painter) {
|
||||
if !self.mesh.is_empty() {
|
||||
p.add(Shape::mesh(self.mesh));
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke along points with their unit normals, with round ends.
|
||||
pub fn ribbon(&mut self, points: impl Iterator<Item = (Pos2, Vec2)>, half: f32, color: Color32) {
|
||||
let (core, rim) = ((half - self.feather / 2.0).max(0.0), half + self.feather / 2.0);
|
||||
let mut last: Option<(Pos2, Vec2, u32)> = None;
|
||||
for (p, n) in points {
|
||||
let m = &mut self.mesh;
|
||||
let at = m.vertices.len() as u32;
|
||||
m.colored_vertex(p + n * rim, Color32::TRANSPARENT);
|
||||
m.colored_vertex(p + n * core, color);
|
||||
m.colored_vertex(p - n * core, color);
|
||||
m.colored_vertex(p - n * rim, Color32::TRANSPARENT);
|
||||
match last {
|
||||
None => self.arc(p, n, PI, CAP, core, rim, color, Some([at + 1, at, at + 2, at + 3])),
|
||||
Some((.., before)) => {
|
||||
for k in 0..3 {
|
||||
m.add_triangle(before + k, before + 1 + k, at + k);
|
||||
m.add_triangle(before + 1 + k, at + 1 + k, at + k);
|
||||
}
|
||||
}
|
||||
}
|
||||
last = Some((p, n, at));
|
||||
}
|
||||
if let Some((p, n, at)) = last {
|
||||
self.arc(p, -n, PI, CAP, core, rim, color, Some([at + 2, at + 3, at + 1, at]));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn disc(&mut self, c: Pos2, r: f32, color: Color32) {
|
||||
let r = r.max(0.0);
|
||||
self.arc(c, Vec2::X, TAU, 10, (r - self.feather / 2.0).max(0.0), r + self.feather / 2.0, color, None);
|
||||
}
|
||||
|
||||
/// A filled arc, clockwise on the screen. `ends` are corners that exist already: inner and outer of the first, then
|
||||
/// of the last.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn arc(&mut self, c: Pos2, from: Vec2, angle: f32, steps: u32, core: f32, rim: f32, color: Color32, ends: Option<[u32; 4]>) {
|
||||
let m = &mut self.mesh;
|
||||
let turn = egui::emath::Rot2::from_angle(angle / steps as f32);
|
||||
let mut d = from;
|
||||
let mut first = 0;
|
||||
let mut before = (0, 0);
|
||||
for k in 0..=steps {
|
||||
let now = match ends {
|
||||
Some([i, o, ..]) if k == 0 => (i, o),
|
||||
Some([.., i, o]) if k == steps => (i, o),
|
||||
_ => {
|
||||
let at = m.vertices.len() as u32;
|
||||
m.colored_vertex(c + d * core, color);
|
||||
m.colored_vertex(c + d * rim, Color32::TRANSPARENT);
|
||||
(at, at + 1)
|
||||
}
|
||||
};
|
||||
d = turn * d;
|
||||
if k == 0 {
|
||||
first = now.0;
|
||||
} else {
|
||||
if k > 1 {
|
||||
m.add_triangle(first, before.0, now.0);
|
||||
}
|
||||
m.add_triangle(before.0, before.1, now.0);
|
||||
m.add_triangle(before.1, now.1, now.0);
|
||||
}
|
||||
before = now;
|
||||
}
|
||||
}
|
||||
|
||||
/// A horizontal stroke from edge to edge, wavy if `amp` is not 0.
|
||||
pub fn line(&mut self, x: std::ops::Range<f32>, y: f32, half: f32, amp: f32, phase: f32, color: Color32) {
|
||||
let length = x.end - x.start;
|
||||
if length <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let half = half.min(length / 2.0);
|
||||
let (a, b) = (x.start + half, x.end - half);
|
||||
if b - a < 0.1 {
|
||||
return self.disc(pos2((a + b) / 2.0, y), half, color);
|
||||
}
|
||||
if amp < 0.02 {
|
||||
return self.ribbon([pos2(a, y), pos2(b, y)].map(|p| (p, Vec2::Y)).into_iter(), half, color);
|
||||
}
|
||||
let k = TAU / WAVELENGTH;
|
||||
let n = ((b - a) / STEP).ceil().max(1.0) as usize;
|
||||
let step = (b - a) / n as f32;
|
||||
let (mut sin, mut cos) = ((a - phase) * k).sin_cos();
|
||||
let (dsin, dcos) = (step * k).sin_cos();
|
||||
let wave = (0..=n).map(move |i| {
|
||||
let slope = amp * k * cos;
|
||||
let out = (pos2(a + i as f32 * step, y + amp * sin), vec2(-slope, 1.0) / (1.0 + slope * slope).sqrt());
|
||||
(sin, cos) = (sin * dcos + cos * dsin, cos * dcos - sin * dsin);
|
||||
out
|
||||
});
|
||||
self.ribbon(wave, half, color);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
pub look: Look,
|
||||
pub size: Option<u64>,
|
||||
pub parts: &'a [Part],
|
||||
/// Bytes per second now: arriving, or read while checking.
|
||||
pub speed: f64,
|
||||
/// Share checked so far, while `look` is `Checking`.
|
||||
pub checked: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct BarState {
|
||||
drive: Drive,
|
||||
tiles: Tiles,
|
||||
fill: Fade,
|
||||
track: Fade,
|
||||
look: Look,
|
||||
/// Where the fill of unknown size is, 0 to 1 of its loop.
|
||||
place: f32,
|
||||
/// How many the last frame took.
|
||||
corners: usize,
|
||||
}
|
||||
|
||||
impl Default for BarState {
|
||||
fn default() -> BarState {
|
||||
let c = Fade::new(Color32::TRANSPARENT);
|
||||
BarState { drive: Drive::new(), tiles: Tiles::default(), fill: c, track: c, look: Look::Waiting, place: UNKNOWN, corners: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws a progress bar in `rect`, which should be `HEIGHT` high.
|
||||
pub fn bar(ui: &Ui, t: &Theme, id: Id, rect: Rect, b: &Bar) {
|
||||
if !ui.is_rect_visible(rect) || rect.width() <= STROKE {
|
||||
return;
|
||||
}
|
||||
with_state(ui.ctx(), id, |s: &mut BarState, seen| draw_bar(ui.painter(), t, rect, b, s, seen));
|
||||
}
|
||||
|
||||
fn draw_bar(p: &Painter, t: &Theme, rect: Rect, b: &Bar, s: &mut BarState, seen: bool) {
|
||||
let moves = matches!(b.look, Look::Running | Look::Checking);
|
||||
let speed = if moves { b.speed } else { 0.0 };
|
||||
if !seen {
|
||||
s.drive.snap(speed);
|
||||
(s.fill, s.track) = (Fade::new(b.look.colour(t)), Fade::new(b.look.track(t)));
|
||||
} else if b.look == Look::Checking && s.look != Look::Checking {
|
||||
// The full bar becomes what is still to check.
|
||||
s.track = Fade::new(s.fill.now());
|
||||
s.fill = Fade::new(b.look.colour(t));
|
||||
}
|
||||
let changed = s.look != b.look;
|
||||
s.look = b.look;
|
||||
let (amp, moved) = s.drive.step(speed);
|
||||
let (fill, track) = (s.fill.step(b.look.colour(t)), s.track.step(b.look.track(t)));
|
||||
let amp = amp.min(1.0) * AMPLITUDE.min((rect.height() - STROKE) / 2.0 - 0.5).max(0.0);
|
||||
let (phase, y, half) = (s.drive.phase, rect.center().y, STROKE / 2.0);
|
||||
let mut ink = Ink::with_room(p, s.corners + 16);
|
||||
// The wave hangs on to the bar's left end, wherever the bar is.
|
||||
let phase = phase + rect.left();
|
||||
|
||||
if b.size.is_none() && !matches!(b.look, Look::Checking | Look::Done) {
|
||||
let length = rect.width() * UNKNOWN;
|
||||
let lap = rect.width() + length;
|
||||
s.place = (s.place + 2.0 * moved / lap) % 1.0;
|
||||
let end = rect.left() + s.place * lap;
|
||||
let (l, r) = ((end - length).max(rect.left()), end.min(rect.right()));
|
||||
ink.line(rect.left()..l - GAP, y, half, 0.0, 0.0, track);
|
||||
ink.line(l..r, y, half, amp, phase, fill);
|
||||
ink.line(r + GAP..rect.right(), y, half, 0.0, 0.0, track);
|
||||
return ink.paint(p);
|
||||
}
|
||||
|
||||
let size = b.size.unwrap_or(0);
|
||||
let whole = |done: f32| Part { start: 0, end: Some(SCALE as u64), done: (finite(done).clamp(0.0, 1.0) * SCALE) as u64 };
|
||||
let snap = !seen || (changed && b.look == Look::Checking);
|
||||
match b.look {
|
||||
Look::Done => s.tiles.follow(SCALE as u64, &[whole(1.0)], snap),
|
||||
Look::Checking => s.tiles.follow(SCALE as u64, &[whole(b.checked)], snap),
|
||||
_ if b.parts.len() > MOST_PARTS => {
|
||||
let done: u64 = b.parts.iter().map(|p| p.done).sum();
|
||||
s.tiles.follow(SCALE as u64, &[whole((done as f64 / size.max(1) as f64) as f32)], snap);
|
||||
}
|
||||
_ => s.tiles.follow(size, b.parts, snap),
|
||||
}
|
||||
s.tiles.step();
|
||||
let gap = GAP.min(rect.width() * 0.25 / s.tiles.len().max(1) as f32);
|
||||
let mut run: Option<(f32, f32)> = None;
|
||||
for c in s.tiles.cells() {
|
||||
// A gap that closes ends with the two round ends on top of each other.
|
||||
let edge = |open: f32| gap / 2.0 * open - half * (1.0 - open);
|
||||
let l = rect.left() + c.left * rect.width() + if c.first { 0.0 } else { edge(c.gap_before) };
|
||||
let l = l.max(rect.left());
|
||||
let r = rect.left() + c.right * rect.width() - if c.last { 0.0 } else { edge(c.gap_after) };
|
||||
let r = r.min(rect.right());
|
||||
let head = if c.full { r } else { (l + c.filled * (r - l)).min(r) };
|
||||
// The first bytes show as a dot.
|
||||
let begun = head - l;
|
||||
let head = if begun > 0.0 { l + begun.max((begun * 8.0).min(STROKE.min((r - l) / 3.0))) } else { head };
|
||||
if head - l > 0.5 {
|
||||
match &mut run {
|
||||
Some((_, end)) if !c.first && c.gap_before == 0.0 => *end = head,
|
||||
_ => {
|
||||
if let Some((a, z)) = run.replace((l, head)) {
|
||||
ink.line(a..z, y, half, amp, phase, fill);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !c.full {
|
||||
let from = if head - l > 0.5 { head + gap } else { l };
|
||||
ink.line(from..r, y, half, 0.0, 0.0, track);
|
||||
if c.last && b.look != Look::Checking && r - from > STROKE {
|
||||
ink.disc(pos2(r - half, y), half * 0.75, fill);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((a, z)) = run {
|
||||
ink.line(a..z, y, half, amp, phase, fill);
|
||||
}
|
||||
s.corners = ink.mesh.vertices.len();
|
||||
ink.paint(p);
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct RingState {
|
||||
drive: Drive,
|
||||
share: Spring,
|
||||
turn: f32,
|
||||
fill: Fade,
|
||||
track: Fade,
|
||||
}
|
||||
|
||||
impl Default for RingState {
|
||||
fn default() -> RingState {
|
||||
let c = Fade::new(Color32::TRANSPARENT);
|
||||
RingState { drive: Drive::new(), share: Spring::new(0.0), turn: 0.0, fill: c, track: c }
|
||||
}
|
||||
}
|
||||
|
||||
/// Radius, stroke and wave height of a ring that fits in a square of this side.
|
||||
fn ring_sizes(side: f32) -> (f32, f32, f32) {
|
||||
let stroke = (side / 10.0).clamp(2.0, STROKE);
|
||||
// A wave in a ring this small is a smudge.
|
||||
let amp = if side < 20.0 { 0.0 } else { side / 25.0 };
|
||||
(side / 2.0 - stroke / 2.0 - amp - 0.5, stroke, amp)
|
||||
}
|
||||
|
||||
/// A whole number, so the wave closes.
|
||||
fn ring_waves(r: f32) -> f32 {
|
||||
(TAU * r / RING_WAVELENGTH).round().clamp(5.0, 10.0)
|
||||
}
|
||||
|
||||
fn ring_points(c: Pos2, r: f32, amp: f32, phase: f32, from: f32, to: f32) -> impl Iterator<Item = (Pos2, Vec2)> {
|
||||
let waves = ring_waves(r);
|
||||
let n = ((to - from).abs() * r / STEP * 3.0).ceil().max(2.0) as usize;
|
||||
(0..=n).map(move |i| {
|
||||
let a = from + (to - from) * i as f32 / n as f32;
|
||||
let (sin, cos) = (waves * a - phase).sin_cos();
|
||||
let (rr, dr) = (r + amp * sin, amp * waves * cos);
|
||||
let (out, along) = (Vec2::angled(a), Vec2::angled(a + FRAC_PI_2));
|
||||
// Points inwards: the same side as a line's normal, which points down.
|
||||
(c + out * rr, (along * dr - out * rr).normalized())
|
||||
})
|
||||
}
|
||||
|
||||
/// A progress ring. `share` is None when the size is unknown.
|
||||
pub fn ring(ui: &Ui, t: &Theme, id: Id, rect: Rect, look: Look, share: Option<f32>, speed: f64) {
|
||||
let side = rect.width().min(rect.height());
|
||||
if !ui.is_rect_visible(rect) || side < 8.0 {
|
||||
return;
|
||||
}
|
||||
with_state(ui.ctx(), id, |s: &mut RingState, seen| {
|
||||
let speed = if matches!(look, Look::Running | Look::Checking) { speed } else { 0.0 };
|
||||
let target = if look == Look::Done { 1.0 } else { share.map_or(UNKNOWN, |x| finite(x).clamp(0.0, 1.0)) } * SCALE;
|
||||
if !seen {
|
||||
s.drive.snap(speed);
|
||||
s.share.snap(target);
|
||||
(s.fill, s.track) = (Fade::new(look.colour(t)), Fade::new(look.track(t)));
|
||||
}
|
||||
s.share.target = target;
|
||||
let share01 = (s.share.step(EFFECT) / SCALE).clamp(0.0, 1.0);
|
||||
let (amp, moved) = s.drive.step(speed);
|
||||
let (fill, track) = (s.fill.step(look.colour(t)), s.track.step(look.track(t)));
|
||||
let (r, stroke, most) = ring_sizes(side);
|
||||
if share.is_none() && look != Look::Done {
|
||||
s.turn = (s.turn + moved / r) % TAU;
|
||||
} else {
|
||||
s.turn = 0.0;
|
||||
}
|
||||
let from = s.turn - FRAC_PI_2;
|
||||
let to = from + TAU * share01;
|
||||
let mut ink = Ink::new(ui.painter());
|
||||
let c = rect.center();
|
||||
// Round ends reach half a stroke further, on both sides.
|
||||
let gap = (stroke * 2.0) / r;
|
||||
if share01 < 1.0 && TAU * (1.0 - share01) > 2.0 * gap {
|
||||
ink.ribbon(ring_points(c, r, 0.0, 0.0, if share01 > 0.002 { to + gap } else { from }, from + TAU - if share01 > 0.002 { gap } else { 0.0 }), stroke / 2.0, track);
|
||||
}
|
||||
if share01 > 0.002 {
|
||||
ink.ribbon(ring_points(c, r, most * amp.min(1.0), s.drive.phase / WAVELENGTH * TAU, from, to), stroke / 2.0, fill);
|
||||
}
|
||||
ink.paint(ui.painter());
|
||||
});
|
||||
}
|
||||
|
||||
/// The ring as pixels, not premultiplied, for the tray. It doesn't move there.
|
||||
pub fn ring_rgba(px: u32, share: f32, fill: Color32, track: Color32) -> Option<Vec<u8>> {
|
||||
use resvg::tiny_skia::{LineCap, Paint, PathBuilder, Pixmap, Stroke, Transform};
|
||||
let mut map = Pixmap::new(px, px)?;
|
||||
let (r, stroke, amp) = ring_sizes(px as f32);
|
||||
let share = finite(share).clamp(0.0, 1.0);
|
||||
let (from, to, c) = (-FRAC_PI_2, TAU * share - FRAC_PI_2, pos2(px as f32 / 2.0, px as f32 / 2.0));
|
||||
let gap = stroke * 2.0 / r.max(1.0);
|
||||
let mut draw = |from: f32, to: f32, amp: f32, color: Color32| {
|
||||
let mut path = PathBuilder::new();
|
||||
for (i, (p, _)) in ring_points(c, r.max(1.0), amp, 0.0, from, to).enumerate() {
|
||||
if i == 0 { path.move_to(p.x, p.y) } else { path.line_to(p.x, p.y) }
|
||||
}
|
||||
let [cr, cg, cb, ca] = color.to_srgba_unmultiplied();
|
||||
let mut paint = Paint::default();
|
||||
paint.set_color_rgba8(cr, cg, cb, ca);
|
||||
let stroke = Stroke { width: stroke, line_cap: LineCap::Round, ..Stroke::default() };
|
||||
if let Some(path) = path.finish() {
|
||||
map.stroke_path(&path, &paint, &stroke, Transform::identity(), None);
|
||||
}
|
||||
};
|
||||
if share < 1.0 && TAU * (1.0 - share) > 2.0 * gap {
|
||||
draw(to + gap, from + TAU - gap, 0.0, track);
|
||||
}
|
||||
if share > 0.0 {
|
||||
draw(from, to, amp, fill);
|
||||
}
|
||||
Some(map.pixels().iter().flat_map(|p| { let c = p.demultiply(); [c.red(), c.green(), c.blue(), c.alpha()] }).collect())
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct SliderState {
|
||||
drive: Drive,
|
||||
/// How far the handle still is from its value, 0 to SCALE.
|
||||
lag: Spring,
|
||||
last: f32,
|
||||
/// Pointer minus handle when it was grabbed.
|
||||
grab: Option<f32>,
|
||||
}
|
||||
|
||||
impl Default for SliderState {
|
||||
fn default() -> SliderState {
|
||||
SliderState { drive: Drive::new(), lag: Spring::new(0.0), last: 0.0, grab: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// A slider whose filled side waves with `speed`. `value` is 0 to 1; a change by the user comes back in it.
|
||||
pub fn slider(ui: &mut Ui, t: &Theme, width: f32, value: &mut f32, speed: f64, label: &str) -> Response {
|
||||
const STEP_KEY: f32 = 0.02;
|
||||
let (rect, mut resp) = ui.allocate_exact_size(vec2(width.max(size::CONTROL), size::CONTROL), Sense::click_and_drag());
|
||||
let enabled = ui.is_enabled();
|
||||
let (left, span) = (rect.left() + space::XS, rect.width() - 2.0 * space::XS);
|
||||
let before = finite(*value).clamp(0.0, 1.0);
|
||||
let mut now = before;
|
||||
with_state(ui.ctx(), resp.id, |s: &mut SliderState, seen| {
|
||||
if !seen {
|
||||
s.drive.snap(speed);
|
||||
s.lag.snap(0.0);
|
||||
s.last = before;
|
||||
}
|
||||
if resp.is_pointer_button_down_on() && enabled {
|
||||
if let Some(p) = resp.interact_pointer_pos() {
|
||||
let handle = left + before * span;
|
||||
let grab = *s.grab.get_or_insert(if (p.x - handle).abs() <= space::S { p.x - handle } else { 0.0 });
|
||||
let to = ((p.x - grab - left) / span).clamp(0.0, 1.0);
|
||||
// A press away from the handle: it springs there, and stays under the pointer from then on.
|
||||
if resp.contains_pointer() && ui.input(|i| i.pointer.any_pressed()) {
|
||||
s.lag.x += (before - to) * SCALE;
|
||||
s.last = to;
|
||||
}
|
||||
now = to;
|
||||
}
|
||||
resp.request_focus();
|
||||
} else {
|
||||
s.grab = None;
|
||||
}
|
||||
if resp.has_focus() {
|
||||
let keys = |k: Key| ui.input(|i| i.num_presses(k)) as f32;
|
||||
let step = keys(Key::ArrowRight) + keys(Key::ArrowUp) - keys(Key::ArrowLeft) - keys(Key::ArrowDown);
|
||||
now = (now + step * STEP_KEY).clamp(0.0, 1.0);
|
||||
ui.memory_mut(|m| {
|
||||
let keep = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() };
|
||||
m.set_focus_lock_filter(resp.id, keep);
|
||||
});
|
||||
}
|
||||
// Changed from outside or by a key: the handle springs over.
|
||||
if s.grab.is_none() && now != s.last {
|
||||
s.lag.x += (s.last - now) * SCALE;
|
||||
}
|
||||
s.last = now;
|
||||
s.lag.target = 0.0;
|
||||
let shown = (now + s.lag.step(FAST) / SCALE).clamp(0.0, 1.0);
|
||||
let (amp, _) = s.drive.step(if enabled { speed } else { 0.0 });
|
||||
let dim = |c: Color32| if enabled { c } else { alpha(t.on_surface, state::DISABLED) };
|
||||
let x = left + shown * span;
|
||||
let y = rect.center().y;
|
||||
let mut ink = Ink::new(ui.painter());
|
||||
ink.line(x + space::S - space::XS / 2.0..rect.right(), y, STROKE / 2.0, 0.0, 0.0, if enabled { t.secondary_container } else { alpha(t.on_surface, state::PRESS) });
|
||||
ink.line(rect.left()..x - space::S + space::XS / 2.0, y, STROKE / 2.0, amp.min(1.0) * AMPLITUDE, s.drive.phase + rect.left(), dim(t.primary));
|
||||
ink.paint(ui.painter());
|
||||
let hot = if s.grab.is_some() { state::PRESS } else if resp.hovered() && enabled { state::HOVER } else { 0.0 };
|
||||
let halo = spring(resp.id.with("halo"), hot, EFFECT);
|
||||
if halo > 0.001 {
|
||||
ui.painter().circle_filled(pos2(x, y), size::HIT / 2.0, alpha(t.primary, halo));
|
||||
}
|
||||
let thick = spring(resp.id.with("thick"), if s.grab.is_some() { 2.0 } else { 4.0 }, FAST).clamp(1.0, 6.0);
|
||||
let handle = Rect::from_center_size(pos2(x, y), vec2(thick, size::CONTROL - space::M));
|
||||
ui.painter().rect_filled(handle, crate::tokens::radius::FULL, dim(t.primary));
|
||||
if resp.has_focus() && s.grab.is_none() {
|
||||
ui.painter().rect_stroke(handle.expand(space::XS), crate::tokens::radius::S, Stroke::new(size::FOCUS_RING, t.secondary), egui::StrokeKind::Middle);
|
||||
}
|
||||
});
|
||||
if now != before {
|
||||
*value = now;
|
||||
resp.mark_changed();
|
||||
}
|
||||
resp.widget_info(|| egui::WidgetInfo::slider(enabled, f64::from(now), label));
|
||||
if enabled { resp.on_hover_cursor(CursorIcon::PointingHand) } else { resp }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pace_follows_the_speed_and_survives_nonsense() {
|
||||
assert_eq!([0.0, -5.0, f64::NAN, f64::INFINITY].map(pace), [0.0; 4]);
|
||||
assert!(pace(1.0) > 0.0 && pace(1e5) < pace(1e6) && pace(1e6) < pace(1e7));
|
||||
assert_eq!(pace(1e12), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phase_never_jumps_when_the_speed_does() {
|
||||
let mut d = Drive::new();
|
||||
let mut speed = 1e3;
|
||||
for i in 0..600 {
|
||||
motion::begin_frame(1.0 / 60.0, Motion::Normal);
|
||||
if i % 40 == 0 {
|
||||
speed = [0.0, 1e8, 1e3, 1e6][(i / 40) % 4];
|
||||
}
|
||||
let before = d.phase;
|
||||
let (_, moved) = d.step(speed);
|
||||
assert!((0.0..=TRAVEL.1 * 1.2 / 60.0).contains(&moved), "{moved}");
|
||||
let step = (d.phase - before).rem_euclid(WAVELENGTH);
|
||||
assert!((step - moved).abs() < 1e-3);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ring_pixels_fill_with_the_share() {
|
||||
let count = |share| ring_rgba(32, share, Color32::RED, Color32::TRANSPARENT).unwrap().chunks(4).filter(|p| p[3] > 128).count();
|
||||
assert_eq!(count(0.0), 0);
|
||||
assert!(count(0.3) > 10 && count(0.6) > count(0.3) && count(1.0) > count(0.6));
|
||||
assert!(ring_rgba(32, f32::NAN, Color32::RED, Color32::RED).is_some());
|
||||
}
|
||||
}
|
||||
|
|
@ -16,6 +16,9 @@ use medlar_app::ui::gallery;
|
|||
use medlar_app::{fonts, icons};
|
||||
use medlar_core::settings::{Appearance, Settings};
|
||||
|
||||
#[path = "visuals/gallery.rs"]
|
||||
mod progress;
|
||||
|
||||
type Scene = (&'static str, fn(&mut App, &mut Ui));
|
||||
|
||||
const SCENES: &[Scene] = &[("window", App::show), ("tokens", |app, ui| app.frame(ui, sheet)),
|
||||
|
|
@ -29,6 +32,8 @@ const SCENES: &[Scene] = &[("window", App::show), ("tokens", |app, ui| app.frame
|
|||
("sheet", |app, ui| over(app, ui, "sheet")),
|
||||
("fab", |app, ui| over(app, ui, "fab")),
|
||||
("toasts", |app, ui| over(app, ui, "toasts")),
|
||||
("progress", |app, ui| app.frame(ui, progress::gallery)),
|
||||
("progress-states", |app, ui| app.frame(ui, progress::states)),
|
||||
];
|
||||
|
||||
fn pair(s: &str, sep: char) -> Option<(f32, f32)> {
|
||||
|
|
|
|||
404
crates/app/tests/visuals.rs
Normal file
404
crates/app/tests/visuals.rs
Normal file
|
|
@ -0,0 +1,404 @@
|
|||
//! The progress widgets: no broken numbers, nothing outside its place, no frames at rest, the tick once.
|
||||
//!
|
||||
//! MEDLAR_SEQUENCE=dir cargo test -p medlar --test visuals sequence saves frames of a split and of finishing
|
||||
//! cargo test --release -p medlar --test visuals -- --ignored --nocapture what 200 bars cost
|
||||
|
||||
#[path = "visuals/gallery.rs"]
|
||||
mod gallery;
|
||||
|
||||
use eframe::egui::{self, Color32, Context, Id, Rect, Shape, Ui, pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use gallery::{MB, Sim, part};
|
||||
use medlar_app::app::App;
|
||||
use medlar_app::desktop::Sources;
|
||||
use medlar_app::theme::Theme;
|
||||
use medlar_app::ui::graph::{self, History};
|
||||
use medlar_app::ui::odometer;
|
||||
use medlar_app::ui::parts::{self, Block};
|
||||
use medlar_app::ui::shape::{self, Kind};
|
||||
use medlar_app::ui::wave::{self, Bar, Look};
|
||||
use medlar_core::model::Part;
|
||||
use medlar_core::settings::{Appearance, Motion, Settings};
|
||||
use std::time::Duration;
|
||||
|
||||
const LOOKS: [Look; 6] = [Look::Waiting, Look::Running, Look::Paused, Look::Checking, Look::Failed, Look::Done];
|
||||
|
||||
fn settings(motion: Motion) -> Settings {
|
||||
Settings { motion, appearance: Appearance::Light, desktop_colors: Some(false), ..Settings::default() }
|
||||
}
|
||||
|
||||
/// A context that is driven by hand.
|
||||
struct Stage {
|
||||
ctx: Context,
|
||||
app: App,
|
||||
time: f64,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
fn new(motion: Motion) -> Stage {
|
||||
let ctx = Context::default();
|
||||
let nowhere = Sources { caelestia: "/nonexistent".into(), kde: "/nonexistent".into() };
|
||||
let app = App::new(&ctx, settings(motion), nowhere);
|
||||
let mut s = Stage { ctx, app, time: 0.0 };
|
||||
s.frame(|_, _| {});
|
||||
s
|
||||
}
|
||||
|
||||
fn frame(&mut self, draw: impl Fn(&Theme, &mut Ui)) -> egui::FullOutput {
|
||||
self.time += 1.0 / 60.0;
|
||||
let input = egui::RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 1000.0))),
|
||||
time: Some(self.time),
|
||||
predicted_dt: 1.0 / 60.0,
|
||||
..Default::default()
|
||||
};
|
||||
let app = &mut self.app;
|
||||
let mut out = self.ctx.run_ui(input, |ui| app.frame(ui, |app, ui| draw(&app.theme.clone(), ui)));
|
||||
out.textures_delta.clear();
|
||||
out
|
||||
}
|
||||
|
||||
/// Frames until it rests. Returns how many it took.
|
||||
fn rest(&mut self, draw: impl Fn(&Theme, &mut Ui)) -> usize {
|
||||
for i in 0..600 {
|
||||
if !asks_now(&self.frame(&draw)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
panic!("never rests");
|
||||
}
|
||||
}
|
||||
|
||||
/// Does it want the next frame at once?
|
||||
fn asks_now(out: &egui::FullOutput) -> bool {
|
||||
out.viewport_output.values().any(|v| v.repaint_delay < Duration::from_millis(1))
|
||||
}
|
||||
|
||||
/// All drawn points are numbers, and inside `bounds`.
|
||||
fn check(out: &egui::FullOutput, bounds: Rect, what: &str) {
|
||||
let mut seen = 0;
|
||||
for s in &out.shapes {
|
||||
walk(&s.shape, &mut |p: egui::Pos2| {
|
||||
assert!(p.x.is_finite() && p.y.is_finite(), "{what}: {p:?}");
|
||||
assert!(bounds.contains(p), "{what}: {p:?} outside {bounds:?}");
|
||||
seen += 1;
|
||||
});
|
||||
}
|
||||
assert!(seen > 0, "{what}: nothing drawn");
|
||||
}
|
||||
|
||||
fn walk(s: &Shape, f: &mut impl FnMut(egui::Pos2)) {
|
||||
if let Shape::Mesh(m) = s {
|
||||
assert!(m.is_valid());
|
||||
m.vertices.iter().for_each(|v| f(v.pos));
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_parts() -> Vec<(&'static str, Option<u64>, Vec<Part>)> {
|
||||
let m = MB;
|
||||
vec![
|
||||
("none", Some(400 * m), vec![]),
|
||||
("zero", Some(400 * m), vec![part(0, 400 * m, 0)]),
|
||||
("one byte", Some(400 * m), vec![part(0, 400 * m, 1)]),
|
||||
("almost", Some(400 * m), vec![part(0, 400 * m, 400 * m - 1)]),
|
||||
("full", Some(400 * m), vec![part(0, 400 * m, 400 * m)]),
|
||||
("empty file", Some(0), vec![part(0, 0, 0)]),
|
||||
("split", Some(400 * m), vec![part(0, 100 * m, 100 * m), part(100 * m, 101 * m, 5), part(101 * m, 400 * m, 80 * m)]),
|
||||
("sixty", Some(6000), (0..60).map(|i| part(i * 100, i * 100 + 100, i)).collect()),
|
||||
("thousands", Some(500_000), (0..5000).map(|i| part(i * 100, i * 100 + 100, 50)).collect()),
|
||||
("unknown", None, vec![Part { start: 0, end: None, done: 7 * m }]),
|
||||
("too much", Some(10), vec![part(0, 10, 99)]),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bars_rings_and_maps_stay_in_their_place() {
|
||||
for motion in [Motion::Off, Motion::Reduced, Motion::Normal, Motion::Expressive] {
|
||||
let mut s = Stage::new(motion);
|
||||
for (name, size, parts) in sample_parts() {
|
||||
for look in LOOKS {
|
||||
for (speed, checked) in [(0.0, 0.0), (1e4, 0.003), (1e12, 1.0), (f64::NAN, f32::NAN), (f64::INFINITY, 2.0)] {
|
||||
for w in [1.0, 6.0, 40.0, 333.3] {
|
||||
let bar = Rect::from_min_size(pos2(50.0, 50.0), vec2(w, wave::HEIGHT));
|
||||
// The wide strip of nothing keeps "nothing drawn" for the checks that matter.
|
||||
for _ in 0..2 {
|
||||
let b = Bar { look, size, parts: &parts, speed, checked };
|
||||
let out = s.frame(|t, ui| wave::bar(ui, t, Id::unique("bar"), bar, &b));
|
||||
if w > wave::STROKE {
|
||||
check(&out, bar.expand(0.6), &format!("bar {name} {look:?} {speed} {w} {motion:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let ring = Rect::from_min_size(pos2(50.0, 50.0), vec2(24.0, 24.0));
|
||||
let share = size.map(|s| parts.iter().map(|p| p.done).sum::<u64>() as f32 / s as f32);
|
||||
let out = s.frame(|t, ui| wave::ring(ui, t, Id::unique("ring"), ring, look, share, speed));
|
||||
check(&out, ring.expand(0.6), &format!("ring {name} {look:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_graph_and_digits_stay_in_their_place() {
|
||||
let mut s = Stage::new(Motion::Expressive);
|
||||
let r = Rect::from_min_size(pos2(50.0, 50.0), vec2(48.0, 48.0));
|
||||
for i in 0..400 {
|
||||
let look = LOOKS[(i / 7) % LOOKS.len()];
|
||||
let kind = Kind::ALL[(i / 11) % Kind::ALL.len()];
|
||||
let out = s.frame(|t, ui| {
|
||||
shape::badge(ui, t, Id::unique("badge"), r, kind, look);
|
||||
shape::loading(ui, t, Id::unique("load"), r);
|
||||
});
|
||||
check(&out, r.expand(r.width() * 0.3), "shapes");
|
||||
}
|
||||
let r = Rect::from_min_size(pos2(50.0, 50.0), vec2(300.0, 80.0));
|
||||
let mut h = History::new(20);
|
||||
for v in [0.0, f64::NAN, 1e15, 3.0, 0.0, 1e6] {
|
||||
for _ in 0..12 {
|
||||
h.push(v);
|
||||
// Samples beyond the edges are cut off by the clip.
|
||||
let out = s.frame(|t, ui| { graph::graph(ui, t, Id::unique("graph"), r, &h, Some(v)); });
|
||||
for c in &out.shapes {
|
||||
walk(&c.shape, &mut |p| assert!(p.x.is_finite() && p.y >= r.top() - 2.0 && p.y <= r.bottom() + 2.0, "{p:?}"));
|
||||
}
|
||||
let at = s.frame(|_, ui| { odometer::odometer(ui, Id::unique("odo"), pos2(60.0, 60.0), &odometer::rate(v), medlar_app::fonts::semi(45.0), Color32::WHITE); });
|
||||
assert!(!at.shapes.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn still_things_draw_no_frames() {
|
||||
for motion in [Motion::Off, Motion::Reduced, Motion::Normal, Motion::Expressive] {
|
||||
let mut s = Stage::new(motion);
|
||||
let parts = [part(0, 100, 60), part(100, 400, 10)];
|
||||
let draw = |look: Look, speed: f64| {
|
||||
move |t: &Theme, ui: &mut Ui| {
|
||||
let r = Rect::from_min_size(pos2(50.0, 50.0), vec2(300.0, wave::HEIGHT));
|
||||
let b = Bar { look, size: Some(400), parts: &parts, speed, checked: 0.5 };
|
||||
wave::bar(ui, t, Id::unique("bar"), r, &b);
|
||||
wave::ring(ui, t, Id::unique("ring"), r.translate(vec2(0.0, 40.0)), look, Some(0.3), speed);
|
||||
let blocks = parts.map(|part| Block { part, speed, server: None, failed: false });
|
||||
parts::map(ui, t, Id::unique("map"), r.translate(vec2(0.0, 80.0)), 400, &blocks);
|
||||
odometer::speed(ui, t, Id::unique("speed"), pos2(50.0, 200.0), speed);
|
||||
}
|
||||
};
|
||||
for (look, speed) in [(Look::Running, 0.0), (Look::Paused, 5e6), (Look::Waiting, 0.0), (Look::Failed, 0.0), (Look::Checking, 0.0), (Look::Done, 0.0)] {
|
||||
// From a lively start.
|
||||
for _ in 0..90 {
|
||||
s.frame(draw(Look::Running, 2e7));
|
||||
}
|
||||
let moving = asks_now(&s.frame(draw(Look::Running, 2e7)));
|
||||
assert_eq!(moving, matches!(motion, Motion::Normal | Motion::Expressive), "{motion:?} at speed, before {look:?}: {:?}", s.ctx.repaint_causes());
|
||||
s.rest(draw(look, speed));
|
||||
// At rest it stays at rest.
|
||||
for _ in 0..5 {
|
||||
assert!(!asks_now(&s.frame(draw(look, speed))), "{motion:?} {look:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_still_bar_is_flat() {
|
||||
let r = Rect::from_min_size(pos2(50.0, 50.0), vec2(300.0, wave::HEIGHT));
|
||||
let height = |motion, speed| {
|
||||
let mut s = Stage::new(motion);
|
||||
let parts = [part(0, 400, 300)];
|
||||
let out = s.frame(|t, ui| wave::bar(ui, t, Id::unique("bar"), r, &Bar { look: Look::Running, size: Some(400), parts: &parts, speed, checked: 0.0 }));
|
||||
let mut ys = egui::Rangef::NOTHING;
|
||||
for c in &out.shapes {
|
||||
walk(&c.shape, &mut |p| ys = egui::Rangef::new(ys.min.min(p.y), ys.max.max(p.y)));
|
||||
}
|
||||
ys.span()
|
||||
};
|
||||
let flat = height(Motion::Normal, 0.0);
|
||||
assert!(flat <= wave::STROKE + 1.1, "{flat}");
|
||||
assert_eq!(height(Motion::Reduced, 1e8), flat);
|
||||
assert_eq!(height(Motion::Off, 1e8), flat);
|
||||
assert!(height(Motion::Normal, 1e4) > flat + 1.0 && height(Motion::Normal, 1e8) > height(Motion::Normal, 1e4) + 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tick_plays_once_and_can_be_interrupted() {
|
||||
let r = Rect::from_min_size(pos2(50.0, 50.0), vec2(48.0, 48.0));
|
||||
// The tick leaves out the corner of the square.
|
||||
let corner = |out: &egui::FullOutput| {
|
||||
let mut far = f32::MAX;
|
||||
for c in &out.shapes {
|
||||
walk(&c.shape, &mut |p| far = far.min(p.distance(r.left_top())));
|
||||
}
|
||||
far
|
||||
};
|
||||
let mut s = Stage::new(Motion::Normal);
|
||||
let draw = |look| move |t: &Theme, ui: &mut Ui| shape::badge(ui, t, Id::unique("badge"), r, Kind::Video, look);
|
||||
let frames = |s: &mut Stage, look, n| (0..n).map(|_| corner(&s.frame(draw(look)))).last().unwrap();
|
||||
// Already done when it comes into view: no tick.
|
||||
let plain = frames(&mut s, Look::Done, 60);
|
||||
let mut s = Stage::new(Motion::Normal);
|
||||
assert!((frames(&mut s, Look::Running, 30) - plain).abs() < 0.5);
|
||||
let tick = frames(&mut s, Look::Done, 70);
|
||||
assert!(tick > plain + 2.0, "a tick: {tick} {plain}");
|
||||
assert!((frames(&mut s, Look::Done, 200) - plain).abs() < 0.5, "once");
|
||||
assert_eq!(s.rest(draw(Look::Done)), 0);
|
||||
frames(&mut s, Look::Running, 60);
|
||||
frames(&mut s, Look::Done, 40);
|
||||
assert!((frames(&mut s, Look::Waiting, 60) - plain).abs() < 0.5, "interrupted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_moves_smoothly() {
|
||||
let mut s = Stage::new(Motion::Normal);
|
||||
let mut sim = Sim::default();
|
||||
let r = Rect::from_min_size(pos2(50.0, 50.0), vec2(400.0, wave::HEIGHT));
|
||||
let bar = |s: &mut Stage, sim: &Sim| s.frame(|t, ui| wave::bar(ui, t, Id::unique("bar"), r, &Bar { look: Look::Paused, size: Some(sim.size), parts: &sim.parts, speed: 0.0, checked: 0.0 }));
|
||||
bar(&mut s, &sim);
|
||||
assert!(!asks_now(&bar(&mut s, &sim)));
|
||||
sim.split();
|
||||
assert!(asks_now(&bar(&mut s, &sim)), "glides");
|
||||
for _ in 0..300 {
|
||||
check(&bar(&mut s, &sim), r.expand(0.6), "split");
|
||||
}
|
||||
assert!(!asks_now(&bar(&mut s, &sim)));
|
||||
sim.hand_over();
|
||||
sim.hand_over();
|
||||
sim.merge();
|
||||
for _ in 0..300 {
|
||||
check(&bar(&mut s, &sim), r.expand(0.6), "merge");
|
||||
}
|
||||
assert!(!asks_now(&bar(&mut s, &sim)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_slider_follows_pointer_and_keys() {
|
||||
let mut app = None;
|
||||
let mut h = Harness::builder().with_size(vec2(400.0, 100.0)).build_ui_state(
|
||||
move |ui, v: &mut f32| {
|
||||
let app = app.get_or_insert_with(|| App::new(ui.ctx(), settings(Motion::Normal), Sources { caelestia: "/x".into(), kde: "/x".into() }));
|
||||
app.frame(ui, |app, ui| { wave::slider(ui, &app.theme.clone(), 208.0, v, 0.0, "Limit"); });
|
||||
},
|
||||
0.5,
|
||||
);
|
||||
h.run_steps(60);
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let r = h.get_by_label("Limit").rect();
|
||||
let at = |share: f32| pos2(r.left() + 4.0 + share * 200.0, r.center().y);
|
||||
h.drag_at(at(0.5));
|
||||
h.run_steps(2);
|
||||
h.hover_at(at(0.75));
|
||||
h.run_steps(2);
|
||||
assert!((h.state() - 0.75).abs() < 0.01, "{}", h.state());
|
||||
h.hover_at(pos2(2000.0, 0.0));
|
||||
h.run_steps(2);
|
||||
assert_eq!(*h.state(), 1.0);
|
||||
h.drop_at(pos2(2000.0, 0.0));
|
||||
h.run_steps(60);
|
||||
h.key_press(egui::Key::ArrowLeft);
|
||||
h.run_steps(60);
|
||||
assert!((h.state() - 0.98).abs() < 1e-4, "{}", h.state());
|
||||
// A press elsewhere jumps there.
|
||||
h.drag_at(at(0.2));
|
||||
h.run_steps(2);
|
||||
assert!((h.state() - 0.2).abs() < 0.01, "{}", h.state());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gallery_draws() {
|
||||
let mut s = Stage::new(Motion::Normal);
|
||||
let input = || egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 700.0))), ..Default::default() };
|
||||
for draw in [gallery::gallery, gallery::states] {
|
||||
let mut out = s.ctx.run_ui(input(), |ui| s.app.frame(ui, draw));
|
||||
out.textures_delta.clear();
|
||||
assert!(out.shapes.len() > 20);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence() {
|
||||
let Ok(dir) = std::env::var("MEDLAR_SEQUENCE") else { return };
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut app = None;
|
||||
let mut h = Harness::builder().with_size(vec2(360.0, 150.0)).with_step_dt(1.0 / 60.0).wgpu().build_ui_state(
|
||||
move |ui, sim: &mut Sim| {
|
||||
if app.is_none() {
|
||||
app = Some(App::new(ui.ctx(), settings(Motion::Normal), Sources { caelestia: "/x".into(), kde: "/x".into() }));
|
||||
return ui.ctx().request_repaint();
|
||||
}
|
||||
app.as_mut().unwrap().frame(ui, |app, ui| {
|
||||
let t = app.theme.clone();
|
||||
sim.tick(1.0 / 60.0);
|
||||
let r = Rect::from_min_size(pos2(16.0, 16.0), vec2(328.0, wave::HEIGHT));
|
||||
let b = Bar { look: sim.look, size: Some(sim.size), parts: &sim.parts, speed: sim.speed(), checked: sim.checked };
|
||||
wave::bar(ui, &t, Id::unique("bar"), r, &b);
|
||||
let blocks: Vec<Block> = sim.parts.iter().map(|p| Block { part: *p, speed: sim.speed(), server: None, failed: false }).collect();
|
||||
parts::map(ui, &t, Id::unique("map"), r.translate(vec2(0.0, 24.0)).with_max_y(72.0), sim.size, &blocks);
|
||||
let at = Rect::from_min_size(pos2(16.0, 88.0), vec2(48.0, 48.0));
|
||||
shape::badge(ui, &t, Id::unique("badge"), at, Kind::Archive, sim.look);
|
||||
odometer::speed(ui, &t, Id::unique("speed"), pos2(80.0, 112.0), sim.speed());
|
||||
});
|
||||
},
|
||||
Sim::default(),
|
||||
);
|
||||
h.run_steps(30);
|
||||
let mut n = 0;
|
||||
let mut play = |h: &mut Harness<Sim>, frames: usize, every: usize| {
|
||||
for i in 0..frames {
|
||||
h.step();
|
||||
if i % every == 0 {
|
||||
h.render().unwrap().save(format!("{dir}/{n:03}.png")).unwrap();
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
h.state_mut().split();
|
||||
play(&mut h, 18, 3);
|
||||
h.state_mut().split();
|
||||
h.state_mut().scrub = 0.9;
|
||||
play(&mut h, 12, 3);
|
||||
h.state_mut().hand_over();
|
||||
play(&mut h, 18, 3);
|
||||
h.state_mut().finish();
|
||||
play(&mut h, 60, 6);
|
||||
play(&mut h, 70, 14);
|
||||
}
|
||||
|
||||
/// CPU time of this thread in ms, whatever else the PC is doing. It steps by about 1 ms: good for sums.
|
||||
fn cpu() -> f64 {
|
||||
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").unwrap();
|
||||
stat.split(' ').next().unwrap().parse::<f64>().unwrap() / 1e6
|
||||
}
|
||||
|
||||
/// 200 lively bars of eight parts each.
|
||||
#[test]
|
||||
#[ignore = "measures: run it in release"]
|
||||
fn cost() {
|
||||
let mut s = Stage::new(Motion::Normal);
|
||||
let mut parts: Vec<Part> = (0..8).map(|i| part(i * 1000, i * 1000 + 1000, 200 + i * 50)).collect();
|
||||
const FRAMES: usize = 600;
|
||||
let (mut all, mut ours) = (0.0, 0.0);
|
||||
for i in 0..FRAMES + 30 {
|
||||
parts.iter_mut().for_each(|p| p.done = (p.done + 1).min(990));
|
||||
let begin = cpu();
|
||||
let out = s.frame(|t, ui| {
|
||||
for i in 0..200 {
|
||||
let at = pos2(10.0 + (i % 2) as f32 * 490.0, 10.0 + (i / 2) as f32 * 9.8);
|
||||
let b = Bar { look: Look::Running, size: Some(8000), parts: &parts, speed: 2e7, checked: 0.0 };
|
||||
wave::bar(ui, t, Id::unique(("bar", i)), Rect::from_min_size(at, vec2(480.0, wave::HEIGHT)), &b);
|
||||
}
|
||||
});
|
||||
let made = cpu();
|
||||
let drawn = s.ctx.tessellate(out.shapes, 1.0);
|
||||
assert!(!drawn.is_empty());
|
||||
// The first frames warm up.
|
||||
if i >= 30 {
|
||||
all += cpu() - begin;
|
||||
ours += made - begin;
|
||||
}
|
||||
}
|
||||
let per = |sum: f64| sum / FRAMES as f64;
|
||||
println!("200 bars: {:.2} ms CPU per frame, {:.2} without egui's tessellation", per(all), per(ours));
|
||||
if !cfg!(debug_assertions) {
|
||||
assert!(per(all) < 4.0);
|
||||
}
|
||||
}
|
||||
239
crates/app/tests/visuals/gallery.rs
Normal file
239
crates/app/tests/visuals/gallery.rs
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
//! A simulated download, every look of the progress widgets, and controls to set the speed and stage part events. Shared by the
|
||||
//! screenshots, the tests and `cargo run -p medlar --example visuals`.
|
||||
|
||||
use eframe::egui::{self, Align2, Id, Rect, Ui, pos2, vec2};
|
||||
use medlar_app::app::App;
|
||||
use medlar_app::motion;
|
||||
use medlar_app::tokens::{size, space, text};
|
||||
use medlar_app::ui::graph::{self, History};
|
||||
use medlar_app::ui::parts::{self, Block};
|
||||
use medlar_app::ui::shape::{self, Form, Kind};
|
||||
use medlar_app::ui::wave::{self, Bar, Look};
|
||||
use medlar_app::ui::odometer;
|
||||
use medlar_app::{fonts, icons};
|
||||
use medlar_core::model::Part;
|
||||
|
||||
pub const MB: u64 = 1_000_000;
|
||||
|
||||
/// A download of 400 MB that runs at whatever speed the scrubber says.
|
||||
#[derive(Clone)]
|
||||
pub struct Sim {
|
||||
pub size: u64,
|
||||
pub parts: Vec<Part>,
|
||||
/// The scrubber, 0 to 1.
|
||||
pub scrub: f32,
|
||||
pub look: Look,
|
||||
pub checked: f32,
|
||||
pub history: History,
|
||||
sample: f32,
|
||||
/// Splits a few times by itself; seconds so far.
|
||||
auto: Option<f32>,
|
||||
}
|
||||
|
||||
impl Default for Sim {
|
||||
fn default() -> Sim {
|
||||
let mut history = History::new(60);
|
||||
for i in 0..58 {
|
||||
history.push(6e6 + 3e6 * (i as f64 * 0.35).sin() + 1e6 * (i as f64 * 1.7).sin());
|
||||
}
|
||||
Sim { size: 400 * MB, parts: vec![part(0, 400 * MB, 60 * MB)], scrub: 0.6, look: Look::Running, checked: 0.0, history, sample: 0.0, auto: None }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn part(start: u64, end: u64, done: u64) -> Part {
|
||||
Part { start, end: Some(end), done }
|
||||
}
|
||||
|
||||
impl Sim {
|
||||
pub fn speed(&self) -> f64 {
|
||||
if matches!(self.look, Look::Running | Look::Checking) { f64::from(self.scrub).powi(2) * 40e6 } else { 0.0 }
|
||||
}
|
||||
|
||||
pub fn tick(&mut self, dt: f32) {
|
||||
let mut bytes = (self.speed() * f64::from(dt)) as u64;
|
||||
match self.look {
|
||||
Look::Running => {
|
||||
let open = self.parts.iter().filter(|p| left(p) > 0).count().max(1) as u64;
|
||||
bytes /= open;
|
||||
for p in &mut self.parts {
|
||||
p.done += bytes.min(left(p));
|
||||
}
|
||||
if self.parts.iter().all(|p| left(p) == 0) {
|
||||
self.look = Look::Checking;
|
||||
self.checked = 0.0;
|
||||
}
|
||||
}
|
||||
Look::Checking => {
|
||||
self.checked += bytes as f32 * 8.0 / self.size as f32;
|
||||
if self.checked >= 1.0 {
|
||||
self.look = Look::Done;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.sample += dt;
|
||||
if self.sample >= graph::STEP && self.speed() > 0.0 {
|
||||
self.sample = 0.0;
|
||||
self.history.push(self.speed());
|
||||
}
|
||||
if let Some(before) = self.auto {
|
||||
let now = before + dt;
|
||||
self.auto = Some(now);
|
||||
for at in [0.1, 0.2, 0.3, 0.4] {
|
||||
if before < at && now >= at {
|
||||
self.split();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The part with most left is cut in the middle of what is left.
|
||||
pub fn split(&mut self) {
|
||||
let Some(p) = self.parts.iter_mut().max_by_key(|p| left(p)).filter(|p| left(p) > MB) else { return };
|
||||
let (mid, end) = (p.start + p.done + left(p) / 2, p.end.unwrap());
|
||||
p.end = Some(mid);
|
||||
self.parts.push(part(mid, end, 0));
|
||||
self.parts.sort_by_key(|p| p.start);
|
||||
}
|
||||
|
||||
/// The first open part finishes, and takes half of what another still has.
|
||||
pub fn hand_over(&mut self) {
|
||||
if let Some(p) = self.parts.iter_mut().find(|p| left(p) > 0) {
|
||||
p.done += left(p);
|
||||
}
|
||||
self.split();
|
||||
}
|
||||
|
||||
/// Finished neighbours become one part.
|
||||
pub fn merge(&mut self) {
|
||||
let mut out: Vec<Part> = Vec::new();
|
||||
for p in &self.parts {
|
||||
match out.last_mut() {
|
||||
Some(q) if left(q) == 0 && left(p) == 0 => {
|
||||
q.end = p.end;
|
||||
q.done += p.done;
|
||||
}
|
||||
_ => out.push(*p),
|
||||
}
|
||||
}
|
||||
self.parts = out;
|
||||
}
|
||||
|
||||
pub fn finish(&mut self) {
|
||||
for p in &mut self.parts {
|
||||
p.done += left(p);
|
||||
}
|
||||
self.look = Look::Done;
|
||||
}
|
||||
}
|
||||
|
||||
fn left(p: &Part) -> u64 {
|
||||
p.end.unwrap() - p.start - p.done
|
||||
}
|
||||
|
||||
/// The simulated download with its controls. In a test it splits by itself.
|
||||
pub fn gallery(app: &mut App, ui: &mut Ui) {
|
||||
let id = Id::unique("gallery sim");
|
||||
let mut sim: Sim = ui.data(|d| d.get_temp(id)).unwrap_or_else(|| Sim { auto: cfg!(test).then_some(0.0), ..Sim::default() });
|
||||
let t = app.theme.clone();
|
||||
if matches!(sim.look, Look::Running | Look::Checking) && sim.speed() > 0.0 {
|
||||
sim.tick(motion::dt());
|
||||
motion::keep_alive();
|
||||
}
|
||||
let area = ui.max_rect().shrink(space::L);
|
||||
let w = area.width().min(720.0);
|
||||
let row = |y: f32, h: f32| Rect::from_min_size(pos2(area.left(), area.top() + y), vec2(w, h));
|
||||
let done: u64 = sim.parts.iter().map(|p| p.done).sum();
|
||||
|
||||
shape::badge(ui, &t, id.with("badge"), Rect::from_min_size(area.min, vec2(size::CONTROL, size::CONTROL)), Kind::Archive, sim.look);
|
||||
let x = area.left() + size::CONTROL + space::M;
|
||||
ui.painter().text(pos2(x, area.top()), Align2::LEFT_TOP, "archlinux-2026.11.01-x86_64.iso", fonts::med(text::BODY), t.on_surface);
|
||||
let words = format!("{} of {}", odometer::amount(done), odometer::amount(sim.size));
|
||||
ui.painter().text(pos2(x, area.top() + 20.0), Align2::LEFT_TOP, words, fonts::ui(text::LABEL), t.on_variant);
|
||||
let bar = Bar { look: sim.look, size: Some(sim.size), parts: &sim.parts, speed: sim.speed(), checked: sim.checked };
|
||||
wave::bar(ui, &t, id.with("bar"), row(52.0, wave::HEIGHT), &bar);
|
||||
let open = sim.parts.iter().filter(|p| left(p) > 0).count().max(1) as f64;
|
||||
let blocks: Vec<Block> = sim.parts.iter().enumerate().map(|(i, p)| Block {
|
||||
part: *p,
|
||||
speed: if left(p) > 0 { sim.speed() / open } else { 0.0 },
|
||||
server: Some(if i % 2 == 0 { "mirror.example.org" } else { "cdn.example.net" }),
|
||||
failed: sim.look == Look::Failed && left(p) > 0,
|
||||
}).collect();
|
||||
parts::map(ui, &t, id.with("map"), row(80.0, size::CONTROL), sim.size, &blocks);
|
||||
odometer::speed(ui, &t, id.with("speed"), pos2(area.left(), area.top() + 152.0), sim.speed());
|
||||
graph::graph(ui, &t, id.with("graph"), row(184.0, 80.0), &sim.history, Some(10e6));
|
||||
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(row(268.0, size::CONTROL)), |ui| {
|
||||
let speed = sim.speed();
|
||||
wave::slider(ui, &t, w, &mut sim.scrub, speed, "Speed");
|
||||
});
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(row(312.0, size::HIT)), |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let mut hit = |name: &str| ui.add(egui::Button::new(name)).clicked();
|
||||
if hit("Split") { sim.split() }
|
||||
if hit("Hand over") { sim.hand_over() }
|
||||
if hit("Merge") { sim.merge() }
|
||||
if hit("Pause") { sim.look = Look::Paused }
|
||||
if hit("Run") { sim.look = Look::Running }
|
||||
if hit("Fail") { sim.look = Look::Failed }
|
||||
if hit("Check") { (sim.look, sim.checked) = (Look::Checking, 0.0) }
|
||||
if hit("Finish") { sim.finish() }
|
||||
if hit("Start over") { sim = Sim::default() }
|
||||
});
|
||||
});
|
||||
ui.data_mut(|d| d.insert_temp(id, sim));
|
||||
}
|
||||
|
||||
/// Every look of every widget.
|
||||
pub fn states(app: &mut App, ui: &mut Ui) {
|
||||
let id = Id::unique("gallery states");
|
||||
let t = app.theme.clone();
|
||||
let p = ui.painter().clone();
|
||||
let area = ui.max_rect().shrink(space::L);
|
||||
let some = [part(0, 100, 60), part(100, 180, 80), part(180, 300, 40), part(300, 400, 0)];
|
||||
let full = [part(0, 400, 400)];
|
||||
let thin = [part(0, 400, 2)];
|
||||
let rows: [(&str, Bar); 10] = [
|
||||
("Waiting", Bar { look: Look::Waiting, size: Some(400), parts: &some, ..Bar::default() }),
|
||||
("Slow", Bar { look: Look::Running, size: Some(400), parts: &some, speed: 3e4, ..Bar::default() }),
|
||||
("Fast", Bar { look: Look::Running, size: Some(400), parts: &some, speed: 4e7, ..Bar::default() }),
|
||||
("Stalled", Bar { look: Look::Running, size: Some(400), parts: &some, ..Bar::default() }),
|
||||
("Begun", Bar { look: Look::Running, size: Some(400), parts: &thin, speed: 4e6, ..Bar::default() }),
|
||||
("Unknown size", Bar { look: Look::Running, size: None, parts: &[], speed: 4e6, ..Bar::default() }),
|
||||
("Paused", Bar { look: Look::Paused, size: Some(400), parts: &some, ..Bar::default() }),
|
||||
("Checking", Bar { look: Look::Checking, size: Some(400), parts: &full, speed: 4e7, checked: 0.4 }),
|
||||
("Failed", Bar { look: Look::Failed, size: Some(400), parts: &some, ..Bar::default() }),
|
||||
("Done", Bar { look: Look::Done, size: Some(400), parts: &full, ..Bar::default() }),
|
||||
];
|
||||
let w = (area.width() - 160.0).clamp(80.0, 420.0);
|
||||
for (i, (name, b)) in rows.iter().enumerate() {
|
||||
let y = area.top() + i as f32 * 32.0;
|
||||
p.text(pos2(area.left(), y + 16.0), Align2::LEFT_CENTER, name, fonts::ui(text::BODY), t.on_variant);
|
||||
wave::bar(ui, &t, id.with(("bar", i)), Rect::from_min_size(pos2(area.left() + 104.0, y + 10.0), vec2(w, wave::HEIGHT)), b);
|
||||
let share = b.size.map(|_| b.parts.iter().map(|p| p.done).sum::<u64>() as f32 / 400.0);
|
||||
let ring = Rect::from_center_size(pos2(area.left() + 104.0 + w + 32.0, y + 16.0), vec2(28.0, 28.0));
|
||||
wave::ring(ui, &t, id.with(("ring", i)), ring, b.look, if b.look == Look::Checking { Some(b.checked) } else { share }, b.speed);
|
||||
}
|
||||
let y = area.top() + 336.0;
|
||||
for (i, kind) in Kind::ALL.into_iter().enumerate() {
|
||||
let r = Rect::from_min_size(pos2(area.left() + i as f32 * 56.0, y), vec2(size::CONTROL, size::CONTROL));
|
||||
shape::badge(ui, &t, id.with(("kind", i)), r, kind, Look::Running);
|
||||
}
|
||||
for (i, f) in Form::ALL.into_iter().enumerate() {
|
||||
shape::form(&p, pos2(area.left() + 20.0 + i as f32 * 56.0, y + 76.0), 20.0, f, if f == Form::Tick { t.success } else { t.tertiary });
|
||||
}
|
||||
for (i, (side, share)) in [(16.0, 0.3), (24.0, 0.6), (48.0, 0.45), (96.0, 0.7)].into_iter().enumerate() {
|
||||
let r = Rect::from_center_size(pos2(area.left() + 24.0 + i as f32 * 80.0, y + 160.0), vec2(side, side));
|
||||
wave::ring(ui, &t, id.with(("big ring", i)), r, Look::Running, Some(share), 2e7);
|
||||
}
|
||||
shape::loading(ui, &t, id.with("loading"), Rect::from_center_size(pos2(area.left() + 368.0, y + 160.0), vec2(48.0, 48.0)));
|
||||
icons::paint(&p, pos2(area.left() + 424.0, y + 160.0), 24.0, "download", t.on_variant);
|
||||
let many: Vec<Block> = (0..4000).map(|i| {
|
||||
let done = if (i / 37) % 3 == 0 { 100 } else { (i * 7919 % 101) as u64 };
|
||||
Block { part: part(i as u64 * 100, i as u64 * 100 + 100, done), speed: if i % 600 == 0 { 1e6 } else { 0.0 }, server: None, failed: false }
|
||||
}).collect();
|
||||
let map = Rect::from_min_size(pos2(area.left(), y + 224.0), vec2(w + 160.0, size::CONTROL));
|
||||
parts::map(ui, &t, id.with("strip"), map, 400_000, &many);
|
||||
let blocks: Vec<Block> = some.iter().enumerate().map(|(i, p)| Block { part: *p, speed: if i == 2 { 1e6 } else { 0.0 }, server: None, failed: i == 0 }).collect();
|
||||
parts::map(ui, &t, id.with("failed map"), map.translate(vec2(0.0, 56.0)), 400, &blocks);
|
||||
}
|
||||
|
|
@ -27,6 +27,22 @@
|
|||
"priority.highest": "Highest",
|
||||
"priority.only": "Only this one",
|
||||
|
||||
"unit.b": "{n} B",
|
||||
"unit.kb": "{n} kB",
|
||||
"unit.mb": "{n} MB",
|
||||
"unit.gb": "{n} GB",
|
||||
"unit.tb": "{n} TB",
|
||||
"unit.pb": "{n} PB",
|
||||
"unit.rate": "{amount}/s",
|
||||
|
||||
"map.range": "{from} to {to}",
|
||||
"map.from": "{speed} from {server}",
|
||||
"map.still": "No data right now",
|
||||
"map.done": "Finished",
|
||||
"map.share": "{percent}% done",
|
||||
"graph.limit": "Limit {speed}",
|
||||
"graph.ago": "{speed}, {n} s ago",
|
||||
|
||||
"settings.damaged": "Some settings could not be read and are back to their defaults: {keys}. The old file is kept.",
|
||||
"settings.damaged_all": "The settings file could not be read, so every setting is back to its default. The old file is kept.",
|
||||
|
||||
|
|
|
|||
|
|
@ -24,4 +24,7 @@
|
|||
- D-020 — 2026-11-25 — Connections start at 2 (or what the host stood, kept 7 days) and double, then go up by one, while the new ones bring ≥ 30 % of a fair share and more than twice the noise; measured 3 s after 1 s of settling. A failed try holds 30 s, doubling to 4 min; counts that were not proven are tried lower. Never below 2 without a refusal or cap. — The user's line is slow: a connection has to prove itself. — 02
|
||||
- D-021 — 2026-11-25 — A refusal (429, 503, any other 4xx, no connection, 200 for a range) while others deliver lowers the count for 10 min for all downloads of that host, and is remembered; alone, 4xx and 200 are final. New requests per host: 16 at once, then 4/s. Idle connections close after 0.5 s; a host that refused gets 0.3 s to notice a closed one. A part that waits after a failure keeps its place, so that failures cause no further cuts. — Must not look like abuse. — 02
|
||||
- D-022 — 2026-11-25 — A failed part never ends the download while others deliver. It ends after 5 failures in a row without a byte (1 s, doubling, half of it chance, ≤ 60 s) with nothing else delivering, or when Retry-After is longer than 60 s. Changed, disk, store, encoding and contradicting replies end it at once. Longer waits and task retries are S007's. — FEATURES 1.6. — 02
|
||||
- D-026 — 2026-11-25 — Amounts on screen count in thousands: B, kB, MB, GB, one decimal, and speeds as the same per second (`ui::odometer::{amount, rate}`). — It is what the units mean, and disks and lines are sold in them. No setting until someone asks. — 03, 04
|
||||
- D-027 — 2026-11-25 — Wave height and travel follow the logarithm of the bytes per second, from 0 to 64 MiB/s, not a share of the limit or of the fastest so far. At 0 B/s, when paused, and with motion off or reduced the bar is flat and draws no frames. — The same speed always looks the same, and a slow line still moves visibly. — 03
|
||||
- D-028 — 2026-11-25 — Progress widgets keep their springs per `Id` and start in place when they were not drawn in the frame before, so scrolling shows no motion and the tick plays only for someone who saw the download finish. A list row's id comes from the task's id, not its position. — 03
|
||||
- D-023 — 2026-11-25 — Menus are Medlar's own (`ui::menu`), not egui's: one open at a time, own keyboard. Dialogs never close by a click on the scrim (the side sheet does); Enter does the main action unless a button has the focus; dangerous questions start on Cancel. Elevated buttons have no shadow. — egui's arrow keys leave its menus; typed links must not be lost. — 03 and later
|
||||
|
|
|
|||
|
|
@ -67,5 +67,15 @@ Numbers (debug build, test timing 0.2 s + 0.6 s): 512 KiB/s per connection, cap
|
|||
- `LivePart`: new `pos()` and `received()` (bytes from the network, what S006 limits); `part::split` is gone.
|
||||
Not done: a lone connection that crawls is replaced only when a second one is wanted (tried after each hold, 30 s to 4 min). Servers without ranges still fail at the first error. Not tried on the real line. In an early build the crawling test ran over 60 s three times while all tests shared the CPU; not seen in 64 runs since, half of them under full load.
|
||||
|
||||
## S014 — Wavy bars, parts map, shapes and speed graph (2026-11-25)
|
||||
Done: `ui::wave` (bar, ring, `ring_rgba` for the tray, slider), `ui::parts` (`Tiles`, map, density strip), `ui::shape` (badge, loading, form), `ui::graph`, `ui::odometer`. Live gallery: `cargo run -p medlar --example visuals`; scenes `progress`, `progress-states`.
|
||||
Verified: `--test visuals` green (bounds and NaN at every look, speed, width and motion level; no frames at rest; flat when still; tick once); shots in light and dark, hover, and a frame sequence looked at; 200 bars of 8 parts cost 3.6 ms CPU a frame in release with the PC busy (1.4 ours, the rest egui's tessellation).
|
||||
- Every call takes `(ui, &theme, id, rect, …)`; the id must come from the task's id (D-028). Draw `bar` `wave::HEIGHT` high.
|
||||
- `Bar`: `look` = `Look::from(task.state)`; `size` = task size; `parts` = `LivePart::get()` of every part, in any order, finished ones too; `speed` = the task's bytes/s now, 0 when nothing arrives (or bytes/s read while checking); `checked` = share hashed. S006's snapshot needs: state, size, parts, speed, checked.
|
||||
- `parts::Block`: one per part: `part`, `speed` of its connection, `server` (host), `failed`. `map` draws blocks, or a density strip over 256 parts or under 4 px each.
|
||||
- `graph::History`: `push` the total speed once a second (`graph::STEP`), also 0; `limit` = bytes/s in force. `odometer::speed` for the big number, `odometer(…)` for any text with digits, `amount`/`rate` for text (D-026).
|
||||
- `badge`: `Kind` comes from the category; nothing maps names to kinds yet. `loading` shows only after 0.3 s; draw it for as long as something is waited for.
|
||||
Not done: the map has no keyboard focus (its numbers belong in the detail list too). Not seen on a real GPU or by hand: the feel of the springs. `wave::slider` is the wavy one for limits, S013's is the plain one.
|
||||
|
||||
## Later
|
||||
-
|
||||
|
|
|
|||
Loading…
Reference in a new issue