S018: settings, palette, shortcuts, first run and backup

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-25 07:46:35 -06:00
commit f2199dfabd
34 changed files with 3860 additions and 140 deletions

View file

@ -12,13 +12,13 @@ FEATURES 8.4 (shortcuts, palette), 8.5 (choice), 9.1, 9.8, D-012.
- ~/Projects/Damson/src/ui/{settings,palette}.rs
## Steps
- [ ] Settings with search, grouped pages, each row with its reason in one line; changes apply at once, undo per page
- [ ] Look page: Follow desktop or Own colour side by side, colour picker, scheme, light, dark, AMOLED, contrast, motion level, live preview with a real wavy bar
- [ ] Downloads, connections, network, logins and sites, notifications, power pages; other plans add theirs
- [ ] Shortcuts page with conflicts and reset; every action reachable
- [ ] Command palette (Ctrl+K) over actions, downloads and settings, instant to open
- [ ] First run: folder, colours, port explanation; skippable, three screens at most
- [ ] Backup and restore of settings
- [x] Settings with search, grouped pages, each row with its reason in one line; changes apply at once, undo per page
- [x] Look page: Follow desktop or Own colour side by side, colour picker, scheme, light, dark, AMOLED, contrast, motion level, live preview with a real wavy bar
- [x] Downloads, connections, network, logins and sites, notifications, power pages; other plans add theirs
- [x] Shortcuts page with conflicts and reset; every action reachable
- [x] Command palette (Ctrl+K) over actions, downloads and settings, instant to open
- [x] First run: folder, colours, port explanation; skippable, three screens at most
- [x] Backup and restore of settings
- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S018: …`, push
## End criteria

View file

@ -22,6 +22,7 @@ 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"] }
tokio = { version = "1", features = ["rt"] }
resvg = { version = "0.45", default-features = false }
[dev-dependencies]

View file

@ -1,19 +1,27 @@
//! The window: settings, theme and motion of a frame, and what is drawn in it.
use crate::desktop::{Sources, Watch};
use crate::desktop::{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::bridge::{Bridge, Data, Opening};
use crate::keys::{self, Action, Group};
use crate::ui::{dialog, gallery, menu};
use crate::views::firstrun::FirstRun;
use crate::views::main::{Main, Reply, Wish, open_outside};
use crate::views::palette::{Palette, Pick};
use crate::views::settings::rows::{self, Page};
use crate::views::settings::{Cx, SignIn, View};
use crate::{fonts, icons, tokens};
use eframe::egui::{self, Context, Ui, ViewportBuilder};
use medlar_core::net_state::Bus;
use medlar_core::paths::Paths;
use medlar_core::settings::{Damage, Settings};
use medlar_core::strings::{self, Catalogue};
use medlar_core::{logging, tr};
use std::io;
use std::process::ExitCode;
use std::sync::Arc;
use std::thread::JoinHandle;
/// Also the name of the desktop file, and what Wayland compositors match rules against.
pub const APP_ID: &str = "medlar";
@ -23,35 +31,135 @@ pub struct App {
pub theme: Theme,
/// The daily screen. Without an engine until it gets one.
pub main: Main,
/// The settings screen, while it is open.
pub screen: Option<Box<View>>,
pub palette: Palette,
/// Until it is through.
pub first: Option<FirstRun>,
/// Where settings are kept. Without it they are not.
pub paths: Option<Paths>,
sign_in: Option<SignIn>,
/// The desktop's colours, if it has any.
pub desktop: Desktop,
sources: Sources,
watch: Watch,
/// What `theme` was made from; a change in settings rebuilds it.
themed: Settings,
/// What the engine and the shortcuts know.
applied: Settings,
/// When changed settings are written.
save_at: Option<f64>,
saving: Option<JoinHandle<io::Result<()>>>,
}
/// Seconds without a change before the settings are written.
const SAVE_AFTER: f64 = 0.4;
impl App {
pub fn new(ctx: &Context, settings: Settings, sources: Sources) -> App {
fonts::install(ctx);
let theme = Theme::build(&settings, sources.read());
let desktop = sources.read();
let theme = Theme::build(&settings, desktop);
theme.apply(ctx, settings.motion);
keys::set(&settings);
let watch = Watch::start(sources.clone(), ctx);
App { themed: settings.clone(), settings, theme, main: Main::default(), sources, watch }
App {
themed: settings.clone(),
applied: settings.clone(),
settings,
theme,
main: Main::default(),
screen: None,
palette: Palette::default(),
first: None,
paths: None,
sign_in: None,
desktop,
sources,
watch,
save_at: None,
saving: None,
}
}
fn follow_theme(&mut self, ctx: &Context) {
if self.watch.take() || self.themed != self.settings {
let desktop = self.watch.take();
if desktop {
self.desktop = self.sources.read();
}
if desktop || self.themed != self.settings {
self.themed = self.settings.clone();
self.theme = Theme::build(&self.settings, self.sources.read());
self.theme = Theme::build(&self.settings, self.desktop);
self.theme.apply(ctx, self.settings.motion);
}
}
/// Changed settings count at once; they are written a moment later, beside the window.
fn follow_settings(&mut self, ctx: &Context) {
let now = ctx.input(|i| i.time);
if self.applied != self.settings {
keys::set(&self.settings);
self.main.bridge.apply(&self.settings);
if let Some(paths) = self.paths.as_ref().filter(|_| self.applied.language != self.settings.language) {
strings::set(Catalogue::load(&paths.languages(), &self.settings.language).0);
}
self.applied = self.settings.clone();
self.save_at = Some(now + SAVE_AFTER);
// With the new colours and words.
ctx.request_repaint();
}
match self.save_at {
Some(at) if now >= at => self.save(Some(ctx.clone())),
Some(at) => ctx.request_repaint_after_secs((at - now) as f32),
None => {}
}
if self.saving.as_ref().is_some_and(|s| s.is_finished()) {
self.saved();
}
}
fn save(&mut self, ctx: Option<Context>) {
self.saved();
self.save_at = None;
let Some(path) = self.paths.as_ref().map(Paths::settings) else { return };
let settings = self.settings.clone();
self.saving = Some(std::thread::spawn(move || {
let done = settings.save(&path);
if let Some(ctx) = ctx {
ctx.request_repaint();
}
done
}));
}
/// Waits for the last write, which takes no time once it `is_finished`.
fn saved(&mut self) {
if let Some(Ok(Err(e))) = self.saving.take().map(JoinHandle::join) {
log::warn!("settings: {e}");
let why = match e.kind() {
io::ErrorKind::PermissionDenied => tr!("backup.not_allowed"),
io::ErrorKind::StorageFull => tr!("settings.full"),
_ => tr!("backup.disk"),
};
self.main.toasts.error(tr!("settings.not_saved", why = why), None);
}
}
/// Writes what is not written yet, and waits for it.
pub fn finish(&mut self) {
if self.save_at.is_some() {
self.save(None);
}
self.saved();
}
/// Runs one frame around `draw`: theme and springs before it, the next frame after it only if something moves.
pub fn frame(&mut self, ui: &mut Ui, draw: impl FnOnce(&mut App, &mut Ui)) {
self.follow_theme(ui.ctx());
motion::begin_frame(ui.input(|i| i.stable_dt), self.settings.motion);
ui.painter().rect_filled(ui.ctx().content_rect(), 0.0, self.theme.surface);
draw(self, ui);
self.follow_settings(ui.ctx());
if motion::busy() {
ui.ctx().request_repaint();
}
@ -63,7 +171,128 @@ impl App {
}
fn view(&mut self, ui: &mut Ui) {
self.main.show(ui, &self.theme, &self.settings);
let t = self.theme.clone();
if let Some(first) = &mut self.first {
if first.show(ui, &t, &mut self.settings, self.desktop) {
self.first = None;
motion::keep_alive();
}
let bottom = ui.ctx().content_rect().bottom();
return self.main.messages(ui, &t, bottom);
}
self.keys(ui);
match self.screen.take() {
Some(mut screen) => {
if self.settings_screen(ui, &t, &mut screen) {
screen.close(&self.settings, &self.main.bridge);
motion::keep_alive();
} else {
self.screen = Some(screen);
}
}
None => self.main.show(ui, &t, &self.settings),
}
let bridge = &self.main.bridge;
if let Some(ask) = &mut self.sign_in {
ask.show(ui, &t, &mut self.settings, bridge);
}
if self.palette.is_open() {
let shot = match self.main.bridge.data() {
Data::Ready(shot, _) => Some(shot),
_ => None,
};
let some = !self.main.list.selected.is_empty();
match self.palette.show(ui, &t, shot.as_deref(), some) {
Some(Pick::Action(a)) => self.run(ui, a),
Some(Pick::Download(id)) => {
self.close_settings();
self.main.list.go_to(id);
}
Some(Pick::Page(page)) => self.open_settings(page),
Some(Pick::Setting(id, page)) => {
self.open_settings(page);
if let (Some(screen), Some(row)) = (&mut self.screen, rows::all().find(|r| r.id == id)) {
screen.go_to(ui, &row);
}
}
None => {}
}
}
match self.main.wish.take() {
Some(Wish::Settings) => self.open_settings(Page::Look),
Some(Wish::Network) => self.open_settings(Page::Network),
Some(Wish::SignIn(url, ids)) => self.sign_in = SignIn::new(&url, ids),
None => {}
}
if let Some(Reply::Settings(before)) = self.main.answer.take() {
self.settings = *before;
}
}
fn settings_screen(&mut self, ui: &mut Ui, t: &Theme, screen: &mut View) -> bool {
let main = &mut self.main;
let mut cx = Cx { t, s: &mut self.settings, desktop: self.desktop, bridge: &main.bridge, toasts: &mut main.toasts, paths: self.paths.as_ref() };
let close = screen.show(ui, &mut cx);
let bottom = ui.ctx().content_rect().bottom();
main.messages(ui, t, bottom);
close
}
pub fn open_settings(&mut self, page: Page) {
match &mut self.screen {
Some(screen) => screen.go(page),
None => self.screen = Some(Box::new(View::open(&self.settings, page))),
}
motion::keep_alive();
}
fn close_settings(&mut self) {
if let Some(mut screen) = self.screen.take() {
screen.close(&self.settings, &self.main.bridge);
}
motion::keep_alive();
}
/// The shortcuts that count anywhere.
fn keys(&mut self, ui: &Ui) {
let recording = self.screen.as_ref().is_some_and(|s| s.recording());
if self.palette.is_open() && keys::pressed(ui, Action::Palette) {
return self.palette.toggle();
}
if recording || dialog::any_open(ui.ctx()) || menu::any_open(ui.ctx()) || self.main.list.dragging() {
return;
}
for e in keys::ALL.iter().filter(|e| e.group == Group::App) {
// The settings have a search of their own.
let theirs = e.action == Action::Find && self.screen.is_some();
if !theirs && keys::pressed(ui, e.action) {
self.run(ui, e.action);
}
}
}
/// Does an action by name.
pub fn run(&mut self, ui: &Ui, action: Action) {
match action {
Action::Palette => self.palette.toggle(),
Action::Settings if self.screen.is_some() => self.close_settings(),
Action::Settings => self.open_settings(Page::Look),
Action::Network => self.open_settings(Page::Network),
Action::Snail => {
self.settings.toggle_snail();
let on = self.settings.mode == medlar_core::settings::Mode::Snail;
self.main.toasts.info("slow_motion_video", if on { tr!("snail.on") } else { tr!("snail.off") });
}
Action::Quit => ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close),
other => {
let anywhere = matches!(other, Action::ResumeAll | Action::PauseAll);
if self.screen.is_some() && !anywhere {
self.close_settings();
}
self.main.run(ui, other);
}
}
motion::keep_alive();
}
}
@ -84,6 +313,7 @@ impl eframe::App for Window {
/// Saves where the downloads are.
fn on_exit(&mut self, _: Option<&eframe::glow::Context>) {
self.app.finish();
self.app.main.bridge.close();
}
@ -116,6 +346,11 @@ fn open(engine: bool, show: fn(&mut App, &mut Ui)) -> ExitCode {
if let Some(damage) = &damage {
log::warn!("settings: {damage:?}");
}
let (catalogue, problem) = Catalogue::load(&paths.languages(), &settings.language);
if let Some(problem) = problem {
log::warn!("language: {problem}");
}
strings::set(catalogue);
let mut viewport = ViewportBuilder::default()
.with_title("Medlar")
.with_app_id(APP_ID)
@ -133,6 +368,10 @@ fn open(engine: bool, show: fn(&mut App, &mut Ui)) -> ExitCode {
let make = move |cc: &eframe::CreationContext| {
let mut app = App::new(&cc.egui_ctx, settings, Sources::detect());
if engine {
if app.settings.desktop_colors.is_none() {
app.first = Some(FirstRun::default());
}
app.paths = Some(paths.clone());
app.main.outside = open_outside;
app.main.remember(paths.data.join("view.json"));
if let Some(damage) = damage {

View file

@ -2,13 +2,16 @@
//! sends commands, and waits for nothing.
use eframe::egui::Context;
use medlar_core::auth::Login;
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::secret::{Secret, Secrets};
use medlar_core::settings::Settings;
use medlar_core::site::Sites;
use medlar_core::snapshot::Snapshot;
use medlar_core::store::Store;
use medlar_core::tr;
@ -42,7 +45,7 @@ pub struct Opening {
enum Engine {
Opening,
Failed(String),
Open { manager: Arc<Manager>, store: Arc<Store>, lists: Arc<Lists>, replies: mpsc::Sender<Reply> },
Open { manager: Arc<Manager>, store: Arc<Store>, sites: Arc<Sites>, 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,
@ -52,6 +55,8 @@ struct Inner {
/// Held only to copy what it points to.
engine: Mutex<Engine>,
errors: Mutex<Vec<String>>,
/// Settings that changed while it was opening.
late: Mutex<Option<Settings>>,
}
/// The window's end of the engine.
@ -72,7 +77,7 @@ impl Default for Bridge {
impl Bridge {
fn with(engine: Engine, opening: Option<(Opening, Context)>) -> Bridge {
Bridge { inner: Arc::new(Inner { engine: Mutex::new(engine), errors: Mutex::default() }), opening }
Bridge { inner: Arc::new(Inner { engine: Mutex::new(engine), errors: Mutex::default(), late: Mutex::default() }), opening }
}
/// Opens the engine in the background. A frame is drawn when it is there, and after each change of the list.
@ -101,6 +106,9 @@ impl Bridge {
// The window may be gone by now; dropping the engine closes it.
if matches!(*engine, Engine::Opening) {
*engine = made;
if let Some(settings) = lock(&inner.late).take() {
apply(&engine, &settings);
}
}
drop(engine);
ctx.request_repaint();
@ -163,6 +171,60 @@ impl Bridge {
});
}
/// New settings count at once, also for what runs.
pub fn apply(&mut self, settings: &Settings) {
if let Some((opening, _)) = &mut self.opening {
opening.settings = settings.clone();
}
let engine = lock(&self.inner.engine);
if matches!(*engine, Engine::Opening) {
*lock(&self.inner.late) = Some(settings.clone());
}
apply(&engine, settings);
}
/// Puts a login in the keyring under `name`, or a proxy's when that is given, then sends `after`. That the
/// keyring didn't take it comes back through `take_errors`.
pub fn save_login(&self, place: Place, login: Login, after: Vec<Command>) {
let (sites, replies, manager) = match &mut *lock(&self.inner.engine) {
Engine::Open { sites, replies, manager, .. } => (sites.clone(), replies.clone(), manager.clone()),
Engine::Still { sent, .. } => return sent.extend(after),
_ => return,
};
let inner = self.inner.clone();
let ctx = self.opening.as_ref().map(|(_, ctx)| ctx.clone());
std::thread::spawn(move || {
let made = tokio::runtime::Builder::new_current_thread().enable_all().build();
let Ok(runtime) = made.inspect_err(|e| log::error!("login: {e}")) else { return };
let kept = runtime.block_on(async {
match &place {
Place::Site { name, host } => Some(sites.secrets.save(name, host, &Secret { login: Some(login), ..Secret::default() }).await),
Place::Proxy(proxy) => sites.save_proxy_login(proxy, login).await,
}
});
if let Some(words) = kept.and_then(|k| k.words()) {
lock(&inner.errors).push(words);
}
for command in after {
let _ = replies.send(manager.send(command));
}
if let Some(ctx) = ctx {
ctx.request_repaint();
}
});
}
/// Takes a login out of the keyring.
pub fn forget_login(&self, name: String) {
let Engine::Open { sites, .. } = &*lock(&self.inner.engine) else { return };
let sites = sites.clone();
std::thread::spawn(move || {
if let Ok(runtime) = tokio::runtime::Builder::new_current_thread().enable_all().build() {
runtime.block_on(sites.secrets.remove(&name));
}
});
}
/// The engine itself, for what the bridge has no word for.
pub fn manager(&self) -> Option<Arc<Manager>> {
match &*lock(&self.inner.engine) {
@ -195,6 +257,20 @@ impl Bridge {
}
}
/// Whose login it is.
pub enum Place {
Site { name: String, host: String },
Proxy(String),
}
fn apply(engine: &Engine, settings: &Settings) {
if let Engine::Open { manager, sites, .. } = engine {
manager.set_limits(settings.limits());
manager.set_recovery(settings.tries, settings.auto_resume);
sites.set(settings);
}
}
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())
@ -207,13 +283,18 @@ fn make(opening: Opening, inner: &Arc<Inner>, ctx: &Context) -> Result<Engine, S
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| {
let no_network = |e: http::Error| {
log::error!("engine: {e:?}");
tr!("open.network")
})?;
};
let client = http::client(&ClientOptions::default()).map_err(no_network)?;
let session = if matches!(bus, Bus::Off) { Bus::Off } else { Bus::Session };
let secrets = Arc::new(Secrets::new(session.clone()));
let sites = Sites::new(ClientOptions::default(), &settings, secrets, session).map_err(no_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.sites = Some(sites.clone());
config.recovery.bus = bus;
config.recovery.tries = settings.tries;
config.recovery.auto_resume = settings.auto_resume;
@ -234,7 +315,7 @@ fn make(opening: Opening, inner: &Arc<Inner>, ctx: &Context) -> Result<Engine, S
}
})
.map_err(|e| words(&e))?;
Ok(Engine::Open { manager, store, lists, replies })
Ok(Engine::Open { manager, store, sites, lists, replies })
}
/// Where files go when nothing else was said.

View file

@ -67,8 +67,10 @@ pub const ICONS: &[(&str, &str)] = &[
("info_fill", "M480 -280Q497 -280 508.5 -291.5Q520 -303 520 -320V-480Q520 -497 508.5 -508.5Q497 -520 480 -520Q463 -520 451.5 -508.5Q440 -497 440 -480V-320Q440 -303 451.5 -291.5Q463 -280 480 -280ZM480 -600Q497 -600 508.5 -611.5Q520 -623 520 -640Q520 -657 508.5 -668.5Q497 -680 480 -680Q463 -680 451.5 -668.5Q440 -657 440 -640Q440 -623 451.5 -611.5Q463 -600 480 -600ZM480 -80Q397 -80 324 -111.5Q251 -143 197 -197Q143 -251 111.5 -324Q80 -397 80 -480Q80 -563 111.5 -636Q143 -709 197 -763Q251 -817 324 -848.5Q397 -880 480 -880Q563 -880 636 -848.5Q709 -817 763 -763Q817 -709 848.5 -636Q880 -563 880 -480Q880 -397 848.5 -324Q817 -251 763 -197Q709 -143 636 -111.5Q563 -80 480 -80ZM480 -160Q614 -160 707 -253Q800 -346 800 -480Q800 -614 707 -707Q614 -800 480 -800Q346 -800 253 -707Q160 -614 160 -480Q160 -346 253 -253Q346 -160 480 -160ZM480 -160Q346 -160 253 -253Q160 -346 160 -480Q160 -614 253 -707Q346 -800 480 -800Q614 -800 707 -707Q800 -614 800 -480Q800 -346 707 -253Q614 -160 480 -160Z"),
("key", "M280 -400Q247 -400 223.5 -423.5Q200 -447 200 -480Q200 -513 223.5 -536.5Q247 -560 280 -560Q313 -560 336.5 -536.5Q360 -513 360 -480Q360 -447 336.5 -423.5Q313 -400 280 -400ZM280 -240Q180 -240 110 -310Q40 -380 40 -480Q40 -580 110 -650Q180 -720 280 -720Q347 -720 401.5 -687Q456 -654 488 -600H823Q831 -600 838.5 -597Q846 -594 852 -588L932 -508Q938 -502 940.5 -495Q943 -488 943 -480Q943 -472 940.5 -465Q938 -458 932 -452L805 -325Q800 -320 793 -317Q786 -314 779 -313Q772 -312 765 -314Q758 -316 752 -321L700 -360L643 -317Q638 -313 632 -311Q626 -309 620 -309Q614 -309 607.5 -311Q601 -313 596 -317L535 -360H488Q456 -306 401.5 -273Q347 -240 280 -240ZM280 -320Q336 -320 378.5 -354Q421 -388 435 -440H560L618 -399Q618 -399 618 -398.5Q618 -398 618 -399Q618 -399 618 -399Q618 -399 618 -399L700 -460L771 -405Q771 -405 771 -405Q771 -405 771 -405Q771 -405 771 -405Q771 -405 771 -405L846 -480Q845 -480 845.5 -480Q846 -480 846 -480Q846 -480 846 -480Q846 -480 846 -480L806 -520Q806 -521 806 -520.5Q806 -520 806 -520H435Q421 -572 378.5 -606Q336 -640 280 -640Q214 -640 167 -593Q120 -546 120 -480Q120 -414 167 -367Q214 -320 280 -320Z"),
("key_fill", "M280 -360Q230.5 -360 195.2 -395.2Q160 -430.5 160 -480Q160 -529.5 195.2 -564.8Q230.5 -600 280 -600Q329.5 -600 364.8 -564.8Q400 -529.5 400 -480Q400 -430.5 364.8 -395.2Q329.5 -360 280 -360ZM280 -480Q280 -480 280 -480Q280 -480 280 -480Q280 -480 280 -480Q280 -480 280 -480Q280 -480 280 -480Q280 -480 280 -480H805Q805 -480 805 -480Q805 -480 805 -480Q805 -480 805 -480Q805 -480 805 -480Q805 -480 805 -480Q805 -480 805 -480Q800 -480 793 -480Q786 -480 779 -480Q772 -480 765 -480Q758 -480 752 -480H700H643Q638 -480 632 -480Q626 -480 620 -480Q614 -480 607.5 -480Q601 -480 596 -480H280Q280 -480 280 -480Q280 -480 280 -480ZM280 -240Q357 -240 419 -284Q481 -328 506 -400H520L572 -348Q578 -342 585 -339.5Q592 -337 600 -337Q608 -337 615 -339.5Q622 -342 628 -348L680 -400L750 -345Q756 -340 763.5 -337.5Q771 -335 779 -336Q787 -337 793.5 -340.5Q800 -344 805 -350L895 -453Q900 -459 902.5 -466Q905 -473 905 -481Q905 -489 902 -495.5Q899 -502 894 -507L853 -548Q847 -554 839.5 -557Q832 -560 824 -560H506Q482 -628 421.5 -674Q361 -720 280 -720Q180 -720 110 -650Q40 -580 40 -480Q40 -380 110 -310Q180 -240 280 -240Z"),
("keyboard", "M160 -200Q127 -200 103.5 -223.5Q80 -247 80 -280V-680Q80 -713 103.5 -736.5Q127 -760 160 -760H800Q833 -760 856.5 -736.5Q880 -713 880 -680V-280Q880 -247 856.5 -223.5Q833 -200 800 -200ZM160 -280H800Q800 -280 800 -280Q800 -280 800 -280V-680Q800 -680 800 -680Q800 -680 800 -680H160Q160 -680 160 -680Q160 -680 160 -680V-280Q160 -280 160 -280Q160 -280 160 -280ZM360 -320H600Q617 -320 628.5 -331.5Q640 -343 640 -360Q640 -377 628.5 -388.5Q617 -400 600 -400H360Q343 -400 331.5 -388.5Q320 -377 320 -360Q320 -343 331.5 -331.5Q343 -320 360 -320ZM160 -280Q160 -280 160 -280Q160 -280 160 -280V-680Q160 -680 160 -680Q160 -680 160 -680Q160 -680 160 -680Q160 -680 160 -680V-280Q160 -280 160 -280Q160 -280 160 -280ZM240 -560Q257 -560 268.5 -571.5Q280 -583 280 -600Q280 -617 268.5 -628.5Q257 -640 240 -640Q223 -640 211.5 -628.5Q200 -617 200 -600Q200 -583 211.5 -571.5Q223 -560 240 -560ZM360 -560Q377 -560 388.5 -571.5Q400 -583 400 -600Q400 -617 388.5 -628.5Q377 -640 360 -640Q343 -640 331.5 -628.5Q320 -617 320 -600Q320 -583 331.5 -571.5Q343 -560 360 -560ZM480 -560Q497 -560 508.5 -571.5Q520 -583 520 -600Q520 -617 508.5 -628.5Q497 -640 480 -640Q463 -640 451.5 -628.5Q440 -617 440 -600Q440 -583 451.5 -571.5Q463 -560 480 -560ZM600 -560Q617 -560 628.5 -571.5Q640 -583 640 -600Q640 -617 628.5 -628.5Q617 -640 600 -640Q583 -640 571.5 -628.5Q560 -617 560 -600Q560 -583 571.5 -571.5Q583 -560 600 -560ZM720 -560Q737 -560 748.5 -571.5Q760 -583 760 -600Q760 -617 748.5 -628.5Q737 -640 720 -640Q703 -640 691.5 -628.5Q680 -617 680 -600Q680 -583 691.5 -571.5Q703 -560 720 -560ZM240 -440Q257 -440 268.5 -451.5Q280 -463 280 -480Q280 -497 268.5 -508.5Q257 -520 240 -520Q223 -520 211.5 -508.5Q200 -497 200 -480Q200 -463 211.5 -451.5Q223 -440 240 -440ZM360 -440Q377 -440 388.5 -451.5Q400 -463 400 -480Q400 -497 388.5 -508.5Q377 -520 360 -520Q343 -520 331.5 -508.5Q320 -497 320 -480Q320 -463 331.5 -451.5Q343 -440 360 -440ZM480 -440Q497 -440 508.5 -451.5Q520 -463 520 -480Q520 -497 508.5 -508.5Q497 -520 480 -520Q463 -520 451.5 -508.5Q440 -497 440 -480Q440 -463 451.5 -451.5Q463 -440 480 -440ZM600 -440Q617 -440 628.5 -451.5Q640 -463 640 -480Q640 -497 628.5 -508.5Q617 -520 600 -520Q583 -520 571.5 -508.5Q560 -497 560 -480Q560 -463 571.5 -451.5Q583 -440 600 -440ZM720 -440Q737 -440 748.5 -451.5Q760 -463 760 -480Q760 -497 748.5 -508.5Q737 -520 720 -520Q703 -520 691.5 -508.5Q680 -497 680 -480Q680 -463 691.5 -451.5Q703 -440 720 -440Z"),
("keyboard_arrow_down", "M480 -361Q472 -361 465 -363.5Q458 -366 452 -372L268 -556Q257 -567 257 -584Q257 -601 268 -612Q279 -623 296 -623Q313 -623 324 -612L480 -456L636 -612Q647 -623 664 -623Q681 -623 692 -612Q703 -601 703 -584Q703 -567 692 -556L508 -372Q502 -366 495 -363.5Q488 -361 480 -361Z"),
("keyboard_arrow_up", "M480 -528 324 -372Q313 -361 296 -361Q279 -361 268 -372Q257 -383 257 -400Q257 -417 268 -428L452 -612Q464 -624 480 -624Q496 -624 508 -612L692 -428Q703 -417 703 -400Q703 -383 692 -372Q681 -361 664 -361Q647 -361 636 -372Z"),
("keyboard_fill", "M160 -200Q127 -200 103.5 -223.5Q80 -247 80 -280V-680Q80 -713 103.5 -736.5Q127 -760 160 -760H800Q833 -760 856.5 -736.5Q880 -713 880 -680V-280Q880 -247 856.5 -223.5Q833 -200 800 -200ZM160 -280H800Q800 -280 800 -280Q800 -280 800 -280V-680Q800 -680 800 -680Q800 -680 800 -680H160Q160 -680 160 -680Q160 -680 160 -680V-280Q160 -280 160 -280Q160 -280 160 -280ZM360 -320H600Q617 -320 628.5 -331.5Q640 -343 640 -360Q640 -377 628.5 -388.5Q617 -400 600 -400H360Q343 -400 331.5 -388.5Q320 -377 320 -360Q320 -343 331.5 -331.5Q343 -320 360 -320ZM160 -280Q160 -280 160 -280Q160 -280 160 -280V-680Q160 -680 160 -680Q160 -680 160 -680H800Q800 -680 800 -680Q800 -680 800 -680V-280Q800 -280 800 -280Q800 -280 800 -280ZM240 -560Q257 -560 268.5 -571.5Q280 -583 280 -600Q280 -617 268.5 -628.5Q257 -640 240 -640Q223 -640 211.5 -628.5Q200 -617 200 -600Q200 -583 211.5 -571.5Q223 -560 240 -560ZM360 -560Q377 -560 388.5 -571.5Q400 -583 400 -600Q400 -617 388.5 -628.5Q377 -640 360 -640Q343 -640 331.5 -628.5Q320 -617 320 -600Q320 -583 331.5 -571.5Q343 -560 360 -560ZM480 -560Q497 -560 508.5 -571.5Q520 -583 520 -600Q520 -617 508.5 -628.5Q497 -640 480 -640Q463 -640 451.5 -628.5Q440 -617 440 -600Q440 -583 451.5 -571.5Q463 -560 480 -560ZM600 -560Q617 -560 628.5 -571.5Q640 -583 640 -600Q640 -617 628.5 -628.5Q617 -640 600 -640Q583 -640 571.5 -628.5Q560 -617 560 -600Q560 -583 571.5 -571.5Q583 -560 600 -560ZM720 -560Q737 -560 748.5 -571.5Q760 -583 760 -600Q760 -617 748.5 -628.5Q737 -640 720 -640Q703 -640 691.5 -628.5Q680 -617 680 -600Q680 -583 691.5 -571.5Q703 -560 720 -560ZM240 -440Q257 -440 268.5 -451.5Q280 -463 280 -480Q280 -497 268.5 -508.5Q257 -520 240 -520Q223 -520 211.5 -508.5Q200 -497 200 -480Q200 -463 211.5 -451.5Q223 -440 240 -440ZM360 -440Q377 -440 388.5 -451.5Q400 -463 400 -480Q400 -497 388.5 -508.5Q377 -520 360 -520Q343 -520 331.5 -508.5Q320 -497 320 -480Q320 -463 331.5 -451.5Q343 -440 360 -440ZM480 -440Q497 -440 508.5 -451.5Q520 -463 520 -480Q520 -497 508.5 -508.5Q497 -520 480 -520Q463 -520 451.5 -508.5Q440 -497 440 -480Q440 -463 451.5 -451.5Q463 -440 480 -440ZM600 -440Q617 -440 628.5 -451.5Q640 -463 640 -480Q640 -497 628.5 -508.5Q617 -520 600 -520Q583 -520 571.5 -508.5Q560 -497 560 -480Q560 -463 571.5 -451.5Q583 -440 600 -440ZM720 -440Q737 -440 748.5 -451.5Q760 -463 760 -480Q760 -497 748.5 -508.5Q737 -520 720 -520Q703 -520 691.5 -508.5Q680 -497 680 -480Q680 -463 691.5 -451.5Q703 -440 720 -440Z"),
("label", "M160 -160Q127 -160 103.5 -183.5Q80 -207 80 -240V-720Q80 -753 103.5 -776.5Q127 -800 160 -800H600Q619 -800 636 -791.5Q653 -783 664 -768L844 -528Q860 -507 860 -480Q860 -453 844 -432L664 -192Q653 -177 636 -168.5Q619 -160 600 -160ZM160 -240H600Q600 -240 600 -240Q600 -240 600 -240L780 -480Q780 -480 780 -480Q780 -480 780 -480L600 -720Q600 -720 600 -720Q600 -720 600 -720H160Q160 -720 160 -720Q160 -720 160 -720V-240Q160 -240 160 -240Q160 -240 160 -240ZM470 -480Q470 -480 470 -480Q470 -480 470 -480Q470 -480 470 -480Q470 -480 470 -480Q470 -480 470 -480Q470 -480 470 -480Q470 -480 470 -480Q470 -480 470 -480Q470 -480 470 -480Q470 -480 470 -480Z"),
("label_fill", "M160 -160Q127 -160 103.5 -183.5Q80 -207 80 -240V-720Q80 -753 103.5 -776.5Q127 -800 160 -800H600Q619 -800 636 -791.5Q653 -783 664 -768L844 -528Q860 -507 860 -480Q860 -453 844 -432L664 -192Q653 -177 636 -168.5Q619 -160 600 -160ZM160 -240H600Q600 -240 600 -240Q600 -240 600 -240L780 -480Q780 -480 780 -480Q780 -480 780 -480L600 -720Q600 -720 600 -720Q600 -720 600 -720H160Q160 -720 160 -720Q160 -720 160 -720V-240Q160 -240 160 -240Q160 -240 160 -240ZM160 -240Q160 -240 160 -240Q160 -240 160 -240V-720Q160 -720 160 -720Q160 -720 160 -720H600Q600 -720 600 -720Q600 -720 600 -720L780 -480Q780 -480 780 -480Q780 -480 780 -480L600 -240Q600 -240 600 -240Q600 -240 600 -240Z"),
("language", "M480 -80Q398 -80 325 -111.5Q252 -143 197.5 -197.5Q143 -252 111.5 -325Q80 -398 80 -480Q80 -563 111.5 -635.5Q143 -708 197.5 -762.5Q252 -817 325 -848.5Q398 -880 480 -880Q563 -880 635.5 -848.5Q708 -817 762.5 -762.5Q817 -708 848.5 -635.5Q880 -563 880 -480Q880 -398 848.5 -325Q817 -252 762.5 -197.5Q708 -143 635.5 -111.5Q563 -80 480 -80ZM480 -162Q506 -198 525 -237Q544 -276 556 -320H404Q416 -276 435 -237Q454 -198 480 -162ZM376 -178Q358 -211 344.5 -246.5Q331 -282 322 -320H204Q233 -270 276.5 -233Q320 -196 376 -178ZM584 -178Q640 -196 683.5 -233Q727 -270 756 -320H638Q629 -282 615.5 -246.5Q602 -211 584 -178ZM170 -400H306Q303 -420 301.5 -439.5Q300 -459 300 -480Q300 -501 301.5 -520.5Q303 -540 306 -560H170Q165 -540 162.5 -520.5Q160 -501 160 -480Q160 -459 162.5 -439.5Q165 -420 170 -400ZM386 -400H574Q577 -420 578.5 -439.5Q580 -459 580 -480Q580 -501 578.5 -520.5Q577 -540 574 -560H386Q383 -540 381.5 -520.5Q380 -501 380 -480Q380 -459 381.5 -439.5Q383 -420 386 -400ZM654 -400H790Q795 -420 797.5 -439.5Q800 -459 800 -480Q800 -501 797.5 -520.5Q795 -540 790 -560H654Q657 -540 658.5 -520.5Q660 -501 660 -480Q660 -459 658.5 -439.5Q657 -420 654 -400ZM638 -640H756Q727 -690 683.5 -727Q640 -764 584 -782Q602 -749 615.5 -713.5Q629 -678 638 -640ZM404 -640H556Q544 -684 525 -723Q506 -762 480 -798Q454 -762 435 -723Q416 -684 404 -640ZM204 -640H322Q331 -678 344.5 -713.5Q358 -749 376 -782Q320 -764 276.5 -727Q233 -690 204 -640Z"),
@ -91,6 +93,8 @@ pub const ICONS: &[(&str, &str)] = &[
("music_note", "M400 -120Q334 -120 287 -167Q240 -214 240 -280Q240 -346 287 -393Q334 -440 400 -440Q423 -440 442.5 -434.5Q462 -429 480 -418V-800Q480 -817 491.5 -828.5Q503 -840 520 -840H680Q697 -840 708.5 -828.5Q720 -817 720 -800V-720Q720 -703 708.5 -691.5Q697 -680 680 -680H560V-280Q560 -214 513 -167Q466 -120 400 -120Z"),
("note", "M240 -80Q207 -80 183.5 -103.5Q160 -127 160 -160V-800Q160 -833 183.5 -856.5Q207 -880 240 -880H527Q543 -880 557.5 -874Q572 -868 583 -857L777 -663Q788 -652 794 -637.5Q800 -623 800 -607V-160Q800 -127 776.5 -103.5Q753 -80 720 -80ZM520 -640V-800H240Q240 -800 240 -800Q240 -800 240 -800V-160Q240 -160 240 -160Q240 -160 240 -160H720Q720 -160 720 -160Q720 -160 720 -160V-600H560Q543 -600 531.5 -611.5Q520 -623 520 -640ZM240 -800V-640Q240 -623 240 -611.5Q240 -600 240 -600V-800V-640Q240 -623 240 -611.5Q240 -600 240 -600V-160Q240 -160 240 -160Q240 -160 240 -160Q240 -160 240 -160Q240 -160 240 -160V-800Q240 -800 240 -800Q240 -800 240 -800Z"),
("note_fill", "M240 -80Q207 -80 183.5 -103.5Q160 -127 160 -160V-800Q160 -833 183.5 -856.5Q207 -880 240 -880H527Q543 -880 557.5 -874Q572 -868 583 -857L777 -663Q788 -652 794 -637.5Q800 -623 800 -607V-160Q800 -127 776.5 -103.5Q753 -80 720 -80ZM520 -640V-800H240Q240 -800 240 -800Q240 -800 240 -800V-160Q240 -160 240 -160Q240 -160 240 -160H720Q720 -160 720 -160Q720 -160 720 -160V-600H560Q543 -600 531.5 -611.5Q520 -623 520 -640ZM240 -800H520V-640Q520 -623 531.5 -611.5Q543 -600 560 -600H720L520 -800V-640Q520 -623 531.5 -611.5Q543 -600 560 -600H720V-160Q720 -160 720 -160Q720 -160 720 -160H240Q240 -160 240 -160Q240 -160 240 -160V-800Q240 -800 240 -800Q240 -800 240 -800Z"),
("notifications", "M200 -200Q183 -200 171.5 -211.5Q160 -223 160 -240Q160 -257 171.5 -268.5Q183 -280 200 -280H240V-560Q240 -643 290 -707.5Q340 -772 420 -792V-820Q420 -845 437.5 -862.5Q455 -880 480 -880Q505 -880 522.5 -862.5Q540 -845 540 -820V-792Q620 -772 670 -707.5Q720 -643 720 -560V-280H760Q777 -280 788.5 -268.5Q800 -257 800 -240Q800 -223 788.5 -211.5Q777 -200 760 -200ZM480 -500Q480 -500 480 -500Q480 -500 480 -500Q480 -500 480 -500Q480 -500 480 -500ZM480 -80Q447 -80 423.5 -103.5Q400 -127 400 -160H560Q560 -127 536.5 -103.5Q513 -80 480 -80ZM320 -280H640V-560Q640 -626 593 -673Q546 -720 480 -720Q414 -720 367 -673Q320 -626 320 -560Z"),
("notifications_fill", "M200 -200Q183 -200 171.5 -211.5Q160 -223 160 -240Q160 -257 171.5 -268.5Q183 -280 200 -280H240V-560Q240 -643 290 -707.5Q340 -772 420 -792V-820Q420 -845 437.5 -862.5Q455 -880 480 -880Q505 -880 522.5 -862.5Q540 -845 540 -820V-792Q620 -772 670 -707.5Q720 -643 720 -560V-280H760Q777 -280 788.5 -268.5Q800 -257 800 -240Q800 -223 788.5 -211.5Q777 -200 760 -200ZM640 -560V-280H320V-560Q320 -626 367 -673Q414 -720 480 -720Q546 -720 593 -673Q640 -626 640 -560ZM480 -80Q447 -80 423.5 -103.5Q400 -127 400 -160H560Q560 -127 536.5 -103.5Q513 -80 480 -80ZM320 -280H640V-560Q640 -626 593 -673Q546 -720 480 -720Q414 -720 367 -673Q320 -626 320 -560Z"),
("open_in_new", "M200 -120Q167 -120 143.5 -143.5Q120 -167 120 -200V-760Q120 -793 143.5 -816.5Q167 -840 200 -840H440Q457 -840 468.5 -828.5Q480 -817 480 -800Q480 -783 468.5 -771.5Q457 -760 440 -760H200Q200 -760 200 -760Q200 -760 200 -760V-200Q200 -200 200 -200Q200 -200 200 -200H760Q760 -200 760 -200Q760 -200 760 -200V-440Q760 -457 771.5 -468.5Q783 -480 800 -480Q817 -480 828.5 -468.5Q840 -457 840 -440V-200Q840 -167 816.5 -143.5Q793 -120 760 -120ZM760 -704 416 -360Q405 -349 388 -349Q371 -349 360 -360Q349 -371 349 -388Q349 -405 360 -416L704 -760H600Q583 -760 571.5 -771.5Q560 -783 560 -800Q560 -817 571.5 -828.5Q583 -840 600 -840H800Q817 -840 828.5 -828.5Q840 -817 840 -800V-600Q840 -583 828.5 -571.5Q817 -560 800 -560Q783 -560 771.5 -571.5Q760 -583 760 -600Z"),
("package_2", "M440 -183V-457L200 -596V-322Q200 -322 200 -322Q200 -322 200 -322ZM520 -183 760 -322Q760 -322 760 -322Q760 -322 760 -322V-596L520 -457ZM440 -91 160 -252Q141 -263 130.5 -281Q120 -299 120 -321V-639Q120 -661 130.5 -679Q141 -697 160 -708L440 -869Q459 -880 480 -880Q501 -880 520 -869L800 -708Q819 -697 829.5 -679Q840 -661 840 -639V-321Q840 -299 829.5 -281Q819 -263 800 -252L520 -91Q501 -80 480 -80Q459 -80 440 -91ZM640 -619 717 -663 480 -800Q480 -800 480 -800Q480 -800 480 -800L402 -755ZM480 -526 558 -571 321 -708 243 -663Z"),
("package_2_fill", "M440 -91V-456.6L120 -642V-321Q120 -299 130.5 -281Q141 -263 160 -252ZM520 -91 800 -252Q819 -263 829.5 -281Q840 -299 840 -321V-642L520 -456.6ZM480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480Q480 -480 480 -480ZM679 -641 797 -710 520 -869Q501 -880 480 -880Q459 -880 440 -869L361 -824ZM480 -526 599 -594 282 -778 162 -709Z"),

307
crates/app/src/keys.rs Normal file
View file

@ -0,0 +1,307 @@
//! Every action, its name and its shortcut. A new action is a variant of `Action`, a line in `ALL`, an `action.<id>` text,
//! and its arm in `App::run` or `Main::run`; the shortcuts page and the palette show it by themselves.
use eframe::egui::{Event, Key, Modifiers, Ui};
use medlar_core::settings::Settings;
use medlar_core::strings;
use std::cell::RefCell;
use std::collections::HashMap;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Action {
Add,
Find,
Palette,
Settings,
Rail,
View,
ResumeAll,
PauseAll,
Snail,
Network,
Quit,
SelectAll,
OpenOrRun,
Toggle,
Show,
Copy,
Page,
Start,
Resume,
Pause,
Stop,
Redownload,
Rename,
Folder,
Link,
Up,
Down,
Remove,
Bin,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Group {
/// Anywhere in the window.
App,
/// In the list, most of them for the selected downloads.
List,
}
impl Group {
pub const ALL: [Group; 2] = [Group::App, Group::List];
pub fn label(self) -> String {
let id = match self {
Group::App => "app",
Group::List => "list",
};
strings::text(&format!("keys.group.{id}"), &[])
}
}
pub struct Entry {
pub action: Action,
pub id: &'static str,
pub icon: &'static str,
pub group: Group,
/// As `Shortcut::parse` reads it; empty for none.
keys: &'static str,
}
const fn entry(action: Action, id: &'static str, icon: &'static str, group: Group, keys: &'static str) -> Entry {
Entry { action, id, icon, group, keys }
}
pub const ALL: &[Entry] = &[
entry(Action::Add, "add", "add", Group::App, "Ctrl+N"),
entry(Action::Find, "find", "search", Group::App, "Ctrl+F"),
entry(Action::Palette, "palette", "terminal", Group::App, "Ctrl+K"),
entry(Action::Settings, "settings", "settings", Group::App, "Ctrl+,"),
entry(Action::Rail, "rail", "menu", Group::App, "Ctrl+B"),
entry(Action::View, "view", "view_agenda", Group::App, "Ctrl+Shift+V"),
entry(Action::ResumeAll, "resume_all", "play_arrow", Group::App, "Ctrl+Shift+R"),
entry(Action::PauseAll, "pause_all", "pause", Group::App, "Ctrl+Shift+P"),
entry(Action::Snail, "snail", "slow_motion_video", Group::App, "Ctrl+Shift+S"),
entry(Action::Network, "network", "language", Group::App, ""),
entry(Action::Quit, "quit", "power_settings_new", Group::App, "Ctrl+Q"),
entry(Action::SelectAll, "select_all", "select_all", Group::List, "Ctrl+A"),
entry(Action::OpenOrRun, "open", "open_in_new", Group::List, "Enter"),
entry(Action::Toggle, "toggle", "play_circle", Group::List, "Space"),
entry(Action::Show, "show", "folder_open", Group::List, "Ctrl+O"),
entry(Action::Copy, "copy", "content_copy", Group::List, "Ctrl+C"),
entry(Action::Page, "page", "public", Group::List, ""),
entry(Action::Start, "start", "bolt", Group::List, "Ctrl+Enter"),
entry(Action::Resume, "resume", "play_arrow", Group::List, ""),
entry(Action::Pause, "pause", "pause", Group::List, ""),
entry(Action::Stop, "stop", "low_priority", Group::List, ""),
entry(Action::Redownload, "redownload", "replay", Group::List, "Ctrl+R"),
entry(Action::Rename, "rename", "edit", Group::List, "F2"),
entry(Action::Folder, "folder", "folder", Group::List, "Ctrl+M"),
entry(Action::Link, "link", "link", Group::List, "Ctrl+L"),
entry(Action::Up, "up", "arrow_upward", Group::List, "Alt+Up"),
entry(Action::Down, "down", "arrow_downward", Group::List, "Alt+Down"),
entry(Action::Remove, "remove", "close", Group::List, "Del"),
entry(Action::Bin, "bin", "delete", Group::List, "Shift+Del"),
];
impl Entry {
pub fn label(&self) -> String {
strings::text(&format!("action.{}", self.id), &[])
}
}
impl Action {
pub fn entry(self) -> &'static Entry {
ALL.iter().find(|e| e.action == self).expect("every action has a line in ALL")
}
}
/// One key with any of Ctrl, Alt and Shift.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Shortcut {
pub ctrl: bool,
pub alt: bool,
pub shift: bool,
pub key: Key,
}
/// Keys with a short name of their own.
const SHORT: [(Key, &str); 6] = [
(Key::Delete, "Del"),
(Key::ArrowUp, "Up"),
(Key::ArrowDown, "Down"),
(Key::ArrowLeft, "Left"),
(Key::ArrowRight, "Right"),
(Key::Comma, ","),
];
impl Shortcut {
pub fn new(m: Modifiers, key: Key) -> Shortcut {
Shortcut { ctrl: m.command || m.ctrl, alt: m.alt, shift: m.shift, key }
}
/// `Ctrl+Shift+N`. None for what can't be a shortcut.
pub fn parse(text: &str) -> Option<Shortcut> {
let mut m = Modifiers::NONE;
let mut rest = text.trim();
// The key itself may be a plus.
while let Some((name, after)) = rest.split_once('+').filter(|(name, after)| !name.is_empty() && !after.is_empty()) {
match name.to_ascii_lowercase().as_str() {
"ctrl" => m.ctrl = true,
"alt" => m.alt = true,
"shift" => m.shift = true,
_ => return None,
}
rest = after;
}
let short = SHORT.iter().find(|(_, name)| name.eq_ignore_ascii_case(rest)).map(|(k, _)| *k);
Some(Shortcut::new(m, short.or_else(|| Key::from_name(rest))?))
}
pub fn label(self) -> String {
let name = SHORT.iter().find(|(k, _)| *k == self.key).map_or(self.key.name(), |(_, n)| n);
let mods = [(self.ctrl, "Ctrl+"), (self.alt, "Alt+"), (self.shift, "Shift+")];
mods.iter().filter(|(on, _)| *on).map(|(_, n)| *n).chain([name]).collect()
}
/// Moving about, leaving and pasting belong to the window.
pub fn taken(self) -> bool {
let moves = [Key::ArrowUp, Key::ArrowDown, Key::ArrowLeft, Key::ArrowRight, Key::Home, Key::End, Key::PageUp, Key::PageDown, Key::Tab, Key::Escape];
let edits = [Key::V, Key::X, Key::Z];
moves.contains(&self.key) && !self.alt || self.key == Key::Tab || self.ctrl && !self.alt && !self.shift && edits.contains(&self.key)
}
/// Would type something or press what has the keyboard, so it can't count everywhere.
pub fn types(self) -> bool {
let function = self.key.name().strip_prefix('F').is_some_and(|n| n.parse::<u8>().is_ok());
!self.ctrl && !self.alt && !function
}
/// The window system turns copying and cutting into events of their own.
fn fits(self, e: &Event) -> bool {
match e {
Event::Key { key, pressed: true, modifiers, .. } => Shortcut::new(*modifiers, *key) == self,
Event::Copy => self == Shortcut { ctrl: true, alt: false, shift: false, key: Key::C },
Event::Cut => self == Shortcut { ctrl: true, alt: false, shift: false, key: Key::X },
_ => false,
}
}
}
/// What was pressed, for recording a shortcut.
pub fn recorded(ui: &Ui) -> Option<Shortcut> {
let plain = |key| Some(Shortcut { ctrl: true, alt: false, shift: false, key });
ui.input(|i| {
i.events.iter().find_map(|e| match e {
Event::Key { key, pressed: true, modifiers, .. } => Some(Shortcut::new(*modifiers, *key)),
Event::Copy => plain(Key::C),
Event::Cut => plain(Key::X),
Event::Paste(_) => plain(Key::V),
_ => None,
})
})
}
thread_local! {
/// The window's own; set once per change of the settings.
static MAP: RefCell<HashMap<Action, Option<Shortcut>>> = RefCell::default();
}
/// Takes the shortcuts of the settings.
pub fn set(s: &Settings) {
MAP.set(ALL.iter().map(|e| (e.action, of(s, e.action))).collect());
}
/// The shortcut in these settings: the user's own, or the usual one. What can't be read counts as the usual one.
pub fn of(s: &Settings, action: Action) -> Option<Shortcut> {
let e = action.entry();
match s.shortcuts.get(e.id) {
Some(own) if own.is_empty() => None,
Some(own) => Shortcut::parse(own).or(usual(action)),
None => usual(action),
}
}
pub fn usual(action: Action) -> Option<Shortcut> {
Shortcut::parse(action.entry().keys)
}
/// None takes it away.
pub fn change(s: &mut Settings, action: Action, keys: Option<Shortcut>) {
let id = action.entry().id.to_string();
if keys == usual(action) {
s.shortcuts.remove(&id);
} else {
s.shortcuts.insert(id, keys.map(Shortcut::label).unwrap_or_default());
}
}
/// The others with the same keys. Both groups are heard at once, so all of them count.
pub fn conflicts(s: &Settings, action: Action) -> Vec<Action> {
let Some(keys) = of(s, action) else { return vec![] };
ALL.iter().map(|e| e.action).filter(|a| *a != action && of(s, *a) == Some(keys)).collect()
}
/// For tooltips and menus; empty without one.
pub fn label(action: Action) -> String {
MAP.with_borrow(|m| m.get(&action).copied().unwrap_or_else(|| usual(action))).map(Shortcut::label).unwrap_or_default()
}
/// Was its shortcut pressed? Nothing else sees it then.
pub fn pressed(ui: &Ui, action: Action) -> bool {
let Some(keys) = MAP.with_borrow(|m| m.get(&action).copied().unwrap_or_else(|| usual(action))) else { return false };
if keys.types() && ui.ctx().text_edit_focused() {
return false;
}
ui.input_mut(|i| {
let before = i.events.len();
i.events.retain(|e| !keys.fits(e));
i.events.len() < before
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn every_action_has_one_line_a_text_and_readable_keys() {
let mut seen = HashSet::new();
for e in ALL {
assert!(seen.insert(e.id), "{}", e.id);
assert_ne!(e.label(), format!("action.{}", e.id));
assert!(e.keys.is_empty() || usual(e.action).is_some_and(|k| k.label() == e.keys && !k.taken()), "{}", e.keys);
assert_eq!(conflicts(&Settings::default(), e.action), [], "{}", e.id);
if e.group == Group::App {
assert!(usual(e.action).is_none_or(|k| !k.types()), "{}", e.id);
}
}
}
#[test]
fn shortcuts_are_read_and_written_the_same() {
for text in ["Ctrl+N", "Alt+Up", "Shift+Del", "F2", "Ctrl+Alt+Shift+Enter", "Ctrl+,", "Space"] {
assert_eq!(Shortcut::parse(text).unwrap().label(), text);
}
for bad in ["", "Ctrl+", "Meta+N", "Ctrl+Nothing"] {
assert_eq!(Shortcut::parse(bad), None, "{bad}");
}
}
#[test]
fn own_shortcuts_replace_the_usual_ones_and_conflicts_are_seen() {
let mut s = Settings::default();
let n = Shortcut::parse("Ctrl+N");
change(&mut s, Action::Find, n);
assert_eq!((of(&s, Action::Find), conflicts(&s, Action::Find)), (n, vec![Action::Add]));
change(&mut s, Action::Add, None);
assert_eq!((of(&s, Action::Add), conflicts(&s, Action::Find)), (None, vec![]));
change(&mut s, Action::Find, usual(Action::Find));
change(&mut s, Action::Add, usual(Action::Add));
assert!(s.shortcuts.is_empty());
s.shortcuts.insert("add".into(), "rubbish".into());
assert_eq!(of(&s, Action::Add), n);
}
}

View file

@ -7,6 +7,7 @@ pub mod fonts;
#[rustfmt::skip]
mod icondata;
pub mod icons;
pub mod keys;
pub mod motion;
pub mod theme;
pub mod tokens;

View file

@ -63,6 +63,17 @@ fn oklch(l: f64, c: f64, h: f64) -> Color32 {
Color32::from_rgb(r, g, b)
}
/// Hue in degrees and colourfulness of a seed.
pub fn hue_of(c: Color32) -> (f64, f64) {
let (_, chroma, hue) = oklch_of(c);
(hue, chroma)
}
/// A seed of this hue and colourfulness.
pub fn seed(hue: f64, chroma: f64) -> Color32 {
oklch(0.62, chroma, hue)
}
fn luminance(c: Color32) -> f64 {
let [r, g, b] = lin(c);
0.2126 * r + 0.7152 * g + 0.0722 * b

View file

@ -32,12 +32,12 @@ pub struct Field<'a> {
clear: bool,
rows: usize,
round: bool,
bare: bool,
width: Option<f32>,
trail: f32,
}
impl<'a> Field<'a> {
/// `label` may be empty when something else names it; `named` then says it to screen readers.
pub fn new(label: &'a str) -> Self {
Field {
label,
@ -52,11 +52,18 @@ impl<'a> Field<'a> {
clear: false,
rows: 1,
round: false,
bare: false,
width: None,
trail: 0.0,
}
}
/// The label is only for screen readers: the row it stands in shows it.
pub fn bare(mut self) -> Self {
self.bare = true;
self
}
pub fn hint(mut self, hint: &'a str) -> Self {
self.hint = hint;
self
@ -133,7 +140,7 @@ impl<'a> Field<'a> {
}
fn label_above(&self, ui: &mut Ui, t: &Theme) {
if !self.label.is_empty() && !self.round {
if !self.label.is_empty() && !self.round && !self.bare {
let ink = match (self.enabled, self.error.is_some()) {
(false, _) => disabled_ink(t),
(_, true) => t.error,
@ -281,6 +288,8 @@ pub struct Number<'a> {
pub step: f64,
pub enabled: bool,
pub width: f32,
/// See `Field::bare`.
pub bare: bool,
}
impl Number<'_> {
@ -292,7 +301,7 @@ impl Number<'_> {
let bad = read(&typed).is_none_or(|v| !self.range.contains(&v));
let why = tr!("number.range", from = write(*self.range.start()), to = write(*self.range.end()));
let side = 2.0 * tokens::size::HIT;
let field = Field { trail: side - space::S, ..Field::new(self.label) }.unit(self.unit).enabled(self.enabled).width(self.width);
let field = Field { trail: side - space::S, bare: self.bare, ..Field::new(self.label) }.unit(self.unit).enabled(self.enabled).width(self.width);
let field = field.error(bad.then_some(why.as_str()));
let top = ui.cursor().top();
let r = field.show(ui, t, &mut typed);
@ -354,17 +363,19 @@ pub struct Combo<'a> {
pub busy: bool,
pub error: Option<&'a str>,
pub width: f32,
/// See `Field::bare`.
pub bare: bool,
}
impl<'a> Combo<'a> {
pub fn new(label: &'a str, options: &'a [String], width: f32) -> Self {
Combo { label, options, enabled: true, busy: false, error: None, width }
Combo { label, options, enabled: true, busy: false, error: None, width, bare: false }
}
/// True when the choice changed.
pub fn show(self, ui: &mut Ui, t: &Theme, chosen: &mut usize) -> bool {
let width = self.width.min(ui.available_width());
let look = Field { error: self.error, help: self.error, enabled: self.enabled, ..Field::new(self.label) };
let look = Field { error: self.error, help: self.error, enabled: self.enabled, bare: self.bare, ..Field::new(self.label) };
ui.allocate_ui_with_layout(vec2(width, 0.0), Layout::top_down(Align::Min), |ui| {
ui.spacing_mut().item_spacing.y = space::XS;
look.label_above(ui, t);

View file

@ -217,7 +217,7 @@ fn fields(ui: &mut Ui, t: &Theme, d: &mut Demo) {
});
ui.horizontal_top(|ui| {
Field::new("Password").icon("key").password().width(w).show(ui, t, &mut d.password);
Number { label: "Speed limit", unit: "kB/s", range: 0.0..=1000.0, step: 50.0, enabled: true, width: w }.show(ui, t, &mut d.number);
Number { label: "Speed limit", unit: "kB/s", range: 0.0..=1000.0, step: 50.0, enabled: true, width: w, bare: false }.show(ui, t, &mut d.number);
});
ui.horizontal_top(|ui| {
let options = ["Main queue", "Night", "A queue with a name that is much too long for this box"].map(String::from);

View file

@ -18,7 +18,7 @@ use std::time::Duration;
pub struct Item<A> {
text: String,
icon: &'static str,
keys: &'static str,
keys: String,
enabled: bool,
checked: Option<bool>,
danger: bool,
@ -34,7 +34,7 @@ enum What<A> {
impl<A> Item<A> {
fn with(text: impl Into<String>, what: What<A>) -> Self {
Item { text: text.into(), icon: "", keys: "", enabled: true, checked: None, danger: false, what }
Item { text: text.into(), icon: "", keys: String::new(), enabled: true, checked: None, danger: false, what }
}
pub fn new(text: impl Into<String>, action: A) -> Self {
@ -54,8 +54,8 @@ impl<A> Item<A> {
self
}
pub fn keys(mut self, keys: &'static str) -> Self {
self.keys = keys;
pub fn keys(mut self, keys: impl Into<String>) -> Self {
self.keys = keys.into();
self
}
@ -198,7 +198,7 @@ fn size<A>(ctx: &Context, items: &[Item<A>], min_width: f32) -> Vec2 {
let p = ctx.debug_painter();
let lead = if has_lead(items) { LEAD } else { 0.0 };
let wide = items.iter().map(|i| {
let end = match (&i.what, i.keys) {
let end = match (&i.what, i.keys.as_str()) {
(What::Sub(_), _) => tokens::icon::M + space::S,
(_, "") => 0.0,
(_, keys) => text_width(&p, keys, fonts::ui(text::LABEL)) + space::XL,
@ -493,7 +493,7 @@ fn row<A>(ui: &mut Ui, t: &Theme, o: &Open, depth: usize, i: usize, item: &Item<
chevron(p, pos2(end - tokens::icon::S / 2.0, mid), tokens::icon::S, RIGHT, faint);
end -= tokens::icon::M + space::S;
} else if !item.keys.is_empty() {
let keys = line(p, item.keys, fonts::ui(text::LABEL), faint, rect.width());
let keys = line(p, &item.keys, fonts::ui(text::LABEL), faint, rect.width());
end -= keys.size().x;
left(p, pos2(end, mid), keys);
end -= space::M;

View file

@ -6,6 +6,7 @@ use super::list::row::Column;
use super::list::{Act, List, Order};
use crate::bridge::Lists;
use crate::fonts;
use crate::keys::{self, Action};
use crate::theme::Theme;
use crate::tokens::{self, icon, size, space, text};
use crate::ui::menu::{self, Item};
@ -114,7 +115,7 @@ pub fn top(ui: &mut Ui, t: &Theme, rect: Rect, list: &mut List, focus_search: &m
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() {
if button.kind(Kind::Filled).keys(&keys::label(Action::Add)).show(ui, t).clicked() {
out = Some(Order::Add);
}
ui.add_space(space::XS);
@ -239,14 +240,14 @@ pub fn selected(ui: &Ui, t: &Theme, rect: Rect, list: &mut List) -> Option<Order
act = Some(what);
}
};
button("play_arrow", &tr!("act.resume"), "", Act::Resume, false);
button("pause", &tr!("act.pause"), "Space", Act::Pause, false);
button("play_arrow", &tr!("act.resume"), &keys::label(Action::Resume), Act::Resume, false);
button("pause", &tr!("act.pause"), &keys::label(Action::Toggle), Act::Pause, false);
if count <= 1 {
button("folder_open", &tr!("act.show"), "", Act::Show, false);
button("folder_open", &tr!("act.show"), &keys::label(Action::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);
button("content_copy", &tr!("act.copy"), &keys::label(Action::Copy), Act::Copy, false);
button("close", &tr!("act.remove"), &keys::label(Action::Remove), Act::Remove(Files::Keep), false);
button("delete", &tr!("act.delete"), &keys::label(Action::Bin), Act::Remove(Files::Bin), true);
if Button::icon("cancel", &tr!("bar.clear")).keys("Esc").show(ui, t).clicked() {
clear = true;
}

View file

@ -0,0 +1,139 @@
//! The first start: where files go, which colours, and what the browser's port is for. Three screens, each may be left.
use super::settings::look;
use super::settings::rows::folder_error;
use crate::bridge::download_folder;
use crate::desktop::Desktop;
use crate::icons;
use crate::fonts;
use crate::motion::spring;
use crate::theme::{Theme, mix};
use crate::tokens::spring::{DEFAULT, EFFECT};
use crate::tokens::{icon, radius, size, space, text};
use crate::ui::field::Field;
use crate::ui::widgets::{Button, Choice, Kind, cr, left, line};
use eframe::egui::{Align, Key, Layout, Modifiers, Rect, ScrollArea, Sense, Ui, UiBuilder, pos2, vec2};
use medlar_core::settings::Settings;
use medlar_core::tr;
#[derive(Default)]
pub struct FirstRun {
step: usize,
/// None until it was written in.
folder: Option<String>,
look: look::State,
}
const STEPS: usize = 3;
const WIDTH: f32 = 520.0;
const TALL: f32 = 648.0;
impl FirstRun {
/// Begins at a later screen.
pub fn at(step: usize) -> FirstRun {
FirstRun { step, ..FirstRun::default() }
}
/// Draws the screen. True when it is over.
pub fn show(&mut self, ui: &mut Ui, t: &Theme, s: &mut Settings, desktop: Desktop) -> bool {
let window = ui.ctx().content_rect();
ui.painter().rect_filled(window, 0.0, t.surface);
let width = WIDTH.min(window.width() - 2.0 * space::L);
let tall = window.height() >= TALL;
let top = if tall { window.top() + (window.height() - TALL) / 2.0 + space::L } else { window.top() + space::M };
let foot = Rect::from_min_size(
pos2((window.center().x - width / 2.0).round(), if tall { top + TALL - 2.0 * space::L - size::CONTROL } else { window.bottom() - space::M - size::CONTROL }.round()),
vec2(width, size::CONTROL),
);
let room = Rect::from_min_max(pos2(foot.left(), top.round()), pos2(foot.right(), foot.top() - space::M));
let bad = self.folder.as_deref().and_then(folder_error);
let mut child = ui.new_child(UiBuilder::new().max_rect(room.expand2(vec2(space::XS, 0.0))).id_salt("first run"));
ScrollArea::vertical().auto_shrink(false).id_salt(self.step).content_margin(space::XS).show(&mut child, |ui| {
ui.spacing_mut().item_spacing = vec2(space::S, 0.0);
if tall {
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), icon::HERO), Sense::hover());
icons::paint_app(ui.painter(), pos2(r.left() + icon::HERO / 2.0, r.center().y), icon::HERO);
ui.add_space(space::L);
}
let (head, body) = match self.step {
0 => (tr!("first.folder"), tr!("first.folder_body")),
1 => (tr!("first.colours"), tr!("first.colours_body")),
_ => (tr!("first.browser"), tr!("first.browser_body", port = s.connector_port)),
};
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), text::HEADLINE + space::S), Sense::hover());
left(ui.painter(), r.left_center(), line(ui.painter(), &head, fonts::semi(text::HEADLINE), t.on_surface, r.width()));
ui.add_space(space::XS);
let words = ui.painter().layout(body, fonts::ui(text::BODY), t.on_variant, ui.available_width());
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), words.size().y), Sense::hover());
ui.painter().galley(r.min, words, t.on_variant);
ui.add_space(space::L);
match self.step {
0 => {
let mut folder = self.folder.take().unwrap_or_else(|| download_folder(s).display().to_string());
let r = Field::new(&tr!("set.folder")).icon("folder").error(bad.as_deref()).show(ui, t, &mut folder);
if r.changed() && folder_error(&folder).is_none() {
s.download_folder = folder.trim().into();
}
self.folder = Some(folder);
}
1 => {
look::sources(ui, t, s, desktop.seed);
ui.add_space(space::S);
if s.desktop_colors == Some(false) || desktop.seed.is_none() {
ui.spacing_mut().item_spacing.y = space::S;
look::picker(&mut self.look, t, s, ui);
}
}
_ => {
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), size::LARGE + space::S), Sense::hover());
ui.painter().rect_filled(r, cr(radius::L), t.low);
let name = tr!("set.connector");
let wide = r.width() - size::SWITCH[0] - 3.0 * space::L;
left(ui.painter(), pos2(r.left() + space::L, r.center().y), line(ui.painter(), &name, fonts::med(text::BODY), t.on_surface, wide));
let at = Rect::from_center_size(pos2(r.right() - space::L - size::SWITCH[0] / 2.0, r.center().y), size::SWITCH.into());
let mut child = ui.new_child(UiBuilder::new().max_rect(at));
Choice::new(&name).switch(&mut child, t, &mut s.connector);
}
}
});
let (mut next, mut over) = (false, false);
let mut row = ui.new_child(UiBuilder::new().max_rect(foot).layout(Layout::right_to_left(Align::Center)).id_salt("first foot"));
row.spacing_mut().item_spacing.x = space::S;
let words = if self.step + 1 == STEPS { tr!("first.done") } else { tr!("first.next") };
next |= Button::new(&words).kind(Kind::Filled).enabled(bad.is_none()).show(&mut row, t).clicked();
let back = if self.step > 0 { tr!("first.back") } else { tr!("first.skip") };
if Button::new(&back).kind(Kind::Text).show(&mut row, t).clicked() {
if self.step > 0 {
self.step -= 1;
} else {
over = true;
}
}
if self.step > 0 && self.step + 1 < STEPS && Button::new(&tr!("first.skip")).kind(Kind::Text).show(&mut row, t).clicked() {
over = true;
}
self.dots(ui, t, foot);
next |= bad.is_none() && ui.memory(|m| m.focused().is_none()) && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter));
if next {
self.step += 1;
over |= self.step == STEPS;
}
if over {
// D-012: the desktop's, when it has any and nothing else was said.
s.desktop_colors.get_or_insert(desktop.seed.is_some());
}
over
}
/// Which screen it is.
fn dots(&self, ui: &Ui, t: &Theme, foot: Rect) {
let p = ui.painter();
let at = |i: f32| pos2(foot.left() + space::XS + i * space::XL, foot.center().y);
for i in 0..STEPS {
let on = spring(("first dot", i), f32::from(i <= self.step), EFFECT);
p.circle_filled(at(i as f32), space::XS, mix(t.outline_variant, t.primary, on));
}
let x = spring("first mark", self.step as f32, DEFAULT);
p.rect_filled(Rect::from_center_size(at(x), vec2(space::L, space::S)), cr(space::XS), t.primary);
}
}

View file

@ -7,6 +7,7 @@ pub mod row;
use crate::bridge::Lists;
use crate::fonts;
use crate::keys::{self, Action};
use crate::motion;
use crate::theme::{Theme, alpha};
use crate::tokens::{icon, radius, size, space, text};
@ -54,6 +55,10 @@ pub enum Act {
EditName,
/// The network's own sign-in page.
Portal,
/// Ask for the login of its site.
SignIn,
/// Medlar's own network settings.
Network,
}
/// What the user wants, for the one who can do it.
@ -69,7 +74,9 @@ pub enum Order {
pub fn act_of_fix(fix: Fix) -> Act {
match fix {
Fix::TryAgain | Fix::Resume | Fix::CheckNetwork | Fix::SignIn => Act::Resume,
Fix::TryAgain | Fix::Resume => Act::Resume,
Fix::SignIn => Act::SignIn,
Fix::CheckNetwork => Act::Network,
Fix::Restart | Fix::Choose => Act::Redownload,
Fix::NewLink | Fix::EditLink => Act::EditLink,
Fix::FreeSpace => Act::Show,
@ -528,19 +535,19 @@ impl List {
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"),
Item::new(tr!("act.open"), Act::Open).icon("open_in_new").keys(keys::label(Action::OpenOrRun)).enabled(one && first.state() == State::Done),
Item::new(tr!("act.show"), Act::Show).icon("folder_open").keys(keys::label(Action::Show)).enabled(one),
Item::new(tr!("act.copy"), Act::Copy).icon("content_copy").keys(keys::label(Action::Copy)),
];
if one && first.task.source_page.is_some() {
items.push(Item::new(tr!("act.page"), Act::OpenPage).icon("public"));
items.push(Item::new(tr!("act.page"), Act::OpenPage).icon("public").keys(keys::label(Action::Page)));
}
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::new(tr!("act.start"), Act::Start).icon("bolt").keys(keys::label(Action::Start)).enabled(any(&|s| !begun(s) && !ended(s))));
items.push(Item::new(tr!("act.resume"), Act::Resume).icon("play_arrow").keys(keys::label(Action::Resume)).enabled(any(&|s| matches!(s, State::Paused | State::Failed | State::Waiting))));
items.push(Item::new(tr!("act.pause"), Act::Pause).icon("pause").keys(keys::label(Action::Pause)).enabled(any(&|s| begun(s) || matches!(s, State::Queued | State::Waiting))));
items.push(Item::new(tr!("act.stop"), Act::Stop).icon("low_priority").keys(keys::label(Action::Stop)).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))
@ -559,14 +566,14 @@ impl List {
}
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.rename"), Act::EditName).icon("edit").keys(keys::label(Action::Rename)));
items.push(Item::new(tr!("act.move"), Act::EditFolder).icon("folder").keys(keys::label(Action::Folder)));
items.push(Item::new(tr!("fix.edit_link"), Act::EditLink).icon("link").keys(keys::label(Action::Link)).enabled(!ended(first.state())));
}
items.push(Item::new(tr!("act.redownload"), Act::Redownload).icon("replay"));
items.push(Item::new(tr!("act.redownload"), Act::Redownload).icon("replay").keys(keys::label(Action::Redownload)));
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.push(Item::new(tr!("act.remove"), Act::Remove(Files::Keep)).icon("close").keys(keys::label(Action::Remove)));
items.push(Item::new(tr!("act.delete"), Act::Remove(Files::Bin)).icon("delete").keys(keys::label(Action::Bin)).danger());
items
}
@ -578,34 +585,21 @@ impl List {
}
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)),
_ => {}
for e in ui.input(|i| i.events.clone()) {
if let eframe::egui::Event::Paste(text) = e {
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));
// Before the arrows, which some of them have.
for e in keys::ALL.iter().filter(|e| e.group == keys::Group::List) {
if (e.action == Action::SelectAll || !self.selected.is_empty()) && keys::pressed(ui, e.action) {
orders.extend(self.perform(ui, e.action));
}
}
let page = ((self.seen.end - self.seen.start) / layout::COMPACT) as isize * self.layout.columns as isize;
@ -628,40 +622,67 @@ impl List {
{
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;
}
/// Does an action of the list by name. The order is for the main screen, which can do it.
pub fn perform(&mut self, ui: &Ui, action: Action) -> Option<Order> {
if action == Action::SelectAll {
self.selected = self.listing.rows.iter().map(|v| v.id()).collect();
return None;
}
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 chosen = self.chosen();
let first = self.listing.rows.iter().find(|v| self.selected.contains(&v.id())).cloned()?;
let one = chosen.len() == 1;
let act = match action {
Action::OpenOrRun if first.state() == State::Done => Act::Open,
Action::OpenOrRun => row::quick(first.state()).0,
Action::Toggle => {
// 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()));
if any { Act::Pause } else { Act::Resume }
}
Action::Show if one => Act::Show,
Action::Copy => Act::Copy,
Action::Page if one && first.task.source_page.is_some() => Act::OpenPage,
Action::Start => Act::Start,
Action::Resume => Act::Resume,
Action::Pause => Act::Pause,
Action::Stop => Act::Stop,
Action::Redownload => Act::Redownload,
Action::Rename if one => Act::EditName,
Action::Folder if one => Act::EditFolder,
Action::Link if one && !matches!(first.state(), State::Done | State::Gone) => Act::EditLink,
Action::Remove => Act::Remove(Files::Keep),
Action::Bin => Act::Remove(Files::Bin),
Action::Up | Action::Down => {
self.hush(ui);
return self.nudge(if action == Action::Up { -1 } else { 1 });
}
_ => return None,
};
// The next row takes the keyboard when this one goes.
self.hush(ui);
if matches!(act, Act::Remove(_)) {
let last = self.row_of(*chosen.last()?).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();
}
self.cursor = next.map(|v| v.id());
self.anchor = self.cursor;
self.selected = self.cursor.into_iter().collect();
}
Some(Order::Do(act, chosen))
}
/// Selects one download and scrolls to it.
pub fn go_to(&mut self, id: TaskId) {
self.query.filter = Filter::default();
self.selected = HashSet::from([id]);
(self.cursor, self.anchor, self.reveal) = (Some(id), Some(id), Some(id));
}
pub fn dragging(&self) -> bool {
self.drag.is_some()
}
fn step(&mut self, step: isize, m: Modifiers) {

View file

@ -177,12 +177,7 @@ fn fix_button(v: &TaskView) -> Option<(Fix, String)> {
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))
Some((fix, fix.label()))
}
fn fix_icon(fix: Fix) -> &'static str {
@ -191,6 +186,8 @@ fn fix_icon(fix: Fix) -> &'static str {
Act::EditFolder => "folder",
Act::Show => "folder_open",
Act::Portal => "open_in_new",
Act::SignIn => "key",
Act::Network => "settings",
Act::Redownload => "replay",
_ => "refresh",
}

View file

@ -5,6 +5,7 @@ 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::keys::{Action, Group as Where};
use crate::motion::spring;
use crate::theme::Theme;
use crate::tokens::spring::DEFAULT;
@ -48,6 +49,19 @@ impl Default for Prefs {
#[derive(Clone)]
pub enum Reply {
Undo(Vec<TaskId>),
/// The settings from before.
Settings(Box<Settings>),
/// Open this folder.
Open(PathBuf),
}
/// What only the whole window can do.
#[derive(Clone, PartialEq, Debug)]
pub enum Wish {
Settings,
Network,
/// The login of this link's site, for the downloads that wait for it.
SignIn(String, Vec<TaskId>),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@ -77,6 +91,11 @@ pub struct Main {
speeds: bar::Speeds,
ask: Option<Ask>,
focus_search: bool,
/// Orders from elsewhere, done in the next frame.
asked: Vec<Order>,
pub wish: Option<Wish>,
/// A message's button that is the window's business.
pub answer: Option<Reply>,
}
impl Default for Main {
@ -91,6 +110,9 @@ impl Default for Main {
speeds: bar::Speeds::default(),
ask: None,
focus_search: false,
asked: vec![],
wish: None,
answer: None,
}
}
}
@ -148,9 +170,6 @@ impl Main {
/// 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));
@ -164,13 +183,60 @@ impl Main {
}
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.messages(ui, t, window.bottom() - self.floor());
self.asking(ui, t, settings);
self.keep_prefs();
}
/// Draws the messages, over any screen.
pub fn messages(&mut self, ui: &Ui, t: &Theme, bottom: f32) {
for why in self.bridge.take_errors() {
self.toasts.error(why, None);
}
match self.toasts.show(ui.ctx(), t, bottom) {
Some(Reply::Undo(ids)) => ids.into_iter().for_each(|id| self.bridge.send(Command::Restore(id))),
Some(Reply::Open(folder)) => (self.outside)(&folder.to_string_lossy()),
other => self.answer = other,
}
}
/// Does an action by name; what this screen has no part in comes back.
pub fn run(&mut self, ui: &Ui, action: Action) -> Option<Action> {
match action {
Action::Add => self.asked.push(Order::Add),
Action::Find => self.asked.push(Order::Find),
Action::Rail => self.toggle_rail(ui.ctx().content_rect().width()),
Action::View => self.list.form = if self.list.form == Form::Cards { Form::Compact } else { Form::Cards },
Action::ResumeAll | Action::PauseAll => {
let Data::Ready(shot, _) = self.bridge.data() else { return None };
let resume = action == Action::ResumeAll;
for v in shot.iter() {
match v.state() {
State::Paused if resume => self.bridge.send(Command::Resume(v.id())),
State::Running | State::Checking | State::Queued | State::Waiting if !resume => self.bridge.send(Command::Pause(v.id())),
_ => {}
}
}
}
a if a.entry().group == Where::List => {
let order = self.list.perform(ui, a);
self.asked.extend(order);
}
other => return Some(other),
}
motion::keep_alive();
None
}
fn toggle_rail(&mut self, width: f32) {
if width < RAIL_FITS {
self.toasts.info("menu", tr!("rail.no_room"));
} else {
self.prefs.rail = Some(!self.prefs.rail.unwrap_or(width >= RAIL_OPENS));
self.list_prefs_changed();
}
}
/// 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 }
@ -191,13 +257,10 @@ impl Main {
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();
}
match clicked {
Some(rail::Click::Menu) => self.toggle_rail(window.width()),
Some(rail::Click::Settings) => self.wish = Some(Wish::Settings),
None => {}
}
let pad = if window.width() < RAIL_FITS { space::M } else { space::XL };
let mut body = rest.shrink2(vec2(pad, space::L));
@ -207,7 +270,7 @@ impl Main {
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![];
let mut orders = std::mem::take(&mut self.asked);
self.list.keys(ui, &mut orders);
orders.into_iter().for_each(|o| self.order(ui, shot, o));
return self.dropped(ui);
@ -216,7 +279,7 @@ impl Main {
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![];
let mut orders = std::mem::take(&mut self.asked);
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) {
@ -433,6 +496,8 @@ impl Main {
}
// A plain page is what such networks put their own in place of.
Act::Portal => (self.outside)(&format!("http://{}/", first.server)),
Act::SignIn => self.wish = Some(Wish::SignIn(first.task.url.clone(), views.iter().filter(|v| v.server == first.server).map(|v| v.id()).collect())),
Act::Network => self.wish = Some(Wish::Network),
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()),

View file

@ -1,6 +1,9 @@
//! The screens.
pub mod bar;
pub mod firstrun;
pub mod list;
pub mod main;
pub mod palette;
pub mod rail;
pub mod settings;

View file

@ -0,0 +1,262 @@
//! The command palette: one box over actions, downloads and settings. It is there at once, without motion.
use super::list::model::title;
use super::list::row::state_label;
use super::settings::rows::{self, Page};
use crate::keys::{self, Action, Group};
use crate::theme::{Theme, alpha};
use crate::tokens::{elevation, icon, radius, size, space, state, text};
use crate::ui::field;
use crate::ui::widgets::{cr, left, line, text_width};
use crate::{fonts, icons};
use eframe::egui::accesskit::Role;
use eframe::egui::{Align, Area, Color32, Id, Key, LayerId, Modifiers, Order, Rect, ScrollArea, Sense, Ui, UiBuilder, WidgetInfo, pos2, vec2};
use medlar_core::model::TaskId;
use medlar_core::snapshot::Snapshot;
use medlar_core::tr;
#[derive(Clone, PartialEq, Debug)]
pub enum Pick {
Action(Action),
Download(TaskId),
Page(Page),
/// A setting, by its id.
Setting(&'static str, Page),
}
struct Entry {
icon: &'static str,
label: String,
detail: String,
keys: String,
pick: Pick,
score: i32,
}
#[derive(Default)]
pub struct Palette {
open: bool,
query: String,
/// What the rows were made from.
made: Option<(String, u64, bool)>,
rows: Vec<Entry>,
chosen: usize,
/// The keyboard chose: the row must be seen.
reveal: bool,
}
const WIDTH: f32 = 600.0;
const ROW: f32 = size::CONTROL + space::XS;
/// What is offered at most.
const MOST: usize = 60;
/// How well `query` fits: its letters in order, better at the start of words and in runs. None when one is missing.
pub fn fuzzy(query: &str, text: &str) -> Option<i32> {
let mut score = 0;
let mut run = 0;
let mut start = true;
let mut letters = text.chars().flat_map(char::to_lowercase);
let mut passed = 0;
for q in query.chars().filter(|c| !c.is_whitespace()).flat_map(char::to_lowercase) {
loop {
let c = letters.next()?;
passed += 1;
let begins = std::mem::replace(&mut start, !c.is_alphanumeric());
if c == q {
run += 1;
score += 2 + 2 * run + if begins { 10 } else { 0 };
break;
}
run = 0;
score -= 1;
}
}
Some(score - (passed + letters.count() as i32) / 8)
}
impl Palette {
pub fn toggle(&mut self) {
*self = Palette { open: !self.open, ..Palette::default() };
}
pub fn is_open(&self) -> bool {
self.open
}
/// `some`: are there selected downloads?
fn make(&mut self, shot: Option<&Snapshot>, some: bool) {
let now = (self.query.clone(), shot.map_or(0, |s| s.rev), some);
if self.made.as_ref() == Some(&now) {
return;
}
if self.made.as_ref().is_none_or(|m| m.0 != now.0) {
self.chosen = 0;
self.reveal = true;
}
let q = self.query.trim();
let mut rows = vec![];
for e in keys::ALL.iter().filter(|e| e.action != Action::Palette && (e.group == Group::App || some || e.action == Action::SelectAll)) {
let label = e.label();
if let Some(score) = fuzzy(q, &label) {
rows.push(Entry { icon: e.icon, label, detail: String::new(), keys: keys::label(e.action), pick: Pick::Action(e.action), score: score + 4 });
}
}
for p in Page::shown() {
let label = tr!("palette.page", page = p.label());
if let Some(score) = fuzzy(q, &label) {
rows.push(Entry { icon: p.icon(), label, detail: String::new(), keys: String::new(), pick: Pick::Page(p), score });
}
}
// Settings and downloads are too many to offer unasked.
if !q.is_empty() {
for r in rows::all().filter(|r| !matches!(r.kind, rows::Kind::Shortcut(_))) {
let label = r.name();
let words = r.words();
let score = fuzzy(q, &label).or_else(|| words.contains(&q.to_lowercase()).then_some(0));
if let Some(score) = score {
rows.push(Entry { icon: r.page.icon(), label, detail: r.page.label(), keys: String::new(), pick: Pick::Setting(r.id, r.page), score });
}
}
for v in shot.into_iter().flat_map(|s| s.iter()) {
let label = title(v);
if let Some(score) = fuzzy(q, label) {
let detail = tr!("list.dot", a = state_label(v.state()), b = v.server);
rows.push(Entry { icon: "description", label: label.to_string(), detail, keys: String::new(), pick: Pick::Download(v.id()), score });
}
}
rows.sort_by_key(|r| std::cmp::Reverse(r.score));
}
rows.truncate(MOST);
self.rows = rows;
self.chosen = self.chosen.min(self.rows.len().saturating_sub(1));
self.made = Some(now);
}
/// Draws it, if it is open. What was picked closes it.
pub fn show(&mut self, ui: &Ui, t: &Theme, shot: Option<&Snapshot>, some: bool) -> Option<Pick> {
if !self.open {
return None;
}
self.make(shot, some);
let ctx = ui.ctx().clone();
let id = Id::unique("palette");
ctx.memory_mut(|m| m.set_modal_layer(LayerId::new(Order::Middle, id)));
let window = ctx.content_rect();
let mut picked = None;
let mut close = ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape));
let n = self.rows.len();
for (key, by) in [(Key::ArrowDown, 1), (Key::ArrowUp, n.saturating_sub(1))] {
if n > 0 && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, key)) {
self.chosen = (self.chosen + by) % n;
self.reveal = true;
}
}
if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) {
picked = self.rows.get(self.chosen).map(|r| r.pick.clone());
}
let name = keys::Action::Palette.entry().label();
let area = Area::new(id).order(Order::Middle).fixed_pos(window.min).constrain(false).fade_in(false).role(Role::Dialog).accessible_name(name.clone());
area.show(&ctx, |ui| {
let scrim = ui.allocate_rect(window, Sense::CLICK | Sense::DRAG);
ui.painter().rect_filled(window, 0.0, Color32::from_black_alpha((255.0 * elevation::SCRIM) as u8));
close |= scrim.clicked();
let width = WIDTH.min(window.width() - 2.0 * space::L);
let top = (window.height() * 0.12).max(space::L);
let head = size::CONTROL + 2.0 * space::S;
let rows = if n == 0 { ROW } else { n as f32 * ROW };
let room = (window.height() - top - space::L - head - space::S).max(ROW);
let body = rows.min(room).min(10.0 * ROW);
let rect = Rect::from_min_size(pos2((window.center().x - width / 2.0).round(), top.round()), vec2(width, head + body + space::S));
ui.interact(rect, id.with("ground"), Sense::CLICK | Sense::DRAG);
ui.painter().add(elevation::floating(t.dark).as_shape(rect, cr(radius::XL)));
ui.painter().rect_filled(rect, cr(radius::XL), t.container);
let box_ = Rect::from_min_size(rect.min + vec2(space::S, space::S), vec2(width - 2.0 * space::S, size::CONTROL));
let mut child = ui.new_child(UiBuilder::new().max_rect(box_).id_salt("query"));
let r = field::search(&mut child, t, &tr!("palette.hint"), &mut self.query, box_.width());
r.request_focus();
if r.changed() {
ctx.request_repaint();
}
let list = Rect::from_min_max(pos2(rect.left() + space::S, rect.top() + head), pos2(rect.right() - space::S, rect.top() + head + body));
if n == 0 {
left(ui.painter(), list.left_center() + vec2(space::M, 0.0), line(ui.painter(), &tr!("palette.none"), fonts::ui(text::BODY), t.on_variant, list.width()));
return;
}
let mut child = ui.new_child(UiBuilder::new().max_rect(list).id_salt("rows"));
let moved = ctx.input(|i| i.pointer.delta().length_sq() > 0.0);
ScrollArea::vertical().auto_shrink(false).max_height(body).show_viewport(&mut child, |ui, _| {
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
for (i, e) in self.rows.iter().enumerate() {
let (r, a) = ui.allocate_exact_size(vec2(ui.available_width(), ROW), Sense::CLICK);
let on = i == self.chosen;
a.widget_info(|| WidgetInfo::selected(Role::ListBoxOption, true, on, &e.label));
if on && self.reveal {
ui.scroll_to_rect_animation(r, None::<Align>, eframe::egui::style::ScrollAnimation::none());
}
if moved && a.hovered() {
self.chosen = i;
}
if a.clicked() {
picked = Some(e.pick.clone());
}
if !ui.is_rect_visible(r) {
continue;
}
draw(ui, t, r, e, on, a.is_pointer_button_down_on());
}
});
self.reveal = false;
});
if self.made.as_ref().is_some_and(|m| m.0 != self.query) {
ctx.request_repaint();
}
if picked.is_some() || close {
self.open = false;
ctx.request_repaint();
}
picked
}
}
fn draw(ui: &Ui, t: &Theme, rect: Rect, e: &Entry, on: bool, down: bool) {
let p = ui.painter();
let inner = rect.shrink2(vec2(0.0, 2.0));
let corner = cr(radius::inner(radius::XL, space::S));
if on {
p.rect_filled(inner, corner, t.secondary_container);
if down {
p.rect_filled(inner, corner, alpha(t.on_surface, state::PRESS));
}
}
let (ink, faint) = if on { (t.on_secondary_container, t.on_secondary_container) } else { (t.on_surface, t.on_variant) };
let x = rect.left() + space::M;
icons::paint(p, pos2(x + icon::M / 2.0, rect.center().y), icon::M, e.icon, faint);
let x = x + icon::M + space::M;
let mut end = rect.right() - space::M;
if !e.keys.is_empty() {
let w = text_width(p, &e.keys, fonts::med(text::LABEL));
left(p, pos2(end - w, rect.center().y), line(p, &e.keys, fonts::med(text::LABEL), faint, w + 1.0));
end -= w + space::M;
}
if !e.detail.is_empty() {
let detail = line(p, &e.detail, fonts::ui(text::LABEL), faint, (end - x) * 0.4);
end -= detail.size().x;
left(p, pos2(end, rect.center().y), detail);
end -= space::M;
}
left(p, pos2(x, rect.center().y), line(p, &e.label, fonts::ui(text::BODY), ink, end - x));
}
#[cfg(test)]
mod tests {
use super::fuzzy;
#[test]
fn letters_count_in_order_and_word_starts_first() {
assert_eq!(fuzzy("pq", "Queue"), None);
assert!(fuzzy("", "anything").is_some());
assert!(fuzzy("pa", "Pause all").unwrap() > fuzzy("pa", "Keep all").unwrap());
assert!(fuzzy("ra", "Resume all").unwrap() > fuzzy("ra", "Gradual").unwrap());
assert!(fuzzy("pause all", "PAUSE ALL").is_some());
}
}

View file

@ -4,6 +4,7 @@ use super::list::model::{Counts, Filter, Status, kind_label, queue_name};
use crate::bridge::Lists;
use crate::fonts;
use crate::icons;
use crate::keys::{self, Action};
use crate::motion::spring;
use crate::theme::{Theme, alpha, hex, mix};
use crate::tokens::spring::{DEFAULT, EFFECT};
@ -11,7 +12,7 @@ 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 eframe::egui::{Align2, Color32, Rect, ScrollArea, Sense, Ui, UiBuilder, Vec2, WidgetInfo, pos2, vec2};
use medlar_core::tr;
pub const NARROW: f32 = 64.0;
@ -34,8 +35,15 @@ struct Entry {
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 {
/// What was clicked besides the entries.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Click {
Menu,
Settings,
}
/// Draws the rail in `rect`, which is between `NARROW` and `WIDE`.
pub fn show(ui: &mut Ui, t: &Theme, rect: Rect, open: bool, filter: &mut Filter, counts: &Counts, lists: &Lists) -> Option<Click> {
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;
@ -43,12 +51,20 @@ pub fn show(ui: &mut Ui, t: &Theme, rect: Rect, open: bool, filter: &mut Filter,
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();
let mut clicked = Button::icon(if open { "menu_open" } else { "menu" }, &name).keys(&keys::label(Action::Rail)).show(&mut button, t).clicked().then_some(Click::Menu);
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 = Rect::from_min_max(rect.min + vec2(0.0, menu.bottom() - rect.top() + space::S), rect.max);
body.max.y -= ROW + 2.0 * space::S;
let foot = Rect::from_min_max(pos2(rect.left(), body.bottom() + space::S), rect.max);
ui.painter().hline(rect.left() + space::M..=rect.right() - space::M, body.bottom(), (size::HAIRLINE, t.outline_variant));
let mut last = ui.new_child(UiBuilder::new().max_rect(foot).id_salt("foot"));
let entry = Entry { mark: Mark::Icon("settings"), name: tr!("action.settings"), count: 0, on: false };
if section(&mut last, t, rect, " ", &[entry], false).is_some() {
clicked = Some(Click::Settings);
}
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);
@ -96,18 +112,18 @@ fn section(ui: &mut Ui, t: &Theme, rail: Rect, title: &str, entries: &[Entry], s
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() {
if !title.trim().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);
left(p, 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));
let r = Rect::from_min_size(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;
@ -150,10 +166,11 @@ fn section(ui: &mut Ui, t: &Theme, rail: Rect, title: &str, entries: &[Entry], s
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);
left(p, pos2(x, rect.center().y), name);
}
if open < 0.5 {
tip(&r, t, &tr!("rail.tip", name = e.name, n = e.count), "");
let words = if e.count > 0 || title != " " { tr!("rail.tip", name = e.name, n = e.count) } else { e.name.clone() };
tip(&r, t, &words, "");
}
if r.clicked() {
clicked = Some(i);

View file

@ -0,0 +1,156 @@
//! Settings saved to a file and read back.
use super::{Cx, View, plate};
use crate::bridge::download_folder;
use crate::tokens::{icon, size, space, text};
use crate::ui::field::Field;
use crate::ui::widgets::{Button, Kind, left, line};
use crate::views::main::Reply;
use crate::{fonts, icons};
use eframe::egui::{Sense, Ui, pos2, vec2};
use medlar_core::settings::Settings;
use medlar_core::tr;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
#[derive(Default)]
pub struct State {
/// The newest ones, once looked for.
found: Option<Vec<PathBuf>>,
file: String,
error: Option<String>,
}
/// More than this are not listed.
const MOST: usize = 5;
/// Nothing larger is a backup.
const LARGEST: u64 = 4 << 20;
const ROW: f32 = 52.0;
/// Writes the settings into `folder` under a new name.
pub fn write(s: &Settings, folder: &Path) -> io::Result<PathBuf> {
fs::create_dir_all(folder)?;
let stamp = chrono::Local::now().format("%Y-%m-%d-%H%M%S");
for n in 0..100 {
let more = if n == 0 { String::new() } else { format!("-{n}") };
let path = folder.join(format!("medlar-settings-{stamp}{more}.json"));
if !path.exists() {
s.save(&path)?;
return Ok(path);
}
}
Err(io::ErrorKind::AlreadyExists.into())
}
/// Reads a backup without touching it. The second value names what could not be read and is at its default.
pub fn read(path: &Path) -> Result<(Settings, Vec<String>), String> {
let why = |e: io::Error| match e.kind() {
io::ErrorKind::NotFound => tr!("backup.not_there"),
io::ErrorKind::PermissionDenied => tr!("backup.not_allowed"),
_ => tr!("backup.not_one"),
};
let meta = fs::metadata(path).map_err(why)?;
if !meta.is_file() || meta.len() > LARGEST {
return Err(tr!("backup.not_one"));
}
let bytes = fs::read(path).map_err(why)?;
let map: serde_json::Map<String, serde_json::Value> = serde_json::from_slice(&bytes).map_err(|_| tr!("backup.not_one"))?;
// Any JSON object would do otherwise.
if !["download_folder", "own_color", "mode"].iter().all(|k| map.contains_key(*k)) {
return Err(tr!("backup.not_one"));
}
// `load` sets a damaged file aside, so it gets a copy.
let copy = std::env::temp_dir().join(format!("medlar-restore-{}-{}", std::process::id(), medlar_core::model::now()));
fs::create_dir(&copy).map_err(why)?;
let file = copy.join("settings.json");
let loaded = fs::write(&file, &bytes).map(|_| Settings::load(&file));
let _ = fs::remove_dir_all(&copy);
let (settings, damage) = loaded.map_err(why)?;
Ok((settings, damage.map(|d| d.keys).unwrap_or_default()))
}
fn folder(cx: &Cx) -> PathBuf {
cx.paths.map_or_else(|| download_folder(cx.s), |p| p.data.join("backups"))
}
fn find(folder: &Path) -> Vec<PathBuf> {
let mut all: Vec<PathBuf> = fs::read_dir(folder).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| {
p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("medlar-settings-") && n.ends_with(".json"))
}).collect();
// The names begin with the date.
all.sort();
all.reverse();
all.truncate(MOST);
all
}
pub fn show(view: &mut View, cx: &mut Cx, ui: &mut Ui) {
let t = cx.t;
let place = folder(cx);
// Pictures and tests have no folder of their own to look at.
let found = view.backup.found.get_or_insert_with(|| if cx.paths.is_some() { find(&place) } else { vec![] }).clone();
if Button::new(&tr!("backup.save")).with_icon("download").kind(Kind::Filled).show(ui, t).clicked() {
match write(cx.s, &place) {
Ok(path) => {
cx.toasts.action("check_circle", tr!("backup.saved", name = path.file_name().unwrap_or_default().to_string_lossy()), tr!("act.show"), Reply::Open(place.clone()));
view.backup.found = None;
}
Err(e) => {
log::warn!("backup: {e}");
let why = if e.kind() == io::ErrorKind::PermissionDenied { tr!("backup.not_allowed") } else { tr!("backup.disk") };
cx.toasts.error(tr!("backup.not_saved", why = why), None);
}
}
}
let mut wanted = None;
if !found.is_empty() {
ui.add_space(space::XS);
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), text::LABEL + space::S), Sense::hover());
left(ui.painter(), r.left_center(), line(ui.painter(), &tr!("backup.from"), fonts::med(text::LABEL), t.on_variant, r.width()));
}
for path in found {
let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
let (rect, r) = plate(ui, t, ROW, &tr!("backup.restore_this", name = name));
let p = ui.painter();
let x = rect.left() + space::M;
icons::paint(p, pos2(x + icon::M / 2.0, rect.center().y), icon::M, "history", t.on_variant);
let when = name.trim_start_matches("medlar-settings-").trim_end_matches(".json").to_string();
let day = when.get(..10).unwrap_or(&when);
let time = when.get(11..15).map(|t| format!("{}:{}", &t[..2], &t[2..])).unwrap_or_default();
let words = tr!("backup.day", day = day, time = time);
left(p, pos2(x + icon::M + space::M, rect.center().y), line(p, &words, fonts::med(text::BODY), t.on_surface, rect.width() - 160.0));
let button = line(p, &tr!("backup.restore"), fonts::med(text::BODY), t.primary, 120.0);
left(p, pos2(rect.right() - space::M - button.size().x, rect.center().y), button);
if r.clicked() {
wanted = Some(path);
}
}
ui.add_space(space::XS);
let wide = ui.available_width();
let error = view.backup.error.clone();
let r = Field::new(&tr!("backup.file")).hint("/home/…/medlar-settings.json").error(error.as_deref()).show(ui, t, &mut view.backup.file);
if r.changed() {
view.backup.error = None;
}
let full = Path::new(view.backup.file.trim()).is_absolute();
ui.allocate_ui(vec2(wide, size::CONTROL), |ui| {
if Button::new(&tr!("backup.restore")).with_icon("restart_alt").kind(Kind::Tonal).enabled(full).show(ui, t).clicked() {
wanted = Some(PathBuf::from(view.backup.file.trim()));
}
});
let Some(path) = wanted else { return };
match read(&path) {
Ok((new, lost)) => {
let before = std::mem::replace(cx.s, new);
let words = if lost.is_empty() { tr!("backup.restored") } else { tr!("settings.damaged_backup", keys = lost.join(", ")) };
cx.toasts.undo("restart_alt", words, Reply::Settings(Box::new(before)));
view.drafts.clear();
view.backup.error = None;
}
Err(why) => {
view.backup.error = Some(why.clone());
cx.toasts.error(tr!("backup.not_restored", why = why), None);
}
}
}

Some files were not shown because too many files have changed in this diff Show more