diff --git a/Plans/04 Control/S022-control-screens.md b/Plans/04 Control/S022-control-screens.md index c903d2a..5bc8182 100644 --- a/Plans/04 Control/S022-control-screens.md +++ b/Plans/04 Control/S022-control-screens.md @@ -12,14 +12,14 @@ FEATURES 2.1–2.3, 2.6–2.9 and 9.5 on screen (automatic limiter and quota are - crates/app/src/ui/{wave,graph}* ## Steps -- [ ] Mode switch in the toolbar as a connected group, snail included -- [ ] Limit dial: wavy slider with spring handle, log scale, typing and units -- [ ] Priority control in rows and details, share preview; "only this one" -- [ ] Queue page: cards with live totals, drag tasks and order, edit sheet -- [ ] Week grid for modes and starts: paint by drag, keyboard too -- [ ] Done-action picker with countdown sheet -- [ ] Test file `docs/tests/S022-control-screens.md`, with the checks below -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S022: …`, push +- [x] Mode switch in the toolbar as a connected group, snail included +- [x] Limit dial: wavy slider with spring handle, log scale, typing and units +- [x] Priority control in rows and details, share preview; "only this one" +- [x] Queue page: cards with live totals, drag tasks and order, edit sheet +- [x] Week grid for modes and starts: paint by drag, keyboard too +- [x] Done-action picker with countdown sheet +- [x] Test file `docs/tests/S022-control-screens.md`, with the checks below +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S022: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 5d9dc4a..78b5e4e 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -35,7 +35,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H - [x] [S019](04%20Control/S019-limiter-priority.md) Limiter, modes and priority shares - [x] [S021](04%20Control/S021-queues-schedule-power.md) Queues, scheduler and power actions -- [ ] [S022](04%20Control/S022-control-screens.md) Control screens +- [x] [S022](04%20Control/S022-control-screens.md) Control screens ## 05 Connector diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index e7d86f2..c097385 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -190,7 +190,12 @@ impl App { self.screen = Some(screen); } } - None => self.main.show(ui, &t, &self.settings), + None => { + self.main.show(ui, &t, &self.settings); + if let Some(change) = self.main.change.take() { + change.apply(&mut self.settings); + } + } } let bridge = &self.main.bridge; if let Some(ask) = &mut self.sign_in { diff --git a/crates/app/src/bridge.rs b/crates/app/src/bridge.rs index 55e6b27..12bc259 100644 --- a/crates/app/src/bridge.rs +++ b/crates/app/src/bridge.rs @@ -176,6 +176,31 @@ impl Bridge { }); } + /// Saves a queue (id 0 adds one), or removes it when `remove` is set; the lists are read again and the engine told. + pub fn save_queue(&self, queue: Queue, remove: bool) { + let Engine::Open { store, manager, .. } = &*lock(&self.inner.engine) else { return }; + let (store, manager, inner) = (store.clone(), manager.clone(), self.inner.clone()); + let ctx = self.opening.as_ref().map(|(_, ctx)| ctx.clone()); + std::thread::spawn(move || { + let done = if remove { store.delete_queue(queue.id) } else { store.save_queue(queue).map(|_| ()) }; + if let Err(e) = done { + lock(&inner.errors).push(e.to_string()); + } + manager.rescan(); + 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), + } + if let Some(ctx) = ctx { + ctx.request_repaint(); + } + }); + } + /// New settings count at once, also for what runs. pub fn apply(&mut self, settings: &Settings) { if let Some((opening, _)) = &mut self.opening { @@ -394,7 +419,7 @@ pub enum Place { fn apply(engine: &Engine, settings: &Settings) { if let Engine::Open { manager, sites, .. } = engine { - manager.set_limits(settings.limits()); + manager.set_limits(settings.limits_at(chrono::Local::now().naive_local())); manager.set_recovery(settings.tries, settings.auto_resume); sites.set(settings); } diff --git a/crates/app/src/views/control.rs b/crates/app/src/views/control.rs new file mode 100644 index 0000000..c418e5f --- /dev/null +++ b/crates/app/src/views/control.rs @@ -0,0 +1,106 @@ +//! The sheet over the list for speed, queues, the week and "when done", and what runs behind it. + +use super::main::Reply; +use super::modes::{self, Change, MODES}; +use super::queues; +use super::schedule::{self, Awake, Done, Level}; +use crate::bridge::{Bridge, Lists}; +use crate::theme::Theme; +use crate::ui::dialog; +use crate::ui::toast::Toasts; +use crate::ui::widgets::{Tab, tabs}; +use eframe::egui::{Context, Ui}; +use medlar_core::model::TaskId; +use medlar_core::settings::Settings; +use medlar_core::snapshot::Snapshot; +use medlar_core::tr; +use std::time::Duration; + +#[derive(Default)] +pub struct Control { + pub open: bool, + tab: usize, + mb: bool, + queues: queues::Page, + brush: u8, + cells: Vec, + pub done: Done, + awake: Awake, + /// The hour of the week the limits were last set for. + cell: Option, +} + +impl Control { + /// What runs without a screen: the plan of modes, the countdown, the lock against sleep. + pub fn tick(&mut self, ctx: &Context, t: &Theme, settings: &Settings, bridge: &mut Bridge, shot: &Snapshot, toasts: &mut Toasts) { + use chrono::{Datelike, Timelike}; + let local = chrono::Local::now().naive_local(); + let cell = local.weekday().num_days_from_monday() as usize * 24 + local.hour() as usize; + if settings.mode_grid.is_empty() { + self.cell = None; + } else { + if self.cell.is_some_and(|c| c != cell) { + bridge.apply(settings); + } + self.cell = Some(cell); + ctx.request_repaint_after(Duration::from_secs(30)); + } + self.awake.follow(shot.totals.running); + self.done.tick(ctx, t, shot, toasts); + } + + #[allow(clippy::too_many_arguments)] + pub fn show(&mut self, ctx: &Context, t: &Theme, settings: &Settings, bridge: &Bridge, shot: &Snapshot, lists: &Lists, selected: &[TaskId], change: &mut Option) { + if !self.open && !dialog::shown(ctx, "control") { + return; + } + let mut open = self.open; + let closed = dialog::sheet(ctx, t, "control", &tr!("control.title"), open, |ui| { + let (a, b, c, d) = (tr!("control.speed"), tr!("control.queues"), tr!("control.week"), tr!("control.done")); + let options = [ + Tab { icon: "speed", text: &a, count: None }, + Tab { icon: "stacks", text: &b, count: Some(lists.queues.len()) }, + Tab { icon: "schedule", text: &c, count: None }, + Tab { icon: "power_settings_new", text: &d, count: self.done.watcher.armed().map(|_| 1) }, + ]; + tabs(ui, t, &tr!("control.title"), &options, &mut self.tab); + ui.add_space(crate::tokens::space::L); + match self.tab { + 0 => self.speed(ui, t, settings, change), + 1 => self.queues.show(ui, t, lists, shot, bridge, selected), + 2 => self.week(ui, t, settings, change), + _ => { + let names: Vec<_> = lists.queues.iter().map(|q| (q.id, super::list::model::queue_name(lists, q.id))).collect(); + self.done.picker(ui, t, &names); + } + } + }); + if closed { + open = false; + } + self.open = open; + } + + fn speed(&mut self, ui: &mut Ui, t: &Theme, settings: &Settings, change: &mut Option) { + let mode = settings.mode; + let speed = settings.limits_of_ref(mode).speed; + let before = change.clone(); + modes::dial(ui, t, mode, speed, &mut self.mb, change); + let _ = before; + } + + fn week(&mut self, ui: &mut Ui, t: &Theme, settings: &Settings, change: &mut Option) { + use eframe::egui::RichText; + ui.label(RichText::new(tr!("week.help")).font(crate::fonts::ui(crate::tokens::text::LABEL)).color(t.on_variant)); + ui.add_space(crate::tokens::space::S); + if self.cells.len() != 168 { + self.cells = if settings.mode_grid.len() == 168 { settings.mode_grid.clone() } else { vec![0; 168] }; + } + let fills = [t.high, t.tertiary_container, t.secondary_container, t.primary_container, t.error_container]; + let mut levels = vec![Level { name: tr!("week.chosen"), fill: fills[0] }]; + levels.extend(MODES.iter().enumerate().map(|(i, m)| Level { name: modes::label(*m), fill: fills[i + 1] })); + if schedule::week(ui, t, "modes", &mut self.cells, &levels, &mut self.brush) { + *change = Some(Change::Grid(self.cells.clone())); + } + } +} diff --git a/crates/app/src/views/details/tabs.rs b/crates/app/src/views/details/tabs.rs index 67bda01..ea046b2 100644 --- a/crates/app/src/views/details/tabs.rs +++ b/crates/app/src/views/details/tabs.rs @@ -59,6 +59,14 @@ pub fn log_lines(log: &Log, filter: &str) -> Vec { log.iter().filter(|l| f.is_empty() || l.text.to_lowercase().contains(&f)).map(|l| format!("{} {}", when(l.at), redact::text(&l.text))).collect() } +/// What a priority is worth next to the others. +fn share_words(p: Priority) -> String { + if p == Priority::Only { + return tr!("priority.share_only"); + } + tr!("priority.share", n = format!("{:.1}", p.weight() / Priority::Normal.weight())) +} + fn small(ui: &mut Ui, t: &Theme, words: &str) { ui.add(Label::new(RichText::new(words).font(fonts::ui(text::BODY)).color(t.on_variant)).wrap()); } @@ -259,6 +267,7 @@ fn live_edits(ui: &mut Ui, cx: &mut Cx) { let p = Priority::ALL[at]; cx.edit(move |t| t.priority = p); } + small(ui, t, &share_words(v.task.priority)); if cx.lists.queues.len() > 1 { let names: Vec = cx.lists.queues.iter().map(|q| queue_name(cx.lists, q.id)).collect(); let mut at = cx.lists.queues.iter().position(|q| q.id == v.task.queue).unwrap_or(0); diff --git a/crates/app/src/views/main.rs b/crates/app/src/views/main.rs index 370e16e..75e1ce9 100644 --- a/crates/app/src/views/main.rs +++ b/crates/app/src/views/main.rs @@ -4,7 +4,9 @@ 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::add::{self, Adding, Folders, Request}; +use super::control::Control; use super::details::Details; +use super::modes; use super::{bar, rail}; use crate::bridge::{Bridge, Data, Lists}; use crate::keys::{Action, Group as Where}; @@ -96,6 +98,9 @@ pub struct Main { ask: Option, pub adding: Adding, pub details: Details, + pub control: Control, + /// What the screens want settings to become; the window applies it. + pub change: Option, /// Shows a file in its folder in the file manager; false when it can't, so the folder is opened. pub reveal: fn(&Path) -> bool, focus_search: bool, @@ -120,6 +125,8 @@ impl Default for Main { ask: None, adding: Adding::default(), details: Details::default(), + control: Control::default(), + change: None, reveal: |_| false, focus_search: false, asked: vec![], @@ -210,6 +217,11 @@ impl Main { } Data::Ready(shot, lists) => self.ready(ui, t, settings, window, &shot, &lists), } + if let Data::Ready(shot, lists) = self.bridge.data() { + self.control.tick(ui.ctx(), t, settings, &mut self.bridge, &shot, &mut self.toasts); + let selected = self.list.chosen(); + self.control.show(ui.ctx(), t, settings, &self.bridge, &shot, &lists, &selected, &mut self.change); + } self.messages(ui, t, window.bottom() - self.floor()); self.asking(ui, t); self.adding(ui, t, settings); @@ -309,6 +321,15 @@ impl Main { 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 = std::mem::take(&mut self.asked); + let tools = if tools.width() >= 640.0 { + let (a, b) = tools.split_left_right_at_x(tools.right() - modes::WIDTH); + if modes::switch(ui, t, b, settings, &mut self.change) { + self.control.open = true; + } + a.with_max_x(a.right() - space::S) + } else { + tools + }; 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) { diff --git a/crates/app/src/views/mod.rs b/crates/app/src/views/mod.rs index 326deab..5078f95 100644 --- a/crates/app/src/views/mod.rs +++ b/crates/app/src/views/mod.rs @@ -2,10 +2,14 @@ pub mod add; pub mod bar; +pub mod control; pub mod details; pub mod firstrun; pub mod list; pub mod main; +pub mod modes; pub mod palette; +pub mod queues; pub mod rail; +pub mod schedule; pub mod settings; diff --git a/crates/app/src/views/modes.rs b/crates/app/src/views/modes.rs new file mode 100644 index 0000000..c4642e5 --- /dev/null +++ b/crates/app/src/views/modes.rs @@ -0,0 +1,119 @@ +//! Speed modes: the switch in the toolbar and the limit dial. + +use crate::theme::Theme; +use crate::tokens::{space, text}; +use crate::ui::field::Number; +use crate::ui::widgets::{Button, Slider, group, segmented}; +use crate::fonts; +use eframe::egui::{Align, Layout, Rect, RichText, Ui, UiBuilder}; +use medlar_core::settings::{Mode, Settings}; +use medlar_core::tr; + +pub const MODES: [Mode; 4] = [Mode::Low, Mode::Medium, Mode::High, Mode::Snail]; + +/// What the screens ask settings to become. The window applies it. +#[derive(Clone, Debug, PartialEq)] +pub enum Change { + Mode(Mode), + /// A mode's speed limit in bytes per second, 0 for none. + Speed(Mode, u64), + /// The plan of modes by hour of the week. + Grid(Vec), +} + +impl Change { + pub fn apply(self, s: &mut Settings) { + match self { + Change::Mode(m) => { + if (m == Mode::Snail) != (s.mode == Mode::Snail) { + s.toggle_snail(); + } + s.mode = m; + } + Change::Speed(m, v) => s.limits_of(m).speed = v, + Change::Grid(g) => s.mode_grid = if g.iter().all(|c| *c == 0) { vec![] } else { g }, + } + } +} + +pub fn label(m: Mode) -> String { + match m { + Mode::Low => tr!("mode.low"), + Mode::Medium => tr!("mode.medium"), + Mode::High => tr!("mode.high"), + Mode::Snail => tr!("mode.snail"), + } +} + +/// The widest the group is. +pub const WIDTH: f32 = 330.0; + +/// The four modes as one connected group, snail included, and the button for the dial. True when that was clicked. +pub fn switch(ui: &mut Ui, t: &Theme, rect: Rect, s: &Settings, change: &mut Option) -> bool { + let mut child = ui.new_child(UiBuilder::new().max_rect(rect).layout(Layout::right_to_left(Align::Center)).id_salt("modes")); + let ui = &mut child; + let more = Button::icon("tune", &tr!("control.open")).show(ui, t).clicked(); + ui.with_layout(Layout::left_to_right(Align::Center), |ui| { + let (low, medium, high) = (label(Mode::Low), label(Mode::Medium), label(Mode::High)); + let snail = tr!("mode.snail"); + let options = [("", low.as_str()), ("", medium.as_str()), ("", high.as_str()), ("slow_motion_video", snail.as_str())]; + let mut at = MODES.iter().position(|m| *m == s.mode).unwrap_or(2); + if group(ui, t, &tr!("mode.group"), &options, &mut at) { + *change = Some(Change::Mode(MODES[at])); + } + }); + more +} + +/// Positions of the dial: 16 KB/s doubling every ten steps up to 1 GB/s, then no limit. +const TOP: f64 = 161.0; + +pub fn to_speed(pos: f64) -> u64 { + if pos >= TOP { 0 } else { (16384.0 * 2f64.powf(pos.max(0.0) / 10.0)).round() as u64 } +} + +pub fn to_pos(speed: u64) -> f64 { + if speed == 0 { TOP } else { ((speed as f64 / 16384.0).max(1.0).log2() * 10.0).round().min(TOP - 1.0) } +} + +/// "1.5 MB/s", or "no limit". +pub fn speed_words(speed: u64) -> String { + if speed == 0 { + return tr!("speed.none"); + } + let kb = speed as f64 / 1024.0; + if kb >= 1024.0 { format!("{:.1} {}", kb / 1024.0, tr!("unit.mb_s")) } else { format!("{:.0} {}", kb, tr!("unit.kb_s")) } +} + +/// The dial of one mode: a wavy slider on a log scale, and a field to type in. The slider applies live; `done` is true +/// when it is let go or a number was typed, which is when the settings are worth keeping. +pub fn dial(ui: &mut Ui, t: &Theme, mode: Mode, speed: u64, mb: &mut bool, change: &mut Option) -> bool { + let mut done = false; + ui.label(RichText::new(tr!("speed.for", mode = label(mode))).font(fonts::semi(text::BODY)).color(t.on_surface)); + ui.add_space(space::S); + let mut pos = to_pos(speed); + let shown = |p: f64| speed_words(to_speed(p)); + let r = Slider::new(&tr!("speed.dial"), 0.0..=TOP, 1.0).show_value(&shown).show(ui, t, &mut pos); + if r.changed() { + *change = Some(Change::Speed(mode, to_speed(pos))); + } + done |= r.drag_stopped(); + ui.add_space(space::S); + let units = [("", tr!("unit.kb_s")), ("", tr!("unit.mb_s"))]; + let names: Vec<(&str, &str)> = units.iter().map(|(i, n)| (*i, n.as_str())).collect(); + let mut at = usize::from(*mb); + if segmented(ui, t, &tr!("speed.unit"), &names, &mut at) { + *mb = at == 1; + } + ui.add_space(space::S); + let per = if *mb { 1024.0 * 1024.0 } else { 1024.0 }; + let mut typed = speed as f64 / per; + let label = tr!("speed.type"); + let unit = if *mb { tr!("unit.mb_s") } else { tr!("unit.kb_s") }; + if (Number { label: &label, unit: &unit, range: 0.0..=10_000_000.0, step: if *mb { 0.5 } else { 64.0 }, enabled: true, width: 240.0, bare: false }).show(ui, t, &mut typed) { + *change = Some(Change::Speed(mode, (typed.max(0.0) * per) as u64)); + done = true; + } + ui.label(RichText::new(tr!("speed.why")).font(fonts::ui(text::LABEL)).color(t.on_variant)); + done +} diff --git a/crates/app/src/views/queues.rs b/crates/app/src/views/queues.rs new file mode 100644 index 0000000..c96a78a --- /dev/null +++ b/crates/app/src/views/queues.rs @@ -0,0 +1,216 @@ +//! The queue page: a card for each queue with live totals, order by drag or buttons, and the editor. + +use super::list::model::queue_name; +use super::schedule::{self, Level}; +use crate::bridge::{Bridge, Lists}; +use crate::fonts; +use crate::theme::Theme; +use crate::tokens::{radius, size, space, text}; +use crate::ui::field::{Field, Number}; +use crate::ui::widgets::{Button, Choice, Kind, cr, left, line}; +use crate::icons; +use eframe::egui::{Layout, Align, Id, Rect, RichText, Sense, Ui, UiBuilder, pos2, vec2}; +use medlar_core::manager::Command; +use medlar_core::model::{MAIN_QUEUE, Queue, QueueId, State, TaskId}; +use medlar_core::snapshot::Snapshot; +use medlar_core::tr; +use std::path::PathBuf; + +const CARD: f32 = 84.0; + +/// What a card says about its queue, from the snapshot. +#[derive(Default, Clone, Copy, Debug, PartialEq)] +pub struct Totals { + pub running: usize, + pub waiting: usize, + pub done: usize, + pub speed: f64, +} + +pub fn totals(shot: &Snapshot, queue: QueueId) -> Totals { + let mut n = Totals::default(); + for v in shot.iter().filter(|v| v.task.queue == queue) { + match v.state() { + State::Running => { + n.running += 1; + n.speed += v.speed; + } + State::Queued => n.waiting += 1, + State::Done => n.done += 1, + _ => {} + } + } + n +} + +/// The position that puts a queue at place `to` among the others (without itself), given all positions in order. +pub fn position_for(others: &[f64], to: usize) -> f64 { + match (to.checked_sub(1).and_then(|i| others.get(i)), others.get(to)) { + (None, None) => 0.0, + (None, Some(next)) => next - 1.0, + (Some(prev), None) => prev + 1.0, + (Some(prev), Some(next)) => (prev + next) / 2.0, + } +} + +#[derive(Default)] +pub struct Page { + draft: Option, + cells: Vec, + brush: u8, + /// The card in hand and how far it was pulled. + grab: Option<(QueueId, f32)>, +} + +impl Page { + pub fn show(&mut self, ui: &mut Ui, t: &Theme, lists: &Lists, shot: &Snapshot, bridge: &Bridge, selected: &[TaskId]) { + let mut order: Vec<&Queue> = lists.queues.iter().collect(); + order.sort_by(|a, b| a.position.total_cmp(&b.position)); + let width = ui.available_width(); + let mut cards = vec![]; + let mut released = None; + for (i, q) in order.iter().enumerate() { + let (slot, _) = ui.allocate_exact_size(vec2(width, CARD), Sense::hover()); + ui.add_space(space::S); + let pulled = self.grab.filter(|(id, _)| *id == q.id).map_or(0.0, |(_, dy)| dy); + let rect = slot.translate(vec2(0.0, pulled)); + cards.push(rect); + let n = totals(shot, q.id); + let mut moved = None; + self.card(ui, t, rect, q, lists, n, i, order.len(), selected, bridge, &mut moved, &mut released); + if let Some(by) = moved { + let to = (i as i32 + by).clamp(0, order.len() as i32 - 1) as usize; + self.move_to(bridge, &order, i, to); + } + } + if let Some(id) = released { + self.grab = None; + let at = order.iter().position(|q| q.id == id).unwrap_or(0); + if let Some(mid) = cards.get(at).map(|r| r.center().y) { + let to = cards.iter().enumerate().filter(|(j, r)| *j != at && r.center().y < mid).count(); + self.move_to(bridge, &order, at, to); + } + } + if Button::new(&tr!("queue.add")).with_icon("add").show(ui, t).clicked() { + let last = order.last().map_or(0.0, |q| q.position); + self.open(Queue { name: tr!("queue.new"), position: last + 1.0, ..Queue::default() }); + } + self.editor(ui, t, bridge); + } + + fn open(&mut self, q: Queue) { + self.cells = schedule::cells_of(&q.schedule); + self.brush = 1; + self.draft = Some(q); + } + + fn move_to(&mut self, bridge: &Bridge, order: &[&Queue], from: usize, to: usize) { + if from == to { + return; + } + let others: Vec = order.iter().enumerate().filter(|(i, _)| *i != from).map(|(_, q)| q.position).collect(); + bridge.save_queue(Queue { position: position_for(&others, to), ..order[from].clone() }, false); + } + + #[allow(clippy::too_many_arguments)] + fn card(&mut self, ui: &mut Ui, t: &Theme, rect: Rect, q: &Queue, lists: &Lists, n: Totals, i: usize, count: usize, selected: &[TaskId], bridge: &Bridge, moved: &mut Option, released: &mut Option) { + let held = self.grab.is_some_and(|(id, _)| id == q.id); + ui.painter().rect_filled(rect, cr(radius::L), if held { t.highest } else { t.container }); + let inner = rect.shrink(space::M); + let handle = Rect::from_min_size(inner.min, vec2(size::HIT, size::HIT)); + let r = ui.interact(handle, Id::unique(("queue handle", q.id)), Sense::drag()); + icons::paint(ui.painter(), handle.center(), crate::tokens::icon::M, "drag_indicator", t.on_variant); + if r.dragged() { + let dy = self.grab.filter(|(id, _)| *id == q.id).map_or(0.0, |(_, d)| d) + r.drag_delta().y; + self.grab = Some((q.id, dy)); + crate::motion::keep_alive(); + } + if r.drag_stopped() { + *released = Some(q.id); + } + let x = handle.right() + space::S; + let name = queue_name(lists, q.id); + let words = line(ui.painter(), &name, fonts::semi(text::BODY), t.on_surface, inner.right() - x - 4.0 * size::HIT); + left(ui.painter(), pos2(x, inner.top() + size::HIT / 2.0), words); + let mut said = tr!("queue.totals", running = n.running, waiting = n.waiting, done = n.done); + if n.running > 0 { + said = tr!("list.dot", a = said, b = super::modes::speed_words(n.speed as u64)); + } + if q.paused { + said = tr!("list.dot", a = tr!("queue.paused"), b = said); + } + let words = line(ui.painter(), &said, fonts::ui(text::LABEL), t.on_variant, inner.width() - size::HIT - space::S); + left(ui.painter(), pos2(x, inner.top() + size::HIT + space::XS), words); + let bar = Rect::from_min_max(pos2(x, inner.top()), pos2(inner.right(), inner.top() + size::HIT)); + let mut row = ui.new_child(UiBuilder::new().max_rect(bar).layout(Layout::right_to_left(Align::Center)).id_salt(("queue row", q.id))); + let ui = &mut row; + if Button::icon("edit", &tr!("queue.edit")).show(ui, t).clicked() { + self.open(q.clone()); + } + if Button::icon("arrow_downward", &tr!("queue.down")).enabled(i + 1 < count).show(ui, t).clicked() { + *moved = Some(1); + } + if Button::icon("arrow_upward", &tr!("queue.up")).enabled(i > 0).show(ui, t).clicked() { + *moved = Some(-1); + } + if !selected.is_empty() && Button::icon("low_priority", &tr!("queue.move_here", n = selected.len())).show(ui, t).clicked() { + for id in selected { + let to = q.id; + bridge.send(Command::Edit { id: *id, edit: Box::new(move |task| task.queue = to) }); + } + } + } + + /// The edit form of the queue that was opened. Nothing is written until Save. + fn editor(&mut self, ui: &mut Ui, t: &Theme, bridge: &Bridge) { + let Some(mut q) = self.draft.take() else { return }; + ui.add_space(space::L); + ui.label(RichText::new(tr!("queue.edit")).font(fonts::semi(text::TITLE)).color(t.on_surface)); + ui.add_space(space::S); + if q.id != MAIN_QUEUE { + Field::new(&tr!("queue.name")).show(ui, t, &mut q.name); + ui.add_space(space::S); + } + let mut folder = q.folder.as_ref().map(|f| f.display().to_string()).unwrap_or_default(); + if Field::new(&tr!("queue.folder")).hint(&tr!("queue.folder_hint")).show(ui, t, &mut folder).changed() { + q.folder = Some(PathBuf::from(folder.trim())).filter(|f| !f.as_os_str().is_empty()); + } + ui.add_space(space::S); + let mut speed = q.speed_limit.map_or(0.0, |s| (s / 1024) as f64); + if (Number { label: &tr!("queue.limit"), unit: &tr!("unit.kb_s"), range: 0.0..=10_000_000.0, step: 64.0, enabled: true, width: 240.0, bare: false }).show(ui, t, &mut speed) { + q.speed_limit = Some(speed.max(0.0) as u64 * 1024).filter(|s| *s > 0); + } + ui.add_space(space::S); + let mut active = f64::from(q.max_active.unwrap_or(0)); + if (Number { label: &tr!("queue.active"), unit: "", range: 0.0..=100.0, step: 1.0, enabled: true, width: 160.0, bare: false }).show(ui, t, &mut active) { + q.max_active = Some(active as u32).filter(|n| *n > 0); + } + ui.add_space(space::S); + Choice::new(&tr!("queue.pause")).switch(ui, t, &mut q.paused); + ui.add_space(space::M); + ui.label(RichText::new(tr!("queue.schedule")).font(fonts::semi(text::BODY)).color(t.on_surface)); + ui.label(RichText::new(tr!("queue.schedule_help")).font(fonts::ui(text::LABEL)).color(t.on_variant)); + ui.add_space(space::S); + let levels = [Level { name: tr!("queue.off"), fill: t.high }, Level { name: tr!("queue.on"), fill: t.primary }]; + if schedule::week(ui, t, "queue", &mut self.cells, &levels, &mut self.brush) { + q.schedule = schedule::windows(&self.cells); + } + ui.add_space(space::L); + let (mut save, mut cancel, mut remove) = (false, false, false); + ui.horizontal(|ui| { + save = Button::new(&tr!("queue.save")).kind(Kind::Filled).enabled(q.id == MAIN_QUEUE || !q.name.trim().is_empty()).show(ui, t).clicked(); + cancel = Button::new(&tr!("dialog.cancel")).show(ui, t).clicked(); + if q.id != MAIN_QUEUE && q.id != 0 { + remove = Button::new(&tr!("queue.delete")).with_icon("delete").danger(true).show(ui, t).clicked(); + } + }); + if save { + q.name = q.name.trim().to_string(); + bridge.save_queue(q, false); + } else if remove { + bridge.save_queue(q, true); + } else if !cancel { + self.draft = Some(q); + } + } +} diff --git a/crates/app/src/views/schedule.rs b/crates/app/src/views/schedule.rs new file mode 100644 index 0000000..742b02b --- /dev/null +++ b/crates/app/src/views/schedule.rs @@ -0,0 +1,407 @@ +//! The week grid, what happens when downloads are done (with its countdown), and what keeps the machine awake. + +use crate::bridge; +use crate::fonts; +use crate::motion::keep_alive; +use crate::theme::Theme; +use crate::tokens::{space, text}; +use crate::ui::dialog::{Answer, Dialog}; +use crate::ui::field::{Combo, Field, Number}; +use crate::ui::toast::Toasts; +use crate::ui::widgets::{Button, Chip, Kind, cr, ring}; +use eframe::egui::{Color32, Context, EventFilter, Id, Key, Pos2, Rect, RichText, Sense, Ui, pos2, vec2}; +use medlar_core::model::{QueueId, Schedule as Window, now}; +use medlar_core::power::{Action, Inhibitor, Logind, Power, Scope, Seen, Step, Watcher, WhenDone}; +use medlar_core::run::{self, RunSpec, Vars}; +use medlar_core::snapshot::Snapshot; +use medlar_core::tr; +use std::time::Duration; +use tokio::sync::oneshot; + +/// One thing a cell can be. +pub struct Level { + pub name: String, + pub fill: Color32, +} + +const DAYS: [&str; 7] = ["day.mon", "day.tue", "day.wed", "day.thu", "day.fri", "day.sat", "day.sun"]; +const CELL_H: f32 = 14.0; +const GAP: f32 = 2.0; +const LABELS: f32 = 30.0; + +/// Which cell is at this point, as day * 24 + hour. +fn cell_at(grid: Rect, p: Pos2) -> usize { + let w = grid.width() / 7.0; + let day = (((p.x - grid.left()) / w).floor().max(0.0) as usize).min(6); + let hour = (((p.y - grid.top()) / (CELL_H + GAP)).floor().max(0.0) as usize).min(23); + day * 24 + hour +} + +/// The cells between two, along a line, so that a fast drag leaves no holes. +fn between(from: usize, to: usize) -> Vec { + let (a, b) = ((from / 24) as f32, (to / 24) as f32); + let (c, d) = ((from % 24) as f32, (to % 24) as f32); + let steps = (a - b).abs().max((c - d).abs()).max(1.0) as usize; + (0..=steps).map(|i| { + let f = i as f32 / steps as f32; + ((a + (b - a) * f).round() as usize) * 24 + (c + (d - c) * f).round() as usize + }).collect() +} + +/// Paints one value on cells. Level 0 is "nothing". +#[derive(Clone, Copy)] +struct Stroke { + value: u8, + last: usize, +} + +/// A grid of days across and hours down. A brush is chosen above it; a drag paints, and a stroke that starts on a cell +/// that already has the brush erases. With the keyboard: arrows move, Space or Enter paints, Shift and arrows paint while moving. +/// True when a cell changed. +pub fn week(ui: &mut Ui, t: &Theme, id: &str, cells: &mut Vec, levels: &[Level], brush: &mut u8) -> bool { + cells.resize(168, 0); + ui.horizontal_wrapped(|ui| { + for (i, l) in levels.iter().enumerate() { + if Chip::new(&l.name).filter(*brush as usize == i).show(ui, t).response.clicked() { + *brush = i as u8; + } + } + }); + ui.add_space(space::S); + let width = ui.available_width(); + let (rect, _) = ui.allocate_exact_size(vec2(width, 16.0), Sense::hover()); + let grid_left = rect.left() + LABELS; + let w = (width - LABELS) / 7.0; + for (d, key) in DAYS.iter().enumerate() { + let at = pos2(grid_left + w * (d as f32 + 0.5), rect.center().y); + ui.painter().text(at, eframe::egui::Align2::CENTER_CENTER, tr_day(key), fonts::med(text::LABEL), t.on_variant); + } + let (rect, _) = ui.allocate_exact_size(vec2(width, 24.0 * (CELL_H + GAP)), Sense::hover()); + let grid = Rect::from_min_max(pos2(grid_left, rect.top()), rect.max); + let me = Id::unique(("week", id)); + let r = ui.interact(grid, me, Sense::click_and_drag()); + ui.memory_mut(|m| m.set_focus_lock_filter(me, EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() })); + let stroke_key = me.with("stroke"); + let cursor_key = me.with("cursor"); + let mut cursor = ui.data(|d| d.get_temp::(cursor_key)).unwrap_or(0); + let mut stroke = ui.data(|d| d.get_temp::>(stroke_key)).flatten(); + let mut changed = false; + let mut paint = |cells: &mut Vec, i: usize, v: u8| { + if cells[i] != v { + cells[i] = v; + changed = true; + } + }; + if r.is_pointer_button_down_on() + && let Some(p) = r.interact_pointer_pos() + { + let here = cell_at(grid, p); + let s = stroke.unwrap_or_else(|| { + let v = if cells[here] == *brush { 0 } else { *brush }; + Stroke { value: v, last: here } + }); + for i in between(s.last, here) { + paint(cells, i, s.value); + } + stroke = Some(Stroke { last: here, ..s }); + cursor = here; + r.request_focus(); + } else { + stroke = None; + } + if r.has_focus() { + let (dx, dy, shift, go) = ui.input(|i| { + let k = |k| i.key_pressed(k) as i32; + (k(Key::ArrowRight) - k(Key::ArrowLeft), k(Key::ArrowDown) - k(Key::ArrowUp), i.modifiers.shift, i.key_pressed(Key::Space) || i.key_pressed(Key::Enter)) + }); + let (day, hour) = ((cursor / 24) as i32, (cursor % 24) as i32); + cursor = ((day + dx).clamp(0, 6) * 24 + (hour + dy).clamp(0, 23)) as usize; + if go || shift && (dx != 0 || dy != 0) { + let v = if go && cells[cursor] == *brush { 0 } else { *brush }; + paint(cells, cursor, v); + } + } + ui.data_mut(|d| { + d.insert_temp(stroke_key, stroke); + d.insert_temp(cursor_key, cursor); + }); + let p = ui.painter(); + for h in 0..24 { + let y = grid.top() + h as f32 * (CELL_H + GAP); + if h % 3 == 0 { + p.text(pos2(rect.left() + LABELS - space::S, y + CELL_H / 2.0), eframe::egui::Align2::RIGHT_CENTER, format!("{h:02}"), fonts::ui(text::LABEL), t.on_variant); + } + for d in 0..7 { + let cell = Rect::from_min_size(pos2(grid.left() + d as f32 * w + GAP / 2.0, y), vec2(w - GAP, CELL_H)); + let fill = match cells[d * 24 + h] { + 0 => t.high, + v => levels.get(v as usize).map_or(t.high, |l| l.fill), + }; + p.rect_filled(cell, cr(3.0), fill); + } + } + if r.has_focus() { + let (d, h) = (cursor / 24, cursor % 24); + let cell = Rect::from_min_size(pos2(grid.left() + d as f32 * w + GAP / 2.0, grid.top() + h as f32 * (CELL_H + GAP)), vec2(w - GAP, CELL_H)); + ring(ui.painter(), t, cell.expand(1.0), cr(4.0)); + } + changed +} + +fn tr_day(key: &str) -> String { + medlar_core::strings::text(key, &[]) +} + +/// Hours painted on, as the queue's windows: one per run of hours in a day. +pub fn windows(cells: &[u8]) -> Vec { + let mut out = vec![]; + for day in 0..7usize { + let mut h = 0usize; + while h < 24 { + if cells.get(day * 24 + h).copied().unwrap_or(0) == 0 { + h += 1; + continue; + } + let from = h; + while h < 24 && cells.get(day * 24 + h).copied().unwrap_or(0) != 0 { + h += 1; + } + // A whole day is `from == to`. + let (f, to) = ((from * 60) as u16, if h == 24 { 0 } else { (h * 60) as u16 }); + out.push(Window { days: 1 << day, from: f, to: if from == 0 && h == 24 { 0 } else { to } }); + } + } + // Runs that end at midnight and go on the next day stay as they are; the engine reads `to == 0` as the end of the day. + out +} + +/// The cells of a queue's windows. +pub fn cells_of(windows: &[Window]) -> Vec { + let mut cells = vec![0u8; 168]; + for (i, cell) in cells.iter_mut().enumerate() { + let (day, hour) = (i / 24, i % 24); + let at = chrono::NaiveDate::from_ymd_opt(2024, 1, 1 + day as u32).and_then(|d| d.and_hms_opt(hour as u32, 30, 0)).unwrap_or_default(); + *cell = u8::from(windows.iter().any(|w| w.contains(at))); + } + cells +} + +const ACTIONS: [&str; 7] = ["nothing", "quit", "suspend", "hibernate", "shutdown", "logout", "lock"]; + +/// What to do when the downloads are done, armed in the window. +pub struct Done { + pub watcher: Watcher, + action: usize, + scope: usize, + even_failed: bool, + seconds: f64, + program: String, + counting: Option, + working: Option>>, + can: Option>>, + allowed: Vec, +} + +impl Default for Done { + fn default() -> Done { + Done { watcher: Watcher::default(), action: 0, scope: 0, even_failed: false, seconds: 60.0, program: String::new(), counting: None, working: None, can: None, allowed: vec![] } + } +} + +fn action_of(i: usize, program: &str) -> Option { + Some(match i { + 1 => Action::Quit, + 2 => Action::Suspend, + 3 => Action::Hibernate, + 4 => Action::Shutdown, + 5 => Action::Logout, + 6 => Action::Lock, + 7 => { + let mut words = program.split_whitespace().map(String::from); + Action::Run(RunSpec { program: words.next()?, args: words.collect(), timeout: Duration::from_secs(60) }) + } + _ => return None, + }) +} + +fn name_of(a: &Action) -> String { + let key = match a { + Action::Quit => "done.quit", + Action::Suspend => "done.suspend", + Action::Hibernate => "done.hibernate", + Action::Shutdown => "done.shutdown", + Action::Logout => "done.logout", + Action::Lock => "done.lock", + Action::Run(_) => "done.run", + }; + medlar_core::strings::text(key, &[]) +} + +impl Done { + /// The picker, for the sheet. + pub fn picker(&mut self, ui: &mut Ui, t: &Theme, queues: &[(QueueId, String)]) { + if self.can.is_none() && self.allowed.is_empty() { + self.can = Some(bridge::beside(|| { + let p = Logind; + (1..=6).map(|i| action_of(i, "").is_some_and(|a| p.can(&a))).collect() + })); + } + if let Some(rx) = &mut self.can + && let Ok(v) = rx.try_recv() + { + self.allowed = v; + self.can = None; + } + let armed = self.watcher.armed().cloned(); + let mut names: Vec = ACTIONS.iter().map(|a| tr_key(&format!("done.{a}"))).collect(); + names.push(tr!("done.run")); + // What logind refuses is said, not hidden. + for (i, n) in names.iter_mut().enumerate() { + if i >= 1 && i <= 6 && !self.allowed.is_empty() && !self.allowed[i - 1] { + *n = tr!("done.cant", name = n.clone()); + } + } + ui.add_enabled_ui(armed.is_none(), |ui| { + let label = tr!("done.action"); + Combo::new(&label, &names, 260.0).show(ui, t, &mut self.action); + if self.action == 7 { + ui.add_space(space::S); + Field::new(&tr!("done.program")).help(&tr!("done.program_help")).show(ui, t, &mut self.program); + } + ui.add_space(space::S); + let mut scopes = vec![tr!("done.scope_all")]; + scopes.extend(queues.iter().map(|(_, n)| n.clone())); + self.scope = self.scope.min(scopes.len() - 1); + Combo::new(&tr!("done.scope"), &scopes, 260.0).show(ui, t, &mut self.scope); + ui.add_space(space::S); + let mut failed = self.even_failed; + crate::ui::widgets::Choice::new(&tr!("done.failed")).switch(ui, t, &mut failed); + self.even_failed = failed; + ui.add_space(space::S); + Number { label: &tr!("done.countdown"), unit: &tr!("unit.s"), range: 0.0..=3600.0, step: 5.0, enabled: true, width: 200.0, bare: false }.show(ui, t, &mut self.seconds); + }); + ui.add_space(space::L); + match armed { + Some(w) => { + ui.label(RichText::new(tr!("done.armed", action = name_of(&w.action))).font(fonts::med(text::BODY)).color(t.on_surface)); + ui.add_space(space::S); + if Button::new(&tr!("done.disarm")).with_icon("close").show(ui, t).clicked() { + self.watcher.cancel(); + self.counting = None; + } + } + None => { + let action = action_of(self.action, &self.program); + let ok = action.is_some(); + if Button::new(&tr!("done.arm")).with_icon("power_settings_new").kind(Kind::Filled).enabled(ok).show(ui, t).clicked() + && let Some(action) = action + { + let scope = if self.scope == 0 { Scope::All } else { Scope::Queue(queues[self.scope - 1].0) }; + self.watcher.arm(WhenDone { action, scope, even_failed: self.even_failed, countdown: Duration::from_secs(self.seconds as u64) }); + keep_alive(); + } + } + } + } + + /// Looks at the downloads; at the end counts down and then does it. Call each frame. + pub fn tick(&mut self, ctx: &Context, t: &Theme, shot: &Snapshot, toasts: &mut Toasts) { + if let Some(rx) = &mut self.working + && let Ok(done) = rx.try_recv() + { + self.working = None; + if let Err(why) = done { + toasts.error(tr!("done.failed_to", why = why), None); + } + } + let armed = self.watcher.armed().cloned(); + if armed.is_some() { + let seen: Vec = shot.iter().map(|v| Seen { id: v.id(), queue: v.task.queue, state: v.state() }).collect(); + match self.watcher.step(now(), &seen) { + Step::Idle => self.counting = None, + Step::Counting(n) => { + self.counting = Some(n); + ctx.request_repaint_after(Duration::from_millis(500)); + } + Step::Fire(a) => { + self.counting = None; + self.perform(ctx, a); + } + Step::Blocked => { + self.counting = None; + toasts.info("warning", tr!("done.blocked")); + } + } + } else { + self.counting = None; + } + let open = self.counting.is_some(); + if !open && !crate::ui::dialog::shown(ctx, "countdown") { + return; + } + let a = armed.map(|w| name_of(&w.action)).unwrap_or_default(); + let n = self.counting.unwrap_or(0); + let (title, body) = (tr!("done.title", action = a, n = n), tr!("done.body")); + let (now_label, cancel) = (tr!("done.now"), tr!("done.cancel")); + match Dialog::confirm("countdown", &title, &body, &now_label, true).cancel(&cancel).show(ctx, t, open, |_| {}) { + Some(Answer::Main) => { + if let Some(w) = self.watcher.armed().cloned() { + self.watcher.cancel(); + self.counting = None; + self.perform(ctx, w.action); + } + } + Some(Answer::Cancel) => { + self.watcher.cancel(); + self.counting = None; + } + None => {} + } + } + + fn perform(&mut self, ctx: &Context, action: Action) { + match action { + Action::Quit => ctx.send_viewport_cmd(eframe::egui::ViewportCommand::Close), + Action::Run(spec) => { + self.working = Some(bridge::beside(move || { + let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| e.to_string())?; + runtime.block_on(run::run(&spec, &Vars::default())).map(|_| ()) + })); + } + other => self.working = Some(bridge::beside(move || Logind.perform(&other))), + } + } +} + +fn tr_key(key: &str) -> String { + medlar_core::strings::text(key, &[]) +} + +/// Holds the machine awake while something downloads. +#[derive(Default)] +pub enum Awake { + #[default] + No, + Taking(oneshot::Receiver>), + Held(#[allow(dead_code)] Inhibitor), + /// There is no logind: asked once. + Unavailable, +} + +impl Awake { + pub fn follow(&mut self, running: usize) { + *self = match std::mem::take(self) { + Awake::No if running > 0 => Awake::Taking(bridge::beside(Inhibitor::take)), + Awake::Taking(mut rx) => match rx.try_recv() { + Ok(Some(i)) if running > 0 => Awake::Held(i), + Ok(None) => Awake::Unavailable, + Ok(Some(_)) => Awake::No, + Err(oneshot::error::TryRecvError::Empty) => Awake::Taking(rx), + Err(_) => Awake::Unavailable, + }, + Awake::Held(_) if running == 0 => Awake::No, + Awake::Unavailable if running == 0 => Awake::No, + other => other, + }; + } +} diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index 24d017f..a8f0e07 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -706,5 +706,80 @@ "details.sum.bad": "This is not a checksum Medlar knows.", "details.sum.set": "Use and check", "details.sum.check": "Check now", - "details.sum.progress": "Checked {n}%" + "details.sum.progress": "Checked {n}%", + "control.title": "Speed and time", + "control.open": "Speed, queues and time", + "control.speed": "Speed", + "control.queues": "Queues", + "control.week": "Week", + "control.done": "When done", + "mode.group": "Speed mode", + "mode.low": "Low", + "mode.medium": "Medium", + "mode.high": "High", + "mode.snail": "Snail", + "speed.for": "Limit in {mode} mode", + "speed.dial": "Speed limit", + "speed.none": "No limit", + "speed.unit": "Unit", + "speed.type": "Type a speed", + "speed.why": "Changes at once for all downloads. 0 is no limit.", + "unit.mb_s": "MB/s", + "unit.s": "s", + "week.help": "Paint the hours in which a mode should run instead of the chosen one. Drag over the grid, or use the arrow keys and Space.", + "week.chosen": "Chosen mode", + "day.mon": "Mon", + "day.tue": "Tue", + "day.wed": "Wed", + "day.thu": "Thu", + "day.fri": "Fri", + "day.sat": "Sat", + "day.sun": "Sun", + "queue.add": "New queue", + "queue.new": "New queue", + "queue.edit": "Edit queue", + "queue.name": "Name", + "queue.folder": "Folder", + "queue.folder_hint": "The usual folder", + "queue.limit": "Speed limit of the queue", + "queue.active": "Downloads at once (0 for no limit)", + "queue.pause": "Paused", + "queue.paused": "Paused", + "queue.schedule": "When it may run", + "queue.schedule_help": "Paint the hours. Nothing painted means always.", + "queue.off": "Off", + "queue.on": "May run", + "queue.save": "Save", + "queue.delete": "Delete queue", + "queue.up": "Move up", + "queue.down": "Move down", + "queue.move_here": "Move the {n} selected here", + "queue.totals": "{running} running, {waiting} waiting, {done} done", + "done.action": "When all is done", + "done.nothing": "Do nothing", + "done.quit": "Quit Medlar", + "done.suspend": "Suspend", + "done.hibernate": "Hibernate", + "done.shutdown": "Shut down", + "done.logout": "Log out", + "done.lock": "Lock the screen", + "done.run": "Run a program", + "done.cant": "{name} (not possible here)", + "done.program": "Program and arguments", + "done.program_help": "It gets no shell.", + "done.scope": "Which downloads", + "done.scope_all": "All downloads", + "done.failed": "Also when one failed", + "done.countdown": "Countdown", + "done.arm": "Arm", + "done.disarm": "Disarm", + "done.armed": "Armed: {action}", + "done.title": "{action} in {n} s", + "done.body": "The downloads are done. Cancel to stay.", + "done.now": "Do it now", + "done.cancel": "Cancel", + "done.blocked": "A download failed, so nothing was done.", + "done.failed_to": "It could not be done: {why}", + "priority.share": "About {n} times the share of a Normal download.", + "priority.share_only": "Everything else waits while this one runs." } diff --git a/crates/core/src/manager/actor.rs b/crates/core/src/manager/actor.rs index 645a5cd..551e87a 100644 --- a/crates/core/src/manager/actor.rs +++ b/crates/core/src/manager/actor.rs @@ -424,6 +424,7 @@ impl Actor { Msg::ReadMetalink(link, answer) => self.read_metalink(link, answer), Msg::Probe(task, secret, answer) => self.probe(*task, secret, answer), Msg::Limits(limits) => self.set_limits(limits), + Msg::Rescan => self.choose = true, Msg::OnChange(call) => self.on_change.push(call), Msg::Ended(id, result) => self.ended(id, result), Msg::Worked(id, result) => self.worked(id, result), diff --git a/crates/core/src/manager/mod.rs b/crates/core/src/manager/mod.rs index 553cb91..c76d96b 100644 --- a/crates/core/src/manager/mod.rs +++ b/crates/core/src/manager/mod.rs @@ -235,6 +235,8 @@ enum Msg { CheckPartial(PathBuf, NewLink, oneshot::Sender>), Probe(Box, Option, oneshot::Sender>), Limits(Limits), + /// Queues were changed in the store. + Rescan, OnChange(Box), /// A download ended. Ended(TaskId, std::result::Result), @@ -315,6 +317,11 @@ impl Manager { let _ = self.to.send(Msg::Limits(limits)); } + /// Queues were saved in the store: look at them again. + pub fn rescan(&self) { + let _ = self.to.send(Msg::Rescan); + } + /// From the settings; takes effect at the next failure. pub fn set_recovery(&self, tries: u32, auto_resume: bool) { let _ = self.to.send(Msg::Recovery { tries, auto_resume }); diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index ce05914..65728ad 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -25,6 +25,9 @@ pub struct Settings { pub medium: Limits, pub high: Limits, pub snail: Limits, + /// Which mode runs in each hour of the week: 168 cells from Monday 00:00, 0 for the mode chosen, 1 to 4 for low, medium, high, snail. + /// Empty for no plan. + pub mode_grid: Vec, /// Failures in a row before a download fails, 0 for never. pub tries: u32, /// Go on at the next start with what ran when Medlar ended. @@ -132,6 +135,7 @@ impl Default for Settings { medium: Limits::new(1024 * 1024, 3, 24, 8, 8), high: Limits::default(), snail: Limits::new(32 * 1024, 1, 1, 1, 1), + mode_grid: vec![], tries: 10, auto_resume: true, sites: vec![], @@ -216,6 +220,40 @@ impl Settings { } } + /// The mode that counts at this wall time: the plan's, else the chosen one. Snail by hand always wins. + pub fn mode_at(&self, local: chrono::NaiveDateTime) -> Mode { + use chrono::{Datelike, Timelike}; + let cell = local.weekday().num_days_from_monday() as usize * 24 + local.hour() as usize; + let planned = match self.mode_grid.get(cell).copied().unwrap_or(0) { + 1 => Some(Mode::Low), + 2 => Some(Mode::Medium), + 3 => Some(Mode::High), + 4 => Some(Mode::Snail), + _ => None, + }; + if self.mode == Mode::Snail { Mode::Snail } else { planned.unwrap_or(self.mode) } + } + + /// What the limits are at this wall time. + pub fn limits_at(&self, local: chrono::NaiveDateTime) -> Limits { + match self.mode_at(local) { + Mode::Low => self.low, + Mode::Medium => self.medium, + Mode::High => self.high, + Mode::Snail => self.snail, + } + } + + /// To read a mode. + pub fn limits_of_ref(&self, mode: Mode) -> &Limits { + match mode { + Mode::Low => &self.low, + Mode::Medium => &self.medium, + Mode::High => &self.high, + Mode::Snail => &self.snail, + } + } + /// To edit a mode. pub fn limits_of(&mut self, mode: Mode) -> &mut Limits { match mode { diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index b72026e..e4987ac 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -204,3 +204,7 @@ Seen: boxes were ticked together after the tests, against rule 3. - `schedule::{Clock, SystemClock, ManualClock, open, opened_between, Grid, cycle}`; set `Config.clock`. The manager's `choose` now reads queue `paused`, `max_active`, `schedule` and task `after` (a forced start overrides them); `Edit` of `after` refuses loops (`Error::Cycle`). - `power::{Watcher, WhenDone, Action, Scope, Power, Logind, Inhibitor}` (countdown, conditions, failure blocks unless `even_failed`); `run::{RunSpec, Vars, run}`. - Not done: no UI or app wiring for these, the `Grid` is not applied to the limiter, `start_at` stays on `Hold::Until` (asleep time not counted). Tests: `docs/tests/S021-queues-schedule-power.md`. + +## S022 — Control screens (compiled, not tested, no screenshots) +- Toolbar mode switch (`views/modes.rs`, snail included) opens one sheet (`views/control.rs`): Speed dial (log scale, KB/s|MB/s, typing), Queues (`queues.rs` cards, live totals, reorder by handle or buttons, "move selected here", editor with week grid), Week (`Settings.mode_grid` → `limits_at`, applied by `bridge.apply`, rechecked each hour), When done (`schedule.rs`: Watcher countdown dialog, Logind, `run::run`, Inhibitor while running). Priority share text in details. +- Not done: dragging tasks onto queue cards (used a button), start-time grid, priority share preview in list rows, core `Grid` unused (own grid instead). Limit changes save through the settings debounce, not on release. diff --git a/docs/tests/S022-control-screens.md b/docs/tests/S022-control-screens.md new file mode 100644 index 0000000..215b1da --- /dev/null +++ b/docs/tests/S022-control-screens.md @@ -0,0 +1,31 @@ +# S022 Control screens: checks + +Run the app with a throwaway home. Doubts first. + +## Doubts +- Never compiled-and-run: layout of the toolbar below 640 px (switch hidden?) and of the sheet tabs. +- Week grid drag erase rule and keyboard focus lock may fight the window's own arrow keys. +- Countdown actions (suspend, shutdown) only against a fake logind. + +## HIGH +1. Click Low/Medium/High in the toolbar: mode changes, limit applies to a running download. +2. Click snail: toggles; clicking again returns to the old mode. +3. Open the sheet (tune button), Speed tab: drag the dial, shown speed follows on a log scale; far right says No limit. +4. Type 500 in the field with KB/s, then switch to MB/s: value converts, limit stays. +5. Queues tab: add a queue, name it, save; it appears with live totals. +6. Drag a queue card by its handle; order persists after restart. Up/down buttons do the same. +7. Select tasks, press "Move the n selected here" on a queue: tasks move to it. +8. Queue editor: paint hours in the week grid, save; outside them the queue does not start tasks. +9. When done tab: choose Quit, arm with 5 s; when all finish a countdown dialog shows; Cancel stays, waiting runs Quit. +10. A failed download blocks the action unless "Also when one failed" is on. + +## MED +11. Week tab: paint a block as High, wait until/set clock into it: limits switch to High's limit. +12. Keyboard in the week grid: arrows move, Space paints, Shift+arrow paints while moving. +13. Details tab on a task shows the share text for each priority; Only says others wait. +14. Run a program: argument list runs without a shell; failure is shown as a plain message. + +## LOW +15. While downloading, the system is kept awake (check inhibitor via loginctl); lock released when idle. +16. Idle with the sheet closed draws no frames. +17. Disabled actions (not possible here) are labelled.