S015: main window, list, bridge to the engine
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
e2f80d74e8
commit
1dd998cbf5
20 changed files with 4130 additions and 17 deletions
4
Cargo.lock
generated
4
Cargo.lock
generated
|
|
@ -2195,6 +2195,7 @@ dependencies = [
|
|||
name = "medlar"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dirs",
|
||||
"eframe",
|
||||
"egui_kittest",
|
||||
|
|
@ -2202,9 +2203,12 @@ dependencies = [
|
|||
"log",
|
||||
"medlar-cli",
|
||||
"medlar-core",
|
||||
"medlar-testserver",
|
||||
"resvg",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ The daily screen on real data. FEATURES 7.1, 7.4 (undo), 9.5, 9.7, 3.3 (window d
|
|||
- crates/core snapshot and command API
|
||||
|
||||
## Steps
|
||||
- [ ] Bridge: engine runtime on its own threads, snapshot per frame, repaint only on change
|
||||
- [x] Bridge: engine runtime on its own threads, snapshot per frame, repaint only on change
|
||||
- [ ] Layout: collapsing rail (states, queues, tags, types), list, floating toolbar, speed header with graph; 480 px to ultrawide
|
||||
- [ ] Rows in compact and card form: kind shape, name, host, wavy bar, speed, time left, state; fixed heights, ellipsis, virtualised for 10,000
|
||||
- [ ] Search, filters, sort, columns, grouping; multi-select with keyboard, range and lasso; drag to reorder
|
||||
|
|
|
|||
|
|
@ -17,7 +17,9 @@ path = "src/main.rs"
|
|||
medlar-cli.workspace = true
|
||||
medlar-core.workspace = true
|
||||
log.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
|
||||
dirs = "6"
|
||||
eframe = { version = "0.37", default-features = false, features = ["glow", "wayland", "x11", "default_fonts", "system_fonts", "persistence"] }
|
||||
resvg = { version = "0.45", default-features = false }
|
||||
|
|
@ -25,4 +27,6 @@ resvg = { version = "0.45", default-features = false }
|
|||
[dev-dependencies]
|
||||
egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
medlar-testserver.workspace = true
|
||||
tempfile = "3"
|
||||
tokio = { version = "1", features = ["rt-multi-thread"] }
|
||||
|
|
|
|||
|
|
@ -3,11 +3,14 @@
|
|||
use crate::desktop::{Sources, Watch};
|
||||
use crate::motion;
|
||||
use crate::theme::Theme;
|
||||
use crate::bridge::{Bridge, Opening};
|
||||
use crate::ui::gallery;
|
||||
use crate::views::main::{Main, open_outside};
|
||||
use crate::{fonts, icons, tokens};
|
||||
use eframe::egui::{self, Align2, Context, Ui, ViewportBuilder};
|
||||
use eframe::egui::{self, Context, Ui, ViewportBuilder};
|
||||
use medlar_core::net_state::Bus;
|
||||
use medlar_core::paths::Paths;
|
||||
use medlar_core::settings::Settings;
|
||||
use medlar_core::settings::{Damage, Settings};
|
||||
use medlar_core::{logging, tr};
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
|
|
@ -18,6 +21,8 @@ pub const APP_ID: &str = "medlar";
|
|||
pub struct App {
|
||||
pub settings: Settings,
|
||||
pub theme: Theme,
|
||||
/// The daily screen. Without an engine until it gets one.
|
||||
pub main: Main,
|
||||
sources: Sources,
|
||||
watch: Watch,
|
||||
/// What `theme` was made from; a change in settings rebuilds it.
|
||||
|
|
@ -30,7 +35,7 @@ impl App {
|
|||
let theme = Theme::build(&settings, sources.read());
|
||||
theme.apply(ctx, settings.motion);
|
||||
let watch = Watch::start(sources.clone(), ctx);
|
||||
App { themed: settings.clone(), settings, theme, sources, watch }
|
||||
App { themed: settings.clone(), settings, theme, main: Main::default(), sources, watch }
|
||||
}
|
||||
|
||||
fn follow_theme(&mut self, ctx: &Context) {
|
||||
|
|
@ -58,14 +63,7 @@ impl App {
|
|||
}
|
||||
|
||||
fn view(&mut self, ui: &mut Ui) {
|
||||
let (p, t) = (ui.painter(), &self.theme);
|
||||
let center = ui.ctx().content_rect().center() - egui::vec2(0.0, tokens::space::XL);
|
||||
let hero = tokens::icon::HERO;
|
||||
icons::paint_app(p, center - egui::vec2(0.0, hero / 2.0), hero);
|
||||
let title = center + egui::vec2(0.0, tokens::space::L);
|
||||
let title = p.text(title, Align2::CENTER_TOP, tr!("empty.title"), fonts::semi(tokens::text::HEADLINE), t.on_surface);
|
||||
let body = title.center_bottom() + egui::vec2(0.0, tokens::space::XS);
|
||||
p.text(body, Align2::CENTER_TOP, tr!("empty.body"), fonts::ui(tokens::text::BODY), t.on_variant);
|
||||
self.main.show(ui, &self.theme, &self.settings);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -84,6 +82,11 @@ impl eframe::App for Window {
|
|||
self.app.theme.surface.to_normalized_gamma_f32()
|
||||
}
|
||||
|
||||
/// Saves where the downloads are.
|
||||
fn on_exit(&mut self, _: Option<&eframe::glow::Context>) {
|
||||
self.app.main.bridge.close();
|
||||
}
|
||||
|
||||
/// Only the window's place and size are remembered.
|
||||
fn persist_egui_memory(&self) -> bool {
|
||||
false
|
||||
|
|
@ -92,15 +95,16 @@ impl eframe::App for Window {
|
|||
|
||||
/// Opens the window and returns when it is closed.
|
||||
pub fn run() -> ExitCode {
|
||||
open(App::show)
|
||||
open(true, App::show)
|
||||
}
|
||||
|
||||
/// Opens a window with every control instead (`--gallery`).
|
||||
pub fn run_gallery() -> ExitCode {
|
||||
open(|app, ui| app.frame(ui, gallery::show))
|
||||
open(false, |app, ui| app.frame(ui, gallery::show))
|
||||
}
|
||||
|
||||
fn open(show: fn(&mut App, &mut Ui)) -> ExitCode {
|
||||
/// `engine`: with the downloads, else only the window.
|
||||
fn open(engine: bool, show: fn(&mut App, &mut Ui)) -> ExitCode {
|
||||
let paths = Paths::detect();
|
||||
if let Err(e) = paths.create() {
|
||||
eprintln!("{}: {e}", paths.config.display());
|
||||
|
|
@ -109,7 +113,7 @@ fn open(show: fn(&mut App, &mut Ui)) -> ExitCode {
|
|||
if let Err(e) = logging::init(&paths.log(), log::LevelFilter::Info) {
|
||||
eprintln!("{}: {e}", paths.log().display());
|
||||
}
|
||||
if let Some(damage) = damage {
|
||||
if let Some(damage) = &damage {
|
||||
log::warn!("settings: {damage:?}");
|
||||
}
|
||||
let mut viewport = ViewportBuilder::default()
|
||||
|
|
@ -126,10 +130,27 @@ fn open(show: fn(&mut App, &mut Ui)) -> ExitCode {
|
|||
persistence_path: Some(paths.data.join("window.ron")),
|
||||
..Default::default()
|
||||
};
|
||||
let made = eframe::run_native(APP_ID, options, Box::new(move |cc| Ok(Box::new(Window { app: App::new(&cc.egui_ctx, settings, Sources::detect()), show }))));
|
||||
let make = move |cc: &eframe::CreationContext| {
|
||||
let mut app = App::new(&cc.egui_ctx, settings, Sources::detect());
|
||||
if engine {
|
||||
app.main.outside = open_outside;
|
||||
app.main.remember(paths.data.join("view.json"));
|
||||
if let Some(damage) = damage {
|
||||
app.main.toasts.error(damage_words(&damage), None);
|
||||
}
|
||||
let opening = Opening { paths, settings: app.settings.clone(), bus: Bus::System };
|
||||
app.main.bridge = Bridge::open(opening, &cc.egui_ctx);
|
||||
}
|
||||
Ok(Box::new(Window { app, show }) as Box<dyn eframe::App>)
|
||||
};
|
||||
let made = eframe::run_native(APP_ID, options, Box::new(make));
|
||||
if let Err(e) = made {
|
||||
eprintln!("{}", tr!("app.no_window", why = e));
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn damage_words(damage: &Damage) -> String {
|
||||
if damage.keys.is_empty() { tr!("settings.damaged_all") } else { tr!("settings.damaged", keys = damage.keys.join(", ")) }
|
||||
}
|
||||
|
|
|
|||
247
crates/app/src/bridge.rs
Normal file
247
crates/app/src/bridge.rs
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
//! Between the window and the engine. The engine is opened and runs on its own threads; the window reads what is there,
|
||||
//! sends commands, and waits for nothing.
|
||||
|
||||
use eframe::egui::Context;
|
||||
use medlar_core::host::{Caps, Hosts};
|
||||
use medlar_core::http::{self, ClientOptions, Shared};
|
||||
use medlar_core::manager::{Command, Config, Manager, Reply};
|
||||
use medlar_core::model::{Queue, Tag};
|
||||
use medlar_core::paths::Paths;
|
||||
use medlar_core::net_state::Bus;
|
||||
use medlar_core::settings::Settings;
|
||||
use medlar_core::snapshot::Snapshot;
|
||||
use medlar_core::store::Store;
|
||||
use medlar_core::tr;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, mpsc};
|
||||
|
||||
/// What is seldom changed. Read once; `reload` after a change.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Lists {
|
||||
pub queues: Vec<Queue>,
|
||||
pub tags: Vec<Tag>,
|
||||
}
|
||||
|
||||
/// What there is to draw.
|
||||
#[derive(Clone)]
|
||||
pub enum Data {
|
||||
Opening,
|
||||
/// Why not, in plain words.
|
||||
Failed(String),
|
||||
Ready(Arc<Snapshot>, Arc<Lists>),
|
||||
}
|
||||
|
||||
/// How to open the engine. Tests leave the bus off.
|
||||
#[derive(Clone)]
|
||||
pub struct Opening {
|
||||
pub paths: Paths,
|
||||
pub settings: Settings,
|
||||
pub bus: Bus,
|
||||
}
|
||||
|
||||
enum Engine {
|
||||
Opening,
|
||||
Failed(String),
|
||||
Open { manager: Arc<Manager>, store: Arc<Store>, lists: Arc<Lists>, replies: mpsc::Sender<Reply> },
|
||||
/// No engine at all: a list that stands still.
|
||||
Still { shot: Arc<Snapshot>, lists: Arc<Lists>, sent: Vec<Command> },
|
||||
Closed,
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
/// Held only to copy what it points to.
|
||||
engine: Mutex<Engine>,
|
||||
errors: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
/// The window's end of the engine.
|
||||
pub struct Bridge {
|
||||
inner: Arc<Inner>,
|
||||
opening: Option<(Opening, Context)>,
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
impl Default for Bridge {
|
||||
fn default() -> Bridge {
|
||||
Bridge::still(Snapshot::default(), Lists::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl Bridge {
|
||||
fn with(engine: Engine, opening: Option<(Opening, Context)>) -> Bridge {
|
||||
Bridge { inner: Arc::new(Inner { engine: Mutex::new(engine), errors: Mutex::default() }), opening }
|
||||
}
|
||||
|
||||
/// Opens the engine in the background. A frame is drawn when it is there, and after each change of the list.
|
||||
pub fn open(opening: Opening, ctx: &Context) -> Bridge {
|
||||
let bridge = Bridge::with(Engine::Opening, Some((opening, ctx.clone())));
|
||||
bridge.begin();
|
||||
bridge
|
||||
}
|
||||
|
||||
/// A list without an engine, for tests and pictures. Commands are kept, see `take_sent`.
|
||||
pub fn still(shot: Snapshot, lists: Lists) -> Bridge {
|
||||
Bridge::with(Engine::Still { shot: Arc::new(shot), lists: Arc::new(lists), sent: vec![] }, None)
|
||||
}
|
||||
|
||||
/// An engine that is still opening, or could not.
|
||||
pub fn stuck(why: Option<&str>) -> Bridge {
|
||||
Bridge::with(why.map_or(Engine::Opening, |w| Engine::Failed(w.into())), None)
|
||||
}
|
||||
|
||||
fn begin(&self) {
|
||||
let Some((opening, ctx)) = self.opening.clone() else { return };
|
||||
let inner = self.inner.clone();
|
||||
let thread = std::thread::Builder::new().name("engine".into()).spawn(move || {
|
||||
let made = make(opening, &inner, &ctx).unwrap_or_else(Engine::Failed);
|
||||
let mut engine = lock(&inner.engine);
|
||||
// The window may be gone by now; dropping the engine closes it.
|
||||
if matches!(*engine, Engine::Opening) {
|
||||
*engine = made;
|
||||
}
|
||||
drop(engine);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
if let Err(e) = thread {
|
||||
*lock(&self.inner.engine) = Engine::Failed(e.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries again to open it.
|
||||
pub fn retry(&self) {
|
||||
let mut engine = lock(&self.inner.engine);
|
||||
if matches!(*engine, Engine::Failed(_)) && self.opening.is_some() {
|
||||
*engine = Engine::Opening;
|
||||
drop(engine);
|
||||
self.begin();
|
||||
}
|
||||
}
|
||||
|
||||
/// What to draw this frame.
|
||||
pub fn data(&self) -> Data {
|
||||
match &*lock(&self.inner.engine) {
|
||||
Engine::Opening | Engine::Closed => Data::Opening,
|
||||
Engine::Failed(why) => Data::Failed(why.clone()),
|
||||
Engine::Open { manager, lists, .. } => Data::Ready(manager.snapshot(), lists.clone()),
|
||||
Engine::Still { shot, lists, .. } => Data::Ready(shot.clone(), lists.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Never waits. What goes wrong comes back through `take_errors`.
|
||||
pub fn send(&self, command: Command) {
|
||||
match &mut *lock(&self.inner.engine) {
|
||||
Engine::Open { manager, replies, .. } => {
|
||||
let _ = replies.send(manager.send(command));
|
||||
}
|
||||
Engine::Still { sent, .. } => sent.push(command),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors of commands since the last call.
|
||||
pub fn take_errors(&self) -> Vec<String> {
|
||||
std::mem::take(&mut lock(&self.inner.errors))
|
||||
}
|
||||
|
||||
/// Reads queues and tags again.
|
||||
pub fn reload(&self) {
|
||||
let (Engine::Open { store, .. }, Some((_, ctx))) = (&*lock(&self.inner.engine), &self.opening) else { return };
|
||||
let (store, inner, ctx) = (store.clone(), self.inner.clone(), ctx.clone());
|
||||
std::thread::spawn(move || {
|
||||
match read_lists(&store) {
|
||||
Ok(read) => {
|
||||
if let Engine::Open { lists, .. } = &mut *lock(&inner.engine) {
|
||||
*lists = Arc::new(read);
|
||||
}
|
||||
}
|
||||
Err(why) => lock(&inner.errors).push(why),
|
||||
}
|
||||
ctx.request_repaint();
|
||||
});
|
||||
}
|
||||
|
||||
/// The engine itself, for what the bridge has no word for.
|
||||
pub fn manager(&self) -> Option<Arc<Manager>> {
|
||||
match &*lock(&self.inner.engine) {
|
||||
Engine::Open { manager, .. } => Some(manager.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops and saves everything, at most two seconds.
|
||||
pub fn close(&self) {
|
||||
let engine = std::mem::replace(&mut *lock(&self.inner.engine), Engine::Closed);
|
||||
if let Engine::Open { manager, .. } = engine {
|
||||
manager.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Another list that stands still.
|
||||
pub fn set_still(&self, new: Snapshot) {
|
||||
if let Engine::Still { shot, .. } = &mut *lock(&self.inner.engine) {
|
||||
*shot = Arc::new(new);
|
||||
}
|
||||
}
|
||||
|
||||
/// What was sent without an engine.
|
||||
pub fn take_sent(&self) -> Vec<Command> {
|
||||
match &mut *lock(&self.inner.engine) {
|
||||
Engine::Still { sent, .. } => std::mem::take(sent),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_lists(store: &Store) -> Result<Lists, String> {
|
||||
let read = || Ok(Lists { queues: store.queues()?, tags: store.tags()? });
|
||||
read().map_err(|e: medlar_core::store::Error| e.to_string())
|
||||
}
|
||||
|
||||
fn make(opening: Opening, inner: &Arc<Inner>, ctx: &Context) -> Result<Engine, String> {
|
||||
let Opening { paths, settings, bus } = opening;
|
||||
let words = |e: &dyn std::fmt::Display| {
|
||||
log::error!("engine: {e}");
|
||||
e.to_string()
|
||||
};
|
||||
let store = Arc::new(Store::open(&paths.database()).map_err(|e| words(&e))?);
|
||||
let client = http::client(&ClientOptions::default()).map_err(|e| {
|
||||
log::error!("engine: {e:?}");
|
||||
tr!("open.network")
|
||||
})?;
|
||||
let lists = Arc::new(read_lists(&store)?);
|
||||
let shared = Shared { client, store: store.clone(), hosts: Hosts::new(Caps::default()) };
|
||||
let mut config = Config::new(shared, settings.limits());
|
||||
config.recovery.bus = bus;
|
||||
config.recovery.tries = settings.tries;
|
||||
config.recovery.auto_resume = settings.auto_resume;
|
||||
let manager = Arc::new(Manager::open(config).map_err(|e| words(&e))?);
|
||||
let repaint = ctx.clone();
|
||||
manager.on_change(move || repaint.request_repaint());
|
||||
let (replies, inbox) = mpsc::channel::<Reply>();
|
||||
let (inner, ctx) = (inner.clone(), ctx.clone());
|
||||
std::thread::Builder::new()
|
||||
.name("replies".into())
|
||||
.spawn(move || {
|
||||
for reply in inbox {
|
||||
if let Err(e) = reply.wait() {
|
||||
log::warn!("command: {e}");
|
||||
lock(&inner.errors).push(e.to_string());
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(|e| words(&e))?;
|
||||
Ok(Engine::Open { manager, store, lists, replies })
|
||||
}
|
||||
|
||||
/// Where files go when nothing else was said.
|
||||
pub fn download_folder(settings: &Settings) -> PathBuf {
|
||||
let own = PathBuf::from(&settings.download_folder);
|
||||
if own.is_absolute() {
|
||||
return own;
|
||||
}
|
||||
dirs::download_dir().or_else(|| dirs::home_dir().map(|h| h.join("Downloads"))).unwrap_or_else(std::env::temp_dir)
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
//! Medlar's window: theme, motion, widgets and views.
|
||||
|
||||
pub mod app;
|
||||
pub mod bridge;
|
||||
pub mod desktop;
|
||||
pub mod fonts;
|
||||
#[rustfmt::skip]
|
||||
|
|
@ -10,5 +11,6 @@ pub mod motion;
|
|||
pub mod theme;
|
||||
pub mod tokens;
|
||||
pub mod ui;
|
||||
pub mod views;
|
||||
|
||||
pub use app::{run, run_gallery};
|
||||
|
|
|
|||
268
crates/app/src/views/bar.rs
Normal file
268
crates/app/src/views/bar.rs
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
//! What is above the list and what floats over it: speed, search, filters, and the toolbar of the selected ones.
|
||||
|
||||
use super::list::layout::Form;
|
||||
use super::list::model::{Age, Filter, Group, Listing, Sort, Status, host_name, kind_label, queue_name};
|
||||
use super::list::row::Column;
|
||||
use super::list::{Act, List, Order};
|
||||
use crate::bridge::Lists;
|
||||
use crate::fonts;
|
||||
use crate::theme::Theme;
|
||||
use crate::tokens::{self, icon, size, space, text};
|
||||
use crate::ui::menu::{self, Item};
|
||||
use crate::ui::odometer;
|
||||
use crate::ui::widgets::{Button, Chip, Kind, left, line, text_width, toolbar};
|
||||
use crate::ui::{field, graph};
|
||||
use crate::icons;
|
||||
use eframe::egui::{Align, Id, Layout, Rect, Ui, UiBuilder, pos2, vec2};
|
||||
use medlar_core::manager::Files;
|
||||
use medlar_core::snapshot::{Snapshot, Totals};
|
||||
use medlar_core::tr;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
/// The speed of the last minutes, as the graph wants it.
|
||||
pub struct Speeds {
|
||||
history: graph::History,
|
||||
seen: u64,
|
||||
}
|
||||
|
||||
/// Seconds the graph shows.
|
||||
const SPAN: usize = 180;
|
||||
|
||||
impl Default for Speeds {
|
||||
fn default() -> Speeds {
|
||||
Speeds { history: graph::History::new(SPAN + 2), seen: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Speeds {
|
||||
pub fn follow(&mut self, totals: &Totals) {
|
||||
let h = &totals.history;
|
||||
if h.pushed() < self.seen {
|
||||
*self = Speeds::default();
|
||||
}
|
||||
let new = (h.pushed() - self.seen).min(h.samples().len() as u64) as usize;
|
||||
for s in h.samples().skip(h.samples().len() - new) {
|
||||
self.history.push(f64::from(s));
|
||||
}
|
||||
self.seen = h.pushed();
|
||||
}
|
||||
}
|
||||
|
||||
/// How high the header is in a window of this height.
|
||||
pub fn header_height(window: f32) -> f32 {
|
||||
if window < 480.0 { 72.0 } else { 104.0 }
|
||||
}
|
||||
|
||||
const NUMBER: RangeInclusive<f32> = 232.0..=264.0;
|
||||
|
||||
/// The big speed number, what is going on, and the graph.
|
||||
pub fn header(ui: &mut Ui, t: &Theme, rect: Rect, shot: &Snapshot, speeds: &Speeds, limit: u64) {
|
||||
let totals = &shot.totals;
|
||||
let mut words = vec![];
|
||||
if totals.running > 0 {
|
||||
words.push(tr!("header.running", n = totals.running));
|
||||
}
|
||||
if totals.queued > 0 {
|
||||
words.push(tr!("header.queued", n = totals.queued));
|
||||
}
|
||||
if totals.connections > 0 {
|
||||
words.push(tr!("header.connections", n = totals.connections));
|
||||
}
|
||||
let middle = rect.center().y;
|
||||
let id = Id::unique("total speed");
|
||||
let number = pos2(rect.left(), middle - space::M);
|
||||
let drawn = odometer::speed(ui, t, id, number, totals.speed);
|
||||
let wide = (drawn.width() + space::XL).clamp(*NUMBER.start(), *NUMBER.end()).min(rect.width());
|
||||
let graph_rect = Rect::from_min_max(pos2(rect.left() + wide, rect.top()), rect.max);
|
||||
let graph_there = graph_rect.width() >= 120.0;
|
||||
let room = if graph_there { wide - space::L } else { rect.width() };
|
||||
// What doesn't fit is left out whole, the last first.
|
||||
let mut said = tr!("header.idle");
|
||||
while !words.is_empty() {
|
||||
said = words.iter().cloned().reduce(|a, b| tr!("list.dot", a = a, b = b)).unwrap_or_default();
|
||||
if words.len() == 1 || text_width(ui.painter(), &said, fonts::ui(text::LABEL)) <= room {
|
||||
break;
|
||||
}
|
||||
words.pop();
|
||||
}
|
||||
let words = line(ui.painter(), &said, fonts::ui(text::LABEL), t.on_variant, room);
|
||||
left(ui.painter(), pos2(rect.left(), middle + space::XXL - space::XS), words);
|
||||
if graph_there {
|
||||
graph::graph(ui, t, Id::unique("speed graph"), graph_rect, &speeds.history, (limit > 0).then_some(limit as f64));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum Pick {
|
||||
Host(Option<String>),
|
||||
Age(Option<Age>),
|
||||
Clear,
|
||||
Sort(Sort),
|
||||
Down,
|
||||
Group(Group),
|
||||
Column(Column),
|
||||
}
|
||||
|
||||
/// More hosts than this make no menu.
|
||||
const HOSTS: usize = 20;
|
||||
|
||||
/// Search and the buttons beside it.
|
||||
pub fn top(ui: &mut Ui, t: &Theme, rect: Rect, list: &mut List, focus_search: &mut bool) -> Option<Order> {
|
||||
let mut out = None;
|
||||
let mut ui = ui.new_child(UiBuilder::new().max_rect(rect).layout(Layout::right_to_left(Align::Center)).id_salt("top"));
|
||||
let ui = &mut ui;
|
||||
ui.spacing_mut().item_spacing.x = space::XS;
|
||||
let add = tr!("add.button");
|
||||
let button = if rect.width() < 560.0 { Button::icon("add", &add) } else { Button::new(&add).with_icon("add").tip(&add) };
|
||||
if button.kind(Kind::Filled).keys("Ctrl+N").show(ui, t).clicked() {
|
||||
out = Some(Order::Add);
|
||||
}
|
||||
ui.add_space(space::XS);
|
||||
let cards = list.form == Form::Cards;
|
||||
let (face, name) = if cards { ("view_list", tr!("view.rows")) } else { ("view_agenda", tr!("view.cards")) };
|
||||
if Button::icon(face, &name).show(ui, t).clicked() {
|
||||
list.form = if cards { Form::Compact } else { Form::Cards };
|
||||
}
|
||||
let sort = Button::icon("sort", &tr!("view.sort")).show(ui, t);
|
||||
let picked = menu::below(ui, t, &sort, || sorting(list));
|
||||
let on = list.query.filter.host.is_some() || list.query.filter.age.is_some();
|
||||
let filter = Button::icon("filter_list", &tr!("view.filter")).toggle(on).show(ui, t);
|
||||
let picked = picked.or(menu::below(ui, t, &filter, || filtering(list.listing(), &list.query.filter)));
|
||||
match picked {
|
||||
Some(Pick::Host(h)) => list.query.filter.host = h,
|
||||
Some(Pick::Age(a)) => list.query.filter.age = a,
|
||||
Some(Pick::Clear) => list.query.filter = Filter { search: std::mem::take(&mut list.query.filter.search), ..Filter::default() },
|
||||
Some(Pick::Sort(s)) => (list.query.sort, list.query.down) = (s, false),
|
||||
Some(Pick::Down) => list.query.down = !list.query.down,
|
||||
Some(Pick::Group(g)) => list.query.group = g,
|
||||
Some(Pick::Column(c)) => match list.columns.iter().position(|k| *k == c) {
|
||||
Some(i) => {
|
||||
list.columns.remove(i);
|
||||
}
|
||||
None => list.columns.push(c),
|
||||
},
|
||||
None => {}
|
||||
}
|
||||
ui.add_space(space::XS);
|
||||
let width = ui.available_width();
|
||||
let place = Rect::from_min_size(rect.min, vec2(width.min(480.0), rect.height()));
|
||||
let mut ui = ui.new_child(UiBuilder::new().max_rect(place).layout(Layout::top_down(Align::Min)).id_salt("search"));
|
||||
let before = list.query.filter.search.clone();
|
||||
let r = field::search(&mut ui, t, &tr!("search.name"), &mut list.query.filter.search, place.width());
|
||||
if std::mem::take(focus_search) {
|
||||
r.request_focus();
|
||||
}
|
||||
if list.query.filter.search != before {
|
||||
// Typing is not animated.
|
||||
list.hush(&ui);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn sorting(list: &List) -> Vec<Item<Pick>> {
|
||||
let q = &list.query;
|
||||
let sorts = Sort::ALL.map(|s| Item::new(s.label(), Pick::Sort(s)).checked(q.sort == s));
|
||||
let groups = Group::ALL.map(|g| Item::new(g.label(), Pick::Group(g)).checked(q.group == g));
|
||||
let columns = Column::ALL.map(|c| Item::new(c.label(), Pick::Column(c)).checked(list.columns.contains(&c)));
|
||||
vec![
|
||||
Item::sub(tr!("view.sort_by"), sorts.into()).icon("sort"),
|
||||
Item::new(tr!("view.down"), Pick::Down).checked(q.down),
|
||||
Item::line(),
|
||||
Item::sub(tr!("view.group_by"), groups.into()).icon("stacks"),
|
||||
Item::sub(tr!("view.columns"), columns.into()).icon("view_list"),
|
||||
]
|
||||
}
|
||||
|
||||
fn filtering(listing: &Listing, f: &Filter) -> Vec<Item<Pick>> {
|
||||
let mut ages = vec![Item::new(tr!("age.any"), Pick::Age(None)).checked(f.age.is_none())];
|
||||
ages.extend(Age::ALL.map(|a| Item::new(a.label(), Pick::Age(Some(a))).checked(f.age == Some(a))));
|
||||
let mut hosts = vec![Item::new(tr!("host.any"), Pick::Host(None)).checked(f.host.is_none())];
|
||||
// Those with the most downloads, by name.
|
||||
let mut most: Vec<_> = listing.counts.hosts.iter().collect();
|
||||
most.sort_by_key(|(_, n)| std::cmp::Reverse(*n));
|
||||
most.truncate(HOSTS);
|
||||
most.sort();
|
||||
hosts.extend(most.into_iter().map(|(h, _)| Item::new(host_name(h), Pick::Host(Some(h.to_string()))).checked(f.host.as_deref() == Some(h))));
|
||||
vec![
|
||||
Item::sub(tr!("filter.host"), hosts).icon("public"),
|
||||
Item::sub(tr!("filter.age"), ages).icon("calendar_month"),
|
||||
Item::line(),
|
||||
Item::new(tr!("filter.clear"), Pick::Clear).icon("close").enabled(f.narrow() || f.status != Status::All),
|
||||
]
|
||||
}
|
||||
|
||||
/// What the list is narrowed to, each with a cross. Nothing when the rail shows it already.
|
||||
pub fn chips(ui: &mut Ui, t: &Theme, rect: Rect, filter: &mut Filter, lists: &Lists) {
|
||||
let mut ui = ui.new_child(UiBuilder::new().max_rect(rect).layout(Layout::left_to_right(Align::Center)).id_salt("chips"));
|
||||
let ui = &mut ui;
|
||||
ui.set_clip_rect(rect.expand(size::FOCUS_RING * 2.0));
|
||||
ui.spacing_mut().item_spacing.x = space::S;
|
||||
let mut chip = |name: String, icon: &str| !name.is_empty() && Chip::new(&name).icon(icon).closable().show(ui, t).closed;
|
||||
if filter.queue.is_some_and(|q| chip(queue_name(lists, q), "stacks")) {
|
||||
filter.queue = None;
|
||||
}
|
||||
if filter.tag.is_some_and(|g| chip(lists.tags.iter().find(|x| x.id == g).map(|x| x.name.clone()).unwrap_or_default(), "label")) {
|
||||
filter.tag = None;
|
||||
}
|
||||
if filter.kind.is_some_and(|k| chip(kind_label(k), "category")) {
|
||||
filter.kind = None;
|
||||
}
|
||||
if filter.host.as_deref().is_some_and(|h| chip(host_name(h), "public")) {
|
||||
filter.host = None;
|
||||
}
|
||||
if filter.age.is_some_and(|a| chip(a.label(), "calendar_month")) {
|
||||
filter.age = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_chips(f: &Filter) -> bool {
|
||||
f.queue.is_some() || f.tag.is_some() || f.kind.is_some() || f.host.is_some() || f.age.is_some()
|
||||
}
|
||||
|
||||
/// How much of the list the toolbar may cover.
|
||||
pub const TOOLBAR: f32 = size::CONTROL + 2.0 * space::S + 2.0 * space::L;
|
||||
|
||||
/// The bar of the selected ones.
|
||||
pub fn selected(ui: &Ui, t: &Theme, rect: Rect, list: &mut List) -> Option<Order> {
|
||||
let chosen = list.chosen();
|
||||
let count = chosen.len();
|
||||
let mut act = None;
|
||||
let mut clear = false;
|
||||
let at = pos2(rect.center().x, rect.bottom() - space::L);
|
||||
toolbar(ui.ctx(), t, Id::unique("selected"), at, count > 0, |ui| {
|
||||
let words = tr!("bar.count", n = count.max(1));
|
||||
let wide = text_width(ui.painter(), &words, fonts::med(text::BODY));
|
||||
let (r, _) = ui.allocate_exact_size(vec2(wide + space::L + space::XS, size::CONTROL), eframe::egui::Sense::hover());
|
||||
left(ui.painter(), pos2(r.left() + space::M, r.center().y), line(ui.painter(), &words, fonts::med(text::BODY), t.on_surface, wide + 1.0));
|
||||
let mut button = |icon: &str, name: &str, keys: &str, what: Act, danger: bool| {
|
||||
if Button::icon(icon, name).keys(keys).danger(danger).show(ui, t).clicked() {
|
||||
act = Some(what);
|
||||
}
|
||||
};
|
||||
button("play_arrow", &tr!("act.resume"), "", Act::Resume, false);
|
||||
button("pause", &tr!("act.pause"), "Space", Act::Pause, false);
|
||||
if count <= 1 {
|
||||
button("folder_open", &tr!("act.show"), "", Act::Show, false);
|
||||
}
|
||||
button("content_copy", &tr!("act.copy"), "Ctrl+C", Act::Copy, false);
|
||||
button("close", &tr!("act.remove"), "Del", Act::Remove(Files::Keep), false);
|
||||
button("delete", &tr!("act.delete"), "Shift+Del", Act::Remove(Files::Bin), true);
|
||||
if Button::icon("cancel", &tr!("bar.clear")).keys("Esc").show(ui, t).clicked() {
|
||||
clear = true;
|
||||
}
|
||||
});
|
||||
if clear {
|
||||
list.selected.clear();
|
||||
}
|
||||
act.map(|a| Order::Do(a, chosen))
|
||||
}
|
||||
|
||||
/// A line across the list with something to know.
|
||||
pub fn banner(ui: &mut Ui, t: &Theme, rect: Rect, face: &str, words: &str) {
|
||||
let p = ui.painter();
|
||||
p.rect_filled(rect, tokens::radius::M, t.tertiary_container);
|
||||
icons::paint(p, rect.left_center() + vec2(space::L + icon::M / 2.0, 0.0), icon::M, face, t.on_tertiary_container);
|
||||
let x = rect.left() + space::L + icon::M + space::M;
|
||||
let words = line(p, words, fonts::ui(text::BODY), t.on_tertiary_container, rect.right() - space::L - x);
|
||||
left(p, pos2(x, rect.center().y), words);
|
||||
}
|
||||
169
crates/app/src/views/list/flow.rs
Normal file
169
crates/app/src/views/list/flow.rs
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
//! Rows that move: to their new place when the order changes, in when they are new, out when they go.
|
||||
//!
|
||||
//! Places are worked out first and at once; a row that moved is drawn off its place and springs back to it. Big changes and
|
||||
//! those the keyboard made don't move anything.
|
||||
|
||||
use super::layout::{Key, Layout};
|
||||
use super::model::Listing;
|
||||
use crate::motion::{self, Spring};
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT};
|
||||
use eframe::egui::{Rect, Vec2, vec2};
|
||||
use medlar_core::settings::Motion;
|
||||
use medlar_core::snapshot::TaskView;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// More than this and nothing moves.
|
||||
pub const MOST: usize = 30;
|
||||
|
||||
/// Where a cell is, off its place, and how much of it is there.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Shift {
|
||||
x: Spring,
|
||||
y: Spring,
|
||||
fade: Spring,
|
||||
}
|
||||
|
||||
impl Shift {
|
||||
pub fn offset(&self) -> Vec2 {
|
||||
vec2(self.x.x, self.y.x)
|
||||
}
|
||||
|
||||
pub fn opacity(&self) -> f32 {
|
||||
self.fade.x.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
fn new(offset: Vec2, fade: f32) -> Shift {
|
||||
let off = |x: f32| Spring { target: 0.0, ..Spring::new(x) };
|
||||
Shift { x: off(offset.x), y: off(offset.y), fade: Spring { target: 1.0, ..Spring::new(fade) } }
|
||||
}
|
||||
|
||||
fn settled(&self) -> bool {
|
||||
self.x.settled() && self.y.settled() && self.fade.settled()
|
||||
}
|
||||
}
|
||||
|
||||
/// A row that is gone but still seen.
|
||||
pub struct Ghost {
|
||||
pub view: Arc<TaskView>,
|
||||
pub rect: Rect,
|
||||
pub shift: Shift,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Flow {
|
||||
shifts: HashMap<Key, Shift>,
|
||||
pub ghosts: Vec<Ghost>,
|
||||
}
|
||||
|
||||
/// How many rows came, went or moved against the others, about.
|
||||
fn changes(old: &Layout, new: &Layout) -> usize {
|
||||
let rows = |l: &Layout| l.cells.iter().filter(|c| matches!(c.key, Key::Row(_))).map(|c| c.key).collect::<Vec<_>>();
|
||||
let (a, b) = (rows(old), rows(new));
|
||||
let (in_a, in_b): (HashSet<Key>, HashSet<Key>) = (a.iter().copied().collect(), b.iter().copied().collect());
|
||||
let gone = a.iter().filter(|k| !in_b.contains(k)).count();
|
||||
let came = b.iter().filter(|k| !in_a.contains(k)).count();
|
||||
// A row that moves has another one before it; so have the two it left and joined.
|
||||
let mut last = None;
|
||||
let mut before: HashMap<Key, Option<Key>> = HashMap::with_capacity(a.len());
|
||||
for k in a.iter().filter(|k| in_b.contains(k)) {
|
||||
before.insert(*k, last);
|
||||
last = Some(*k);
|
||||
}
|
||||
last = None;
|
||||
let mut other = 0;
|
||||
for k in b.iter().filter(|k| in_a.contains(k)) {
|
||||
other += usize::from(before[k] != last);
|
||||
last = Some(*k);
|
||||
}
|
||||
gone + came + other.div_ceil(3)
|
||||
}
|
||||
|
||||
impl Flow {
|
||||
/// The list has new places. `seen` is the part of it in the window, `views` the rows there were.
|
||||
pub fn change(&mut self, old: &Layout, old_rows: &[Arc<TaskView>], new: &Layout, listing: &Listing, seen: Range<f32>, quiet: bool) {
|
||||
if old.cells.len() == new.cells.len() && old.cells.iter().zip(&new.cells).all(|(a, b)| a.key == b.key) {
|
||||
return;
|
||||
}
|
||||
if quiet || motion::level() == Motion::Off || listing.rows.is_empty() || old.cells.is_empty() || changes(old, new) > MOST {
|
||||
self.clear();
|
||||
return;
|
||||
}
|
||||
// Never further than this, or a row would cross the window in a flash.
|
||||
let far = (seen.end - seen.start).max(1.0);
|
||||
let was: HashMap<Key, Rect> = old.cells.iter().map(|c| (c.key, old.rect(c))).collect();
|
||||
let is: HashMap<Key, Rect> = new.cells.iter().map(|c| (c.key, new.rect(c))).collect();
|
||||
let shown_now = new.visible(seen.start, seen.end);
|
||||
let shown_then = old.visible(seen.start, seen.end);
|
||||
let moved = new.cells[shown_now.clone()].iter().map(|c| c.key).chain(old.cells[shown_then.clone()].iter().map(|c| c.key)).collect::<HashSet<_>>();
|
||||
for key in moved {
|
||||
match (was.get(&key), is.get(&key)) {
|
||||
(Some(a), Some(b)) => {
|
||||
let offset = a.min - b.min + self.shifts.get(&key).map_or(Vec2::ZERO, Shift::offset);
|
||||
let offset = vec2(offset.x, offset.y.clamp(-far, far));
|
||||
if offset != Vec2::ZERO {
|
||||
let s = self.shifts.entry(key).or_insert_with(|| Shift::new(offset, 1.0));
|
||||
(s.x.x, s.y.x) = (offset.x, offset.y);
|
||||
}
|
||||
}
|
||||
(None, Some(_)) => {
|
||||
self.shifts.insert(key, Shift::new(vec2(0.0, -space()), 0.0));
|
||||
}
|
||||
(Some(a), None) => {
|
||||
let shift = self.shifts.remove(&key).unwrap_or_else(|| Shift::new(Vec2::ZERO, 1.0));
|
||||
let view = old.cells[shown_then.clone()].iter().find(|c| c.key == key).filter(|c| matches!(c.key, Key::Row(_))).and_then(|c| old_rows.get(c.at));
|
||||
if let Some(view) = view {
|
||||
let mut shift = shift;
|
||||
shift.fade.target = 0.0;
|
||||
self.ghosts.push(Ghost { view: view.clone(), rect: *a, shift });
|
||||
}
|
||||
}
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
// A row that came back is no ghost.
|
||||
self.ghosts.retain(|g| !is.contains_key(&Key::Row(g.view.id())));
|
||||
motion::keep_alive();
|
||||
}
|
||||
|
||||
/// Nothing moves any more.
|
||||
pub fn clear(&mut self) {
|
||||
self.shifts.clear();
|
||||
self.ghosts.clear();
|
||||
}
|
||||
|
||||
/// Puts a row that was let go where the pointer left it.
|
||||
pub fn drop_at(&mut self, key: Key, offset: Vec2) {
|
||||
if motion::level() != Motion::Off {
|
||||
self.shifts.insert(key, Shift::new(offset, 1.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Once a frame.
|
||||
pub fn step(&mut self) {
|
||||
for s in self.shifts.values_mut().chain(self.ghosts.iter_mut().map(|g| &mut g.shift)) {
|
||||
s.x.step(DEFAULT);
|
||||
s.y.step(DEFAULT);
|
||||
s.fade.step(EFFECT);
|
||||
}
|
||||
self.shifts.retain(|_, s| !s.settled());
|
||||
self.ghosts.retain(|g| g.shift.fade.x > 0.01);
|
||||
}
|
||||
|
||||
pub fn get(&self, key: Key) -> Option<&Shift> {
|
||||
self.shifts.get(&key)
|
||||
}
|
||||
|
||||
pub fn moving(&self) -> impl Iterator<Item = Key> + '_ {
|
||||
self.shifts.keys().copied()
|
||||
}
|
||||
|
||||
pub fn is_still(&self) -> bool {
|
||||
self.shifts.is_empty() && self.ghosts.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn space() -> f32 {
|
||||
crate::tokens::space::L
|
||||
}
|
||||
126
crates/app/src/views/list/layout.rs
Normal file
126
crates/app/src/views/list/layout.rs
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
//! Where every row and heading is, from the top of the list. Heights are fixed, so this needs no drawing.
|
||||
|
||||
use super::model::Listing;
|
||||
use crate::tokens::space;
|
||||
use eframe::egui::{Rect, pos2, vec2};
|
||||
use medlar_core::model::TaskId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ops::Range;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Form {
|
||||
#[default]
|
||||
Compact,
|
||||
Cards,
|
||||
}
|
||||
|
||||
pub const HEAD: f32 = 40.0;
|
||||
pub const COMPACT: f32 = 56.0;
|
||||
pub const CARD: f32 = 112.0;
|
||||
/// Cards stand side by side when each gets this much.
|
||||
pub const CARD_MIN: f32 = 520.0;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub enum Key {
|
||||
Row(TaskId),
|
||||
Head(u32),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Cell {
|
||||
pub key: Key,
|
||||
/// Which row, or which heading.
|
||||
pub at: usize,
|
||||
y: f32,
|
||||
column: u16,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Layout {
|
||||
pub cells: Vec<Cell>,
|
||||
pub height: f32,
|
||||
pub form: Form,
|
||||
pub columns: usize,
|
||||
width: f32,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
pub fn new(listing: &Listing, form: Form, width: f32) -> Layout {
|
||||
let columns = match form {
|
||||
Form::Compact => 1,
|
||||
Form::Cards => (((width + space::S) / (CARD_MIN + space::S)) as usize).max(1),
|
||||
};
|
||||
let step = match form {
|
||||
Form::Compact => COMPACT,
|
||||
Form::Cards => CARD + space::S,
|
||||
};
|
||||
let mut cells = Vec::with_capacity(listing.rows.len() + listing.heads.len());
|
||||
let (mut y, mut column) = (0.0, 0);
|
||||
let mut heads = listing.heads.iter().enumerate().peekable();
|
||||
for (row, v) in listing.rows.iter().enumerate() {
|
||||
if let Some((i, head)) = heads.next_if(|(_, h)| h.first == row) {
|
||||
if column > 0 {
|
||||
(y, column) = (y + step, 0);
|
||||
}
|
||||
// The same heading stays the same cell when others come and go.
|
||||
let name = head.label.bytes().fold(5381u32, |h, b| h.wrapping_mul(33) ^ u32::from(b));
|
||||
cells.push(Cell { key: Key::Head(name), at: i, y, column: 0 });
|
||||
y += HEAD;
|
||||
}
|
||||
cells.push(Cell { key: Key::Row(v.id()), at: row, y, column });
|
||||
column += 1;
|
||||
if usize::from(column) == columns {
|
||||
(y, column) = (y + step, 0);
|
||||
}
|
||||
}
|
||||
let height = y + if column > 0 { step } else { 0.0 };
|
||||
Layout { cells, height, form, columns, width }
|
||||
}
|
||||
|
||||
pub fn fits(&self, form: Form, width: f32) -> bool {
|
||||
self.form == form && self.width == width
|
||||
}
|
||||
|
||||
pub fn width(&self) -> f32 {
|
||||
self.width
|
||||
}
|
||||
|
||||
/// Relative to the top left of the list.
|
||||
pub fn rect(&self, cell: &Cell) -> Rect {
|
||||
let (w, h) = match (cell.key, self.form) {
|
||||
(Key::Head(_), _) => (self.width, HEAD),
|
||||
(_, Form::Compact) => (self.width, COMPACT),
|
||||
(_, Form::Cards) => ((self.width - space::S * (self.columns - 1) as f32) / self.columns as f32, CARD),
|
||||
};
|
||||
Rect::from_min_size(pos2(f32::from(cell.column) * (w + space::S), cell.y), vec2(w, h))
|
||||
}
|
||||
|
||||
/// The cells that reach into this range of heights.
|
||||
pub fn visible(&self, from: f32, to: f32) -> Range<usize> {
|
||||
let start = self.cells.partition_point(|c| c.y + CARD.max(HEAD) < from);
|
||||
let end = self.cells.partition_point(|c| c.y < to);
|
||||
start..end.max(start)
|
||||
}
|
||||
|
||||
/// The cell of a row. Cells are in the order of rows, with headings between.
|
||||
pub fn of_row(&self, listing: &Listing, row: usize) -> Option<&Cell> {
|
||||
let heads = listing.head_of(row).map_or(0, |h| h + 1);
|
||||
self.cells.get(row + heads)
|
||||
}
|
||||
|
||||
/// Which row a new one at this point would come before.
|
||||
pub fn slot(&self, listing: &Listing, at: eframe::egui::Pos2) -> usize {
|
||||
let mut slot = listing.rows.len();
|
||||
for cell in &self.cells {
|
||||
let Key::Row(_) = cell.key else { continue };
|
||||
let r = self.rect(cell);
|
||||
let before = if self.columns == 1 { at.y < r.center().y } else { at.y < r.top() || (at.y < r.bottom() && at.x < r.center().x) };
|
||||
if before {
|
||||
slot = cell.at;
|
||||
break;
|
||||
}
|
||||
}
|
||||
slot
|
||||
}
|
||||
}
|
||||
727
crates/app/src/views/list/mod.rs
Normal file
727
crates/app/src/views/list/mod.rs
Normal file
|
|
@ -0,0 +1,727 @@
|
|||
//! The list of downloads: rows, selection, keyboard, lasso and reordering. It draws only the rows that are seen.
|
||||
|
||||
pub mod flow;
|
||||
pub mod layout;
|
||||
pub mod model;
|
||||
pub mod row;
|
||||
|
||||
use crate::bridge::Lists;
|
||||
use crate::fonts;
|
||||
use crate::motion;
|
||||
use crate::theme::{Theme, alpha};
|
||||
use crate::tokens::{icon, radius, size, space, text};
|
||||
use crate::ui::menu::{self, Item};
|
||||
use crate::ui::widgets::{cr, left, line};
|
||||
use crate::ui::dialog;
|
||||
use eframe::egui::scroll_area::ScrollSource;
|
||||
use eframe::egui::style::ScrollAnimation;
|
||||
use eframe::egui::{
|
||||
CursorIcon, EventFilter, Id, Key, Modifiers, PointerButton, Pos2, Rect, ScrollArea, Sense, Stroke, StrokeKind, Ui, UiBuilder, Vec2, pos2, vec2,
|
||||
};
|
||||
use flow::Flow;
|
||||
use layout::{Form, Layout};
|
||||
use medlar_core::error::Fix;
|
||||
use medlar_core::manager::Files;
|
||||
use medlar_core::model::{self as core, Priority, QueueId, State, TagId, TaskId, Time};
|
||||
use medlar_core::snapshot::{Snapshot, TaskView};
|
||||
use medlar_core::{strings, tr};
|
||||
use model::{Filter, Listing, Query, Sort, places, queue_name};
|
||||
use row::{Column, Columns, Row};
|
||||
use std::collections::HashSet;
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// What can be done with downloads.
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
pub enum Act {
|
||||
Open,
|
||||
Show,
|
||||
Copy,
|
||||
OpenPage,
|
||||
Start,
|
||||
Resume,
|
||||
Pause,
|
||||
Stop,
|
||||
Redownload,
|
||||
KeepBoth,
|
||||
Remove(Files),
|
||||
Priority(Priority),
|
||||
Queue(QueueId),
|
||||
Tag(TagId, bool),
|
||||
/// Ask for another link, folder or name.
|
||||
EditLink,
|
||||
EditFolder,
|
||||
EditName,
|
||||
/// The network's own sign-in page.
|
||||
Portal,
|
||||
}
|
||||
|
||||
/// What the user wants, for the one who can do it.
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub enum Order {
|
||||
Do(Act, Vec<TaskId>),
|
||||
/// New places: queue and position.
|
||||
Place(Vec<(TaskId, QueueId, f64)>),
|
||||
Add,
|
||||
Find,
|
||||
Paste(String),
|
||||
}
|
||||
|
||||
pub fn act_of_fix(fix: Fix) -> Act {
|
||||
match fix {
|
||||
Fix::TryAgain | Fix::Resume | Fix::CheckNetwork | Fix::SignIn => Act::Resume,
|
||||
Fix::Restart | Fix::Choose => Act::Redownload,
|
||||
Fix::NewLink | Fix::EditLink => Act::EditLink,
|
||||
Fix::FreeSpace => Act::Show,
|
||||
Fix::ChangeFolder => Act::EditFolder,
|
||||
Fix::OpenPortal => Act::Portal,
|
||||
}
|
||||
}
|
||||
|
||||
/// For a file that is another one now.
|
||||
pub fn choices() -> Vec<Item<Act>> {
|
||||
vec![
|
||||
Item::new(tr!("fix.restart"), Act::Redownload).icon("replay"),
|
||||
Item::new(tr!("act.keep_both"), Act::KeepBoth).icon("content_copy"),
|
||||
Item::new(tr!("fix.edit_link"), Act::EditLink).icon("link"),
|
||||
]
|
||||
}
|
||||
|
||||
struct Lasso {
|
||||
/// In the list, not in the window: it stays there when the list scrolls.
|
||||
from: Pos2,
|
||||
/// Selected before.
|
||||
base: HashSet<TaskId>,
|
||||
}
|
||||
|
||||
struct Drag {
|
||||
ids: Vec<TaskId>,
|
||||
lead: TaskId,
|
||||
/// Where in the row it was grabbed.
|
||||
grab: Vec2,
|
||||
}
|
||||
|
||||
/// After something the keyboard did, changes don't move for this long.
|
||||
const QUIET: f64 = 0.5;
|
||||
|
||||
pub struct List {
|
||||
pub query: Query,
|
||||
pub form: Form,
|
||||
pub columns: Vec<Column>,
|
||||
pub selected: HashSet<TaskId>,
|
||||
cursor: Option<TaskId>,
|
||||
/// Where a range starts.
|
||||
anchor: Option<TaskId>,
|
||||
listing: Listing,
|
||||
layout: Layout,
|
||||
flow: Flow,
|
||||
lasso: Option<Lasso>,
|
||||
drag: Option<Drag>,
|
||||
quiet_until: f64,
|
||||
reveal: Option<TaskId>,
|
||||
/// The part of the list in the window.
|
||||
seen: Range<f32>,
|
||||
}
|
||||
|
||||
impl Default for List {
|
||||
fn default() -> List {
|
||||
List {
|
||||
query: Query::default(),
|
||||
form: Form::default(),
|
||||
columns: Column::USUAL.to_vec(),
|
||||
selected: HashSet::new(),
|
||||
cursor: None,
|
||||
anchor: None,
|
||||
listing: Listing::default(),
|
||||
layout: Layout::default(),
|
||||
flow: Flow::default(),
|
||||
lasso: None,
|
||||
drag: None,
|
||||
quiet_until: 0.0,
|
||||
reveal: None,
|
||||
seen: 0.0..0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_id() -> Id {
|
||||
Id::unique("downloads")
|
||||
}
|
||||
|
||||
impl List {
|
||||
pub fn listing(&self) -> &Listing {
|
||||
&self.listing
|
||||
}
|
||||
|
||||
/// Does anything move by itself?
|
||||
pub fn is_still(&self) -> bool {
|
||||
self.flow.is_still()
|
||||
}
|
||||
|
||||
/// The keyboard did something: what comes of it shows at once.
|
||||
pub fn hush(&mut self, ui: &Ui) {
|
||||
self.quiet_until = ui.input(|i| i.time) + QUIET;
|
||||
self.flow.clear();
|
||||
}
|
||||
|
||||
/// Brings the rows up to date. Cheap when nothing changed.
|
||||
pub fn follow(&mut self, ui: &Ui, shot: &Snapshot, lists: &Arc<Lists>) {
|
||||
let today = model::today(core::now());
|
||||
if self.listing.fresh(shot, &self.query, lists, today) {
|
||||
return;
|
||||
}
|
||||
let old = std::mem::take(&mut self.listing.rows);
|
||||
self.listing.update(shot, &self.query, lists, today);
|
||||
let layout = Layout::new(&self.listing, self.layout.form, self.layout.width());
|
||||
let quiet = ui.input(|i| i.time) < self.quiet_until || self.drag.is_some();
|
||||
self.flow.change(&self.layout, &old, &layout, &self.listing, self.seen.clone(), quiet);
|
||||
let same = old.len() == self.listing.rows.len() && old.iter().zip(&self.listing.rows).all(|(a, b)| a.id() == b.id());
|
||||
self.layout = layout;
|
||||
if !same {
|
||||
let there: HashSet<TaskId> = self.listing.rows.iter().map(|v| v.id()).collect();
|
||||
self.selected.retain(|id| there.contains(id));
|
||||
self.cursor = self.cursor.filter(|id| there.contains(id));
|
||||
self.anchor = self.anchor.filter(|id| there.contains(id));
|
||||
if let Some(d) = &mut self.drag {
|
||||
d.ids.retain(|id| there.contains(id));
|
||||
}
|
||||
self.drag = self.drag.take().filter(|d| there.contains(&d.lead));
|
||||
}
|
||||
}
|
||||
|
||||
fn row_of(&self, id: TaskId) -> Option<usize> {
|
||||
self.listing.rows.iter().position(|v| v.id() == id)
|
||||
}
|
||||
|
||||
fn movable(&self) -> bool {
|
||||
self.query.sort == Sort::Queue && !self.query.down && self.listing.rows.len() > 1
|
||||
}
|
||||
|
||||
/// The selected ones in the order of the list.
|
||||
pub fn chosen(&self) -> Vec<TaskId> {
|
||||
if self.selected.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
self.listing.rows.iter().map(|v| v.id()).filter(|id| self.selected.contains(id)).collect()
|
||||
}
|
||||
|
||||
fn select_range(&mut self, to: TaskId, keep: bool) {
|
||||
let (Some(b), a) = (self.row_of(to), self.anchor.and_then(|a| self.row_of(a))) else { return };
|
||||
let a = a.unwrap_or(b);
|
||||
if !keep {
|
||||
self.selected.clear();
|
||||
}
|
||||
self.selected.extend(self.listing.rows[a.min(b)..=a.max(b)].iter().map(|v| v.id()));
|
||||
self.anchor = self.anchor.or(Some(to));
|
||||
}
|
||||
|
||||
fn click(&mut self, id: TaskId, m: Modifiers) {
|
||||
if m.shift {
|
||||
self.select_range(id, m.command);
|
||||
} else if m.command {
|
||||
if !self.selected.remove(&id) {
|
||||
self.selected.insert(id);
|
||||
}
|
||||
self.anchor = Some(id);
|
||||
} else {
|
||||
self.selected = HashSet::from([id]);
|
||||
self.anchor = Some(id);
|
||||
}
|
||||
self.cursor = Some(id);
|
||||
}
|
||||
|
||||
/// Draws the list in `rect`. The last rows can be scrolled up by `below`, over which something floats.
|
||||
pub fn show(&mut self, ui: &mut Ui, t: &Theme, rect: Rect, lists: &Arc<Lists>, below: f32) -> Vec<Order> {
|
||||
let mut orders = vec![];
|
||||
let width = rect.width() - space::M;
|
||||
let columns = Columns::fit(width, &self.columns);
|
||||
let mut body = rect;
|
||||
if self.form == Form::Compact && rect.width() > 640.0 && rect.height() > 4.0 * layout::COMPACT {
|
||||
let (head, rest) = rect.split_top_bottom_at_y(rect.top() + size::HIT);
|
||||
body = rest;
|
||||
let sort = row::header(ui, t, head.with_max_x(rect.left() + width), &columns, self.query.sort, self.query.down);
|
||||
if let Some(sort) = sort {
|
||||
self.sort(sort);
|
||||
}
|
||||
let y = head.bottom() - 0.5;
|
||||
ui.painter().hline(rect.left()..=rect.left() + width, y, Stroke::new(size::HAIRLINE, t.outline_variant));
|
||||
}
|
||||
let mut child = ui.new_child(UiBuilder::new().max_rect(body).id_salt("list"));
|
||||
// Under everything: takes the keyboard, and the lasso where there are no rows.
|
||||
let ground = child.interact(body, list_id(), Sense::CLICK | Sense::DRAG | Sense::FOCUSABLE);
|
||||
ground.widget_info(|| eframe::egui::WidgetInfo::labeled(eframe::egui::accesskit::Role::ListBox, true, tr!("list.name")));
|
||||
if ground.has_focus() {
|
||||
let filter = EventFilter { tab: false, horizontal_arrows: true, vertical_arrows: true, escape: true };
|
||||
child.memory_mut(|m| m.set_focus_lock_filter(list_id(), filter));
|
||||
}
|
||||
self.keys(&child, &mut orders);
|
||||
let scroll = ScrollArea::vertical()
|
||||
.id_salt("rows")
|
||||
.auto_shrink(false)
|
||||
.scroll_source(ScrollSource { drag: eframe::egui::scroll_area::DragScroll::Never, ..ScrollSource::default() });
|
||||
scroll.show_viewport(&mut child, |ui, viewport| {
|
||||
ui.spacing_mut().item_spacing = Vec2::ZERO;
|
||||
if !self.layout.fits(self.form, width) {
|
||||
self.layout = Layout::new(&self.listing, self.form, width);
|
||||
self.flow.clear();
|
||||
}
|
||||
let origin = ui.min_rect().min;
|
||||
ui.set_width(width);
|
||||
ui.set_height(self.layout.height + below);
|
||||
self.seen = viewport.min.y..viewport.max.y;
|
||||
self.reveal(ui, origin, below);
|
||||
self.flow.step();
|
||||
let mut frame = Frame { t, origin, columns: &columns, lists, now: core::now(), focused: ground.has_focus(), cursor_rect: None };
|
||||
self.rows(ui, &mut frame, &mut orders);
|
||||
let cursor = frame.cursor_rect;
|
||||
self.lasso(ui, t, origin, &ground);
|
||||
self.drop(ui, t, &mut frame, &mut orders);
|
||||
// The keyboard's menu comes out of the row it is on.
|
||||
let mut at = ground.clone();
|
||||
at.rect = cursor.unwrap_or(ground.rect);
|
||||
if !self.selected.is_empty()
|
||||
&& let Some(act) = menu::context(ui, t, &at, || self.items(lists))
|
||||
{
|
||||
orders.push(Order::Do(act, self.chosen()));
|
||||
}
|
||||
});
|
||||
// Not `clicked`: Space and Enter belong to the rows.
|
||||
if ground.clicked_by(PointerButton::Primary) {
|
||||
ground.request_focus();
|
||||
self.selected.clear();
|
||||
}
|
||||
orders
|
||||
}
|
||||
|
||||
/// Sorts by `sort`, or the other way round when it was already.
|
||||
pub fn sort(&mut self, sort: Sort) {
|
||||
self.query.down = self.query.sort == sort && !self.query.down;
|
||||
self.query.sort = sort;
|
||||
}
|
||||
|
||||
fn reveal(&mut self, ui: &Ui, origin: Pos2, below: f32) {
|
||||
let Some(id) = self.reveal.take() else { return };
|
||||
let Some(cell) = self.row_of(id).and_then(|r| self.layout.of_row(&self.listing, r)) else { return };
|
||||
let r = self.layout.rect(cell);
|
||||
// The first row brings its heading along; the last stays clear of what floats there.
|
||||
let top = if cell.at == 0 { 0.0 } else { r.top() };
|
||||
let r = Rect::from_min_max(pos2(r.left(), top), pos2(r.right(), r.bottom() + if below > space::L { below } else { 0.0 }));
|
||||
if r.top() < self.seen.start || r.bottom() > self.seen.end {
|
||||
ui.scroll_to_rect_animation(r.translate(origin.to_vec2()), None, ScrollAnimation::none());
|
||||
}
|
||||
}
|
||||
|
||||
fn rows(&mut self, ui: &mut Ui, f: &mut Frame, orders: &mut Vec<Order>) {
|
||||
let range = self.layout.visible(self.seen.start, self.seen.end);
|
||||
// Those that move are drawn over those that rest, the one in the hand over all.
|
||||
let mut first = vec![];
|
||||
let mut later = vec![];
|
||||
for i in range.clone() {
|
||||
let key = self.layout.cells[i].key;
|
||||
if self.flow.get(key).is_some() { later.push(i) } else { first.push(i) }
|
||||
}
|
||||
if !self.flow.is_still() {
|
||||
let moving: HashSet<layout::Key> = self.flow.moving().collect();
|
||||
let seen = self.layout.cells[range.clone()].iter().map(|c| c.key).collect::<HashSet<_>>();
|
||||
if moving.iter().any(|k| !seen.contains(k)) {
|
||||
later.extend(self.layout.cells.iter().enumerate().filter(|(i, c)| !range.contains(i) && moving.contains(&c.key)).map(|(i, _)| i));
|
||||
}
|
||||
let ghosts = std::mem::take(&mut self.flow.ghosts);
|
||||
for g in &ghosts {
|
||||
let rect = g.rect.translate(f.origin.to_vec2() + g.shift.offset());
|
||||
let row = self.row(&g.view, f, false);
|
||||
row::ghost(ui, f.t, rect, &row, g.shift.opacity());
|
||||
}
|
||||
self.flow.ghosts = ghosts;
|
||||
}
|
||||
let lead = self.drag.as_ref().map(|d| d.lead);
|
||||
for i in first.into_iter().chain(later) {
|
||||
let cell = self.layout.cells[i];
|
||||
let (offset, opacity) = self.flow.get(cell.key).map_or((Vec2::ZERO, 1.0), |s| (s.offset(), s.opacity()));
|
||||
let rect = self.layout.rect(&cell).translate(f.origin.to_vec2() + offset);
|
||||
match cell.key {
|
||||
layout::Key::Head(_) => self.head(ui, f, cell.at, rect, opacity),
|
||||
// Its place is kept, and it is drawn in the hand.
|
||||
layout::Key::Row(id) if Some(id) == lead => {
|
||||
ui.painter().rect_stroke(rect.shrink(2.0), cr(radius::M), Stroke::new(size::HAIRLINE, f.t.outline_variant), StrokeKind::Inside);
|
||||
}
|
||||
layout::Key::Row(_) => self.one(ui, f, cell.at, rect, opacity, orders),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn row<'a>(&self, view: &'a TaskView, f: &Frame<'a>, cursor: bool) -> Row<'a> {
|
||||
Row {
|
||||
view,
|
||||
kind: self.listing.kind(view.id()),
|
||||
lists: f.lists,
|
||||
form: self.form,
|
||||
columns: f.columns,
|
||||
selected: self.selected.contains(&view.id()),
|
||||
cursor,
|
||||
movable: self.movable(),
|
||||
carried: false,
|
||||
now: f.now,
|
||||
}
|
||||
}
|
||||
|
||||
fn one(&mut self, ui: &mut Ui, f: &mut Frame, at: usize, rect: Rect, opacity: f32, orders: &mut Vec<Order>) {
|
||||
let view = self.listing.rows[at].clone();
|
||||
let id = view.id();
|
||||
let cursor = f.focused && self.cursor == Some(id);
|
||||
if self.cursor == Some(id) {
|
||||
f.cursor_rect = Some(rect);
|
||||
}
|
||||
let dim = if self.drag.as_ref().is_some_and(|d| d.ids.contains(&id)) { 0.4 } else { 1.0 };
|
||||
let frame = Frame { cursor_rect: None, ..*f };
|
||||
let out = row::draw(ui, f.t, rect, &self.row(&view, &frame, cursor), opacity * dim);
|
||||
if out.row.clicked() {
|
||||
ui.memory_mut(|m| m.request_focus(list_id()));
|
||||
self.click(id, ui.input(|i| i.modifiers));
|
||||
}
|
||||
if out.row.double_clicked() {
|
||||
let act = if view.state() == State::Done { Act::Open } else { row::quick(view.state()).0 };
|
||||
orders.push(Order::Do(act, vec![id]));
|
||||
}
|
||||
if out.row.secondary_clicked() {
|
||||
ui.memory_mut(|m| m.request_focus(list_id()));
|
||||
if !self.selected.contains(&id) {
|
||||
self.click(id, Modifiers::NONE);
|
||||
}
|
||||
self.cursor = Some(id);
|
||||
}
|
||||
if let Some(act) = menu::context(ui, f.t, &out.row, || self.items(f.lists)) {
|
||||
orders.push(Order::Do(act, self.chosen()));
|
||||
}
|
||||
if let Some(act) = out.act {
|
||||
orders.push(Order::Do(act, vec![id]));
|
||||
}
|
||||
if out.row.drag_started_by(PointerButton::Primary) {
|
||||
self.begin_lasso(ui, f.origin);
|
||||
}
|
||||
if out.handle.drag_started_by(PointerButton::Primary) {
|
||||
if !self.selected.contains(&id) {
|
||||
self.click(id, Modifiers::NONE);
|
||||
}
|
||||
let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(rect.center());
|
||||
self.drag = Some(Drag { ids: self.chosen(), lead: id, grab: press - rect.min });
|
||||
self.flow.clear();
|
||||
}
|
||||
}
|
||||
|
||||
fn head(&self, ui: &Ui, f: &Frame, at: usize, rect: Rect, opacity: f32) {
|
||||
let Some(head) = self.listing.heads.get(at) else { return };
|
||||
let p = ui.painter();
|
||||
let y = rect.bottom() - space::L;
|
||||
let count = line(p, &head.count.to_string(), fonts::ui(text::LABEL), alpha(f.t.on_variant, opacity), 96.0);
|
||||
let x = rect.left() + row::HEAD_X;
|
||||
let words = line(p, &head.label, fonts::med(text::LABEL), alpha(f.t.on_surface, opacity), rect.right() - x - count.size().x - space::XL);
|
||||
let end = x + words.size().x + space::S;
|
||||
left(p, pos2(x, y), words);
|
||||
left(p, pos2(end, y), count);
|
||||
}
|
||||
|
||||
fn begin_lasso(&mut self, ui: &Ui, origin: Pos2) {
|
||||
let Some(press) = ui.input(|i| i.pointer.press_origin()) else { return };
|
||||
let keep = ui.input(|i| i.modifiers.command || i.modifiers.shift);
|
||||
let base = if keep { self.selected.clone() } else { HashSet::new() };
|
||||
self.lasso = Some(Lasso { from: press - origin.to_vec2(), base });
|
||||
ui.memory_mut(|m| m.request_focus(list_id()));
|
||||
}
|
||||
|
||||
fn lasso(&mut self, ui: &Ui, t: &Theme, origin: Pos2, ground: &eframe::egui::Response) {
|
||||
if ground.drag_started_by(PointerButton::Primary) {
|
||||
self.begin_lasso(ui, origin);
|
||||
}
|
||||
let (down, at) = ui.input(|i| (i.pointer.primary_down(), i.pointer.latest_pos()));
|
||||
let (Some(lasso), Some(at)) = (&self.lasso, at) else { return };
|
||||
if !down {
|
||||
self.lasso = None;
|
||||
return;
|
||||
}
|
||||
scroll_at_edges(ui, at);
|
||||
let rect = Rect::from_two_pos(lasso.from, at - origin.to_vec2());
|
||||
let range = self.layout.visible(rect.top(), rect.bottom());
|
||||
let mut now = lasso.base.clone();
|
||||
for cell in &self.layout.cells[range] {
|
||||
if let layout::Key::Row(id) = cell.key
|
||||
&& self.layout.rect(cell).intersects(rect)
|
||||
{
|
||||
now.insert(id);
|
||||
}
|
||||
}
|
||||
self.selected = now;
|
||||
let shown = rect.translate(origin.to_vec2());
|
||||
let p = ui.painter();
|
||||
p.rect(shown, cr(radius::XS), alpha(t.primary, 0.12), Stroke::new(size::HAIRLINE, t.primary), StrokeKind::Inside);
|
||||
}
|
||||
|
||||
/// A row in the hand: where it would go, and what happens when it is let go.
|
||||
fn drop(&mut self, ui: &mut Ui, t: &Theme, f: &mut Frame, orders: &mut Vec<Order>) {
|
||||
let Some(drag) = &self.drag else { return };
|
||||
let (down, at, escape) = ui.input(|i| (i.pointer.primary_down(), i.pointer.latest_pos(), i.key_pressed(Key::Escape)));
|
||||
let Some(at) = at.filter(|_| !escape) else {
|
||||
self.drag = None;
|
||||
return;
|
||||
};
|
||||
let Some(row) = self.row_of(drag.lead) else { return };
|
||||
let slot = self.layout.slot(&self.listing, at - f.origin.to_vec2());
|
||||
let moves = places(&self.listing, &drag.ids, slot);
|
||||
let home = self.layout.of_row(&self.listing, row).map(|c| self.layout.rect(c)).unwrap_or(Rect::NOTHING);
|
||||
let carried = Rect::from_min_size(at - drag.grab, home.size());
|
||||
if !down {
|
||||
self.flow.drop_at(layout::Key::Row(drag.lead), carried.min - f.origin.to_vec2() - home.min);
|
||||
self.drag = None;
|
||||
if !moves.is_empty() {
|
||||
orders.push(Order::Place(moves));
|
||||
}
|
||||
return;
|
||||
}
|
||||
scroll_at_edges(ui, at);
|
||||
ui.ctx().set_cursor_icon(CursorIcon::Grabbing);
|
||||
self.mark(ui, t, f.origin, row, slot);
|
||||
let view = self.listing.rows[row].clone();
|
||||
let count = drag.ids.len();
|
||||
let frame = Frame { cursor_rect: None, ..*f };
|
||||
let own = Row { carried: true, ..self.row(&view, &frame, false) };
|
||||
let mut over = ui.new_child(UiBuilder::new().max_rect(carried).id_salt("carried"));
|
||||
over.set_clip_rect(over.ctx().content_rect());
|
||||
row::draw(&mut over, t, carried, &own, 1.0);
|
||||
if count > 1 {
|
||||
let shown = over.painter();
|
||||
let words = line(shown, &count.to_string(), fonts::med(text::LABEL), t.on_primary, 96.0);
|
||||
let badge = Rect::from_center_size(carried.right_top() + vec2(-space::S, space::S), vec2((words.size().x + space::M).max(icon::L), icon::L));
|
||||
shown.rect_filled(badge, cr(radius::FULL), t.primary);
|
||||
shown.galley(badge.center() - words.size() / 2.0, words, t.on_primary);
|
||||
}
|
||||
}
|
||||
|
||||
/// The line where a dragged row would land, within its heading.
|
||||
fn mark(&self, ui: &Ui, t: &Theme, origin: Pos2, row: usize, slot: usize) {
|
||||
let range = match self.listing.head_of(row) {
|
||||
Some(h) => self.listing.heads[h].first..self.listing.heads[h].first + self.listing.heads[h].count,
|
||||
None => 0..self.listing.rows.len(),
|
||||
};
|
||||
let slot = slot.clamp(range.start, range.end);
|
||||
let end = slot == range.end;
|
||||
let Some(cell) = self.layout.of_row(&self.listing, if end { slot - 1 } else { slot }) else { return };
|
||||
let r = self.layout.rect(cell).translate(origin.to_vec2());
|
||||
let (p, stroke) = (ui.painter(), Stroke::new(2.0 * size::FOCUS_RING - 1.0, t.primary));
|
||||
if self.layout.columns == 1 {
|
||||
let y = if end { r.bottom() } else { r.top() };
|
||||
p.hline(r.left() + space::XS..=r.right() - space::XS, y, stroke);
|
||||
p.circle_filled(pos2(r.left() + space::XS, y), space::XS, t.primary);
|
||||
} else {
|
||||
let x = if end { r.right() + space::XS } else { r.left() - space::XS };
|
||||
p.vline(x, r.top() + space::XS..=r.bottom() - space::XS, stroke);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the menu offers for the selected ones.
|
||||
fn items(&self, lists: &Lists) -> Vec<Item<Act>> {
|
||||
let views: Vec<&Arc<TaskView>> = self.listing.rows.iter().filter(|v| self.selected.contains(&v.id())).collect();
|
||||
let Some(first) = views.first() else { return vec![] };
|
||||
let one = views.len() == 1;
|
||||
let any = |f: &dyn Fn(State) -> bool| views.iter().any(|v| f(v.state()));
|
||||
let ended = |s: State| matches!(s, State::Done | State::Gone);
|
||||
let mut items = vec![
|
||||
Item::new(tr!("act.open"), Act::Open).icon("open_in_new").keys("Enter").enabled(one && first.state() == State::Done),
|
||||
Item::new(tr!("act.show"), Act::Show).icon("folder_open").enabled(one),
|
||||
Item::new(tr!("act.copy"), Act::Copy).icon("content_copy").keys("Ctrl+C"),
|
||||
];
|
||||
if one && first.task.source_page.is_some() {
|
||||
items.push(Item::new(tr!("act.page"), Act::OpenPage).icon("public"));
|
||||
}
|
||||
items.push(Item::line());
|
||||
let begun = |s: State| matches!(s, State::Running | State::Checking | State::Finishing);
|
||||
items.push(Item::new(tr!("act.start"), Act::Start).icon("bolt").enabled(any(&|s| !begun(s) && !ended(s))));
|
||||
items.push(Item::new(tr!("act.resume"), Act::Resume).icon("play_arrow").enabled(any(&|s| matches!(s, State::Paused | State::Failed | State::Waiting))));
|
||||
items.push(Item::new(tr!("act.pause"), Act::Pause).icon("pause").enabled(any(&|s| begun(s) || matches!(s, State::Queued | State::Waiting))));
|
||||
items.push(Item::new(tr!("act.stop"), Act::Stop).icon("low_priority").enabled(any(&|s| !ended(s))));
|
||||
items.push(Item::line());
|
||||
let priorities = Priority::ALL.iter().rev().map(|p| {
|
||||
Item::new(strings::text(&format!("priority.{}", p.name()), &[]), Act::Priority(*p)).checked(views.iter().all(|v| v.task.priority == *p))
|
||||
});
|
||||
items.push(Item::sub(tr!("act.priority"), priorities.collect()).icon("priority_high"));
|
||||
if lists.queues.len() > 1 {
|
||||
let queues = lists.queues.iter().map(|q| Item::new(queue_name(lists, q.id), Act::Queue(q.id)).checked(views.iter().all(|v| v.task.queue == q.id)));
|
||||
items.push(Item::sub(tr!("act.queue"), queues.collect()).icon("stacks"));
|
||||
}
|
||||
if !lists.tags.is_empty() {
|
||||
let tags = lists.tags.iter().map(|tag| {
|
||||
let on = views.iter().all(|v| v.task.tags.contains(&tag.id));
|
||||
Item::new(&tag.name, Act::Tag(tag.id, !on)).checked(on)
|
||||
});
|
||||
items.push(Item::sub(tr!("act.tags"), tags.collect()).icon("label"));
|
||||
}
|
||||
items.push(Item::line());
|
||||
if one {
|
||||
items.push(Item::new(tr!("act.rename"), Act::EditName).icon("edit").keys("F2"));
|
||||
items.push(Item::new(tr!("act.move"), Act::EditFolder).icon("folder"));
|
||||
items.push(Item::new(tr!("fix.edit_link"), Act::EditLink).icon("link").enabled(!ended(first.state())));
|
||||
}
|
||||
items.push(Item::new(tr!("act.redownload"), Act::Redownload).icon("replay"));
|
||||
items.push(Item::line());
|
||||
items.push(Item::new(tr!("act.remove"), Act::Remove(Files::Keep)).icon("close").keys("Del"));
|
||||
items.push(Item::new(tr!("act.delete"), Act::Remove(Files::Bin)).icon("delete").keys("Shift+Del").danger());
|
||||
items
|
||||
}
|
||||
|
||||
/// The keyboard, while nothing else has it.
|
||||
pub fn keys(&mut self, ui: &Ui, orders: &mut Vec<Order>) {
|
||||
let ctx = ui.ctx();
|
||||
if menu::any_open(ctx) || dialog::any_open(ctx) || self.drag.is_some() {
|
||||
return;
|
||||
}
|
||||
let focused = ui.memory(|m| m.focused());
|
||||
let key = |m: Modifiers, k: Key| ui.input_mut(|i| i.consume_key(m, k));
|
||||
// These work wherever the keyboard is.
|
||||
if key(Modifiers::COMMAND, Key::F) {
|
||||
orders.push(Order::Find);
|
||||
}
|
||||
if key(Modifiers::COMMAND, Key::N) {
|
||||
orders.push(Order::Add);
|
||||
}
|
||||
if focused.is_some_and(|f| f != list_id()) {
|
||||
return;
|
||||
}
|
||||
let events = ui.input(|i| i.events.clone());
|
||||
for e in events {
|
||||
match e {
|
||||
eframe::egui::Event::Copy => orders.push(Order::Do(Act::Copy, self.chosen())),
|
||||
eframe::egui::Event::Paste(text) => orders.push(Order::Paste(text)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if key(Modifiers::COMMAND, Key::A) {
|
||||
self.selected = self.listing.rows.iter().map(|v| v.id()).collect();
|
||||
}
|
||||
if key(Modifiers::NONE, Key::Escape) {
|
||||
self.selected.clear();
|
||||
}
|
||||
for (m, k, step) in [(Modifiers::ALT, Key::ArrowUp, -1), (Modifiers::ALT, Key::ArrowDown, 1)] {
|
||||
if key(m, k) {
|
||||
self.hush(ui);
|
||||
orders.extend(self.nudge(step));
|
||||
}
|
||||
}
|
||||
let page = ((self.seen.end - self.seen.start) / layout::COMPACT) as isize * self.layout.columns as isize;
|
||||
let line = self.layout.columns as isize;
|
||||
let n = self.listing.rows.len() as isize;
|
||||
let mut steps = vec![(Key::ArrowUp, -line), (Key::ArrowDown, line), (Key::PageUp, -page), (Key::PageDown, page), (Key::Home, -n), (Key::End, n)];
|
||||
if line > 1 {
|
||||
steps.extend([(Key::ArrowLeft, -1), (Key::ArrowRight, 1)]);
|
||||
}
|
||||
for (k, step) in steps {
|
||||
for m in [Modifiers::SHIFT | Modifiers::COMMAND, Modifiers::SHIFT, Modifiers::COMMAND, Modifiers::NONE] {
|
||||
if key(m, k) {
|
||||
self.step(step, m);
|
||||
ui.memory_mut(|mem| mem.request_focus(list_id()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if key(Modifiers::COMMAND, Key::Space)
|
||||
&& let Some(id) = self.cursor
|
||||
{
|
||||
self.click(id, Modifiers::COMMAND);
|
||||
}
|
||||
let chosen = self.chosen();
|
||||
let Some(first) = self.listing.rows.iter().find(|v| self.selected.contains(&v.id())).cloned() else { return };
|
||||
let mut act = |act: Act| {
|
||||
orders.push(Order::Do(act, chosen.clone()));
|
||||
};
|
||||
let mut did = true;
|
||||
if key(Modifiers::SHIFT, Key::Delete) {
|
||||
act(Act::Remove(Files::Bin));
|
||||
} else if key(Modifiers::NONE, Key::Delete) {
|
||||
act(Act::Remove(Files::Keep));
|
||||
} else if key(Modifiers::NONE, Key::Space) {
|
||||
// All of them the same way: pause if anything runs.
|
||||
let going = |s: State| matches!(s, State::Running | State::Checking | State::Finishing | State::Queued | State::Waiting);
|
||||
let any = self.listing.rows.iter().any(|v| self.selected.contains(&v.id()) && going(v.state()));
|
||||
act(if any { Act::Pause } else { Act::Resume });
|
||||
} else if key(Modifiers::NONE, Key::Enter) {
|
||||
act(if first.state() == State::Done { Act::Open } else { row::quick(first.state()).0 });
|
||||
} else if chosen.len() == 1 && key(Modifiers::NONE, Key::F2) {
|
||||
act(Act::EditName);
|
||||
} else {
|
||||
did = false;
|
||||
}
|
||||
if did {
|
||||
// The next row takes the keyboard when this one goes.
|
||||
self.hush(ui);
|
||||
let last = self.row_of(*chosen.last().expect("not empty")).unwrap_or(0);
|
||||
let rest = |v: &&Arc<TaskView>| !self.selected.contains(&v.id());
|
||||
let next = self.listing.rows[last..].iter().find(rest).or_else(|| self.listing.rows[..last].iter().rev().find(rest));
|
||||
if matches!(orders.last(), Some(Order::Do(Act::Remove(_), _))) {
|
||||
self.cursor = next.map(|v| v.id());
|
||||
self.anchor = self.cursor;
|
||||
self.selected = self.cursor.into_iter().collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn step(&mut self, step: isize, m: Modifiers) {
|
||||
let n = self.listing.rows.len() as isize;
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let at = match self.cursor.and_then(|id| self.row_of(id)) {
|
||||
Some(at) => (at as isize + step).clamp(0, n - 1),
|
||||
None if step < 0 => if step <= -n { 0 } else { n - 1 },
|
||||
None => if step >= n { n - 1 } else { 0 },
|
||||
};
|
||||
let id = self.listing.rows[at as usize].id();
|
||||
self.cursor = Some(id);
|
||||
self.reveal = Some(id);
|
||||
if m.shift {
|
||||
self.select_range(id, m.command);
|
||||
} else if !m.command {
|
||||
self.selected = HashSet::from([id]);
|
||||
self.anchor = Some(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the selected ones a row up or down.
|
||||
fn nudge(&mut self, step: isize) -> Option<Order> {
|
||||
let chosen = self.chosen();
|
||||
if chosen.is_empty() || !self.movable() {
|
||||
return None;
|
||||
}
|
||||
let first = self.row_of(chosen[0])?;
|
||||
let last = self.row_of(*chosen.last()?)?;
|
||||
let to = if step < 0 { first.checked_sub(1)? } else { last + 2 };
|
||||
self.reveal = Some(if step < 0 { chosen[0] } else { *chosen.last()? });
|
||||
let moves = places(&self.listing, &chosen, to);
|
||||
(!moves.is_empty()).then_some(Order::Place(moves))
|
||||
}
|
||||
}
|
||||
|
||||
/// What all rows of a frame share.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Frame<'a> {
|
||||
t: &'a Theme,
|
||||
origin: Pos2,
|
||||
columns: &'a Columns,
|
||||
lists: &'a Arc<Lists>,
|
||||
now: Time,
|
||||
focused: bool,
|
||||
cursor_rect: Option<Rect>,
|
||||
}
|
||||
|
||||
/// A drag near the top or bottom scrolls.
|
||||
fn scroll_at_edges(ui: &Ui, at: Pos2) {
|
||||
let seen = ui.clip_rect();
|
||||
let edge = space::XXL;
|
||||
let over = (seen.top() + edge - at.y).max(0.0) - (at.y - seen.bottom() + edge).max(0.0);
|
||||
if over != 0.0 {
|
||||
let step = over.clamp(-2.0 * edge, 2.0 * edge) * 16.0 * motion::dt();
|
||||
ui.scroll_with_delta_animation(vec2(0.0, step), ScrollAnimation::none());
|
||||
motion::keep_alive();
|
||||
}
|
||||
}
|
||||
|
||||
/// Has the filter more than its status, and does it leave nothing?
|
||||
pub fn nothing_found(filter: &Filter, listing: &Listing, total: usize) -> bool {
|
||||
total > 0 && listing.rows.is_empty() && (filter.narrow() || filter.status != model::Status::All)
|
||||
}
|
||||
498
crates/app/src/views/list/model.rs
Normal file
498
crates/app/src/views/list/model.rs
Normal file
|
|
@ -0,0 +1,498 @@
|
|||
//! Which downloads the list shows and in which order. Nothing here draws.
|
||||
|
||||
use crate::bridge::Lists;
|
||||
use crate::ui::shape::Kind;
|
||||
use chrono::{Local, TimeZone};
|
||||
use medlar_core::model::{ErrorKind, QueueId, State, TagId, Task, TaskId, Time};
|
||||
use medlar_core::snapshot::{Snapshot, TaskView};
|
||||
use medlar_core::{strings, tr};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// What the rail's first section tells apart.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Hash)]
|
||||
pub enum Status {
|
||||
#[default]
|
||||
All,
|
||||
Active,
|
||||
Waiting,
|
||||
Paused,
|
||||
Failed,
|
||||
Done,
|
||||
}
|
||||
|
||||
impl Status {
|
||||
pub const ALL: [Status; 6] = [Status::All, Status::Active, Status::Waiting, Status::Paused, Status::Failed, Status::Done];
|
||||
|
||||
pub fn of(s: State) -> Status {
|
||||
match s {
|
||||
State::Running | State::Checking | State::Finishing => Status::Active,
|
||||
State::Queued | State::Waiting => Status::Waiting,
|
||||
State::Paused => Status::Paused,
|
||||
State::Failed => Status::Failed,
|
||||
State::Done | State::Gone => Status::Done,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn icon(self) -> &'static str {
|
||||
match self {
|
||||
Status::All => "list",
|
||||
Status::Active => "download",
|
||||
Status::Waiting => "schedule",
|
||||
Status::Paused => "pause",
|
||||
Status::Failed => "error",
|
||||
Status::Done => "download_done",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> String {
|
||||
let name = match self {
|
||||
Status::All => "all",
|
||||
Status::Active => "active",
|
||||
Status::Waiting => "waiting",
|
||||
Status::Paused => "paused",
|
||||
Status::Failed => "failed",
|
||||
Status::Done => "done",
|
||||
};
|
||||
strings::text(&format!("status.{name}"), &[])
|
||||
}
|
||||
}
|
||||
|
||||
/// When a download was added.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
|
||||
pub enum Age {
|
||||
Today,
|
||||
Yesterday,
|
||||
Week,
|
||||
Month,
|
||||
Older,
|
||||
}
|
||||
|
||||
impl Age {
|
||||
pub const ALL: [Age; 5] = [Age::Today, Age::Yesterday, Age::Week, Age::Month, Age::Older];
|
||||
|
||||
/// `today` is when this day began.
|
||||
pub fn of(added: Time, today: Time) -> Age {
|
||||
const DAY: Time = 24 * 3600 * 1000;
|
||||
match today - added {
|
||||
d if d <= 0 => Age::Today,
|
||||
d if d <= DAY => Age::Yesterday,
|
||||
d if d <= 6 * DAY => Age::Week,
|
||||
d if d <= 29 * DAY => Age::Month,
|
||||
_ => Age::Older,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> String {
|
||||
let name = match self {
|
||||
Age::Today => "today",
|
||||
Age::Yesterday => "yesterday",
|
||||
Age::Week => "week",
|
||||
Age::Month => "month",
|
||||
Age::Older => "older",
|
||||
};
|
||||
strings::text(&format!("age.{name}"), &[])
|
||||
}
|
||||
}
|
||||
|
||||
/// When today began, here.
|
||||
pub fn today(now: Time) -> Time {
|
||||
let local = Local.timestamp_millis_opt(now).single();
|
||||
let midnight = local.and_then(|l| l.date_naive().and_hms_opt(0, 0, 0)).and_then(|m| Local.from_local_datetime(&m).earliest());
|
||||
midnight.map_or(now, |m| m.timestamp_millis())
|
||||
}
|
||||
|
||||
/// Day and time as people write it in lists.
|
||||
pub fn when(time: Time) -> String {
|
||||
Local.timestamp_millis_opt(time).single().map(|t| t.format("%Y-%m-%d %H:%M").to_string()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What of the downloads is shown.
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Default)]
|
||||
pub struct Filter {
|
||||
pub status: Status,
|
||||
pub queue: Option<QueueId>,
|
||||
pub tag: Option<TagId>,
|
||||
pub kind: Option<Kind>,
|
||||
pub host: Option<String>,
|
||||
pub age: Option<Age>,
|
||||
pub search: String,
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
/// Is there anything but the status?
|
||||
pub fn narrow(&self) -> bool {
|
||||
*self != Filter { status: self.status, ..Filter::default() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Sort {
|
||||
/// As they will run; the order the user can change.
|
||||
#[default]
|
||||
Queue,
|
||||
Name,
|
||||
Host,
|
||||
Size,
|
||||
Progress,
|
||||
Speed,
|
||||
Left,
|
||||
State,
|
||||
Added,
|
||||
}
|
||||
|
||||
impl Sort {
|
||||
pub const ALL: [Sort; 9] =
|
||||
[Sort::Queue, Sort::Name, Sort::Host, Sort::Size, Sort::Progress, Sort::Speed, Sort::Left, Sort::State, Sort::Added];
|
||||
|
||||
pub fn label(self) -> String {
|
||||
let name = match self {
|
||||
Sort::Queue => "queue",
|
||||
Sort::Name => "name",
|
||||
Sort::Host => "host",
|
||||
Sort::Size => "size",
|
||||
Sort::Progress => "progress",
|
||||
Sort::Speed => "speed",
|
||||
Sort::Left => "left",
|
||||
Sort::State => "state",
|
||||
Sort::Added => "added",
|
||||
};
|
||||
strings::text(&format!("sort.{name}"), &[])
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Group {
|
||||
None,
|
||||
#[default]
|
||||
State,
|
||||
Queue,
|
||||
Host,
|
||||
Kind,
|
||||
Added,
|
||||
}
|
||||
|
||||
impl Group {
|
||||
pub const ALL: [Group; 6] = [Group::None, Group::State, Group::Queue, Group::Host, Group::Kind, Group::Added];
|
||||
|
||||
pub fn label(self) -> String {
|
||||
let name = match self {
|
||||
Group::None => "none",
|
||||
Group::State => "state",
|
||||
Group::Queue => "queue",
|
||||
Group::Host => "host",
|
||||
Group::Kind => "kind",
|
||||
Group::Added => "added",
|
||||
};
|
||||
strings::text(&format!("group.{name}"), &[])
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kind_label(kind: Kind) -> String {
|
||||
let name = match kind {
|
||||
Kind::Video => "video",
|
||||
Kind::Audio => "audio",
|
||||
Kind::Picture => "picture",
|
||||
Kind::Document => "document",
|
||||
Kind::Archive => "archive",
|
||||
Kind::Program => "program",
|
||||
Kind::Other => "other",
|
||||
};
|
||||
strings::text(&format!("kind.{name}"), &[])
|
||||
}
|
||||
|
||||
/// What a file is, by the end of its name, else by what the server calls it.
|
||||
pub fn kind_of(name: &str, mime: Option<&str>) -> Kind {
|
||||
let ending = Path::new(name).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
match ending.as_str() {
|
||||
"mp4" | "mkv" | "webm" | "avi" | "mov" | "m4v" | "mpg" | "mpeg" | "ts" | "wmv" | "flv" | "ogv" | "3gp" => Kind::Video,
|
||||
"mp3" | "flac" | "ogg" | "opus" | "wav" | "m4a" | "aac" | "wma" | "aiff" => Kind::Audio,
|
||||
"jpg" | "jpeg" | "png" | "gif" | "webp" | "avif" | "svg" | "bmp" | "tif" | "tiff" | "heic" | "jxl" | "psd" => Kind::Picture,
|
||||
"pdf" | "doc" | "docx" | "odt" | "txt" | "md" | "epub" | "mobi" | "xls" | "xlsx" | "ods" | "csv" | "ppt" | "pptx" | "odp" | "rtf" | "tex" => Kind::Document,
|
||||
"zip" | "7z" | "rar" | "tar" | "gz" | "xz" | "bz2" | "zst" | "tgz" | "txz" | "lz4" | "lzma" | "cab" => Kind::Archive,
|
||||
"exe" | "msi" | "deb" | "rpm" | "appimage" | "apk" | "dmg" | "pkg" | "flatpak" | "jar" | "run" | "iso" | "img" => Kind::Program,
|
||||
_ => match mime.unwrap_or_default().split('/').next().unwrap_or_default() {
|
||||
"video" => Kind::Video,
|
||||
"audio" => Kind::Audio,
|
||||
"image" => Kind::Picture,
|
||||
"text" => Kind::Document,
|
||||
_ => Kind::Other,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// How many there are, whatever the search.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Counts {
|
||||
pub status: HashMap<Status, usize>,
|
||||
pub queues: HashMap<QueueId, usize>,
|
||||
pub tags: HashMap<TagId, usize>,
|
||||
pub kinds: HashMap<Kind, usize>,
|
||||
/// By name.
|
||||
pub hosts: Vec<(Arc<str>, usize)>,
|
||||
/// Waiting for the network.
|
||||
pub offline: usize,
|
||||
}
|
||||
|
||||
/// What is asked of a task at every change, worked out once.
|
||||
struct Info {
|
||||
of: Arc<Task>,
|
||||
server: Arc<str>,
|
||||
/// Lower case, for sorting.
|
||||
name: String,
|
||||
/// Lower case, for searching.
|
||||
hay: String,
|
||||
kind: Kind,
|
||||
}
|
||||
|
||||
/// A group of rows with a heading.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Head {
|
||||
pub label: String,
|
||||
/// The first of its rows.
|
||||
pub first: usize,
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
/// What is asked for.
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Default)]
|
||||
pub struct Query {
|
||||
pub filter: Filter,
|
||||
pub sort: Sort,
|
||||
pub down: bool,
|
||||
pub group: Group,
|
||||
}
|
||||
|
||||
/// The rows, in order.
|
||||
#[derive(Default)]
|
||||
pub struct Listing {
|
||||
pub rows: Vec<Arc<TaskView>>,
|
||||
pub heads: Vec<Head>,
|
||||
pub counts: Counts,
|
||||
infos: HashMap<TaskId, Info>,
|
||||
seen: Option<(u64, Query, Arc<Lists>, Time, usize)>,
|
||||
}
|
||||
|
||||
struct Entry<'a> {
|
||||
group: u32,
|
||||
/// Both put the smallest first.
|
||||
num: f64,
|
||||
num2: f64,
|
||||
text: &'a str,
|
||||
view: &'a Arc<TaskView>,
|
||||
}
|
||||
|
||||
impl Listing {
|
||||
/// Is this what the list was last made from?
|
||||
pub fn fresh(&self, shot: &Snapshot, query: &Query, lists: &Arc<Lists>, today: Time) -> bool {
|
||||
self.seen.as_ref().is_some_and(|(rev, q, l, t, n)| *rev == shot.rev && *n == shot.len() && q == query && Arc::ptr_eq(l, lists) && *t == today)
|
||||
}
|
||||
|
||||
/// Kind of a row.
|
||||
pub fn kind(&self, id: TaskId) -> Kind {
|
||||
self.infos.get(&id).map_or(Kind::Other, |i| i.kind)
|
||||
}
|
||||
|
||||
/// Which heading a row is under.
|
||||
pub fn head_of(&self, row: usize) -> Option<usize> {
|
||||
self.heads.partition_point(|h| h.first <= row).checked_sub(1)
|
||||
}
|
||||
|
||||
pub fn update(&mut self, shot: &Snapshot, query: &Query, lists: &Arc<Lists>, today: Time) {
|
||||
self.learn(shot);
|
||||
let words: Vec<String> = query.filter.search.to_lowercase().split_whitespace().map(String::from).collect();
|
||||
let places: HashMap<QueueId, f64> = lists.queues.iter().map(|q| (q.id, q.position)).collect();
|
||||
let f = &query.filter;
|
||||
let mut counts = Counts::default();
|
||||
let mut hosts: HashMap<&Arc<str>, usize> = HashMap::new();
|
||||
let mut group_names: HashMap<&str, u32> = HashMap::new();
|
||||
let mut entries = Vec::with_capacity(shot.len());
|
||||
for view in shot.iter() {
|
||||
let (task, info) = (&view.task, &self.infos[&view.id()]);
|
||||
let status = Status::of(task.state);
|
||||
*counts.status.entry(Status::All).or_default() += 1;
|
||||
*counts.status.entry(status).or_default() += 1;
|
||||
*counts.queues.entry(task.queue).or_default() += 1;
|
||||
*counts.kinds.entry(info.kind).or_default() += 1;
|
||||
*hosts.entry(&info.server).or_default() += 1;
|
||||
task.tags.iter().for_each(|t| *counts.tags.entry(*t).or_default() += 1);
|
||||
counts.offline += usize::from(task.state == State::Waiting && task.error.as_ref().and_then(|e| e.kind).is_some_and(|k| matches!(k, ErrorKind::Offline | ErrorKind::Portal)));
|
||||
let shown = (f.status == Status::All || f.status == status)
|
||||
&& f.queue.is_none_or(|q| q == task.queue)
|
||||
&& f.tag.is_none_or(|t| task.tags.contains(&t))
|
||||
&& f.kind.is_none_or(|k| k == info.kind)
|
||||
&& f.host.as_deref().is_none_or(|h| h == &*info.server)
|
||||
&& f.age.is_none_or(|a| a == Age::of(task.added_at, today))
|
||||
&& words.iter().all(|w| info.hay.contains(w.as_str()));
|
||||
if !shown {
|
||||
continue;
|
||||
}
|
||||
let group = match query.group {
|
||||
Group::None => 0,
|
||||
Group::State => Status::ALL.iter().position(|s| *s == status).unwrap_or(0) as u32,
|
||||
Group::Queue => lists.queues.iter().position(|q| q.id == task.queue).unwrap_or(usize::MAX) as u32,
|
||||
Group::Kind => info.kind as u32,
|
||||
Group::Added => Age::of(task.added_at, today) as u32,
|
||||
// Numbered below, by name.
|
||||
Group::Host => {
|
||||
let next = group_names.len() as u32;
|
||||
*group_names.entry(&info.server).or_insert(next)
|
||||
}
|
||||
};
|
||||
let (num, num2, text) = match query.sort {
|
||||
Sort::Queue => (places.get(&task.queue).copied().unwrap_or(f64::MAX), task.position, ""),
|
||||
Sort::Name => (0.0, 0.0, info.name.as_str()),
|
||||
Sort::Host => (0.0, 0.0, &*info.server),
|
||||
Sort::Size => (view.size.map_or(-1.0, |s| s as f64), 0.0, ""),
|
||||
Sort::Progress => (view.progress().map_or(-1.0, f64::from), 0.0, ""),
|
||||
Sort::Speed => (view.speed, 0.0, ""),
|
||||
Sort::Left => (view.left.map_or(f64::MAX, |l| l.as_secs_f64()), 0.0, ""),
|
||||
Sort::State => (status as u32 as f64, task.state as u32 as f64, ""),
|
||||
Sort::Added => (task.added_at as f64, 0.0, ""),
|
||||
};
|
||||
entries.push(Entry { group, num, num2, text, view });
|
||||
}
|
||||
if query.group == Group::Host {
|
||||
let mut names: Vec<(&str, u32)> = group_names.into_iter().collect();
|
||||
names.sort_unstable();
|
||||
let mut place = vec![0; names.len()];
|
||||
names.iter().enumerate().for_each(|(i, (_, n))| place[*n as usize] = i as u32);
|
||||
entries.iter_mut().for_each(|e| e.group = place[e.group as usize]);
|
||||
}
|
||||
let order = |a: &Entry, b: &Entry| a.num.total_cmp(&b.num).then(a.num2.total_cmp(&b.num2)).then_with(|| a.text.cmp(b.text));
|
||||
entries.sort_by(|a, b| {
|
||||
let o = order(a, b);
|
||||
a.group.cmp(&b.group).then(if query.down { o.reverse() } else { o })
|
||||
});
|
||||
self.heads.clear();
|
||||
if query.group != Group::None {
|
||||
let mut last = None;
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
if last != Some(e.group) {
|
||||
last = Some(e.group);
|
||||
self.heads.push(Head { label: self.head_label(query.group, e.view, lists, today), first: i, count: 0 });
|
||||
}
|
||||
self.heads.last_mut().expect("just pushed").count += 1;
|
||||
}
|
||||
}
|
||||
counts.hosts = hosts.into_iter().map(|(h, n)| (h.clone(), n)).collect();
|
||||
counts.hosts.sort_unstable();
|
||||
self.rows = entries.into_iter().map(|e| e.view.clone()).collect();
|
||||
self.counts = counts;
|
||||
self.seen = Some((shot.rev, query.clone(), lists.clone(), today, shot.len()));
|
||||
}
|
||||
|
||||
fn head_label(&self, group: Group, v: &TaskView, lists: &Lists, today: Time) -> String {
|
||||
match group {
|
||||
Group::None => String::new(),
|
||||
Group::State => Status::of(v.state()).label(),
|
||||
Group::Queue => queue_name(lists, v.task.queue),
|
||||
Group::Host => host_name(&v.server),
|
||||
Group::Kind => kind_label(self.kind(v.id())),
|
||||
Group::Added => Age::of(v.task.added_at, today).label(),
|
||||
}
|
||||
}
|
||||
|
||||
fn learn(&mut self, shot: &Snapshot) {
|
||||
if self.infos.len() > shot.len() {
|
||||
self.infos.retain(|id, _| shot.get(*id).is_some());
|
||||
}
|
||||
for v in shot.iter() {
|
||||
match self.infos.get_mut(&v.id()) {
|
||||
Some(i) if Arc::ptr_eq(&i.of, &v.task) && Arc::ptr_eq(&i.server, &v.server) => {}
|
||||
Some(i) => *i = Info::new(v),
|
||||
None => {
|
||||
self.infos.insert(v.id(), Info::new(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Info {
|
||||
fn new(v: &TaskView) -> Info {
|
||||
let name = title(v).to_lowercase();
|
||||
let hay = format!("{name}\n{}", v.task.url.to_lowercase());
|
||||
Info { of: v.task.clone(), server: v.server.clone(), kind: kind_of(&name, v.task.mime.as_deref()), hay, name }
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of a download; the link until there is one.
|
||||
pub fn title(v: &TaskView) -> &str {
|
||||
if v.task.name.is_empty() { &v.task.url } else { &v.task.name }
|
||||
}
|
||||
|
||||
pub fn queue_name(lists: &Lists, id: QueueId) -> String {
|
||||
match lists.queues.iter().find(|q| q.id == id) {
|
||||
Some(q) if !q.name.is_empty() => q.name.clone(),
|
||||
_ => tr!("queue.main"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Without the port, which says little.
|
||||
pub fn host_name(server: &str) -> String {
|
||||
let host = server.rsplit_once(':').map_or(server, |(h, port)| if port.bytes().all(|b| b.is_ascii_digit()) { h } else { server });
|
||||
if host.is_empty() { tr!("list.no_host") } else { host.to_string() }
|
||||
}
|
||||
|
||||
/// "45 s", "12 min", "3 h 20 min": as exact as it is useful.
|
||||
pub fn span(seconds: u64) -> String {
|
||||
match seconds {
|
||||
0..60 => tr!("time.s", n = seconds),
|
||||
60..3600 => tr!("time.min", n = seconds.div_ceil(60).min(59)),
|
||||
3600..86_400 => tr!("time.h", h = seconds / 3600, min = seconds % 3600 / 60),
|
||||
_ => tr!("time.d", d = seconds / 86_400, h = seconds % 86_400 / 3600),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where rows that move to before row `to` get their positions: queue and position of each, or none when they stay.
|
||||
/// Their neighbours are those of the same heading.
|
||||
pub fn places(listing: &Listing, ids: &[TaskId], to: usize) -> Vec<(TaskId, QueueId, f64)> {
|
||||
let Some(head) = ids.first().and_then(|id| listing.rows.iter().position(|v| v.id() == *id)).map(|r| listing.head_of(r)) else { return vec![] };
|
||||
let near = |row: usize| listing.rows.get(row).filter(|v| listing.head_of(row) == head && !ids.contains(&v.id()));
|
||||
let range = head.map_or(0..listing.rows.len(), |h| listing.heads[h].first..listing.heads[h].first + listing.heads[h].count);
|
||||
let to = to.clamp(range.start, range.end);
|
||||
let before = (range.start..to).rev().find_map(near);
|
||||
let after = (to..range.end).find_map(near);
|
||||
let (queue, from, until) = match (before, after) {
|
||||
(Some(b), Some(a)) if a.task.queue == b.task.queue => (b.task.queue, b.task.position, a.task.position),
|
||||
(Some(b), _) => (b.task.queue, b.task.position, b.task.position + 1.0 + ids.len() as f64),
|
||||
(None, Some(a)) => (a.task.queue, a.task.position - 1.0 - ids.len() as f64, a.task.position),
|
||||
(None, None) => return vec![],
|
||||
};
|
||||
let step = (until - from) / (ids.len() + 1) as f64;
|
||||
// In the order they have in the list.
|
||||
let moved = listing.rows.iter().filter(|v| ids.contains(&v.id()));
|
||||
moved.enumerate().map(|(i, v)| (v.id(), queue, from + step * (i + 1) as f64)).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn times_and_names_read_well() {
|
||||
assert_eq!([0, 59, 60, 61, 3599, 3600, 4800, 90_000].map(span), ["0 s", "59 s", "1 min", "2 min", "59 min", "1 h 0 min", "1 h 20 min", "1 d 1 h"]);
|
||||
assert_eq!(["a.org:443", "a.org", "[::1]:80", ""].map(host_name), ["a.org", "a.org", "[::1]", "No server"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kinds_come_from_the_name_first() {
|
||||
assert_eq!(kind_of("a.b.MKV", Some("text/html")), Kind::Video);
|
||||
assert_eq!(kind_of("a.tar.gz", None), Kind::Archive);
|
||||
assert_eq!(kind_of("stream", Some("audio/ogg")), Kind::Audio);
|
||||
assert_eq!(kind_of("", None), Kind::Other);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn days_begin_at_midnight() {
|
||||
const H: Time = 3_600_000;
|
||||
let t = 1_000 * 24 * H;
|
||||
let ages = [t + H, t, t - H, t - 25 * H, t - 8 * 24 * H, t - 90 * 24 * H].map(|a| Age::of(a, t));
|
||||
assert_eq!(ages, [Age::Today, Age::Today, Age::Yesterday, Age::Week, Age::Month, Age::Older]);
|
||||
}
|
||||
}
|
||||
585
crates/app/src/views/list/row.rs
Normal file
585
crates/app/src/views/list/row.rs
Normal file
|
|
@ -0,0 +1,585 @@
|
|||
//! One download as a row or a card, and the columns of rows.
|
||||
|
||||
use super::layout::{CARD_MIN, Form};
|
||||
use super::model::{Sort, host_name, queue_name, span, title, when};
|
||||
use super::{Act, act_of_fix, choices};
|
||||
use crate::bridge::Lists;
|
||||
use crate::motion::{self, spring};
|
||||
use crate::theme::{Theme, alpha, mix};
|
||||
use crate::tokens::spring::EFFECT;
|
||||
use crate::tokens::{self, icon, radius, size, space, text};
|
||||
use crate::ui::odometer::{amount, rate};
|
||||
use crate::ui::shape::{self, Kind};
|
||||
use crate::ui::wave::{self, Bar, Look};
|
||||
use crate::ui::widgets::{Button, Kind as Style, Size, cr, feel, left, line, tip};
|
||||
use crate::ui::{menu, widgets};
|
||||
use crate::{fonts, icons};
|
||||
use eframe::egui::accesskit::Role;
|
||||
use eframe::egui::{Align2, Color32, Id, Painter, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Ui, UiBuilder, WidgetInfo, pos2, vec2};
|
||||
use medlar_core::error::{Fix, Severity};
|
||||
use medlar_core::model::{ErrorKind, Part, State, TaskId, Time};
|
||||
use medlar_core::snapshot::TaskView;
|
||||
use medlar_core::{strings, tr};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ops::Range;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Column {
|
||||
Host,
|
||||
Queue,
|
||||
Progress,
|
||||
Size,
|
||||
Speed,
|
||||
Left,
|
||||
State,
|
||||
Added,
|
||||
}
|
||||
|
||||
impl Column {
|
||||
/// In the order they stand in.
|
||||
pub const ALL: [Column; 8] =
|
||||
[Column::Host, Column::Queue, Column::Progress, Column::Size, Column::Speed, Column::Left, Column::State, Column::Added];
|
||||
pub const USUAL: [Column; 5] = [Column::Progress, Column::Size, Column::Speed, Column::Left, Column::State];
|
||||
/// Which go first when there is no room.
|
||||
const LEAVE: [Column; 8] =
|
||||
[Column::Added, Column::Queue, Column::Host, Column::Size, Column::Left, Column::Speed, Column::State, Column::Progress];
|
||||
|
||||
pub fn sort(self) -> Sort {
|
||||
match self {
|
||||
Column::Host => Sort::Host,
|
||||
Column::Queue => Sort::Queue,
|
||||
Column::Progress => Sort::Progress,
|
||||
Column::Size => Sort::Size,
|
||||
Column::Speed => Sort::Speed,
|
||||
Column::Left => Sort::Left,
|
||||
Column::State => Sort::State,
|
||||
Column::Added => Sort::Added,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> String {
|
||||
match self {
|
||||
Column::Queue => tr!("column.queue"),
|
||||
other => other.sort().label(),
|
||||
}
|
||||
}
|
||||
|
||||
fn width(self) -> f32 {
|
||||
match self {
|
||||
Column::Host => 168.0,
|
||||
Column::Queue => 120.0,
|
||||
Column::Progress => 144.0,
|
||||
Column::Size | Column::Speed => 88.0,
|
||||
Column::Left => 96.0,
|
||||
Column::State => 112.0,
|
||||
Column::Added => 136.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn right(self) -> bool {
|
||||
matches!(self, Column::Size | Column::Speed | Column::Left)
|
||||
}
|
||||
}
|
||||
|
||||
const HANDLE: f32 = 20.0;
|
||||
const BADGE: f32 = 36.0;
|
||||
const BADGE_CARD: f32 = 48.0;
|
||||
const PAD: f32 = space::S;
|
||||
const NAME_MIN: f32 = 176.0;
|
||||
|
||||
/// Where the columns of rows are, from the left edge of the row.
|
||||
pub struct Columns {
|
||||
pub name: Range<f32>,
|
||||
pub list: Vec<(Column, Range<f32>)>,
|
||||
/// Asked for, but there is no room.
|
||||
narrow: bool,
|
||||
}
|
||||
|
||||
impl Columns {
|
||||
pub fn fit(width: f32, wanted: &[Column]) -> Columns {
|
||||
let start = PAD + HANDLE + BADGE + space::M;
|
||||
let room = width - start - space::M - size::HIT - PAD;
|
||||
let mut chosen: Vec<Column> = Column::ALL.into_iter().filter(|c| wanted.contains(c)).collect();
|
||||
let need = |c: &[Column]| c.iter().map(|c| c.width() + space::L).sum::<f32>();
|
||||
let count = chosen.len();
|
||||
for drop in Column::LEAVE {
|
||||
if room - need(&chosen) >= NAME_MIN {
|
||||
break;
|
||||
}
|
||||
chosen.retain(|c| *c != drop);
|
||||
}
|
||||
// What is left over goes to the name, and some of it to the bar.
|
||||
let spare = (room - need(&chosen) - NAME_MIN).max(0.0);
|
||||
let wide = if chosen.contains(&Column::Progress) { (spare * 0.45).min(1000.0) } else { 0.0 };
|
||||
let narrow = chosen.len() < count;
|
||||
let mut x = start + room - need(&chosen) - wide;
|
||||
let name = start..x;
|
||||
let list = chosen.into_iter().map(|c| {
|
||||
let from = x + space::L;
|
||||
x = from + c.width() + if c == Column::Progress { wide } else { 0.0 };
|
||||
(c, from..x)
|
||||
});
|
||||
let list = list.collect();
|
||||
Columns { name, list, narrow }
|
||||
}
|
||||
|
||||
fn has(&self, c: Column) -> bool {
|
||||
self.list.iter().any(|(k, _)| *k == c)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a row shows besides its download.
|
||||
pub struct Row<'a> {
|
||||
pub view: &'a TaskView,
|
||||
pub kind: Kind,
|
||||
pub lists: &'a Lists,
|
||||
pub form: Form,
|
||||
pub columns: &'a Columns,
|
||||
pub selected: bool,
|
||||
/// The keyboard is here.
|
||||
pub cursor: bool,
|
||||
/// Can be dragged to another place.
|
||||
pub movable: bool,
|
||||
/// Under the pointer while it is dragged.
|
||||
pub carried: bool,
|
||||
pub now: Time,
|
||||
}
|
||||
|
||||
pub struct Out {
|
||||
pub row: Response,
|
||||
pub handle: Response,
|
||||
pub act: Option<Act>,
|
||||
}
|
||||
|
||||
pub fn id(task: TaskId) -> Id {
|
||||
Id::unique(("download", task))
|
||||
}
|
||||
|
||||
/// What the button of a row does.
|
||||
pub fn quick(s: State) -> (Act, &'static str, String) {
|
||||
match s {
|
||||
State::Running | State::Checking | State::Finishing | State::Queued | State::Waiting => (Act::Pause, "pause", tr!("act.pause")),
|
||||
State::Paused => (Act::Resume, "play_arrow", tr!("act.resume")),
|
||||
State::Failed => (Act::Resume, "refresh", tr!("fix.try_again")),
|
||||
State::Done => (Act::Show, "folder_open", tr!("act.show")),
|
||||
State::Gone => (Act::Redownload, "replay", tr!("act.redownload")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn state_label(s: State) -> String {
|
||||
strings::text(&format!("state.{}", s.name()), &[])
|
||||
}
|
||||
|
||||
/// What a button for the problem says, and whether it opens a menu.
|
||||
fn fix_button(v: &TaskView) -> Option<(Fix, String)> {
|
||||
if !matches!(v.state(), State::Failed | State::Waiting) {
|
||||
return None;
|
||||
}
|
||||
let fix = v.task.error.as_ref()?.kind?.fix();
|
||||
// Until there are places for these, trying again is what helps.
|
||||
let label = match fix {
|
||||
Fix::CheckNetwork | Fix::SignIn => Fix::TryAgain.label(),
|
||||
other => other.label(),
|
||||
};
|
||||
Some((fix, label))
|
||||
}
|
||||
|
||||
fn fix_icon(fix: Fix) -> &'static str {
|
||||
match act_of_fix(fix) {
|
||||
Act::EditLink => "link",
|
||||
Act::EditFolder => "folder",
|
||||
Act::Show => "folder_open",
|
||||
Act::Portal => "open_in_new",
|
||||
Act::Redownload => "replay",
|
||||
_ => "refresh",
|
||||
}
|
||||
}
|
||||
|
||||
/// The problem in one line, and the time until it is tried again.
|
||||
fn problem(ui: &Ui, v: &TaskView, now: Time, long: bool) -> Option<String> {
|
||||
let e = v.task.error.as_ref().filter(|_| matches!(v.state(), State::Failed | State::Waiting))?;
|
||||
let title = e.kind.map_or_else(|| e.detail.clone(), |k| k.title());
|
||||
let mut words = match (&e.kind, long) {
|
||||
(Some(_), true) if !e.detail.is_empty() && !e.detail.starts_with(&title) => tr!("error.full", what = title, why = e.detail),
|
||||
(Some(_), true) if !e.detail.is_empty() => e.detail.clone(),
|
||||
_ => title,
|
||||
};
|
||||
if let Some(at) = v.retry_at {
|
||||
let left = (at - now).max(0);
|
||||
// The next whole second.
|
||||
let wait = (left % 1000).max(50) as f32 / 1000.0;
|
||||
ui.ctx().request_repaint_after_secs(wait);
|
||||
let next = if left == 0 { tr!("list.trying") } else { tr!("list.retry", time = span((left as u64).div_ceil(1000))) };
|
||||
words = tr!("list.dot", a = next, b = words);
|
||||
}
|
||||
Some(words)
|
||||
}
|
||||
|
||||
fn join(parts: impl IntoIterator<Item = String>) -> String {
|
||||
parts.into_iter().filter(|p| !p.is_empty()).reduce(|a, b| tr!("list.dot", a = a, b = b)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn left_words(v: &TaskView) -> String {
|
||||
match (v.state(), v.left) {
|
||||
(State::Running, Some(l)) => tr!("list.left", time = span(l.as_secs())),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn speed_words(v: &TaskView) -> String {
|
||||
if v.state() == State::Running { rate(v.speed) } else { String::new() }
|
||||
}
|
||||
|
||||
fn size_words(v: &TaskView) -> String {
|
||||
match v.size {
|
||||
Some(size) if matches!(v.state(), State::Done | State::Gone) => amount(size),
|
||||
Some(size) => tr!("list.of", done = amount(v.downloaded), size = amount(size)),
|
||||
None if v.downloaded > 0 => amount(v.downloaded),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn state_words(v: &TaskView) -> String {
|
||||
let waits = v.state() == State::Waiting && v.task.error.is_none();
|
||||
match v.task.start_at.filter(|_| waits) {
|
||||
Some(at) => tr!("list.starts", time = when(at)),
|
||||
None => state_label(v.state()),
|
||||
}
|
||||
}
|
||||
|
||||
fn state_ink(t: &Theme, v: &TaskView) -> Color32 {
|
||||
match v.state() {
|
||||
State::Failed => t.error,
|
||||
State::Waiting if v.task.error.is_some() => t.warning,
|
||||
State::Done => t.success,
|
||||
_ => t.on_variant,
|
||||
}
|
||||
}
|
||||
|
||||
fn bar(ui: &Ui, t: &Theme, rect: Rect, v: &TaskView) {
|
||||
let parts: Vec<Part> = v.parts.iter().map(|p| Part { start: p.start, end: p.end, done: p.done }).collect();
|
||||
let whole = [Part { start: 0, end: v.size, done: v.downloaded }];
|
||||
let parts = if parts.is_empty() { &whole[..] } else { &parts[..] };
|
||||
let b = Bar { look: Look::from(v.state()), size: v.size, parts, speed: v.speed, checked: v.checked };
|
||||
let rect = Rect::from_center_size(rect.center(), vec2(rect.width(), wave::HEIGHT));
|
||||
wave::bar(ui, t, id(v.id()).with("bar"), rect, &b);
|
||||
}
|
||||
|
||||
/// A round icon button that the keyboard passes by: the list has keys for what it does.
|
||||
fn icon_button(ui: &Ui, t: &Theme, id: Id, at: Pos2, name: &str, what: &str, ink: Color32) -> Response {
|
||||
let rect = Rect::from_center_size(at, vec2(size::HIT, size::HIT));
|
||||
let r = ui.interact(rect, id, Sense::CLICK);
|
||||
r.widget_info(|| WidgetInfo::labeled(Role::Button, true, what));
|
||||
let f = feel(&r, true);
|
||||
if f.tint > 0.0 {
|
||||
let corner = widgets::lerp(size::HIT / 2.0, radius::S, f.press);
|
||||
ui.painter().rect_filled(rect.shrink(f.press.max(0.0)), cr(corner), alpha(ink, f.tint));
|
||||
}
|
||||
icons::paint(ui.painter(), rect.center(), icon::M, name, ink);
|
||||
tip(&r, t, what, "");
|
||||
r
|
||||
}
|
||||
|
||||
/// Draws a row and answers the pointer.
|
||||
pub fn draw(ui: &mut Ui, t: &Theme, rect: Rect, row: &Row, opacity: f32) -> Out {
|
||||
let v = row.view;
|
||||
let id = id(v.id());
|
||||
let r = ui.interact(rect, id, Sense::CLICK | Sense::DRAG);
|
||||
r.widget_info(|| WidgetInfo::selected(Role::ListBoxOption, true, row.selected, title(v)));
|
||||
let under = r.contains_pointer() && !row.carried;
|
||||
let mut ui = ui.new_child(UiBuilder::new().max_rect(rect).id_salt(id.with("row")));
|
||||
let ui = &mut ui;
|
||||
if opacity < 1.0 {
|
||||
ui.set_opacity(opacity);
|
||||
}
|
||||
// The ground.
|
||||
let press = r.is_pointer_button_down_on() && !row.carried;
|
||||
let tint = if press { tokens::state::PRESS } else if under { tokens::state::HOVER } else { 0.0 };
|
||||
let tint = spring(id.with("tint"), tint, EFFECT);
|
||||
let chosen = spring(id.with("chosen"), f32::from(row.selected), EFFECT);
|
||||
let (inner, corner, ground) = match row.form {
|
||||
Form::Compact => (rect.shrink2(vec2(0.0, 2.0)), radius::M, t.surface),
|
||||
Form::Cards => (rect, radius::L, t.low),
|
||||
};
|
||||
let fill = mix(ground, t.primary, tokens::state::DRAG * chosen.clamp(0.0, 1.0));
|
||||
let ink = t.on_surface;
|
||||
// What is faint must still read on the tint.
|
||||
let faint = mix(t.on_variant, t.on_surface, chosen.clamp(0.0, 1.0));
|
||||
if row.carried {
|
||||
ui.painter().add(tokens::elevation::floating(t.dark).as_shape(inner, cr(corner)));
|
||||
}
|
||||
if chosen > 0.0 || row.form == Form::Cards || row.carried {
|
||||
ui.painter().rect_filled(inner, cr(corner), if row.carried { mix(fill, t.high, 0.5) } else { fill });
|
||||
}
|
||||
if tint > 0.0 {
|
||||
ui.painter().rect_filled(inner, cr(corner), alpha(ink, tint));
|
||||
}
|
||||
if row.cursor {
|
||||
// Inside: the ring must not leave the list.
|
||||
let ring = Stroke::new(size::FOCUS_RING, t.primary);
|
||||
ui.painter().rect_stroke(inner, cr(corner), ring, StrokeKind::Inside);
|
||||
}
|
||||
// The handle comes with the pointer; its place is always kept.
|
||||
let handle_rect = Rect::from_min_size(inner.min + vec2(PAD - space::XS, 0.0), vec2(HANDLE + space::XS, inner.height()));
|
||||
let handle = ui.interact(handle_rect, id.with("handle"), if row.movable { Sense::DRAG } else { Sense::hover() });
|
||||
let handle_seen = spring(id.with("handle seen"), f32::from(row.movable && (under || row.carried)), EFFECT);
|
||||
if handle_seen > 0.0 {
|
||||
let grip = if handle.hovered() || row.carried { ink } else { faint };
|
||||
icons::paint(ui.painter(), handle_rect.center(), icon::M, "drag_indicator", alpha(grip, handle_seen.min(1.0)));
|
||||
if row.movable && handle.hovered() {
|
||||
ui.ctx().set_cursor_icon(eframe::egui::CursorIcon::Grab);
|
||||
}
|
||||
}
|
||||
let paint = Paint { t, row, ink, faint };
|
||||
let act = match row.form {
|
||||
Form::Compact => paint.compact(ui, inner),
|
||||
Form::Cards => paint.card(ui, inner),
|
||||
};
|
||||
Out { row: r, handle, act }
|
||||
}
|
||||
|
||||
struct Paint<'a> {
|
||||
t: &'a Theme,
|
||||
row: &'a Row<'a>,
|
||||
ink: Color32,
|
||||
faint: Color32,
|
||||
}
|
||||
|
||||
impl Paint<'_> {
|
||||
fn put(&self, p: &Painter, x: Range<f32>, y: f32, words: &str, font: eframe::egui::FontId, ink: Color32, right: bool) {
|
||||
if words.is_empty() {
|
||||
return;
|
||||
}
|
||||
let g = line(p, words, font, ink, x.end - x.start);
|
||||
if right {
|
||||
let rect = Align2::RIGHT_CENTER.anchor_size(pos2(x.end, y), g.size());
|
||||
p.galley(rect.min, g, ink);
|
||||
} else {
|
||||
left(p, pos2(x.start, y), g);
|
||||
}
|
||||
}
|
||||
|
||||
fn badge(&self, ui: &Ui, center: Pos2, side: f32) {
|
||||
let v = self.row.view;
|
||||
shape::badge(ui, self.t, id(v.id()).with("badge"), Rect::from_center_size(center, vec2(side, side)), self.row.kind, Look::from(v.state()));
|
||||
}
|
||||
|
||||
/// `fix`: there is no other button for the problem, so this one is it.
|
||||
fn quick(&self, ui: &Ui, at: Pos2, fix: bool) -> Option<Act> {
|
||||
let v = self.row.view;
|
||||
let serious = |k: ErrorKind| v.state() == State::Failed || k.severity() != Severity::Passing;
|
||||
let kind = v.task.error.as_ref().and_then(|e| e.kind).filter(|k| fix && serious(*k));
|
||||
if let Some((fix, what)) = fix_button(v).filter(|_| kind.is_some()) {
|
||||
let r = icon_button(ui, self.t, id(v.id()).with("quick"), at, fix_icon(fix), &what, self.faint);
|
||||
return if fix == Fix::Choose { menu::below(ui, self.t, &r, choices) } else { r.clicked().then(|| act_of_fix(fix)) };
|
||||
}
|
||||
let (act, icon, what) = quick(v.state());
|
||||
icon_button(ui, self.t, id(v.id()).with("quick"), at, icon, &what, self.faint).clicked().then_some(act)
|
||||
}
|
||||
|
||||
/// A button for the problem with its right edge at `right`. Gives back its left edge, too.
|
||||
fn fix(&self, ui: &mut Ui, right: f32, y: f32, most: f32) -> (f32, Option<Act>) {
|
||||
let v = self.row.view;
|
||||
let Some((fix, label)) = fix_button(v) else { return (right, None) };
|
||||
let width = (widgets::text_width(ui.painter(), &label, fonts::med(text::BODY)) + 2.0 * space::M).min(most);
|
||||
let rect = Rect::from_min_size(pos2(right - width, y - size::HIT / 2.0), vec2(width, size::HIT));
|
||||
let mut child = ui.new_child(UiBuilder::new().max_rect(rect).id_salt(id(v.id()).with("fix")));
|
||||
let style = if v.state() == State::Failed { Style::Filled } else { Style::Tonal };
|
||||
let r = Button::new(&label).size(Size::S).kind(style).width(width).show(&mut child, self.t);
|
||||
let act = match fix {
|
||||
Fix::Choose => menu::below(ui, self.t, &r, choices),
|
||||
fix => r.clicked().then(|| act_of_fix(fix)),
|
||||
};
|
||||
(rect.left(), act)
|
||||
}
|
||||
|
||||
fn compact(&self, ui: &mut Ui, rect: Rect) -> Option<Act> {
|
||||
let (t, v, columns) = (self.t, self.row.view, self.row.columns);
|
||||
let p = ui.painter().clone();
|
||||
let y = rect.center().y;
|
||||
let x0 = rect.left();
|
||||
self.badge(ui, pos2(x0 + PAD + HANDLE + BADGE / 2.0, y), BADGE);
|
||||
let mut name = x0 + columns.name.start..x0 + columns.name.end;
|
||||
let problem = problem(ui, v, self.row.now, false);
|
||||
let alone = !columns.has(Column::Progress) && name.end - name.start <= 2.0 * NAME_MIN;
|
||||
let mut act = self.quick(ui, pos2(rect.right() - PAD - size::HIT / 2.0, y), alone);
|
||||
// The button for a problem takes the place of the bar, which says nothing then.
|
||||
if problem.is_some() {
|
||||
let place = columns.list.iter().find(|(c, _)| *c == Column::Progress).map(|(_, r)| x0 + r.start..x0 + r.end);
|
||||
match place {
|
||||
Some(place) => {
|
||||
let wide = fix_width(&p, v).min(place.end - place.start);
|
||||
act = self.fix(ui, place.start + wide, y, place.end - place.start).1.or(act);
|
||||
}
|
||||
None if !alone => {
|
||||
let (edge, fixed) = self.fix(ui, name.end, y, NAME_MIN);
|
||||
name.end = edge - space::S;
|
||||
act = fixed.or(act);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
for (c, x) in &columns.list {
|
||||
let x = x0 + x.start..x0 + x.end;
|
||||
let put = |words: String, ink| self.put(&p, x.clone(), y, &words, fonts::ui(text::LABEL), ink, c.right());
|
||||
match c {
|
||||
Column::Host => put(host_name(&v.server), self.faint),
|
||||
Column::Queue => put(queue_name(self.row.lists, v.task.queue), self.faint),
|
||||
Column::Size => put(v.size.map(amount).unwrap_or_default(), self.faint),
|
||||
Column::Speed => put(speed_words(v), self.ink),
|
||||
Column::Left => put(if v.state() == State::Running { v.left.map(|l| span(l.as_secs())).unwrap_or_default() } else { String::new() }, self.faint),
|
||||
Column::State => put(state_words(v), if self.row.selected { self.faint } else { state_ink(t, v) }),
|
||||
Column::Added => put(when(v.task.added_at), self.faint),
|
||||
Column::Progress if problem.is_some() => {}
|
||||
Column::Progress => {
|
||||
let percent = v.progress().map(|s| tr!("list.percent", n = (s * 100.0).floor())).unwrap_or_default();
|
||||
let words = 40.0;
|
||||
bar(ui, t, Rect::from_x_y_ranges(x.start..=x.end - words, y - 1.0..=y + 1.0), v);
|
||||
self.put(&p, x.end - words..x.end, y, &percent, fonts::ui(text::LABEL), self.faint, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The second line: the problem, else what has no column.
|
||||
let bar_here = problem.is_none() && !columns.has(Column::Progress) && v.state() != State::Done;
|
||||
let second = problem.clone().unwrap_or_else(|| {
|
||||
let mut parts = vec![];
|
||||
if columns.narrow && !columns.has(Column::State) {
|
||||
parts.push(state_words(v));
|
||||
}
|
||||
if columns.narrow && !columns.has(Column::Speed) {
|
||||
parts.push(speed_words(v));
|
||||
}
|
||||
if columns.narrow && !columns.has(Column::Left) {
|
||||
parts.push(left_words(v));
|
||||
}
|
||||
if columns.narrow && !columns.has(Column::Size) && parts.len() < 3 {
|
||||
parts.push(size_words(v));
|
||||
}
|
||||
if !columns.has(Column::Host) {
|
||||
parts.push(host_name(&v.server));
|
||||
}
|
||||
join(parts)
|
||||
});
|
||||
let ink = if problem.is_some() && !self.row.selected { state_ink(t, v) } else { self.faint };
|
||||
let name_font = fonts::med(text::BODY);
|
||||
if bar_here {
|
||||
// Three lines in the same height.
|
||||
self.put(&p, name.clone(), y - 15.0, title(v), name_font, self.ink, false);
|
||||
self.put(&p, name.clone(), y + 3.0, &second, fonts::ui(text::LABEL), ink, false);
|
||||
bar(ui, t, Rect::from_x_y_ranges(name.start..=name.end, y + 17.0..=y + 19.0), v);
|
||||
} else if second.is_empty() {
|
||||
self.put(&p, name, y, title(v), name_font, self.ink, false);
|
||||
} else {
|
||||
self.put(&p, name.clone(), y - 9.0, title(v), name_font, self.ink, false);
|
||||
self.put(&p, name, y + 10.0, &second, fonts::ui(text::LABEL), ink, false);
|
||||
}
|
||||
act
|
||||
}
|
||||
|
||||
fn card(&self, ui: &mut Ui, rect: Rect) -> Option<Act> {
|
||||
let (t, v) = (self.t, self.row.view);
|
||||
let p = ui.painter().clone();
|
||||
let badge = pos2(rect.left() + PAD + HANDLE + BADGE_CARD / 2.0, rect.center().y);
|
||||
self.badge(ui, badge, BADGE_CARD);
|
||||
let (x0, x1) = (badge.x + BADGE_CARD / 2.0 + space::L, rect.right() - space::L);
|
||||
let rows = [rect.top() + 26.0, rect.top() + 50.0, rect.top() + 84.0];
|
||||
let mut act = self.quick(ui, pos2(x1 - size::HIT / 2.0 + space::XS, rows[2]), false);
|
||||
let edge = x1 - size::HIT - space::S;
|
||||
let speed = speed_words(v);
|
||||
let speed_wide = if speed.is_empty() { 0.0 } else { widgets::text_width(&p, &speed, fonts::semi(text::TITLE)) + space::L };
|
||||
self.put(&p, x0..x1 - speed_wide, rows[0], title(v), fonts::semi(text::BODY), self.ink, false);
|
||||
self.put(&p, x0..x1, rows[0], &speed, fonts::semi(text::TITLE), self.ink, true);
|
||||
if let Some(problem) = problem(ui, v, self.row.now, true) {
|
||||
let ink = if self.row.selected { self.faint } else { state_ink(t, v) };
|
||||
self.put(&p, x0..x1, rows[1], &problem, fonts::ui(text::LABEL), ink, false);
|
||||
let (from, fixed) = self.fix(ui, edge, rows[2], CARD_MIN / 2.0);
|
||||
act = fixed.or(act);
|
||||
bar(ui, t, Rect::from_x_y_ranges(x0..=from - space::L, rows[2] - 1.0..=rows[2] + 1.0), v);
|
||||
return act;
|
||||
}
|
||||
let state = state_words(v);
|
||||
let after = left_words(v);
|
||||
let after = if after.is_empty() { state.clone() } else { after };
|
||||
let after_wide = widgets::text_width(&p, &after, fonts::ui(text::LABEL)) + space::L;
|
||||
let host = host_name(&v.server);
|
||||
let mut parts = vec![host, size_words(v)];
|
||||
if v.state() == State::Running && v.connections > 0 {
|
||||
parts.push(tr!("list.connections", n = v.connections));
|
||||
}
|
||||
self.put(&p, x0..x1 - after_wide, rows[1], &join(parts), fonts::ui(text::LABEL), self.faint, false);
|
||||
let ink = if after == state && !self.row.selected { state_ink(t, v) } else { self.faint };
|
||||
self.put(&p, x0..x1, rows[1], &after, fonts::ui(text::LABEL), ink, true);
|
||||
bar(ui, t, Rect::from_x_y_ranges(x0..=edge, rows[2] - 1.0..=rows[2] + 1.0), v);
|
||||
act
|
||||
}
|
||||
}
|
||||
|
||||
fn fix_width(p: &Painter, v: &TaskView) -> f32 {
|
||||
fix_button(v).map_or(0.0, |(_, label)| widgets::text_width(p, &label, fonts::med(text::BODY)) + 2.0 * space::M)
|
||||
}
|
||||
|
||||
/// The space a heading's words start at.
|
||||
pub const HEAD_X: f32 = PAD + HANDLE;
|
||||
|
||||
/// The names of the columns. A click sorts by one, another turns the order round.
|
||||
pub fn header(ui: &mut Ui, t: &Theme, rect: Rect, columns: &Columns, sort: Sort, down: bool) -> Option<Sort> {
|
||||
let mut clicked = None;
|
||||
let name = (Sort::Name, tr!("sort.name"), columns.name.clone(), false);
|
||||
let all = std::iter::once(name).chain(columns.list.iter().map(|(c, x)| (c.sort(), c.label(), x.clone(), c.right())));
|
||||
for (key, label, x, right) in all {
|
||||
let font = fonts::med(text::LABEL);
|
||||
let on = key == sort;
|
||||
let arrow = icon::S + space::XS;
|
||||
let wide = (widgets::text_width(ui.painter(), &label, font.clone()) + arrow).min(x.end - x.start);
|
||||
let (from, to) = if right { (rect.left() + x.end - wide, rect.left() + x.end) } else { (rect.left() + x.start, rect.left() + x.start + wide) };
|
||||
let hit = Rect::from_x_y_ranges(from - space::S..=to + space::S, rect.y_range());
|
||||
let r = ui.interact(hit, Id::unique(("column", &label)), Sense::click());
|
||||
r.widget_info(|| WidgetInfo::selected(Role::ColumnHeader, true, on, &label));
|
||||
let f = feel(&r, true);
|
||||
let p = ui.painter();
|
||||
p.rect_filled(hit.shrink(2.0), cr(radius::S), alpha(t.on_surface, f.tint));
|
||||
if f.focus {
|
||||
p.rect_stroke(hit.shrink(2.0), cr(radius::S), Stroke::new(size::FOCUS_RING, t.primary), StrokeKind::Inside);
|
||||
}
|
||||
let ink = if on { t.on_surface } else { t.on_variant };
|
||||
let y = rect.center().y;
|
||||
let words = line(p, &label, font, ink, wide - arrow);
|
||||
let turn = spring(r.id.with("turn"), f32::from(!down), tokens::spring::FAST);
|
||||
// The words keep their column's edge; the arrow stands on the other side.
|
||||
if right {
|
||||
let x = to - words.size().x;
|
||||
left(p, pos2(x, y), words);
|
||||
if on {
|
||||
widgets::chevron(p, pos2(x - arrow / 2.0, y), icon::S, turn, ink);
|
||||
}
|
||||
} else {
|
||||
let x = from + words.size().x;
|
||||
left(p, pos2(from, y), words);
|
||||
if on {
|
||||
widgets::chevron(p, pos2(x + arrow / 2.0 + 1.0, y), icon::S, turn, ink);
|
||||
}
|
||||
}
|
||||
if r.clicked() {
|
||||
clicked = Some(key);
|
||||
}
|
||||
}
|
||||
clicked
|
||||
}
|
||||
|
||||
/// A download on its way out.
|
||||
pub fn ghost(ui: &mut Ui, t: &Theme, rect: Rect, row: &Row, opacity: f32) {
|
||||
motion::keep_alive();
|
||||
let p = ui.painter();
|
||||
let (inner, corner) = match row.form {
|
||||
Form::Compact => (rect.shrink2(vec2(0.0, 2.0)), radius::M),
|
||||
Form::Cards => (rect, radius::L),
|
||||
};
|
||||
let ink = alpha(t.on_surface, opacity);
|
||||
p.rect_filled(inner, cr(corner), alpha(t.low, opacity));
|
||||
let side = if row.form == Form::Compact { BADGE } else { BADGE_CARD };
|
||||
let badge = pos2(inner.left() + PAD + HANDLE + side / 2.0, inner.center().y);
|
||||
shape::form(p, badge, side / 2.0, row.kind.form(), alpha(t.secondary_container, opacity));
|
||||
let x = badge.x + side / 2.0 + space::M;
|
||||
left(p, pos2(x, inner.center().y), line(p, title(row.view), fonts::med(text::BODY), ink, inner.right() - space::XL - x));
|
||||
}
|
||||
453
crates/app/src/views/main.rs
Normal file
453
crates/app/src/views/main.rs
Normal file
|
|
@ -0,0 +1,453 @@
|
|||
//! The daily screen: rail, speed, search and the list, and what happens when something is asked of downloads.
|
||||
|
||||
use super::list::model::{Filter, Group, Sort, Status, title};
|
||||
use super::list::row::Column;
|
||||
use super::list::{self, Act, List, Order, layout::Form};
|
||||
use super::{bar, rail};
|
||||
use crate::bridge::{Bridge, Data, Lists, download_folder};
|
||||
use crate::motion::spring;
|
||||
use crate::theme::Theme;
|
||||
use crate::tokens::spring::DEFAULT;
|
||||
use crate::tokens::{icon, size, space, text};
|
||||
use crate::ui::dialog::{Answer, Dialog};
|
||||
use crate::ui::field::Field;
|
||||
use crate::ui::shape;
|
||||
use crate::ui::toast::Toasts;
|
||||
use crate::ui::widgets::{Button, Kind, centered, line};
|
||||
use crate::{fonts, icons, motion};
|
||||
use eframe::egui::{Id, Pos2, Rect, Ui, UiBuilder, Vec2, pos2, text::LayoutJob, vec2};
|
||||
use medlar_core::manager::{Command, Files};
|
||||
use medlar_core::model::{State, Task, TaskId};
|
||||
use medlar_core::settings::Settings;
|
||||
use medlar_core::snapshot::{Snapshot, TaskView};
|
||||
use medlar_core::tr;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// How the list looks; kept between runs.
|
||||
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Prefs {
|
||||
pub form: Form,
|
||||
pub sort: Sort,
|
||||
pub down: bool,
|
||||
pub group: Group,
|
||||
pub columns: Vec<Column>,
|
||||
/// None until the user opens or closes it: it follows the window.
|
||||
pub rail: Option<bool>,
|
||||
}
|
||||
|
||||
impl Default for Prefs {
|
||||
fn default() -> Prefs {
|
||||
Prefs { form: Form::Compact, sort: Sort::Queue, down: false, group: Group::State, columns: Column::USUAL.to_vec(), rail: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a message's button does.
|
||||
#[derive(Clone)]
|
||||
pub enum Reply {
|
||||
Undo(Vec<TaskId>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum What {
|
||||
Add,
|
||||
Link,
|
||||
Folder,
|
||||
Name,
|
||||
}
|
||||
|
||||
/// The one question that may be open.
|
||||
struct Ask {
|
||||
what: What,
|
||||
id: TaskId,
|
||||
text: String,
|
||||
open: bool,
|
||||
}
|
||||
|
||||
pub struct Main {
|
||||
pub bridge: Bridge,
|
||||
pub list: List,
|
||||
pub toasts: Toasts<Reply>,
|
||||
/// Opens a file, folder or page outside; tests put something else here.
|
||||
pub outside: fn(&str),
|
||||
prefs: Prefs,
|
||||
prefs_file: Option<PathBuf>,
|
||||
speeds: bar::Speeds,
|
||||
ask: Option<Ask>,
|
||||
focus_search: bool,
|
||||
}
|
||||
|
||||
impl Default for Main {
|
||||
fn default() -> Main {
|
||||
Main {
|
||||
bridge: Bridge::default(),
|
||||
list: List::default(),
|
||||
toasts: Toasts::default(),
|
||||
outside: |_| {},
|
||||
prefs: Prefs::default(),
|
||||
prefs_file: None,
|
||||
speeds: bar::Speeds::default(),
|
||||
ask: None,
|
||||
focus_search: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens something with the desktop's program for it.
|
||||
pub fn open_outside(what: &str) {
|
||||
let what = what.to_string();
|
||||
// Waits for the opener, which would stay behind as a zombie.
|
||||
std::thread::spawn(move || {
|
||||
// Only full paths and web addresses get here, so nothing can look like an option.
|
||||
match std::process::Command::new("xdg-open").arg(&what).status() {
|
||||
Ok(status) if status.success() => {}
|
||||
Ok(status) => log::warn!("xdg-open: {status}"),
|
||||
Err(e) => log::warn!("xdg-open: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The narrowest window with an open rail, unless the user wants it.
|
||||
const RAIL_OPENS: f32 = 960.0;
|
||||
/// Narrower than this, the rail is never open: the list would have no room.
|
||||
const RAIL_FITS: f32 = 640.0;
|
||||
|
||||
impl Main {
|
||||
/// Reads how the list looked, and keeps it there.
|
||||
pub fn remember(&mut self, file: PathBuf) {
|
||||
if let Some(prefs) = std::fs::read(&file).ok().and_then(|b| serde_json::from_slice(&b).ok()) {
|
||||
self.set_prefs(prefs);
|
||||
}
|
||||
self.prefs_file = Some(file);
|
||||
}
|
||||
|
||||
pub fn set_prefs(&mut self, prefs: Prefs) {
|
||||
let q = &mut self.list.query;
|
||||
(self.list.form, q.sort, q.down, q.group) = (prefs.form, prefs.sort, prefs.down, prefs.group);
|
||||
self.list.columns = prefs.columns.clone();
|
||||
self.prefs = prefs;
|
||||
}
|
||||
|
||||
fn keep_prefs(&mut self) {
|
||||
let q = &self.list.query;
|
||||
let now = Prefs { form: self.list.form, sort: q.sort, down: q.down, group: q.group, columns: self.list.columns.clone(), rail: self.prefs.rail };
|
||||
if now == self.prefs {
|
||||
return;
|
||||
}
|
||||
self.prefs = now;
|
||||
if let Some(file) = &self.prefs_file {
|
||||
let saved = serde_json::to_vec_pretty(&self.prefs).map_err(std::io::Error::from).and_then(|b| std::fs::write(file, b));
|
||||
if let Err(e) = saved {
|
||||
log::warn!("{}: {e}", file.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the screen.
|
||||
pub fn show(&mut self, ui: &mut Ui, t: &Theme, settings: &Settings) {
|
||||
let window = ui.ctx().content_rect();
|
||||
for why in self.bridge.take_errors() {
|
||||
self.toasts.error(why, None);
|
||||
}
|
||||
match self.bridge.data() {
|
||||
Data::Opening => {
|
||||
let r = Rect::from_center_size(window.center(), Vec2::splat(size::LARGE));
|
||||
shape::loading(ui, t, Id::unique("opening"), r);
|
||||
}
|
||||
Data::Failed(why) => {
|
||||
let again = tr!("fix.try_again");
|
||||
if self.state(ui, t, window, Face::Icon("error"), &tr!("open.failed"), &why, Some(("refresh", &again))) {
|
||||
self.bridge.retry();
|
||||
}
|
||||
}
|
||||
Data::Ready(shot, lists) => self.ready(ui, t, settings, window, &shot, &lists),
|
||||
}
|
||||
if let Some(Reply::Undo(ids)) = self.toasts.show(ui.ctx(), t, window.bottom() - self.floor()) {
|
||||
ids.into_iter().for_each(|id| self.bridge.send(Command::Restore(id)));
|
||||
}
|
||||
self.asking(ui, t, settings);
|
||||
self.keep_prefs();
|
||||
}
|
||||
|
||||
/// How much at the bottom the toolbar takes.
|
||||
fn floor(&self) -> f32 {
|
||||
if self.list.selected.is_empty() { 0.0 } else { bar::TOOLBAR - space::L }
|
||||
}
|
||||
|
||||
fn ready(&mut self, ui: &mut Ui, t: &Theme, settings: &Settings, window: Rect, shot: &Arc<Snapshot>, lists: &Arc<Lists>) {
|
||||
self.list.follow(ui, shot, lists);
|
||||
self.speeds.follow(&shot.totals);
|
||||
// Rail, then everything else beside it.
|
||||
let open = window.width() >= RAIL_FITS && self.prefs.rail.unwrap_or(window.width() >= RAIL_OPENS);
|
||||
let v = spring("rail", if open { rail::WIDE } else { rail::NARROW }, DEFAULT).max(rail::NARROW - space::S);
|
||||
// A window that is being resized must not wait for it.
|
||||
let (side, rest) = window.split_left_right_at_x(window.left() + v.min(window.width() / 2.0));
|
||||
let clicked = {
|
||||
let listing = self.list.listing();
|
||||
let mut filter = self.list.query.filter.clone();
|
||||
let clicked = rail::show(ui, t, side, open, &mut filter, &listing.counts, lists);
|
||||
self.list.query.filter = filter;
|
||||
clicked
|
||||
};
|
||||
if clicked {
|
||||
if window.width() < RAIL_FITS {
|
||||
self.toasts.info("menu", tr!("rail.no_room"));
|
||||
} else {
|
||||
self.prefs.rail = Some(!open);
|
||||
self.list_prefs_changed();
|
||||
}
|
||||
}
|
||||
let pad = if window.width() < RAIL_FITS { space::M } else { space::XL };
|
||||
let mut body = rest.shrink2(vec2(pad, space::L));
|
||||
body.max.y = window.bottom();
|
||||
if shot.is_empty() {
|
||||
let add = tr!("add.button");
|
||||
if self.state(ui, t, rest, Face::App, &tr!("empty.title"), &tr!("empty.body"), Some(("add", &add))) {
|
||||
self.begin(What::Add, 0, String::new());
|
||||
}
|
||||
let mut orders = vec![];
|
||||
self.list.keys(ui, &mut orders);
|
||||
orders.into_iter().for_each(|o| self.order(ui, shot, o));
|
||||
return self.dropped(ui);
|
||||
}
|
||||
let (head, rest) = body.split_top_bottom_at_y(body.top() + bar::header_height(window.height()));
|
||||
bar::header(ui, t, head, shot, &self.speeds, settings.limits().speed);
|
||||
let (_, rest) = rest.split_top_bottom_at_y(rest.top() + space::M);
|
||||
let (tools, mut rest) = rest.split_top_bottom_at_y(rest.top() + size::CONTROL);
|
||||
let mut orders = vec![];
|
||||
orders.extend(bar::top(ui, t, tools, &mut self.list, &mut self.focus_search));
|
||||
rest.min.y += space::S;
|
||||
if bar::has_chips(&self.list.query.filter) {
|
||||
let (chips, after) = rest.split_top_bottom_at_y(rest.top() + size::HIT);
|
||||
bar::chips(ui, t, chips, &mut self.list.query.filter, lists);
|
||||
rest = after.with_min_y(after.top() + space::S);
|
||||
}
|
||||
let offline = self.list.listing().counts.offline;
|
||||
if offline > 0 && rest.height() > 160.0 {
|
||||
let (line, after) = rest.split_top_bottom_at_y(rest.top() + size::CONTROL);
|
||||
bar::banner(ui, t, line, "wifi_off", &tr!("list.offline", n = offline));
|
||||
rest = after.with_min_y(after.top() + space::S);
|
||||
}
|
||||
// What was clicked above counts in this frame.
|
||||
self.list.follow(ui, shot, lists);
|
||||
if list::nothing_found(&self.list.query.filter, self.list.listing(), shot.len()) {
|
||||
self.list.keys(ui, &mut orders);
|
||||
let clear = tr!("filter.clear");
|
||||
let f = self.list.query.filter.clone();
|
||||
let (words, body) = if f.search.is_empty() { (tr!("none.title"), tr!("none.body")) } else { (tr!("none.search", what = f.search.trim()), tr!("none.search_body")) };
|
||||
let button = if f.status != Status::All || f.narrow() { Some(("close", clear.as_str())) } else { None };
|
||||
if self.state(ui, t, rest, Face::Icon("search"), &words, &body, button) {
|
||||
self.list.query.filter = Filter::default();
|
||||
}
|
||||
} else {
|
||||
self.list_in(ui, t, rest, lists, &mut orders);
|
||||
}
|
||||
for order in orders {
|
||||
self.order(ui, shot, order);
|
||||
}
|
||||
self.dropped(ui);
|
||||
}
|
||||
|
||||
fn list_in(&mut self, ui: &mut Ui, t: &Theme, rest: Rect, lists: &Arc<Lists>, orders: &mut Vec<Order>) {
|
||||
let below = if self.list.selected.is_empty() { space::L } else { bar::TOOLBAR };
|
||||
// The scroll bar stands in the margin, so rows end where everything else does.
|
||||
orders.extend(self.list.show(ui, t, rest.with_max_x(rest.right() + space::M), lists, below));
|
||||
orders.extend(bar::selected(ui, t, rest, &mut self.list));
|
||||
}
|
||||
|
||||
fn list_prefs_changed(&mut self) {
|
||||
// Written with the rest at the end of the frame, which compares with what was kept.
|
||||
let rail = self.prefs.rail;
|
||||
self.prefs = Prefs { rail, columns: vec![], ..self.prefs.clone() };
|
||||
}
|
||||
|
||||
/// Files let go over the window. What becomes of them is the Add dialog's business.
|
||||
fn dropped(&mut self, ui: &Ui) {
|
||||
if ui.input(|i| !i.raw.dropped_files.is_empty()) {
|
||||
self.begin(What::Add, 0, String::new());
|
||||
}
|
||||
}
|
||||
|
||||
/// A screen that says one thing. True when its button was clicked.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn state(&self, ui: &mut Ui, t: &Theme, rect: Rect, face: Face, head: &str, body: &str, button: Option<(&str, &str)>) -> bool {
|
||||
let p = ui.painter().with_clip_rect(rect);
|
||||
let width = (rect.width() - 2.0 * space::L).min(420.0);
|
||||
let head = line(&p, head, fonts::semi(text::HEADLINE), t.on_surface, width);
|
||||
let mut job = LayoutJob::simple(body.into(), fonts::ui(text::BODY), t.on_variant, width);
|
||||
job.halign = eframe::egui::Align::Center;
|
||||
let body = p.layout_job(job);
|
||||
let small = rect.height() < 320.0;
|
||||
let side = if small { icon::XL } else { icon::HERO };
|
||||
let button_height = if button.is_some() { size::CONTROL + space::XL } else { 0.0 };
|
||||
let total = side + space::L + head.size().y + space::XS + body.size().y + button_height;
|
||||
let mut y = (rect.center().y - total / 2.0).max(rect.top() + space::S);
|
||||
let x = rect.center().x;
|
||||
match face {
|
||||
Face::App => icons::paint_app(&p, pos2(x, y + side / 2.0), side),
|
||||
Face::Icon(name) => {
|
||||
shape::form(&p, pos2(x, y + side / 2.0), side / 2.0, shape::Form::Cookie9, t.secondary_container);
|
||||
icons::paint(&p, pos2(x, y + side / 2.0), if small { icon::M } else { icon::XL }, name, t.on_secondary_container);
|
||||
}
|
||||
}
|
||||
y += side + space::L;
|
||||
let r = Rect::from_min_size(Pos2::new(x - width / 2.0, y), vec2(width, head.size().y));
|
||||
centered(&p, r, head);
|
||||
y = r.bottom() + space::XS;
|
||||
p.galley(pos2(x, y), body.clone(), t.on_variant);
|
||||
y += body.size().y + space::XL;
|
||||
let Some((icon, words)) = button else { return false };
|
||||
let wide = crate::ui::widgets::text_width(&p, words, fonts::med(text::BODY)) + crate::tokens::icon::M + space::S + 2.0 * space::L;
|
||||
let place = Rect::from_min_size(pos2(x - wide / 2.0, y), vec2(wide, size::CONTROL));
|
||||
let mut child = ui.new_child(UiBuilder::new().max_rect(place).id_salt("state"));
|
||||
Button::new(words).with_icon(icon).kind(Kind::Filled).show(&mut child, t).clicked()
|
||||
}
|
||||
|
||||
fn begin(&mut self, what: What, id: TaskId, text: String) {
|
||||
self.ask = Some(Ask { what, id, text, open: true });
|
||||
}
|
||||
|
||||
/// Adding, and changing the link, folder or name of a download.
|
||||
fn asking(&mut self, ui: &Ui, t: &Theme, settings: &Settings) {
|
||||
let Some(ask) = &mut self.ask else { return };
|
||||
let (head, label, main) = match ask.what {
|
||||
What::Add => (tr!("add.title"), tr!("add.links"), tr!("add.do")),
|
||||
What::Link => (tr!("ask.link"), tr!("ask.link_field"), tr!("ask.save")),
|
||||
What::Folder => (tr!("ask.folder"), tr!("ask.folder_field"), tr!("ask.move")),
|
||||
What::Name => (tr!("ask.name"), tr!("ask.name_field"), tr!("ask.rename")),
|
||||
};
|
||||
let good = match ask.what {
|
||||
What::Add => !links(&ask.text).is_empty(),
|
||||
What::Link => links(&ask.text).len() == 1,
|
||||
What::Folder => Path::new(ask.text.trim()).is_absolute(),
|
||||
What::Name => !ask.text.trim().is_empty(),
|
||||
};
|
||||
let body = if ask.what == What::Add { tr!("add.body", folder = download_folder(settings).display()) } else { String::new() };
|
||||
let text = &mut ask.text;
|
||||
let rows = if ask.what == What::Add { 4 } else { 1 };
|
||||
let answer = Dialog::new("ask", &head, &main).body(&body).width(size::DIALOG_M).enabled(good).show(ui.ctx(), t, ask.open, |ui| {
|
||||
let r = Field::new(&label).rows(rows).show(ui, t, text);
|
||||
if ui.memory(|m| m.focused().is_none()) {
|
||||
r.request_focus();
|
||||
}
|
||||
});
|
||||
let Some(answer) = answer else { return };
|
||||
ask.open = false;
|
||||
if answer == Answer::Cancel {
|
||||
return;
|
||||
}
|
||||
let (what, id, text) = (ask.what, ask.id, ask.text.trim().to_string());
|
||||
match what {
|
||||
What::Add => {
|
||||
for url in links(&text) {
|
||||
self.bridge.send(Command::Add(Box::new(Task { url, folder: download_folder(settings), ..Task::default() })));
|
||||
}
|
||||
}
|
||||
What::Link => {
|
||||
let url = links(&text).remove(0);
|
||||
self.bridge.send(Command::Edit { id, edit: Box::new(move |t| t.url = url) });
|
||||
self.bridge.send(Command::Resume(id));
|
||||
}
|
||||
What::Folder => self.bridge.send(Command::Move { id, folder: PathBuf::from(text) }),
|
||||
What::Name => self.bridge.send(Command::Rename { id, name: text }),
|
||||
}
|
||||
}
|
||||
|
||||
fn order(&mut self, ui: &Ui, shot: &Snapshot, order: Order) {
|
||||
match order {
|
||||
Order::Add => self.begin(What::Add, 0, String::new()),
|
||||
Order::Find => self.focus_search = true,
|
||||
Order::Paste(text) => {
|
||||
if !links(&text).is_empty() {
|
||||
self.begin(What::Add, 0, text);
|
||||
}
|
||||
}
|
||||
Order::Place(moves) => {
|
||||
for (id, queue, position) in moves {
|
||||
self.bridge.send(Command::Edit { id, edit: Box::new(move |t| (t.queue, t.position) = (queue, position)) });
|
||||
}
|
||||
}
|
||||
Order::Do(act, ids) => {
|
||||
let views: Vec<Arc<TaskView>> = ids.iter().filter_map(|id| shot.get(*id).cloned()).collect();
|
||||
if !views.is_empty() {
|
||||
self.act(ui, act, &views);
|
||||
}
|
||||
}
|
||||
}
|
||||
motion::keep_alive();
|
||||
}
|
||||
|
||||
fn act(&mut self, ui: &Ui, act: Act, views: &[Arc<TaskView>]) {
|
||||
let first = &views[0];
|
||||
let each = |make: &dyn Fn(TaskId) -> Command| views.iter().for_each(|v| self.bridge.send(make(v.id())));
|
||||
match act {
|
||||
Act::Start => each(&Command::Start),
|
||||
Act::Resume => each(&Command::Resume),
|
||||
Act::Pause => each(&Command::Pause),
|
||||
Act::Stop => each(&Command::Stop),
|
||||
Act::Redownload => each(&Command::Redownload),
|
||||
Act::KeepBoth => each(&Command::KeepBoth),
|
||||
Act::Priority(p) => each(&|id| Command::Edit { id, edit: Box::new(move |t| t.priority = p) }),
|
||||
Act::Queue(q) => each(&|id| Command::Edit { id, edit: Box::new(move |t| t.queue = q) }),
|
||||
Act::Tag(tag, on) => each(&|id| Command::Edit {
|
||||
id,
|
||||
edit: Box::new(move |t| {
|
||||
t.tags.retain(|g| *g != tag);
|
||||
if on {
|
||||
t.tags.push(tag);
|
||||
}
|
||||
}),
|
||||
}),
|
||||
Act::Remove(files) => {
|
||||
each(&|id| Command::Remove { id, files });
|
||||
let words = match (files, views.len()) {
|
||||
(Files::Keep, 1) => tr!("toast.removed_one", name = title(first)),
|
||||
(Files::Keep, n) => tr!("toast.removed", n = n),
|
||||
(Files::Bin, 1) => tr!("toast.binned_one", name = title(first)),
|
||||
(Files::Bin, n) => tr!("toast.binned", n = n),
|
||||
};
|
||||
self.toasts.undo("delete", words, Reply::Undo(views.iter().map(|v| v.id()).collect()));
|
||||
}
|
||||
Act::Open => {
|
||||
let path = first.task.folder.join(&first.task.name);
|
||||
if first.state() == State::Done && path.is_absolute() {
|
||||
(self.outside)(&path.to_string_lossy());
|
||||
}
|
||||
}
|
||||
Act::Show => {
|
||||
if first.task.folder.is_absolute() {
|
||||
(self.outside)(&first.task.folder.to_string_lossy());
|
||||
}
|
||||
}
|
||||
Act::Copy => {
|
||||
let all: Vec<&str> = views.iter().map(|v| v.task.url.as_str()).collect();
|
||||
ui.ctx().copy_text(all.join("\n"));
|
||||
self.toasts.info("content_copy", tr!("toast.copied", n = views.len()));
|
||||
}
|
||||
Act::OpenPage => {
|
||||
if let Some(page) = first.task.source_page.as_deref().filter(|p| p.starts_with("http://") || p.starts_with("https://")) {
|
||||
(self.outside)(page);
|
||||
}
|
||||
}
|
||||
// A plain page is what such networks put their own in place of.
|
||||
Act::Portal => (self.outside)(&format!("http://{}/", first.server)),
|
||||
Act::EditLink => self.begin(What::Link, first.id(), first.task.url.clone()),
|
||||
Act::EditFolder => self.begin(What::Folder, first.id(), first.task.folder.to_string_lossy().into_owned()),
|
||||
Act::EditName => self.begin(What::Name, first.id(), first.task.name.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Face {
|
||||
App,
|
||||
Icon(&'static str),
|
||||
}
|
||||
|
||||
/// The web addresses in a text, one after another.
|
||||
pub fn links(text: &str) -> Vec<String> {
|
||||
let is = |w: &&str| ["http://", "https://"].iter().any(|s| w.len() > s.len() && w.get(..s.len()).is_some_and(|h| h.eq_ignore_ascii_case(s)));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
text.split_whitespace().filter(is).filter(|w| seen.insert(w.to_string())).map(String::from).collect()
|
||||
}
|
||||
6
crates/app/src/views/mod.rs
Normal file
6
crates/app/src/views/mod.rs
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
//! The screens.
|
||||
|
||||
pub mod bar;
|
||||
pub mod list;
|
||||
pub mod main;
|
||||
pub mod rail;
|
||||
164
crates/app/src/views/rail.rs
Normal file
164
crates/app/src/views/rail.rs
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
//! What the list can show, at the left: states, queues, tags and types. Narrow, it keeps only the icons.
|
||||
|
||||
use super::list::model::{Counts, Filter, Status, kind_label, queue_name};
|
||||
use crate::bridge::Lists;
|
||||
use crate::fonts;
|
||||
use crate::icons;
|
||||
use crate::motion::spring;
|
||||
use crate::theme::{Theme, alpha, hex, mix};
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT};
|
||||
use crate::tokens::{icon, radius, size, space, text};
|
||||
use crate::ui::shape::{self, Kind};
|
||||
use crate::ui::widgets::{Button, cr, feel, left, lerp, line, ring, text_width, tip};
|
||||
use eframe::egui::accesskit::Role;
|
||||
use eframe::egui::{Align2, Color32, Rect, ScrollArea, Sense, Ui, UiBuilder, Vec2, WidgetInfo, vec2};
|
||||
use medlar_core::tr;
|
||||
|
||||
pub const NARROW: f32 = 64.0;
|
||||
pub const WIDE: f32 = 216.0;
|
||||
const ROW: f32 = size::CONTROL;
|
||||
const GAP: f32 = space::XS;
|
||||
|
||||
enum Mark {
|
||||
Icon(&'static str),
|
||||
Kind(Kind),
|
||||
/// The first letter of its name.
|
||||
Letter,
|
||||
Dot(Color32),
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
mark: Mark,
|
||||
name: String,
|
||||
count: usize,
|
||||
on: bool,
|
||||
}
|
||||
|
||||
/// Draws the rail in `rect`, which is between `NARROW` and `WIDE`. True when its button was clicked.
|
||||
pub fn show(ui: &mut Ui, t: &Theme, rect: Rect, open: bool, filter: &mut Filter, counts: &Counts, lists: &Lists) -> bool {
|
||||
ui.painter().rect_filled(rect, 0.0, t.low);
|
||||
let mut child = ui.new_child(UiBuilder::new().max_rect(rect).id_salt("rail"));
|
||||
let ui = &mut child;
|
||||
ui.set_clip_rect(rect);
|
||||
let menu = Rect::from_min_size(rect.min + vec2((NARROW - size::CONTROL) / 2.0, space::M), Vec2::splat(size::CONTROL));
|
||||
let mut button = ui.new_child(UiBuilder::new().max_rect(menu).id_salt("menu"));
|
||||
let name = if open { tr!("rail.close") } else { tr!("rail.open") };
|
||||
let clicked = Button::icon(if open { "menu_open" } else { "menu" }, &name).show(&mut button, t).clicked();
|
||||
if rect.width() > NARROW + 80.0 {
|
||||
let words = line(ui.painter(), "Medlar", fonts::semi(text::TITLE), t.on_surface, rect.right() - menu.right());
|
||||
left(ui.painter(), menu.right_center() + vec2(space::S, 0.0), words);
|
||||
}
|
||||
let body = Rect::from_min_max(rect.min + vec2(0.0, menu.bottom() - rect.top() + space::S), rect.max);
|
||||
let mut body = ui.new_child(UiBuilder::new().max_rect(body).id_salt("entries"));
|
||||
ScrollArea::vertical().auto_shrink(false).show(&mut body, |ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(0.0, GAP);
|
||||
let at = |n: Option<&usize>| n.copied().unwrap_or(0);
|
||||
let states = Status::ALL.map(|s| Entry { mark: Mark::Icon(s.icon()), name: s.label(), count: at(counts.status.get(&s)), on: filter.status == s });
|
||||
if let Some(i) = section(ui, t, rect, "", &states, true) {
|
||||
filter.status = Status::ALL[i];
|
||||
}
|
||||
if lists.queues.len() > 1 {
|
||||
let queues: Vec<Entry> = lists
|
||||
.queues
|
||||
.iter()
|
||||
.map(|q| Entry { mark: Mark::Letter, name: queue_name(lists, q.id), count: at(counts.queues.get(&q.id)), on: filter.queue == Some(q.id) })
|
||||
.collect();
|
||||
if let Some(i) = section(ui, t, rect, &tr!("rail.queues"), &queues, false) {
|
||||
filter.queue = Some(lists.queues[i].id).filter(|q| filter.queue != Some(*q));
|
||||
}
|
||||
}
|
||||
if !lists.tags.is_empty() {
|
||||
let colour = |c: &Option<String>| c.as_deref().and_then(hex).unwrap_or(t.outline);
|
||||
let tags: Vec<Entry> = lists
|
||||
.tags
|
||||
.iter()
|
||||
.map(|g| Entry { mark: Mark::Dot(colour(&g.color)), name: g.name.clone(), count: at(counts.tags.get(&g.id)), on: filter.tag == Some(g.id) })
|
||||
.collect();
|
||||
if let Some(i) = section(ui, t, rect, &tr!("rail.tags"), &tags, false) {
|
||||
filter.tag = Some(lists.tags[i].id).filter(|g| filter.tag != Some(*g));
|
||||
}
|
||||
}
|
||||
// Types that are there, and the one that is asked for.
|
||||
let there: Vec<Kind> = Kind::ALL.into_iter().filter(|k| counts.kinds.contains_key(k) || filter.kind == Some(*k)).collect();
|
||||
let kinds: Vec<Entry> =
|
||||
there.iter().map(|k| Entry { mark: Mark::Kind(*k), name: kind_label(*k), count: at(counts.kinds.get(k)), on: filter.kind == Some(*k) }).collect();
|
||||
if !kinds.is_empty()
|
||||
&& let Some(i) = section(ui, t, rect, &tr!("rail.kinds"), &kinds, false)
|
||||
{
|
||||
filter.kind = Some(there[i]).filter(|k| filter.kind != Some(*k));
|
||||
}
|
||||
ui.add_space(space::L);
|
||||
});
|
||||
clicked
|
||||
}
|
||||
|
||||
/// Entries under a title. Gives back the one that was clicked. `slide`: one is always on, and the mark slides to it.
|
||||
fn section(ui: &mut Ui, t: &Theme, rail: Rect, title: &str, entries: &[Entry], slide: bool) -> Option<usize> {
|
||||
let room = rail.width() - 2.0 * space::M;
|
||||
// How far it is open.
|
||||
let open = ((rail.width() - NARROW) / (WIDE - NARROW)).clamp(0.0, 1.0);
|
||||
if !title.is_empty() {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(rail.width(), lerp(space::L, space::XXL, open).round()), Sense::hover());
|
||||
let p = ui.painter();
|
||||
let x = rail.left() + space::XL;
|
||||
p.hline(rail.left() + space::M..=rail.right() - space::M, lerp(r.top() + space::S - 2.0, r.top(), open), (size::HAIRLINE, alpha(t.outline_variant, 1.0 - open)));
|
||||
let words = line(p, title, fonts::med(text::LABEL), alpha(t.on_variant, open), WIDE - 2.0 * space::XL);
|
||||
left(p, eframe::egui::pos2(x, r.bottom() - space::M), words);
|
||||
}
|
||||
let top = ui.cursor().top();
|
||||
if slide && let Some(on) = entries.iter().position(|e| e.on) {
|
||||
let y = spring("rail mark", on as f32 * (ROW + GAP), DEFAULT);
|
||||
let r = Rect::from_min_size(eframe::egui::pos2(rail.left() + space::M, top + y), vec2(room, ROW));
|
||||
ui.painter().rect_filled(r, cr(radius::FULL.min(ROW / 2.0)), t.secondary_container);
|
||||
}
|
||||
let mut clicked = None;
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
let (whole, _) = ui.allocate_exact_size(vec2(rail.width(), ROW), Sense::hover());
|
||||
let rect = Rect::from_min_size(whole.min + vec2(space::M, 0.0), vec2(room, ROW));
|
||||
let r = ui.interact(rect, eframe::egui::Id::unique(("rail", title, i)), Sense::click());
|
||||
r.widget_info(|| WidgetInfo::selected(Role::Button, true, e.on, &e.name));
|
||||
let f = feel(&r, true);
|
||||
let p = ui.painter();
|
||||
let corner = cr(ROW / 2.0);
|
||||
let on = spring(r.id.with("on"), f32::from(e.on), EFFECT).clamp(0.0, 1.0);
|
||||
if !slide && on > 0.0 {
|
||||
p.rect_filled(rect, corner, alpha(t.secondary_container, on));
|
||||
}
|
||||
if f.tint > 0.0 {
|
||||
p.rect_filled(rect, corner, alpha(t.on_surface, f.tint));
|
||||
}
|
||||
if f.focus {
|
||||
ring(p, t, rect.shrink(2.0 * size::FOCUS_RING), corner);
|
||||
}
|
||||
let ink = mix(t.on_variant, t.on_secondary_container, on);
|
||||
let at = rect.left_center() + vec2(size::CONTROL / 2.0, 0.0);
|
||||
match e.mark {
|
||||
Mark::Icon(name) => icons::paint(p, at, icon::M, name, ink),
|
||||
Mark::Kind(k) => shape::form(p, at, icon::M / 2.0, k.form(), ink),
|
||||
Mark::Letter => {
|
||||
let first: String = e.name.chars().take(1).flat_map(char::to_uppercase).collect();
|
||||
p.circle_stroke(at, icon::M / 2.0 - 1.0, (1.5, ink));
|
||||
p.text(at, Align2::CENTER_CENTER, first, fonts::semi(text::LABEL), ink);
|
||||
}
|
||||
Mark::Dot(c) => {
|
||||
p.circle_filled(at, space::S - 2.0, c);
|
||||
}
|
||||
}
|
||||
if open > 0.0 {
|
||||
let count = if e.count > 0 { e.count.to_string() } else { String::new() };
|
||||
let count_wide = text_width(p, &count, fonts::ui(text::LABEL));
|
||||
let ink = alpha(ink, open);
|
||||
p.text(rect.right_center() - vec2(space::L, 0.0), Align2::RIGHT_CENTER, count, fonts::ui(text::LABEL), ink);
|
||||
let x = rect.left() + size::CONTROL;
|
||||
let name = line(p, &e.name, fonts::med(text::BODY), ink, WIDE - 2.0 * space::M - size::CONTROL - count_wide - space::XL);
|
||||
left(p, eframe::egui::pos2(x, rect.center().y), name);
|
||||
}
|
||||
if open < 0.5 {
|
||||
tip(&r, t, &tr!("rail.tip", name = e.name, n = e.count), "");
|
||||
}
|
||||
if r.clicked() {
|
||||
clicked = Some(i);
|
||||
}
|
||||
}
|
||||
clicked
|
||||
}
|
||||
542
crates/app/tests/main.rs
Normal file
542
crates/app/tests/main.rs
Normal file
|
|
@ -0,0 +1,542 @@
|
|||
//! The daily screen: what the list shows, the pointer, the keyboard, commands, motion, and the engine behind it.
|
||||
|
||||
#[path = "main/fixture.rs"]
|
||||
mod fixture;
|
||||
|
||||
use eframe::egui::{Event, Key, Modifiers, PointerButton, Pos2, Vec2, pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use fixture::{all, failed, lists, many, shot, view};
|
||||
use medlar_app::app::App;
|
||||
use medlar_app::bridge::{Bridge, Opening};
|
||||
use medlar_app::desktop::Sources;
|
||||
use medlar_app::ui::shape::Kind;
|
||||
use medlar_app::views::list::layout::Form;
|
||||
use medlar_app::views::list::model::{Age, Filter, Group, Listing, Query, Sort, Status, places};
|
||||
use medlar_app::views::main::links;
|
||||
use medlar_core::manager::{Command, Files};
|
||||
use medlar_core::model::{ErrorKind, State, Task, TaskId};
|
||||
use medlar_core::net_state::Bus;
|
||||
use medlar_core::paths::Paths;
|
||||
use medlar_core::settings::{Motion, Settings};
|
||||
use medlar_core::snapshot::{Snapshot, TaskView};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
type H = Harness<'static, Option<App>>;
|
||||
|
||||
fn harness_at(size: Vec2, set: impl Fn(&mut App) + 'static) -> H {
|
||||
let frame = move |ui: &mut eframe::egui::Ui, s: &mut Option<App>| {
|
||||
let Some(app) = s else {
|
||||
let nowhere = Sources { caelestia: "/nonexistent".into(), kde: "/nonexistent".into() };
|
||||
let mut app = App::new(ui.ctx(), Settings { motion: Motion::Normal, ..Settings::default() }, nowhere);
|
||||
set(&mut app);
|
||||
*s = Some(app);
|
||||
ui.ctx().request_repaint();
|
||||
return;
|
||||
};
|
||||
app.show(ui);
|
||||
};
|
||||
let mut h = Harness::builder().with_size(size).with_step_dt(1.0 / 60.0).build_ui_state(frame, None);
|
||||
h.run_steps(60);
|
||||
h
|
||||
}
|
||||
|
||||
fn harness(views: Vec<TaskView>) -> H {
|
||||
let shot = std::cell::RefCell::new(Some(shot(views)));
|
||||
harness_at(vec2(1280.0, 900.0), move |app| app.main.bridge = Bridge::still(shot.take().unwrap(), lists()))
|
||||
}
|
||||
|
||||
fn app(h: &mut H) -> &mut App {
|
||||
h.state_mut().as_mut().unwrap()
|
||||
}
|
||||
|
||||
fn set(h: &mut H, views: Vec<TaskView>) {
|
||||
thread_local!(static REV: std::cell::Cell<u64> = const { std::cell::Cell::new(1000) });
|
||||
let mut shot = shot(views);
|
||||
REV.set(REV.get() + 1);
|
||||
shot.rev = REV.get();
|
||||
app(h).main.bridge.set_still(shot);
|
||||
}
|
||||
|
||||
fn simple(n: i64) -> Vec<TaskView> {
|
||||
(1..=n).map(|id| view(id, &format!("file-{id:02}.zip"), "a.example.org", State::Paused, 1000, 0.5)).collect()
|
||||
}
|
||||
|
||||
fn row(h: &H, name: &str) -> eframe::egui::Rect {
|
||||
h.get_by_label(name).rect()
|
||||
}
|
||||
|
||||
fn pointer(h: &mut H, pos: Pos2, button: PointerButton, pressed: bool, modifiers: Modifiers) {
|
||||
h.input_mut().events.push(Event::ModifiersChanged(modifiers));
|
||||
h.input_mut().events.push(Event::PointerMoved(pos));
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button, pressed, modifiers });
|
||||
h.step();
|
||||
}
|
||||
|
||||
fn click_with(h: &mut H, pos: Pos2, modifiers: Modifiers) {
|
||||
pointer(h, pos, PointerButton::Primary, true, modifiers);
|
||||
pointer(h, pos, PointerButton::Primary, false, modifiers);
|
||||
h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE));
|
||||
// Two clicks must not make a double click.
|
||||
h.run_steps(30);
|
||||
}
|
||||
|
||||
fn click(h: &mut H, pos: Pos2) {
|
||||
click_with(h, pos, Modifiers::NONE);
|
||||
}
|
||||
|
||||
fn drag(h: &mut H, from: Pos2, to: Pos2) {
|
||||
pointer(h, from, PointerButton::Primary, true, Modifiers::NONE);
|
||||
for i in 1..=10 {
|
||||
h.input_mut().events.push(Event::PointerMoved(from + (to - from) * (i as f32 / 10.0)));
|
||||
h.step();
|
||||
}
|
||||
pointer(h, to, PointerButton::Primary, false, Modifiers::NONE);
|
||||
h.step();
|
||||
}
|
||||
|
||||
fn key(h: &mut H, modifiers: Modifiers, key: Key) {
|
||||
h.key_press_modifiers(modifiers, key);
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
fn selected(h: &mut H) -> Vec<TaskId> {
|
||||
app(h).main.list.chosen()
|
||||
}
|
||||
|
||||
fn sent(h: &mut H) -> Vec<Command> {
|
||||
app(h).main.bridge.take_sent()
|
||||
}
|
||||
|
||||
/// The middle of a row's name, where nothing else answers.
|
||||
fn name(h: &H, of: &str) -> Pos2 {
|
||||
let r = row(h, of);
|
||||
pos2(r.left() + 160.0, r.center().y)
|
||||
}
|
||||
|
||||
fn listed(query: &Query, shot: &Snapshot) -> (Vec<TaskId>, Listing) {
|
||||
let mut listing = Listing::default();
|
||||
listing.update(shot, query, &Arc::new(lists()), medlar_app::views::list::model::today(medlar_core::model::now()));
|
||||
(listing.rows.iter().map(|v| v.id()).collect(), listing)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_search_sort_and_groups() {
|
||||
let mut views = all();
|
||||
Arc::make_mut(&mut views[7].task).tags = vec![2];
|
||||
Arc::make_mut(&mut views[4].task).queue = 2;
|
||||
let s = shot(views);
|
||||
let plain = Query { group: Group::None, ..Query::default() };
|
||||
let ids = |q: &Query| listed(q, &s).0;
|
||||
let with = |f: Filter| ids(&Query { filter: f, ..plain.clone() });
|
||||
assert_eq!(with(Filter { status: Status::Failed, ..Filter::default() }), [9, 10]);
|
||||
assert_eq!(with(Filter { kind: Some(Kind::Audio), ..Filter::default() }), [8, 5]);
|
||||
assert_eq!(with(Filter { tag: Some(2), ..Filter::default() }), [8]);
|
||||
assert_eq!(with(Filter { queue: Some(2), ..Filter::default() }), [5]);
|
||||
assert_eq!(with(Filter { host: Some("share.example.org:443".into()), ..Filter::default() }), [4, 12]);
|
||||
assert!(with(Filter { age: Some(Age::Older), ..Filter::default() }).is_empty());
|
||||
assert_eq!(with(Filter { search: " Example.EDU mp3".into(), ..Filter::default() }), [5]);
|
||||
// The second queue comes after the first.
|
||||
assert_eq!(ids(&plain).last(), Some(&5));
|
||||
let by = |sort, down| ids(&Query { sort, down, ..plain.clone() });
|
||||
assert_eq!(by(Sort::Size, true)[0], 7);
|
||||
assert_eq!(by(Sort::Speed, true)[..2], [1, 2]);
|
||||
assert_eq!(by(Sort::Name, false)[0], 2);
|
||||
assert_eq!(by(Sort::Added, true)[0], 1);
|
||||
let (rows, listing) = listed(&Query::default(), &s);
|
||||
let heads: Vec<_> = listing.heads.iter().map(|h| (h.label.as_str(), h.count)).collect();
|
||||
assert_eq!(heads, [("Downloading", 3), ("Waiting", 4), ("Paused", 1), ("Failed", 2), ("Done", 3)]);
|
||||
assert_eq!(rows[..3], [1, 2, 3]);
|
||||
assert_eq!((listing.head_of(2), listing.head_of(3)), (Some(0), Some(1)));
|
||||
for group in Group::ALL {
|
||||
let (rows, listing) = listed(&Query { group, ..Query::default() }, &s);
|
||||
assert_eq!(rows.len(), 13, "{group:?}");
|
||||
assert_eq!(listing.heads.iter().map(|h| h.count).sum::<usize>(), if group == Group::None { 0 } else { 13 });
|
||||
}
|
||||
assert_eq!(listing.counts.offline, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_places_are_between_the_neighbours() {
|
||||
let (_, l) = listed(&Query { group: Group::None, ..Query::default() }, &shot(simple(6)));
|
||||
assert_eq!(places(&l, &[5], 1), [(5, 1, 1.5)]);
|
||||
assert_eq!(places(&l, &[1], 6), [(1, 1, 7.0)]);
|
||||
assert_eq!(places(&l, &[6], 0), [(6, 1, 0.0)]);
|
||||
let two = places(&l, &[1, 2], 4);
|
||||
assert!(two[0].2 > 4.0 && two[0].2 < two[1].2 && two[1].2 < 5.0, "{two:?}");
|
||||
assert!(places(&l, &[99], 2).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_are_found_in_any_text() {
|
||||
assert_eq!(links("see https://a.org/x\n HTTP://b.org/y, file:///etc/passwd https:// https://a.org/x"), ["https://a.org/x", "HTTP://b.org/y,"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_selects_one_some_and_ranges() {
|
||||
let mut h = harness(simple(8));
|
||||
let (a, b, c) = (name(&h, "file-01.zip"), name(&h, "file-03.zip"), name(&h, "file-05.zip"));
|
||||
click(&mut h, a);
|
||||
assert_eq!(selected(&mut h), [1]);
|
||||
click_with(&mut h, b, Modifiers::COMMAND);
|
||||
assert_eq!(selected(&mut h), [1, 3]);
|
||||
click_with(&mut h, c, Modifiers::SHIFT);
|
||||
assert_eq!(selected(&mut h), [3, 4, 5]);
|
||||
click(&mut h, a);
|
||||
assert_eq!(selected(&mut h), [1]);
|
||||
let below = pos2(a.x, 860.0);
|
||||
click(&mut h, below);
|
||||
assert!(selected(&mut h).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lasso_selects_what_it_touches() {
|
||||
let mut h = harness(simple(8));
|
||||
let (from, to) = (name(&h, "file-02.zip"), name(&h, "file-05.zip"));
|
||||
drag(&mut h, from, to + vec2(60.0, 0.0));
|
||||
assert_eq!(selected(&mut h), [2, 3, 4, 5]);
|
||||
// From the empty ground, too.
|
||||
let start = pos2(900.0, 880.0);
|
||||
let end = name(&h, "file-07.zip");
|
||||
drag(&mut h, start, end);
|
||||
assert_eq!(selected(&mut h), [7, 8]);
|
||||
assert!(sent(&mut h).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handle_moves_a_row_to_another_place() {
|
||||
let mut h = harness(simple(8));
|
||||
let r = row(&h, "file-06.zip");
|
||||
let target = row(&h, "file-02.zip");
|
||||
drag(&mut h, r.left_center() + vec2(16.0, 0.0), target.left_top() + vec2(16.0, 6.0));
|
||||
let sent = sent(&mut h);
|
||||
assert_eq!(sent.len(), 1);
|
||||
let Some(Command::Edit { id: 6, edit }) = sent.into_iter().next() else { panic!("no edit of 6") };
|
||||
let mut t = Task::default();
|
||||
edit(&mut t);
|
||||
assert_eq!((t.queue, t.position), (1, 1.5));
|
||||
// Sorted by anything else there is no handle: the same drag is a lasso.
|
||||
app(&mut h).main.list.query.sort = Sort::Name;
|
||||
h.run_steps(5);
|
||||
drag(&mut h, r.left_center() + vec2(16.0, 0.0), target.left_top() + vec2(16.0, 6.0));
|
||||
assert!(self::sent(&mut h).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_moves_selects_and_acts() {
|
||||
let mut h = harness(simple(30));
|
||||
key(&mut h, Modifiers::NONE, Key::ArrowDown);
|
||||
assert_eq!(selected(&mut h), [1]);
|
||||
key(&mut h, Modifiers::NONE, Key::ArrowDown);
|
||||
key(&mut h, Modifiers::SHIFT, Key::ArrowDown);
|
||||
assert_eq!(selected(&mut h), [2, 3]);
|
||||
key(&mut h, Modifiers::NONE, Key::End);
|
||||
assert_eq!(selected(&mut h), [30]);
|
||||
// It was scrolled to.
|
||||
assert!(row(&h, "file-30.zip").bottom() <= 900.0);
|
||||
key(&mut h, Modifiers::NONE, Key::Home);
|
||||
key(&mut h, Modifiers::NONE, Key::Space);
|
||||
assert!(matches!(sent(&mut h)[..], [Command::Resume(1)]));
|
||||
key(&mut h, Modifiers::ALT, Key::ArrowDown);
|
||||
assert!(matches!(sent(&mut h)[..], [Command::Edit { id: 1, .. }]));
|
||||
key(&mut h, Modifiers::COMMAND, Key::A);
|
||||
assert_eq!(selected(&mut h).len(), 30);
|
||||
key(&mut h, Modifiers::NONE, Key::Escape);
|
||||
assert!(selected(&mut h).is_empty());
|
||||
// In the search field the keys are its own.
|
||||
key(&mut h, Modifiers::COMMAND, Key::F);
|
||||
key(&mut h, Modifiers::COMMAND, Key::A);
|
||||
key(&mut h, Modifiers::NONE, Key::Delete);
|
||||
assert!(selected(&mut h).is_empty() && sent(&mut h).is_empty());
|
||||
h.input_mut().events.push(Event::Text("file-07".into()));
|
||||
h.run_steps(5);
|
||||
assert_eq!(app(&mut h).main.list.listing().rows.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removal_is_undone_from_the_message() {
|
||||
let mut h = harness(simple(4));
|
||||
let at = name(&h, "file-02.zip");
|
||||
click(&mut h, at);
|
||||
key(&mut h, Modifiers::NONE, Key::Delete);
|
||||
assert!(matches!(sent(&mut h)[..], [Command::Remove { id: 2, files: Files::Keep }]));
|
||||
// The keyboard goes on from the next row.
|
||||
assert_eq!(selected(&mut h), [3]);
|
||||
key(&mut h, Modifiers::SHIFT, Key::Delete);
|
||||
assert!(matches!(sent(&mut h)[..], [Command::Remove { id: 3, files: Files::Bin }]));
|
||||
h.run_steps(60);
|
||||
let undo = h.get_all_by_label("Undo").map(|n| n.rect().center()).max_by(|a, b| a.y.total_cmp(&b.y)).unwrap();
|
||||
click(&mut h, undo);
|
||||
assert!(matches!(sent(&mut h)[..], [Command::Restore(3)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_selects_its_row_and_acts() {
|
||||
let mut h = harness(simple(4));
|
||||
let at = name(&h, "file-03.zip");
|
||||
pointer(&mut h, at, PointerButton::Secondary, true, Modifiers::NONE);
|
||||
pointer(&mut h, at, PointerButton::Secondary, false, Modifiers::NONE);
|
||||
h.run_steps(30);
|
||||
assert_eq!(selected(&mut h), [3]);
|
||||
let item = h.get_by_label("Start now").rect().center();
|
||||
click(&mut h, item);
|
||||
assert!(matches!(sent(&mut h)[..], [Command::Start(3)]));
|
||||
// The same from the keyboard.
|
||||
key(&mut h, Modifiers::SHIFT, Key::F10);
|
||||
h.run_steps(30);
|
||||
assert!(h.query_by_label("Start now").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toolbar_acts_on_all_selected() {
|
||||
let mut h = harness(simple(4));
|
||||
let (a, b) = (name(&h, "file-01.zip"), name(&h, "file-03.zip"));
|
||||
click(&mut h, a);
|
||||
click_with(&mut h, b, Modifiers::SHIFT);
|
||||
h.run_steps(60);
|
||||
// The toolbar's is the lowest of that name.
|
||||
let resume = h.get_all_by_label("Resume").map(|n| n.rect().center()).max_by(|a, b| a.y.total_cmp(&b.y)).unwrap();
|
||||
click(&mut h, resume);
|
||||
assert!(matches!(sent(&mut h)[..], [Command::Resume(1), Command::Resume(2), Command::Resume(3)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn problems_offer_their_fix() {
|
||||
let mut h = harness(all());
|
||||
// A grouped list is longer than the window.
|
||||
app(&mut h).main.list.query.filter.status = Status::Failed;
|
||||
h.run_steps(60);
|
||||
let choose = h.get_by_label("Choose").rect().center();
|
||||
click(&mut h, choose);
|
||||
let keep = h.get_by_label("Keep both").rect().center();
|
||||
click(&mut h, keep);
|
||||
assert!(matches!(sent(&mut h)[..], [Command::KeepBoth(10)]));
|
||||
let link = h.get_by_label("Get new link").rect().center();
|
||||
click(&mut h, link);
|
||||
h.run_steps(60);
|
||||
let save = h.get_by_label("Save and resume").rect().center();
|
||||
click(&mut h, save);
|
||||
assert!(matches!(sent(&mut h)[..], [Command::Edit { id: 9, .. }, Command::Resume(9)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_next_try_is_counted_down() {
|
||||
let mut v = failed(view(1, "a.zip", "a.example.org", State::Waiting, 1000, 0.0), ErrorKind::Busy, "");
|
||||
v.retry_at = Some(medlar_core::model::now() + 2500);
|
||||
let mut h = harness(vec![v]);
|
||||
// Asleep until the next second, not awake all the time.
|
||||
let delay = h.output().viewport_output.values().map(|o| o.repaint_delay).min().unwrap();
|
||||
assert!(delay > Duration::from_millis(20) && delay <= Duration::from_secs(1), "{delay:?}");
|
||||
h.step();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_state_of_the_screen() {
|
||||
let mut h = harness(vec![]);
|
||||
let add = h.get_by_label("Add").rect().center();
|
||||
click(&mut h, add);
|
||||
h.run_steps(60);
|
||||
assert!(h.get_all_by_label("Add downloads").count() > 0);
|
||||
h.input_mut().events.push(Event::Text("https://a.example.org/x.zip nonsense".into()));
|
||||
h.run_steps(5);
|
||||
let go = h.get_by_label("Download").rect().center();
|
||||
click(&mut h, go);
|
||||
let sent = sent(&mut h);
|
||||
let [Command::Add(task)] = &sent[..] else { panic!("not added") };
|
||||
assert_eq!(task.url, "https://a.example.org/x.zip");
|
||||
|
||||
let mut h = harness(all());
|
||||
app(&mut h).main.list.query.filter.search = "no such thing".into();
|
||||
h.run_steps(60);
|
||||
let clear = h.get_by_label("Clear filters").rect().center();
|
||||
click(&mut h, clear);
|
||||
assert_eq!(app(&mut h).main.list.listing().rows.len(), 13);
|
||||
|
||||
for why in [None, Some("The download list could not be read.")] {
|
||||
let mut h = harness_at(vec2(480.0, 360.0), move |app| app.main.bridge = Bridge::stuck(why));
|
||||
h.run_steps(5);
|
||||
assert_eq!(h.query_by_label("Try again").is_some(), why.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_size_and_form_draws_inside_its_list() {
|
||||
for size in [vec2(480.0, 360.0), vec2(640.0, 480.0), vec2(900.0, 700.0), vec2(3440.0, 1440.0)] {
|
||||
for form in [Form::Compact, Form::Cards] {
|
||||
let mut h = harness_at(size, move |app| {
|
||||
app.main.bridge = Bridge::still(shot(all()), lists());
|
||||
app.main.list.form = form;
|
||||
});
|
||||
h.run_steps(30);
|
||||
let rows: Vec<_> = h.get_all_by_role(eframe::egui::accesskit::Role::ListBoxOption).map(|n| n.rect()).collect();
|
||||
assert!(!rows.is_empty(), "{size} {form:?}");
|
||||
for r in &rows {
|
||||
assert!(r.left() >= 64.0 && r.right() <= size.x, "{size} {form:?} {r}");
|
||||
}
|
||||
for (i, a) in rows.iter().enumerate() {
|
||||
assert!(rows[..i].iter().all(|b| !a.shrink(0.5).intersects(*b)), "{size} {form:?} {a}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn top(h: &H, of: &str) -> f32 {
|
||||
row(h, of).top()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_few_changes_move_and_many_do_not() {
|
||||
let mut h = harness(simple(10));
|
||||
let home = top(&h, "file-01.zip");
|
||||
// One more, above all.
|
||||
let mut views = simple(10);
|
||||
let mut new = view(11, "new.zip", "a.example.org", State::Paused, 1000, 0.0);
|
||||
Arc::make_mut(&mut new.task).position = 0.5;
|
||||
views.push(new);
|
||||
set(&mut h, views.clone());
|
||||
h.step();
|
||||
h.step();
|
||||
let mid = top(&h, "file-01.zip");
|
||||
assert!(mid > home - 12.0 && mid < home + 56.0, "{home} {mid}");
|
||||
h.run_steps(120);
|
||||
assert_eq!(top(&h, "file-01.zip"), home + 56.0);
|
||||
assert!(app(&mut h).main.list.is_still() && !h.ctx.has_requested_repaint(), "at rest");
|
||||
// To another state, under another heading.
|
||||
Arc::make_mut(&mut views[4].task).state = State::Done;
|
||||
set(&mut h, views.clone());
|
||||
h.run_steps(2);
|
||||
assert!(!app(&mut h).main.list.is_still());
|
||||
h.run_steps(120);
|
||||
assert!(app(&mut h).main.list.is_still());
|
||||
// Gone.
|
||||
views.remove(2);
|
||||
set(&mut h, views.clone());
|
||||
h.run_steps(2);
|
||||
assert!(!app(&mut h).main.list.is_still());
|
||||
h.run_steps(120);
|
||||
// 40 at once.
|
||||
views.extend((20..60).map(|id| view(id, &format!("bulk-{id}.zip"), "a.example.org", State::Paused, 1000, 0.0)));
|
||||
set(&mut h, views);
|
||||
h.run_steps(2);
|
||||
assert!(app(&mut h).main.list.is_still());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_keyboard_moves_nothing() {
|
||||
let mut h = harness(simple(10));
|
||||
let at = name(&h, "file-02.zip");
|
||||
click(&mut h, at);
|
||||
key(&mut h, Modifiers::NONE, Key::Delete);
|
||||
let mut views = simple(10);
|
||||
views.remove(1);
|
||||
set(&mut h, views);
|
||||
h.run_steps(2);
|
||||
assert!(app(&mut h).main.list.is_still());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_drawn_at_rest() {
|
||||
let mut h = harness(simple(10));
|
||||
h.run_steps(120);
|
||||
assert!(!h.ctx.has_requested_repaint());
|
||||
}
|
||||
|
||||
/// The time of one frame, without drawing it on the screen. Numbers count in release: `--release -- --nocapture frame`.
|
||||
#[test]
|
||||
fn frame_of_ten_thousand_rows_is_quick() {
|
||||
for form in [Form::Compact, Form::Cards] {
|
||||
let mut h = harness_at(vec2(1600.0, 900.0), move |app| {
|
||||
app.main.bridge = Bridge::still(many(10_000, 1), lists());
|
||||
app.main.list.form = form;
|
||||
});
|
||||
let at = pos2(900.0, 600.0);
|
||||
h.input_mut().events.push(Event::PointerMoved(at));
|
||||
h.run_steps(30);
|
||||
let measure = |h: &mut H, scroll: bool, change: bool| {
|
||||
let mut times = vec![];
|
||||
for i in 0..120u64 {
|
||||
if change && i % 6 == 0 {
|
||||
app(h).main.bridge.set_still(many(10_000, i + 2));
|
||||
}
|
||||
if scroll {
|
||||
let delta = vec2(0.0, -230.0);
|
||||
h.input_mut().events.push(Event::MouseWheel {
|
||||
unit: eframe::egui::MouseWheelUnit::Point,
|
||||
delta,
|
||||
phase: eframe::egui::TouchPhase::Move,
|
||||
source: eframe::egui::MouseWheelSource::Trackpad,
|
||||
modifiers: Modifiers::NONE,
|
||||
});
|
||||
}
|
||||
let begun = Instant::now();
|
||||
h.step();
|
||||
times.push(begun.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
times.sort_by(f64::total_cmp);
|
||||
(times[60], times[113], times[119])
|
||||
};
|
||||
let scrolling = measure(&mut h, true, false);
|
||||
let both = measure(&mut h, true, true);
|
||||
println!("{form:?}: scrolling median {:.2}, 95 % {:.2}, worst {:.2} ms; with changes {:.2}, {:.2}, {:.2} ms", scrolling.0, scrolling.1, scrolling.2, both.0, both.1, both.2);
|
||||
if !cfg!(debug_assertions) {
|
||||
assert!(scrolling.1 < 8.0 && both.1 < 8.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_real_engine_downloads_and_closes() {
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
let server = runtime.block_on(medlar_testserver::TestServer::start());
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let at = |n: &str| dir.path().join(n);
|
||||
let paths = Paths { config: at("config"), data: at("data"), state: at("state"), cache: at("cache"), portable: false };
|
||||
paths.create().unwrap();
|
||||
let folder = at("downloads");
|
||||
let mut h = harness_at(vec2(1000.0, 700.0), |_| {});
|
||||
let ctx = h.ctx.clone();
|
||||
let settings = Settings { download_folder: folder.to_string_lossy().into(), ..Settings::default() };
|
||||
app(&mut h).settings.download_folder = settings.download_folder.clone();
|
||||
app(&mut h).main.bridge = Bridge::open(Opening { paths: paths.clone(), settings, bus: Bus::Off }, &ctx);
|
||||
let until = |h: &mut H, what: &str, f: &dyn Fn(&H) -> bool| {
|
||||
let end = Instant::now() + Duration::from_secs(60);
|
||||
while !f(h) {
|
||||
assert!(Instant::now() < end, "{what}");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
h.step();
|
||||
}
|
||||
};
|
||||
until(&mut h, "the engine", &|h| h.state().as_ref().unwrap().main.bridge.manager().is_some());
|
||||
let url = server.url(&medlar_testserver::TestServer::data_path(5, 2_000_000));
|
||||
let task = Task { url, folder: folder.clone(), ..Task::default() };
|
||||
app(&mut h).main.bridge.send(Command::Add(Box::new(task)));
|
||||
until(&mut h, "the download", &|h| h.state().as_ref().unwrap().main.list.listing().rows.first().is_some_and(|v| v.state() == State::Done));
|
||||
assert_eq!(std::fs::read_dir(&folder).unwrap().count(), 1);
|
||||
// An order that can't be followed says why.
|
||||
let id = app(&mut h).main.list.listing().rows[0].id();
|
||||
app(&mut h).main.bridge.send(Command::Rename { id, name: "..".into() });
|
||||
until(&mut h, "the error", &|h| !h.state().as_ref().unwrap().main.toasts.is_empty());
|
||||
let begun = Instant::now();
|
||||
app(&mut h).main.bridge.close();
|
||||
assert!(begun.elapsed() < Duration::from_secs(3));
|
||||
h.step();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_list_that_cannot_be_opened_says_so() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bad = dir.path().join("a file");
|
||||
std::fs::write(&bad, "x").unwrap();
|
||||
let paths = Paths { config: bad.clone(), data: bad.clone(), state: bad.clone(), cache: bad, portable: false };
|
||||
let mut h = harness_at(vec2(1000.0, 700.0), |_| {});
|
||||
let ctx = h.ctx.clone();
|
||||
app(&mut h).main.bridge = Bridge::open(Opening { paths, settings: Settings::default(), bus: Bus::Off }, &ctx);
|
||||
let end = Instant::now() + Duration::from_secs(20);
|
||||
while h.query_by_label("Try again").is_none() {
|
||||
assert!(Instant::now() < end);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
h.step();
|
||||
}
|
||||
assert!(!h.get_by_label("Try again").accesskit_node().is_disabled());
|
||||
}
|
||||
138
crates/app/tests/main/fixture.rs
Normal file
138
crates/app/tests/main/fixture.rs
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
//! Downloads in every state, for pictures and tests.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use medlar_app::bridge::Lists;
|
||||
use medlar_core::http::{PartState, PartView};
|
||||
use medlar_core::model::{ErrorKind, Queue, State, Tag, Task, TaskError, TaskId, now};
|
||||
use medlar_core::snapshot::{Counters, Snapshot, TaskView, Totals};
|
||||
use medlar_core::speed::History;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
pub const MB: u64 = 1_000_000;
|
||||
|
||||
pub fn view(id: TaskId, name: &str, host: &str, state: State, size: u64, done: f64) -> TaskView {
|
||||
let downloaded = (size as f64 * done) as u64;
|
||||
let task = Task {
|
||||
id,
|
||||
url: format!("https://{host}/files/{name}"),
|
||||
name: name.into(),
|
||||
folder: "/home/you/Downloads".into(),
|
||||
state,
|
||||
position: id as f64,
|
||||
size: Some(size),
|
||||
downloaded,
|
||||
added_at: now() - id * 3_600_000,
|
||||
..Task::default()
|
||||
};
|
||||
TaskView {
|
||||
task: Arc::new(task),
|
||||
rev: id as u64,
|
||||
size: Some(size),
|
||||
downloaded,
|
||||
speed: 0.0,
|
||||
left: None,
|
||||
parts: Arc::new([]),
|
||||
connections: 0,
|
||||
wanted: 0,
|
||||
resumable: Some(true),
|
||||
checked: 0.0,
|
||||
retry_at: None,
|
||||
fails: 0,
|
||||
server: format!("{host}:443").into(),
|
||||
history: Arc::default(),
|
||||
log: Arc::default(),
|
||||
counters: Counters::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn running(mut v: TaskView, speed: f64, parts: u64) -> TaskView {
|
||||
let size = v.size.unwrap_or(0);
|
||||
let each = size / parts;
|
||||
let share = v.downloaded as f64 / size as f64;
|
||||
v.parts = (0..parts)
|
||||
.map(|i| PartView {
|
||||
id: i as _,
|
||||
start: i * each,
|
||||
end: Some(if i + 1 == parts { size } else { (i + 1) * each }),
|
||||
done: ((each as f64) * (share * (0.7 + 0.1 * (i % 5) as f64)).min(1.0)) as u64,
|
||||
state: PartState::Running,
|
||||
speed: speed / parts as f64,
|
||||
fails: 0,
|
||||
})
|
||||
.collect();
|
||||
(v.speed, v.connections, v.wanted) = (speed, parts as u32, parts as u32);
|
||||
v.left = Some(Duration::from_secs_f64((size - v.downloaded) as f64 / speed));
|
||||
v
|
||||
}
|
||||
|
||||
pub fn failed(mut v: TaskView, kind: ErrorKind, detail: &str) -> TaskView {
|
||||
let task = Arc::make_mut(&mut v.task);
|
||||
task.error = Some(TaskError { kind: Some(kind), detail: detail.into() });
|
||||
v
|
||||
}
|
||||
|
||||
pub fn totals(views: &[TaskView]) -> Totals {
|
||||
let mut history = History::default();
|
||||
(0..150).for_each(|i| history.push(9.0e6 + 4.0e6 * (f64::from(i) * 0.13).sin() + 1.5e6 * (f64::from(i) * 0.71).cos()));
|
||||
Totals {
|
||||
running: views.iter().filter(|v| v.state() == State::Running).count(),
|
||||
queued: views.iter().filter(|v| v.state() == State::Queued).count(),
|
||||
speed: views.iter().map(|v| v.speed).sum(),
|
||||
connections: views.iter().map(|v| v.connections).sum(),
|
||||
history: Arc::new(history),
|
||||
counters: Counters::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn all() -> Vec<TaskView> {
|
||||
let long = "a-very-long-name-of-a-recording-that-nobody-shortened-2026-11-24-evening-session-part-03-final-corrected-version-with-subtitles-and-chapters-remastered.mkv";
|
||||
let mut retry = failed(view(7, "dataset-2026.tar.zst", "data.example.net", State::Waiting, 8200 * MB, 0.33), ErrorKind::Busy, "data.example.net has too many requests right now (status 429).");
|
||||
retry.retry_at = Some(now() + 42_000);
|
||||
vec![
|
||||
running(view(1, "archlinux-2026.11.01-x86_64.iso", "mirror.example.org", State::Running, 1180 * MB, 0.46), 8.4e6, 8),
|
||||
running(view(2, long, "video.example.com", State::Running, 4310 * MB, 0.18), 2.1e6, 4),
|
||||
view(3, "field-notes.pdf", "papers.example.edu", State::Finishing, 18 * MB, 1.0),
|
||||
view(4, "holiday-photos.zip", "share.example.org", State::Queued, 640 * MB, 0.0),
|
||||
view(5, "lecture-12.mp3", "audio.example.edu", State::Queued, 92 * MB, 0.0),
|
||||
failed(view(6, "map-tiles.7z", "tiles.example.org", State::Waiting, 2300 * MB, 0.61), ErrorKind::Offline, "This computer is not connected."),
|
||||
retry,
|
||||
view(8, "podcast-archive.flac", "audio.example.edu", State::Paused, 410 * MB, 0.72),
|
||||
failed(view(9, "report-final.docx", "files.example.com", State::Failed, 4 * MB, 0.5), ErrorKind::Expired, "files.example.com gave out the file before but refuses now (status 403). A new link for the same file continues the download."),
|
||||
failed(view(10, "firmware-3.2.img", "vendor.example.com", State::Failed, 64 * MB, 0.9), ErrorKind::Changed, "vendor.example.com now has another version of the file."),
|
||||
view(11, "wallpaper-forest.png", "images.example.org", State::Done, 12 * MB, 1.0),
|
||||
view(12, "fonts-collection.zip", "share.example.org", State::Done, 210 * MB, 1.0),
|
||||
view(13, "concert.mkv", "video.example.com", State::Gone, 2100 * MB, 1.0),
|
||||
]
|
||||
}
|
||||
|
||||
pub fn lists() -> Lists {
|
||||
let queue = |id, name: &str| Queue { id, name: name.into(), position: id as f64, ..Queue::default() };
|
||||
let tag = |id, name: &str, color: &str| Tag { id, name: name.into(), color: Some(color.into()) };
|
||||
Lists { queues: vec![queue(1, ""), queue(2, "Night"), queue(3, "Work")], tags: vec![tag(1, "Study", "#3f7fd0"), tag(2, "Music", "#b5622b")] }
|
||||
}
|
||||
|
||||
pub fn shot(views: Vec<TaskView>) -> Snapshot {
|
||||
let totals = totals(&views);
|
||||
let mut shot: Snapshot = views.into_iter().collect();
|
||||
shot.totals = totals;
|
||||
shot
|
||||
}
|
||||
|
||||
/// Many, some of them running.
|
||||
pub fn many(n: i64, rev: u64) -> Snapshot {
|
||||
let names = ["video.mkv", "song.mp3", "photo.jpg", "book.pdf", "pack.zip", "tool.AppImage", "thing.bin"];
|
||||
let states = [State::Done, State::Paused, State::Queued, State::Failed, State::Done, State::Done, State::Done];
|
||||
let views = (1..=n).map(|id| {
|
||||
let name = format!("{id:05}-{}", names[id as usize % names.len()]);
|
||||
let host = format!("host{}.example.org", id % 40);
|
||||
let mut v = if id <= 8 {
|
||||
running(view(id, &name, &host, State::Running, 900 * MB, 0.2), 1.0e6 + rev as f64 * 1000.0, 8)
|
||||
} else {
|
||||
view(id, &name, &host, states[id as usize % states.len()], (id as u64 % 900 + 1) * MB, 0.4)
|
||||
};
|
||||
v.rev = rev;
|
||||
v
|
||||
});
|
||||
shot(views.collect())
|
||||
}
|
||||
|
|
@ -8,16 +8,20 @@
|
|||
use eframe::egui::{self, Align2, Color32, Event, Modifiers, PointerButton, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use medlar_app::app::App;
|
||||
use medlar_app::bridge::Bridge;
|
||||
use medlar_app::desktop::Sources;
|
||||
use medlar_app::motion::spring;
|
||||
use medlar_app::theme::{alpha, mix};
|
||||
use medlar_app::tokens::{self, radius, space, text};
|
||||
use medlar_app::ui::gallery;
|
||||
use medlar_app::views::list::layout::Form;
|
||||
use medlar_app::{fonts, icons};
|
||||
use medlar_core::settings::{Appearance, Settings};
|
||||
|
||||
#[path = "visuals/gallery.rs"]
|
||||
mod progress;
|
||||
#[path = "main/fixture.rs"]
|
||||
mod downloads;
|
||||
|
||||
type Scene = (&'static str, fn(&mut App, &mut Ui));
|
||||
|
||||
|
|
@ -32,6 +36,13 @@ 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")),
|
||||
("main", |app, ui| main_view(app, ui, |_| {})),
|
||||
("main-cards", |app, ui| main_view(app, ui, |app| app.main.list.form = Form::Cards)),
|
||||
("main-selected", |app, ui| main_view(app, ui, |app| app.main.list.selected = [2, 4, 9].into())),
|
||||
("main-filtered", |app, ui| main_view(app, ui, |app| app.main.list.query.filter.kind = Some(medlar_app::ui::shape::Kind::Archive))),
|
||||
("main-nothing", |app, ui| main_view(app, ui, |app| app.main.list.query.filter.search = "no such thing".into())),
|
||||
("main-failed", |app, ui| main_view(app, ui, |app| app.main.bridge = Bridge::stuck(Some("The download list was made by a newer Medlar (format 9, this one knows 2). Update Medlar to open it.")))),
|
||||
("main-opening", |app, ui| main_view(app, ui, |app| app.main.bridge = Bridge::stuck(None))),
|
||||
("progress", |app, ui| app.frame(ui, progress::gallery)),
|
||||
("progress-states", |app, ui| app.frame(ui, progress::states)),
|
||||
];
|
||||
|
|
@ -96,6 +107,17 @@ fn shots() {
|
|||
}
|
||||
}
|
||||
|
||||
/// The main screen with downloads in every state, changed once by `set`.
|
||||
fn main_view(app: &mut App, ui: &mut Ui, set: fn(&mut App)) {
|
||||
let seen = egui::Id::unique("main view set");
|
||||
if ui.data(|d| d.get_temp::<bool>(seen).is_none()) {
|
||||
ui.data_mut(|d| d.insert_temp(seen, true));
|
||||
app.main.bridge = Bridge::still(downloads::shot(downloads::all()), downloads::lists());
|
||||
set(app);
|
||||
}
|
||||
app.show(ui);
|
||||
}
|
||||
|
||||
fn over(app: &mut App, ui: &mut Ui, what: &str) {
|
||||
gallery::open(ui, what);
|
||||
app.frame(ui, |app, ui| gallery::page(app, ui, 3));
|
||||
|
|
|
|||
|
|
@ -5,6 +5,131 @@
|
|||
"empty.title": "No downloads yet",
|
||||
"empty.body": "Links you add will show up here.",
|
||||
|
||||
"status.all": "All",
|
||||
"status.active": "Downloading",
|
||||
"status.waiting": "Waiting",
|
||||
"status.paused": "Paused",
|
||||
"status.failed": "Failed",
|
||||
"status.done": "Done",
|
||||
"age.any": "Any day",
|
||||
"age.today": "Today",
|
||||
"age.yesterday": "Yesterday",
|
||||
"age.week": "Last 7 days",
|
||||
"age.month": "Last 30 days",
|
||||
"age.older": "Older",
|
||||
"host.any": "Any server",
|
||||
"kind.video": "Video",
|
||||
"kind.audio": "Audio",
|
||||
"kind.picture": "Pictures",
|
||||
"kind.document": "Documents",
|
||||
"kind.archive": "Archives",
|
||||
"kind.program": "Programs",
|
||||
"kind.other": "Other",
|
||||
"sort.queue": "Queue order",
|
||||
"sort.name": "Name",
|
||||
"sort.host": "Server",
|
||||
"sort.size": "Size",
|
||||
"sort.progress": "Progress",
|
||||
"sort.speed": "Speed",
|
||||
"sort.left": "Time left",
|
||||
"sort.state": "State",
|
||||
"sort.added": "Added",
|
||||
"column.queue": "Queue",
|
||||
"group.none": "No groups",
|
||||
"group.state": "State",
|
||||
"group.queue": "Queue",
|
||||
"group.host": "Server",
|
||||
"group.kind": "Type",
|
||||
"group.added": "Day added",
|
||||
"time.s": "{n} s",
|
||||
"time.min": "{n} min",
|
||||
"time.h": "{h} h {min} min",
|
||||
"time.d": "{d} d {h} h",
|
||||
|
||||
"list.name": "Downloads",
|
||||
"list.no_host": "No server",
|
||||
"list.dot": "{a} · {b}",
|
||||
"list.of": "{done} of {size}",
|
||||
"list.left": "{time} left",
|
||||
"list.percent": "{n}%",
|
||||
"list.starts": "Starts {time}",
|
||||
"list.retry": "Next try in {time}",
|
||||
"list.trying": "Trying again",
|
||||
"list.connections": {"one": "{n} connection", "other": "{n} connections"},
|
||||
"list.offline": {"one": "No network. {n} download goes on when it is back.", "other": "No network. {n} downloads go on when it is back."},
|
||||
|
||||
"header.idle": "Nothing is downloading",
|
||||
"header.running": {"one": "{n} downloading", "other": "{n} downloading"},
|
||||
"header.queued": {"one": "{n} in line", "other": "{n} in line"},
|
||||
"header.connections": {"one": "{n} connection", "other": "{n} connections"},
|
||||
"rail.open": "Show names",
|
||||
"rail.close": "Show icons only",
|
||||
"rail.no_room": "The window is too narrow to show names here.",
|
||||
"rail.queues": "Queues",
|
||||
"rail.tags": "Tags",
|
||||
"rail.kinds": "Types",
|
||||
"rail.tip": "{name}: {n}",
|
||||
"search.name": "Search",
|
||||
"view.rows": "Show as rows",
|
||||
"view.cards": "Show as cards",
|
||||
"view.sort": "Order and columns",
|
||||
"view.filter": "Filter",
|
||||
"view.sort_by": "Sort by",
|
||||
"view.down": "Reverse order",
|
||||
"view.group_by": "Group by",
|
||||
"view.columns": "Columns",
|
||||
"filter.host": "Server",
|
||||
"filter.age": "Day added",
|
||||
"filter.clear": "Clear filters",
|
||||
"bar.count": {"one": "{n} selected", "other": "{n} selected"},
|
||||
"bar.clear": "Select nothing",
|
||||
|
||||
"none.title": "Nothing here",
|
||||
"none.body": "No download fits these filters.",
|
||||
"none.search": "Nothing found for “{what}”",
|
||||
"none.search_body": "Names and links were searched, within the filters that are set.",
|
||||
"open.failed": "The download list can't be opened",
|
||||
"open.network": "Secure connections could not be set up on this computer.",
|
||||
|
||||
"act.open": "Open",
|
||||
"act.show": "Show in folder",
|
||||
"act.copy": "Copy link",
|
||||
"act.page": "Open the page it came from",
|
||||
"act.start": "Start now",
|
||||
"act.resume": "Resume",
|
||||
"act.pause": "Pause",
|
||||
"act.stop": "Stop and put last",
|
||||
"act.priority": "Priority",
|
||||
"act.queue": "Queue",
|
||||
"act.tags": "Tags",
|
||||
"act.rename": "Rename",
|
||||
"act.move": "Move to folder",
|
||||
"act.redownload": "Download again",
|
||||
"act.keep_both": "Keep both",
|
||||
"act.remove": "Remove from list",
|
||||
"act.delete": "Move file to bin",
|
||||
|
||||
"toast.removed_one": "{name} was removed from the list",
|
||||
"toast.removed": {"one": "{n} download was removed from the list", "other": "{n} downloads were removed from the list"},
|
||||
"toast.binned_one": "{name} was moved to the bin",
|
||||
"toast.binned": {"one": "{n} download was moved to the bin", "other": "{n} downloads were moved to the bin"},
|
||||
"toast.copied": {"one": "Link copied", "other": "{n} links copied"},
|
||||
|
||||
"add.button": "Add",
|
||||
"add.title": "Add downloads",
|
||||
"add.links": "Links, one per line",
|
||||
"add.body": "They are saved to {folder}.",
|
||||
"add.do": "Download",
|
||||
"ask.link": "Change the link",
|
||||
"ask.link_field": "Link",
|
||||
"ask.save": "Save and resume",
|
||||
"ask.folder": "Move to another folder",
|
||||
"ask.folder_field": "Folder",
|
||||
"ask.move": "Move",
|
||||
"ask.name": "Rename",
|
||||
"ask.name_field": "Name",
|
||||
"ask.rename": "Rename",
|
||||
|
||||
"app.no_window": "Medlar could not open a window: {why}",
|
||||
|
||||
"queue.main": "Main",
|
||||
|
|
|
|||
|
|
@ -169,6 +169,18 @@ impl Snapshot {
|
|||
}
|
||||
}
|
||||
|
||||
/// For tests and pictures; the manager's own come from the manager.
|
||||
impl FromIterator<TaskView> for Snapshot {
|
||||
fn from_iter<I: IntoIterator<Item = TaskView>>(views: I) -> Snapshot {
|
||||
let mut shot = Snapshot::default();
|
||||
for view in views {
|
||||
shot.rev = shot.rev.max(view.rev);
|
||||
shot.put(view);
|
||||
}
|
||||
shot
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
|||
Loading…
Reference in a new issue