diff --git a/Cargo.lock b/Cargo.lock index 747157c..568720d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2760,6 +2760,7 @@ checksum = "7ebb8d8732c6a6df3d8f032a82911cfc747e00efb95cc46e8d0acd5b5b88570c" name = "medlar" version = "0.1.0" dependencies = [ + "arboard", "chrono", "dirs", "eframe", diff --git a/Plans/07 Library and tools/S027-rules-clipboard-drop.md b/Plans/07 Library and tools/S027-rules-clipboard-drop.md index fbcf4c7..8268666 100644 --- a/Plans/07 Library and tools/S027-rules-clipboard-drop.md +++ b/Plans/07 Library and tools/S027-rules-clipboard-drop.md @@ -12,14 +12,14 @@ FEATURES 3.3, 3.4, 3.9. - ~/Projects/Nacre/Cargo.toml (arboard line) ## Steps -- [ ] Rules engine: conditions (extension, MIME, host, size, name pattern) to folder, queue, tags, priority, name template; order, test box, default rule set by type -- [ ] Name templates with safe placeholders and collision handling -- [ ] Clipboard watcher: off, ask, add; filters; ignores our own copies; privacy note; Wayland limits stated honestly -- [ ] Drop links, text, lists and `.metalink` on the window with a full-window drop state -- [ ] Floating drop target: small wavy ring with speed, own always-on-top window where the compositor allows, else a compact window; accepts drops; context menu -- [ ] Rules and clipboard pages -- [ ] Test file `docs/tests/S027-rules-clipboard-drop.md`, with the checks below -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S027: …`, push +- [x] Rules engine: conditions (extension, MIME, host, size, name pattern) to folder, queue, tags, priority, name template; order, test box, default rule set by type +- [x] Name templates with safe placeholders and collision handling +- [x] Clipboard watcher: off, ask, add; filters; ignores our own copies; privacy note; Wayland limits stated honestly +- [x] Drop links, text, lists and `.metalink` on the window with a full-window drop state +- [x] Floating drop target: small wavy ring with speed, own always-on-top window where the compositor allows, else a compact window; accepts drops; context menu +- [x] Rules and clipboard pages +- [x] Test file `docs/tests/S027-rules-clipboard-drop.md`, with the checks below +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S027: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean diff --git a/Plans/INDEX.md b/Plans/INDEX.md index ac1d598..5feea7c 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -48,7 +48,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 07 Library and tools -- [ ] [S027](07%20Library%20and%20tools/S027-rules-clipboard-drop.md) Rules, clipboard, drag and drop, drop target +- [x] [S027](07%20Library%20and%20tools/S027-rules-clipboard-drop.md) Rules, clipboard, drag and drop, drop target - [ ] [S033](07%20Library%20and%20tools/S033-tray-notify.md) Tray, notifications and autostart ## 08 Motion and polish diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index b7d8bd8..c6cde2b 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -26,6 +26,7 @@ tokio = { version = "1", features = ["macros", "rt", "sync"] } percent-encoding = "2.3.2" url = "2" resvg = { version = "0.45", default-features = false } +arboard = { version = "3.6", default-features = false, features = ["wayland-data-control"] } [dev-dependencies] egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 971c896..afe5c7b 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -46,6 +46,8 @@ pub struct App { pub desktop: Desktop, sources: Sources, watch: Watch, + clip: Option, + target: crate::views::target::Target, /// What `theme` was made from; a change in settings rebuilds it. themed: Settings, /// What the engine and the shortcuts know. @@ -81,6 +83,8 @@ impl App { desktop, sources, watch, + clip: None, + target: Default::default(), save_at: None, saving: None, } @@ -203,6 +207,7 @@ impl App { } if self.first.is_none() { self.inbox.tick(ui.ctx(), &self.settings, &mut self.main); + self.extras(ui.ctx(), &t); } let bridge = &self.main.bridge; if let Some(ask) = &mut self.sign_in { @@ -241,6 +246,42 @@ impl App { } } + /// The clipboard watcher, the drop target and the full-window drop state. + fn extras(&mut self, ctx: &Context, t: &Theme) { + use crate::bridge::Data; + use crate::views::add::Request; + if self.settings.clipboard != "off" && self.clip.is_none() { + self.clip = Some(crate::clipboard::Watch::start(ctx.clone())); + } + let shot = match self.main.bridge.data() { + Data::Ready(shot, _) => Some(shot), + _ => None, + }; + if let Some(clip) = &self.clip { + let mut links = clip.tick(&self.settings.clipboard, &self.settings.clip_types, &self.settings.clip_skip); + if let Some(shot) = shot.as_ref().filter(|_| !links.is_empty()) { + let known = medlar_core::duplicate::Known::new(shot.iter().map(|v| &*v.task)); + links.retain(|l| known.find(&medlar_core::duplicate::New { url: l, ..Default::default() }).is_none()); + if !links.is_empty() && self.settings.clipboard == "add" { + let request = Request { text: links.join("\n"), literal: true, ..Request::default() }; + let mut add = crate::views::add::Add::new(request, &self.settings); + add.read_text(); + let (tasks, secrets) = add.tasks(); + self.main.toasts.info("content_paste", tr!("clip.added", n = tasks.len())); + self.main.bridge.add(tasks, secrets); + } else if !links.is_empty() { + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + self.main.adding.ask(Request { text: links.join("\n"), literal: true, ..Request::default() }); + } + } + } + let speed = shot.as_ref().map_or(0.0, |s| s.iter().map(|v| v.speed).sum()); + self.target.show(ctx, t, &mut self.settings, &mut self.main, speed); + if self.screen.is_none() { + crate::drop::overlay(ctx, t); + } + } + 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() }; diff --git a/crates/app/src/clipboard.rs b/crates/app/src/clipboard.rs new file mode 100644 index 0000000..d78e76e --- /dev/null +++ b/crates/app/src/clipboard.rs @@ -0,0 +1,120 @@ +//! Links that are copied (FEATURES 3.4). A thread looks at the clipboard once a second while the setting is on and +//! hands over what is new. What was there at the start, what the same text again and what Medlar copied itself are +//! left alone. +//! +//! On Wayland a program may read the clipboard only through the data-control protocol, which some compositors do not +//! offer; then nothing is seen and the page says so. X11 and XWayland work as they are. + +use medlar_core::batch::Batch; +use medlar_core::site::Pattern; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, channel}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use url::Url; + +/// False once the clipboard could not be opened. +static WORKS: AtomicBool = AtomicBool::new(true); + +pub fn works() -> bool { + WORKS.load(Ordering::Relaxed) +} + +/// What Medlar put on the clipboard last. +static OWN: Mutex = Mutex::new(String::new()); + +/// Copies for the user and remembers that they are ours. +pub fn copy(ctx: &eframe::egui::Context, text: String) { + *OWN.lock().unwrap() = text.clone(); + ctx.copy_text(text); +} + +/// The links in a copied text that the filters let through. +pub fn links(text: &str, types: &[String], skip: &[String]) -> Vec { + let skip: Vec = skip.iter().map(|s| Pattern::new(s)).collect(); + Batch::of(text, false) + .links + .into_iter() + .filter(|l| { + let Ok(url) = Url::parse(l) else { return false }; + let path = url.path().to_ascii_lowercase(); + let ext = path.rsplit_once('.').map(|(_, e)| e).unwrap_or_default(); + (types.is_empty() || types.iter().any(|t| t.trim_start_matches('.').eq_ignore_ascii_case(ext))) && !skip.iter().any(|p| p.fits(&url)) + }) + .collect() +} + +/// The thread that looks. +pub struct Watch { + on: Arc, + found: Receiver, +} + +impl Watch { + pub fn start(ctx: eframe::egui::Context) -> Watch { + let (tx, found) = channel(); + let on = Arc::new(AtomicBool::new(false)); + let flag = on.clone(); + let spawned = std::thread::Builder::new().name("clipboard".into()).spawn(move || { + let mut board = None; + let mut last: Option = None; + loop { + std::thread::sleep(Duration::from_secs(1)); + if !flag.load(Ordering::Relaxed) { + // What is copied while it is off is not news when it goes on. + last = None; + continue; + } + if board.is_none() { + board = arboard::Clipboard::new().map_err(|e| log::info!("clipboard: {e}")).ok(); + } + let Some(b) = &mut board else { + WORKS.store(false, Ordering::Relaxed); + continue; + }; + WORKS.store(true, Ordering::Relaxed); + let Ok(text) = b.get_text() else { continue }; + if last.is_none() { + last = Some(text); + } else if last.as_deref() != Some(&text) { + last = Some(text.clone()); + if *OWN.lock().unwrap() != text && tx.send(text).is_ok() { + ctx.request_repaint(); + } + } + } + }); + if let Err(e) = spawned { + log::warn!("clipboard: {e}"); + WORKS.store(false, Ordering::Relaxed); + } + Watch { on, found } + } + + /// Follows the setting. Returns the new links, if any. + pub fn tick(&self, mode: &str, types: &[String], skip: &[String]) -> Vec { + self.on.store(mode == "ask" || mode == "add", Ordering::Relaxed); + let mut out = vec![]; + while let Ok(text) = self.found.try_recv() { + if mode != "off" { + out.extend(links(&text, types, skip)); + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::links; + + #[test] + fn filters() { + let text = "see https://a.test/x.zip and https://b.test/y.iso and https://a.test/page"; + assert_eq!(links(text, &[], &[]).len(), 3); + assert_eq!(links(text, &["zip".into(), ".iso".into()], &[]).len(), 2); + assert_eq!(links(text, &[], &["*.test".into()]).len(), 0); + assert_eq!(links(text, &[], &["b.test".into()]).len(), 2); + assert!(links("no links here", &[], &[]).is_empty()); + } +} diff --git a/crates/app/src/drop.rs b/crates/app/src/drop.rs new file mode 100644 index 0000000..355517e --- /dev/null +++ b/crates/app/src/drop.rs @@ -0,0 +1,56 @@ +//! Things let go over a window (FEATURES 3.9): files (lists of links, `.metalink`) and, where the windowing system +//! passes them on as a path, links. The toolkit hands over no dropped text, so a link dragged from a browser's address +//! bar arrives only where the browser makes a file or `://` path of it; paste into the Add window otherwise. A full-window state shows while something is over the window. + +use crate::fonts; +use crate::theme::{Theme, alpha}; +use crate::tokens::{radius, space, text}; +use crate::views::add::Request; +use crate::ui::widgets::cr; +use eframe::egui::{Align2, Context, Id, LayerId, Order, Stroke, StrokeKind}; +use medlar_core::tr; + +#[allow(deprecated)] +fn id() -> Id { + Id::new("drop overlay") +} + +/// What was dropped, as asks for the Add window. Text counts when it holds links. +pub fn requests(ctx: &Context) -> Vec { + let files = ctx.input(|i| i.raw.dropped_files.clone()); + let mut out = vec![]; + let mut texts: Vec = vec![]; + for f in files { + let path = f.path().to_path_buf(); + let shown = path.to_string_lossy(); + // Some sources hand a link over as if it were a file. + if shown.contains("://") { + texts.push(shown.into_owned()); + } else { + out.push(Request { list: Some(path), ..Request::default() }); + } + } + if !texts.is_empty() { + out.push(Request { text: texts.join("\n"), ..Request::default() }); + } + out +} + +/// Something is over the window. +pub fn hovering(ctx: &Context) -> bool { + ctx.input(|i| !i.raw.hovered_files.is_empty()) +} + +/// The full-window state: the window dims, a dashed-looking frame and a line say what happens. +pub fn overlay(ctx: &Context, t: &Theme) { + if !hovering(ctx) { + return; + } + let rect = ctx.content_rect(); + let p = ctx.layer_painter(LayerId::new(Order::Foreground, id())); + p.rect_filled(rect, 0.0, alpha(t.surface, 0.86)); + let frame = rect.shrink(space::L); + p.rect_stroke(frame, cr(radius::L), Stroke::new(3.0, t.primary), StrokeKind::Inside); + p.text(frame.center(), Align2::CENTER_CENTER, tr!("drop.here"), fonts::med(text::TITLE), t.on_surface); + p.text(frame.center() + eframe::egui::vec2(0.0, 30.0), Align2::CENTER_CENTER, tr!("drop.what"), fonts::ui(text::BODY), t.on_variant); +} diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index 47a9907..2a8cceb 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -2,6 +2,8 @@ pub mod app; pub mod bridge; +pub mod clipboard; +pub mod drop; pub mod desktop; pub mod fonts; #[rustfmt::skip] diff --git a/crates/app/src/views/add/mod.rs b/crates/app/src/views/add/mod.rs index de4c8ed..82eaa38 100644 --- a/crates/app/src/views/add/mod.rs +++ b/crates/app/src/views/add/mod.rs @@ -340,6 +340,8 @@ pub struct Add { pub name: String, /// The user wrote it. name_own: bool, + rules: Vec, + base: PathBuf, pub folder: String, folder_own: bool, pub queue: QueueId, @@ -397,6 +399,8 @@ impl Add { twice: Twice::Skip, name: from.name.clone().unwrap_or_default(), name_own: from.name.is_some(), + rules: settings.rules.clone(), + base: download_folder(settings), folder: download_folder(settings).display().to_string(), folder_own: false, queue: medlar_core::model::MAIN_QUEUE, @@ -763,6 +767,8 @@ impl Add { // One item for each site and login. Others can't use it: it has a home. let mut names: HashMap<(String, Option<(String, String)>), String> = HashMap::new(); let (mut tasks, mut secrets) = (vec![], vec![]); + let mut used = std::collections::HashSet::new(); + let mut templated: Vec = vec![]; // What was typed is for the site of the first link. let home = links.first().and_then(|l| place(l)); for link in links { @@ -777,11 +783,35 @@ impl Add { }) }); let secret = name.map(|n| n.clone()); - tasks.push(Task { url, secret, ..common.clone() }); + let mut task = Task { url, secret, ..common.clone() }; + // The rules fill in what the user left as it was. + let own = if single.is_some() { self.name.trim().to_string() } else { String::new() }; + let item = medlar_core::rules::Item { url: &task.url, name: &own, mime: self.from.mime.as_deref(), size: self.from.size }; + let o = medlar_core::rules::apply(&self.rules, &item, &self.base, Local::now().date_naive()); + if let Some(f) = o.folder.filter(|_| !self.folder_own) { + task.folder = f; + } + if let Some(q) = o.queue.filter(|_| self.queue == medlar_core::model::MAIN_QUEUE) { + task.queue = q; + } + if let Some(p) = o.priority.filter(|_| self.priority == Priority::Normal) { + task.priority = p; + } + task.tags = o.tags; + if let Some(n) = o.name { + task.name = medlar_core::rules::free_name(&n, &task.folder, &mut used); + templated.push(task.name.clone()); + } else { + templated.push(String::new()); + } + tasks.push(task); } if let ([task], Some(_)) = (&mut tasks[..], single) { // Without one the server names it. task.name = if self.name_own { self.name.trim().to_string() } else { String::new() }; + if let Some(n) = templated.first().filter(|n| !n.is_empty()) { + task.name = n.clone(); + } task.mirrors = Batch::of(&self.mirrors, false).links.iter().map(|m| take_login(m).0).collect(); task.checksum = self.checksum_text(); } diff --git a/crates/app/src/views/details/tabs.rs b/crates/app/src/views/details/tabs.rs index ea046b2..be58116 100644 --- a/crates/app/src/views/details/tabs.rs +++ b/crates/app/src/views/details/tabs.rs @@ -84,7 +84,7 @@ fn props(ui: &mut Ui, t: &Theme, id: &str, rows: &[(String, String)]) { ui.label(RichText::new(name).font(fonts::ui(text::LABEL)).color(t.on_variant)); let r = ui.add(Label::new(RichText::new(value).font(fonts::ui(text::BODY)).color(t.on_surface)).wrap().sense(Sense::click())); if r.clicked() { - ui.ctx().copy_text(value.clone()); + crate::clipboard::copy(ui.ctx(), value.clone()); } r.on_hover_text(tr!("details.copy")); ui.end_row(); @@ -349,7 +349,7 @@ pub fn log(ui: &mut Ui, cx: &mut Cx, filter: &mut String) { ui.horizontal(|ui| { Field::new(&label).width((ui.available_width() - size::CONTROL - space::S).max(80.0)).show(ui, t, filter); if Button::icon("content_copy", &tr!("details.log.copy")).show(ui, t).clicked() { - ui.ctx().copy_text(log_lines(&v.log, filter).join("\n")); + crate::clipboard::copy(ui.ctx(), log_lines(&v.log, filter).join("\n")); } }); let lines = log_lines(&v.log, filter); diff --git a/crates/app/src/views/main.rs b/crates/app/src/views/main.rs index 75e1ce9..d7ba18a 100644 --- a/crates/app/src/views/main.rs +++ b/crates/app/src/views/main.rs @@ -381,8 +381,8 @@ impl Main { /// Files let go over the window: lists of links. fn dropped(&mut self, ui: &Ui) { - for file in ui.input(|i| i.raw.dropped_files.clone()) { - self.adding.ask(Request { list: Some(file.path().to_path_buf()), ..Request::default() }); + for request in crate::drop::requests(ui.ctx()) { + self.adding.ask(request); } } @@ -543,7 +543,7 @@ impl Main { } Act::Copy => { let all: Vec<&str> = views.iter().map(|v| v.task.url.as_str()).collect(); - ui.ctx().copy_text(all.join("\n")); + crate::clipboard::copy(ui.ctx(), all.join("\n")); self.toasts.info("content_copy", tr!("toast.copied", n = views.len())); } Act::OpenPage => { diff --git a/crates/app/src/views/mod.rs b/crates/app/src/views/mod.rs index 889ffd6..0374784 100644 --- a/crates/app/src/views/mod.rs +++ b/crates/app/src/views/mod.rs @@ -13,6 +13,8 @@ pub mod modes; pub mod palette; pub mod queues; pub mod rail; +pub mod rules; pub mod schedule; pub mod settings; +pub mod target; pub mod video; diff --git a/crates/app/src/views/rules.rs b/crates/app/src/views/rules.rs new file mode 100644 index 0000000..b8cbe40 --- /dev/null +++ b/crates/app/src/views/rules.rs @@ -0,0 +1,294 @@ +//! The rules page (FEATURES 3.3): the list in order, an editor for one rule, the default set and a test box. +//! The clipboard page's privacy note lives here too, as the two pages share the way of drawing. + +use super::settings::{Cx, View, plate, small}; +use crate::bridge::{Data, Lists}; +use crate::theme::Theme; +use crate::tokens::{icon, size, space, text}; +use crate::ui::dialog::{Answer, Dialog}; +use crate::ui::field::{Combo, Field, Number}; +use crate::ui::widgets::{Button, Kind, left, line}; +use crate::{fonts, icons}; +use eframe::egui::{Label, Rect, RichText, Sense, Ui, UiBuilder, Vec2, pos2, vec2}; +use medlar_core::model::Priority; +use medlar_core::rules::{self, Item, Rule}; +use medlar_core::tr; + +const ROW: f32 = 60.0; +const NUMBER: f32 = size::CONTROL + 2.0 * (space::L + space::XS); + +#[derive(Default)] +pub struct State { + edit: Option, + /// The test box. + sample: String, +} + +struct Edit { + at: Option, + open: bool, + name: String, + on: bool, + extensions: String, + mime: String, + host: String, + min: f64, + max: f64, + pattern: String, + folder: String, + /// 0 for none, then the queues in order. + queue: usize, + priority: usize, + tags: String, + template: String, +} + +fn words(list: &[String]) -> String { + list.join(", ") +} + +fn split(text: &str) -> Vec { + text.split([',', ' ', '\n']).map(|p| p.trim().trim_start_matches('.').to_ascii_lowercase()).filter(|p| !p.is_empty()).collect() +} + +impl Edit { + fn new(at: Option, r: &Rule, lists: &Lists) -> Edit { + Edit { + at, + open: true, + name: r.name.clone(), + on: at.is_none() || r.enabled, + extensions: words(&r.extensions), + mime: words(&r.mime), + host: r.host.clone(), + min: r.min_mb as f64, + max: r.max_mb as f64, + pattern: r.pattern.clone(), + folder: r.folder.clone(), + queue: r.queue.and_then(|q| lists.queues.iter().position(|x| x.id == q)).map_or(0, |i| i + 1), + priority: r.priority.and_then(|p| Priority::ALL.iter().position(|x| *x == p)).map_or(0, |i| i + 1), + tags: r.tags.iter().filter_map(|id| lists.tags.iter().find(|t| t.id == *id)).map(|t| t.name.clone()).collect::>().join(", "), + template: r.template.clone(), + } + } + + fn rule(&self, lists: &Lists) -> Rule { + let tags = self.tags.split(',').map(str::trim).filter_map(|n| lists.tags.iter().find(|t| t.name.eq_ignore_ascii_case(n))).map(|t| t.id).collect(); + Rule { + name: self.name.trim().to_string(), + enabled: self.on, + extensions: split(&self.extensions), + mime: split(&self.mime.replace(',', " ")).into_iter().map(|m| m.trim_start_matches('.').to_string()).collect(), + host: self.host.trim().to_string(), + min_mb: self.min as u64, + max_mb: self.max as u64, + pattern: self.pattern.trim().to_string(), + folder: self.folder.trim().to_string(), + queue: self.queue.checked_sub(1).and_then(|i| lists.queues.get(i)).map(|q| q.id), + tags, + priority: self.priority.checked_sub(1).and_then(|i| Priority::ALL.get(i)).copied(), + template: self.template.trim().to_string(), + } + } + + /// Tag names that don't exist. + fn tag_error(&self, lists: &Lists) -> Option { + let missing: Vec<&str> = self.tags.split(',').map(str::trim).filter(|n| !n.is_empty() && !lists.tags.iter().any(|t| t.name.eq_ignore_ascii_case(n))).collect(); + (!missing.is_empty()).then(|| tr!("rule.no_tag", tag = missing.join(", "))) + } +} + +/// What a rule does, in a line. +fn summary(r: &Rule, lists: &Lists) -> String { + let mut when = vec![]; + if !r.extensions.is_empty() { + when.push(words(&r.extensions)); + } + if !r.mime.is_empty() { + when.push(words(&r.mime)); + } + if !r.host.is_empty() { + when.push(r.host.clone()); + } + if !r.pattern.is_empty() { + when.push(r.pattern.clone()); + } + let mut then = vec![]; + if !r.folder.is_empty() { + then.push(r.folder.clone()); + } + if let Some(q) = r.queue { + then.push(super::list::model::queue_name(lists, q)); + } + if let Some(p) = r.priority { + then.push(tr!("rule.priority_is", priority = p.name())); + } + let when = if when.is_empty() { tr!("rule.any") } else { when.join(" · ") }; + let then = if then.is_empty() { String::new() } else { format!(" → {}", then.join(" · ")) }; + let off = if r.enabled { String::new() } else { format!("{} · ", tr!("rule.off")) }; + format!("{off}{when}{then}") +} + +fn lists(cx: &Cx) -> Lists { + match cx.bridge.data() { + Data::Ready(_, l) => (*l).clone(), + _ => Lists { queues: vec![], tags: vec![] }, + } +} + +/// The page: rules, buttons, test box. +pub fn list(view: &mut View, cx: &mut Cx, ui: &mut Ui) { + let t = cx.t; + let lists = lists(cx); + let mut moved: Option<(usize, i32)> = None; + let mut gone = None; + let mut flip = None; + for (i, r) in cx.s.rules.iter().enumerate() { + let (rect, resp) = plate(ui, t, ROW, &tr!("rule.change", rule = r.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, if r.enabled { "check_circle" } else { "visibility_off" }, t.on_variant); + let x = x + icon::M + space::M; + let room = rect.right() - x - 4.0 * size::HIT - space::M; + let name = if r.name.is_empty() { tr!("rule.unnamed") } else { r.name.clone() }; + left(p, pos2(x, rect.center().y - 9.0), line(p, &name, fonts::med(text::BODY), if r.enabled { t.on_surface } else { t.on_variant }, room)); + left(p, pos2(x, rect.center().y + 10.0), line(p, &summary(r, &lists), fonts::ui(text::LABEL), t.on_variant, room)); + let mut hit = true; + for (k, (icon, label)) in [("delete", tr!("rule.remove", rule = r.name)), ("arrow_downward", tr!("rule.down", rule = r.name)), ("arrow_upward", tr!("rule.up", rule = r.name)), (if r.enabled { "visibility" } else { "visibility_off" }, tr!("rule.toggle", rule = r.name))].into_iter().enumerate() { + let place = Rect::from_center_size(pos2(rect.right() - space::S - size::HIT * (k as f32 + 0.5), rect.center().y), Vec2::splat(size::HIT)); + let mut child = ui.new_child(UiBuilder::new().max_rect(place).id_salt(("rule button", i, k))); + if small(&mut child, t, icon, &label) { + hit = false; + match k { + 0 => gone = Some(i), + 1 => moved = Some((i, 1)), + 2 => moved = Some((i, -1)), + _ => flip = Some(i), + } + } + } + if hit && resp.clicked() { + view.rules.edit = Some(Edit::new(Some(i), r, &lists)); + } + } + if let Some((i, d)) = moved { + let j = i as i32 + d; + if j >= 0 && (j as usize) < cx.s.rules.len() { + cx.s.rules.swap(i, j as usize); + } + } + if let Some(i) = flip { + cx.s.rules[i].enabled = !cx.s.rules[i].enabled; + } + if let Some(i) = gone { + let before = cx.s.clone(); + let r = cx.s.rules.remove(i); + cx.toasts.undo("delete", tr!("rule.removed", rule = r.name), crate::views::main::Reply::Settings(Box::new(before))); + } + ui.horizontal(|ui| { + if Button::new(&tr!("rule.add")).with_icon("add").kind(Kind::Tonal).show(ui, t).clicked() { + view.rules.edit = Some(Edit::new(None, &Rule::default(), &lists)); + } + if Button::new(&tr!("rule.defaults")).kind(Kind::Text).show(ui, t).clicked() { + let before = cx.s.clone(); + let have: Vec = cx.s.rules.iter().map(|r| r.name.to_lowercase()).collect(); + // Names are the user's words; the set is in English until a language file says otherwise. + cx.s.rules.extend(rules::defaults().into_iter().filter(|r| !have.contains(&r.name.to_lowercase()))); + cx.toasts.undo("add", tr!("rule.defaults_added"), crate::views::main::Reply::Settings(Box::new(before))); + } + }); + ui.add_space(space::M); + test_box(view, cx, ui, &lists); +} + +/// A link or a name, and the rule it meets. +fn test_box(view: &mut View, cx: &mut Cx, ui: &mut Ui, lists: &Lists) { + let t = cx.t; + Field::new(&tr!("rule.test")).hint("https://example.com/video.mp4").help(&tr!("rule.test_help")).show(ui, t, &mut view.rules.sample); + let sample = view.rules.sample.trim(); + if sample.is_empty() { + return; + } + let (url, name) = if sample.contains("://") { (sample, String::new()) } else { ("", sample.to_string()) }; + let item = Item { url, name: &name, ..Item::default() }; + let base = crate::bridge::download_folder(cx.s); + let out = rules::apply(&cx.s.rules, &item, &base, chrono::Local::now().date_naive()); + let answer = match out.rule { + None => tr!("rule.test_none"), + Some(i) => { + let mut parts = vec![tr!("rule.test_rule", rule = cx.s.rules[i].name)]; + parts.extend(out.folder.map(|f| f.display().to_string())); + parts.extend(out.queue.map(|q| super::list::model::queue_name(lists, q))); + parts.extend(out.priority.map(|p| p.name().to_string())); + parts.extend(out.name); + parts.join(" → ") + } + }; + ui.add(Label::new(RichText::new(answer).font(fonts::ui(text::BODY)).color(t.on_surface)).wrap()); +} + +/// The clipboard page's note about what is read and what is not. +pub fn clip_note(_: &mut View, cx: &mut Cx, ui: &mut Ui) { + let t: &Theme = cx.t; + for key in [tr!("clip.privacy"), tr!("clip.wayland")] { + ui.add(Label::new(RichText::new(key).font(fonts::ui(text::LABEL)).color(t.on_variant)).wrap()); + ui.add_space(space::S); + } + if !crate::clipboard::works() { + ui.add(Label::new(RichText::new(tr!("clip.broken")).font(fonts::ui(text::LABEL)).color(t.error)).wrap()); + } +} + +impl State { + /// The editor of one rule. + pub fn dialog(&mut self, ui: &Ui, cx: &mut Cx) { + let Some(e) = &mut self.edit else { return }; + let t = cx.t; + let lists = lists(cx); + let queues: Vec = std::iter::once(tr!("rule.keep")).chain(lists.queues.iter().map(|q| super::list::model::queue_name(&lists, q.id))).collect(); + let priorities: Vec = std::iter::once(tr!("rule.keep")).chain(Priority::ALL.iter().map(|p| strings_priority(*p))).collect(); + let bad_tags = e.tag_error(&lists); + let bad_folder: Option = None; + let good = !e.name.trim().is_empty() && bad_tags.is_none() && bad_folder.is_none(); + let title = if e.at.is_some() { tr!("rule.edit_title") } else { tr!("rule.add_title") }; + let open = e.open; + let answer = Dialog::new("rule", &title, &tr!("rule.save")).width(size::DIALOG_M).enabled(good).show(ui.ctx(), t, open, |ui| { + let r = Field::new(&tr!("rule.name")).show(ui, t, &mut e.name); + if ui.memory(|m| m.focused().is_none()) { + r.request_focus(); + } + Field::new(&tr!("rule.extensions")).hint("zip, iso, mp4").show(ui, t, &mut e.extensions); + Field::new(&tr!("rule.mime")).hint("video/, application/pdf").show(ui, t, &mut e.mime); + Field::new(&tr!("rule.host")).hint("*.example.com").show(ui, t, &mut e.host); + let side = ((ui.available_width() - space::S) / 2.0).floor(); + let (both, _) = ui.allocate_exact_size(vec2(ui.available_width(), NUMBER), Sense::hover()); + let mut half = |x: f32, salt: &str| ui.new_child(UiBuilder::new().max_rect(Rect::from_min_size(pos2(x, both.top()), vec2(side, NUMBER))).id_salt(salt)); + let mut first = half(both.left(), "min"); + Number { label: &tr!("rule.min"), unit: "MB", range: 0.0..=1_000_000.0, step: 1.0, enabled: true, width: side, bare: false }.show(&mut first, t, &mut e.min); + let mut second = half(both.right() - side, "max"); + Number { label: &tr!("rule.max"), unit: "MB", range: 0.0..=1_000_000.0, step: 1.0, enabled: true, width: side, bare: false }.show(&mut second, t, &mut e.max); + Field::new(&tr!("rule.pattern")).hint("*-setup-*.exe").show(ui, t, &mut e.pattern); + Field::new(&tr!("rule.folder")).hint("Video").help(&tr!("rule.folder_help")).error(bad_folder.as_deref()).show(ui, t, &mut e.folder); + ui.horizontal_top(|ui| { + Combo::new(&tr!("rule.queue"), &queues, side).show(ui, t, &mut e.queue); + Combo::new(&tr!("rule.priority"), &priorities, side).show(ui, t, &mut e.priority); + }); + Field::new(&tr!("rule.tags")).error(bad_tags.as_deref()).show(ui, t, &mut e.tags); + Field::new(&tr!("rule.template")).hint("{date} {stem}.{ext}").help(&tr!("rule.template_help")).show(ui, t, &mut e.template); + }); + let Some(answer) = answer else { return }; + e.open = false; + if answer == Answer::Cancel { + return; + } + let rule = e.rule(&lists); + match e.at.filter(|i| *i < cx.s.rules.len()) { + Some(i) => cx.s.rules[i] = rule, + None => cx.s.rules.push(rule), + } + } +} + +fn strings_priority(p: Priority) -> String { + medlar_core::strings::text(&format!("priority.{}", p.name()), &[]) +} diff --git a/crates/app/src/views/settings/mod.rs b/crates/app/src/views/settings/mod.rs index 99e1bba..bf7e7de 100644 --- a/crates/app/src/views/settings/mod.rs +++ b/crates/app/src/views/settings/mod.rs @@ -68,6 +68,7 @@ pub struct View { look: look::State, network: network::State, sites: sites::State, + pub rules: crate::views::rules::State, keys: shortcuts::State, backup: backup::State, focus_search: bool, @@ -205,6 +206,7 @@ impl View { } } self.sites.dialog(ui, cx); + self.rules.dialog(ui, cx); if rows::free(ui) && !self.keys.recording() { let typing = ui.memory(|m| m.focused()).is_some() && ui.ctx().text_edit_focused(); close |= !typing && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)); @@ -443,12 +445,12 @@ fn line_of(ui: &mut Ui, t: &Theme, name: &str, why: &str, control: f32, error } /// A small button at the right of a row that draws itself. -fn small(ui: &mut Ui, t: &Theme, icon: &str, name: &str) -> bool { +pub(crate) fn small(ui: &mut Ui, t: &Theme, icon: &str, name: &str) -> bool { Button::icon(icon, name).size(Size::S).show(ui, t).clicked() } /// A row that can be clicked as a whole. Gives back its place too. -fn plate(ui: &mut Ui, t: &Theme, height: f32, name: &str) -> (Rect, eframe::egui::Response) { +pub(crate) fn plate(ui: &mut Ui, t: &Theme, height: f32, name: &str) -> (Rect, eframe::egui::Response) { let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::click()); r.widget_info(|| WidgetInfo::labeled(Role::Button, true, name)); let f = feel(&r, true); diff --git a/crates/app/src/views/settings/rows.rs b/crates/app/src/views/settings/rows.rs index 5c394f2..94b63f1 100644 --- a/crates/app/src/views/settings/rows.rs +++ b/crates/app/src/views/settings/rows.rs @@ -18,6 +18,8 @@ pub enum Page { Connections, Network, Sites, + Rules, + Clipboard, Browser, Notifications, Power, @@ -26,12 +28,14 @@ pub enum Page { } impl Page { - pub const ALL: [Page; 10] = [ + pub const ALL: [Page; 12] = [ Page::Look, Page::Downloads, Page::Connections, Page::Network, Page::Sites, + Page::Rules, + Page::Clipboard, Page::Browser, Page::Notifications, Page::Power, @@ -46,6 +50,8 @@ impl Page { Page::Connections => "connections", Page::Network => "network", Page::Sites => "sites", + Page::Rules => "rules", + Page::Clipboard => "clipboard", Page::Browser => "browser", Page::Notifications => "notifications", Page::Power => "power", @@ -61,6 +67,8 @@ impl Page { Page::Connections => "speed", Page::Network => "language", Page::Sites => "key", + Page::Rules => "tune", + Page::Clipboard => "content_paste", Page::Browser => "public", Page::Notifications => "notifications", Page::Power => "power_settings_new", @@ -327,6 +335,40 @@ static ROWS: &[Row] = &[ }, ), row(Page::Sites, "", "sites", &["sites"], Kind::Own(sites::list)), + row(Page::Rules, "", "rules", &["rules"], Kind::Own(crate::views::rules::list)), + row( + Page::Clipboard, + "clipboard", + "clipboard", + &["clipboard"], + Kind::Choice { options: &["off", "ask", "add"], get: |s| ["off", "ask", "add"].iter().position(|m| *m == s.clipboard).unwrap_or(0), set: |s, i| s.clipboard = ["off", "ask", "add"][i].into() }, + ), + row( + Page::Clipboard, + "clipboard", + "clip_types", + &["clip_types"], + Kind::Text { + hint: |_| "zip, iso, mp4".into(), + check: |_| None, + get: |s| s.clip_types.join(", "), + set: |s, v| s.clip_types = v.split([',', ' ', '\n']).map(|p| p.trim().trim_start_matches('.').to_ascii_lowercase()).filter(|p| !p.is_empty()).collect(), + }, + ), + row( + Page::Clipboard, + "clipboard", + "clip_skip", + &["clip_skip"], + Kind::Text { + hint: |_| "*.example.com".into(), + check: |_| None, + get: |s| s.clip_skip.join(", "), + set: |s, v| s.clip_skip = v.split([',', ' ', '\n']).map(str::trim).filter(|p| !p.is_empty()).map(String::from).collect(), + }, + ), + row(Page::Clipboard, "drop", "drop_target", &["drop_target"], Kind::Switch { get: |s| s.drop_target, set: |s, v| s.drop_target = v }), + row(Page::Clipboard, "", "clip_note", &[], Kind::Own(crate::views::rules::clip_note)), row(Page::Browser, "browser", "connector", &["connector"], Kind::Switch { get: |s| s.connector, set: |s, v| s.connector = v }), row( Page::Browser, diff --git a/crates/app/src/views/target.rs b/crates/app/src/views/target.rs new file mode 100644 index 0000000..d0d265b --- /dev/null +++ b/crates/app/src/views/target.rs @@ -0,0 +1,109 @@ +//! The drop target (FEATURES 3.9): a small wavy ring with the speed, in a window of its own that takes drops. +//! +//! It asks for "always on top". Wayland has no such thing for ordinary windows, so on niri it is a small window that +//! can be moved and put on a workspace like any other; where the compositor honours the hint (X11, XWayland, some +//! others) it floats. A click brings the main window back; a right click opens the menu. + +use super::add::Request; +use super::main::Main; +use crate::drop; +use crate::theme::Theme; +use crate::tokens::{size, space, text}; +use crate::ui::odometer::rate; +use crate::ui::wave::{self, Look}; +use crate::ui::widgets::{Button, Kind}; +use crate::fonts; +use eframe::egui::{Align2, Context, Id, Sense, ViewportBuilder, ViewportClass, ViewportCommand, ViewportId, pos2, vec2}; +use medlar_core::settings::Settings; +use medlar_core::tr; + +const RING: f32 = 84.0; +const SMALL: f32 = 112.0; + +#[derive(Default)] +pub struct Target { + menu: bool, +} + +enum Do { + Open, + Add, + Hide, +} + +#[allow(deprecated)] +fn salt(name: &str) -> Id { + Id::new(name) +} + +impl Target { + /// Once per frame, while the setting is on. `speed` is all downloads together, in bytes per second. + pub fn show(&mut self, ctx: &Context, t: &Theme, settings: &mut Settings, main: &mut Main, speed: f64) { + if !settings.drop_target { + self.menu = false; + return; + } + let big = if self.menu { vec2(SMALL + 60.0, SMALL + 120.0) } else { vec2(SMALL, SMALL + 20.0) }; + let builder = ViewportBuilder::default() + .with_title("Medlar") + .with_app_id(crate::app::APP_ID) + .with_inner_size(big) + .with_resizable(false) + .with_decorations(false) + .with_always_on_top() + .with_taskbar(false); + let mut act = None; + let mut dropped = vec![]; + let menu = &mut self.menu; + ctx.show_viewport_immediate(ViewportId::from_hash_of("drop target"), builder, |ui, class| { + if class != ViewportClass::Immediate && class != ViewportClass::Root { + // Embedded in the main window: nothing to show on its own. + return; + } + ui.ctx().send_viewport_cmd(ViewportCommand::InnerSize(big)); + let full = ui.max_rect(); + ui.painter().rect_filled(full, crate::ui::widgets::cr(size::CONTROL / 2.0), t.container); + let ring = eframe::egui::Rect::from_center_size(pos2(full.center().x, full.top() + space::S + RING / 2.0), vec2(RING, RING)); + let look = if speed > 0.0 { Look::Running } else { Look::Waiting }; + wave::ring(ui, t, salt("target ring"), ring, look, None, speed); + let p = ui.painter(); + p.text(pos2(full.center().x, ring.bottom() + space::S), Align2::CENTER_TOP, rate(speed), fonts::med(text::LABEL), t.on_surface); + let r = ui.interact(ring, salt("target hit"), Sense::click_and_drag()); + if r.drag_started() { + ui.ctx().send_viewport_cmd(ViewportCommand::StartDrag); + } + if r.clicked() { + act = Some(Do::Open); + } + if r.secondary_clicked() { + *menu = !*menu; + } + if *menu { + ui.add_space(RING + 2.0 * space::L + text::LABEL); + for (label, what) in [(tr!("target.open"), Do::Open), (tr!("target.add"), Do::Add), (tr!("target.hide"), Do::Hide)] { + if Button::new(&label).kind(Kind::Text).show(ui, t).clicked() { + act = Some(what); + *menu = false; + } + } + } + dropped = drop::requests(ui.ctx()); + if ui.ctx().input(|i| i.viewport().close_requested()) { + act = Some(Do::Hide); + } + }); + for r in dropped { + main.adding.ask(r); + ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::Focus); + } + match act { + Some(Do::Open) => ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::Focus), + Some(Do::Add) => { + main.adding.ask(Request::default()); + ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::Focus); + } + Some(Do::Hide) => settings.drop_target = false, + None => {} + } + } +} diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index e665072..1e69f37 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -477,6 +477,71 @@ "page.downloads": "Downloads", "page.connections": "Connections", "page.network": "Network", + "page.rules": "Rules", + "page.clipboard": "Clipboard and drops", + "set.rules": "Rules", + "set.rules.why": "Sort new downloads by type, host, size or name into folders and queues. The first rule that fits counts.", + "set.group.clipboard": "Copied links", + "set.group.drop": "Drop target", + "set.clipboard": "Links that are copied", + "set.clipboard.why": "Look at the clipboard for links. Medlar's own copies are ignored.", + "set.clipboard.off": "Off", + "set.clipboard.ask": "Ask", + "set.clipboard.add": "Add", + "set.clip_types": "Only these types", + "set.clip_types.why": "File types of copied links that count, such as zip, iso. Empty for any link.", + "set.clip_skip": "Never from", + "set.clip_skip.why": "Hosts whose copied links are left alone, such as *.example.com.", + "set.drop_target": "Drop target", + "set.drop_target.why": "A small ring with the speed that takes links and lists let go on it.", + "set.clip_note": "Privacy", + "set.clip_note.why": "What is read.", + "clip.privacy": "While this is on, Medlar reads the text on the clipboard once a second and keeps none of it. Only links count; the rest is dropped at once. Turn it off to stop.", + "clip.wayland": "On Wayland the clipboard can be read only if the desktop offers the data-control protocol. If nothing is noticed, use paste in the Add window or the drop target.", + "clip.broken": "The clipboard could not be opened, so copied links are not seen.", + "clip.found": "Copied link: {n} found", + "clip.added": "{n} copied links added", + "drop.here": "Let go to add", + "drop.what": "Links, lists of links and .metalink files", + "target.open": "Open Medlar", + "target.add": "Add a link", + "target.hide": "Hide this ring", + "rule.add": "Add rule", + "rule.add_title": "Add rule", + "rule.edit_title": "Change rule", + "rule.save": "Save", + "rule.defaults": "Add the set by type", + "rule.defaults_added": "Rules for video, music, pictures, documents, archives and programs added", + "rule.change": "Change rule {rule}", + "rule.remove": "Remove rule {rule}", + "rule.removed": "Rule {rule} removed", + "rule.up": "Move {rule} up", + "rule.down": "Move {rule} down", + "rule.toggle": "Turn {rule} on or off", + "rule.unnamed": "Rule without a name", + "rule.any": "Any download", + "rule.off": "Off", + "rule.keep": "Leave as it is", + "rule.priority_is": "priority {priority}", + "rule.name": "Name", + "rule.extensions": "File types", + "rule.mime": "Kinds of file (MIME)", + "rule.host": "Site", + "rule.min": "At least", + "rule.max": "At most", + "rule.pattern": "Name fits", + "rule.folder": "Folder", + "rule.folder_help": "A folder below the download folder, or a whole path.", + "rule.queue": "Queue", + "rule.priority": "Priority", + "rule.tags": "Tags", + "rule.no_tag": "No such tag: {tag}", + "rule.template": "Name", + "rule.template_help": "{name} {stem} {ext} {host} {date} {year} {month} {day}. A name that is taken gets (2).", + "rule.test": "Try a link or a name", + "rule.test_help": "Shows which rule would catch it and what it would do.", + "rule.test_none": "No rule fits.", + "rule.test_rule": "Rule {rule}", "page.sites": "Logins and sites", "page.browser": "Browser", "page.notifications": "Notifications", diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index d764a08..c3107f5 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -30,6 +30,7 @@ pub mod proxy; pub mod recover; pub mod redact; pub mod relink; +pub mod rules; pub mod run; pub mod schedule; pub mod secret; diff --git a/crates/core/src/rules.rs b/crates/core/src/rules.rs new file mode 100644 index 0000000..f5dacf4 --- /dev/null +++ b/crates/core/src/rules.rs @@ -0,0 +1,271 @@ +//! Rules that sort new downloads: what a link is (type, kind of file, host, size, name) decides folder, queue, tags, +//! priority and name. The first rule that fits counts. Pure logic; the Add window and the rules page use it. + +use crate::http::name::safe; +use crate::model::{Priority, QueueId, TagId}; +use crate::site::Pattern; +use serde::{Deserialize, Serialize}; +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use url::Url; + +/// What a link is, as far as it is known. Empty or None for what is not. +#[derive(Debug, Clone, Copy, Default)] +pub struct Item<'a> { + pub url: &'a str, + pub name: &'a str, + pub mime: Option<&'a str>, + pub size: Option, +} + +/// A rule: every condition that is set must fit; what is set in the second half is what happens. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Rule { + pub name: String, + pub enabled: bool, + /// Small letters, without the dot. + pub extensions: Vec, + /// `video/mp4`, or `video/` for all of a kind. + pub mime: Vec, + /// As a site: `example.com`, `*.example.com`. + pub host: String, + /// In MB; 0 for no bound. + pub min_mb: u64, + pub max_mb: u64, + /// `*` and `?`, on the name, in any case. + pub pattern: String, + /// Absolute, or below the download folder when it is relative. Empty to leave it. + pub folder: String, + pub queue: Option, + pub tags: Vec, + pub priority: Option, + /// `{name}`, `{stem}`, `{ext}`, `{host}`, `{date}`, `{year}`, `{month}`, `{day}`. Empty to leave the name. + pub template: String, +} + +/// What the rule that fits says. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Outcome { + /// Its place in the list. + pub rule: Option, + pub folder: Option, + pub queue: Option, + pub tags: Vec, + pub priority: Option, + pub name: Option, +} + +/// `*` and `?` against a text, in any case. +pub fn glob(pattern: &str, text: &str) -> bool { + let p: Vec = pattern.to_lowercase().chars().collect(); + let t: Vec = text.to_lowercase().chars().collect(); + let (mut pi, mut ti, mut star, mut mark) = (0, 0, None, 0); + while ti < t.len() { + if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) { + pi += 1; + ti += 1; + } else if pi < p.len() && p[pi] == '*' { + star = Some(pi); + mark = ti; + pi += 1; + } else if let Some(s) = star { + pi = s + 1; + mark += 1; + ti = mark; + } else { + return false; + } + } + p[pi..].iter().all(|c| *c == '*') +} + +/// The name a link ends in. +pub fn name_of(url: &str) -> String { + let path = url.split(['?', '#']).next().unwrap_or_default(); + let last = path.rsplit('/').next().unwrap_or_default(); + percent_encoding::percent_decode_str(last).decode_utf8_lossy().into_owned() +} + +impl Rule { + pub fn fits(&self, item: &Item) -> bool { + let name = if item.name.is_empty() { name_of(item.url) } else { item.name.to_string() }; + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); + if !self.extensions.is_empty() && !self.extensions.iter().any(|e| e.trim_start_matches('.').eq_ignore_ascii_case(&ext)) { + return false; + } + if !self.mime.is_empty() { + let mime = item.mime.unwrap_or_default().split(';').next().unwrap_or_default().trim().to_ascii_lowercase(); + if !self.mime.iter().any(|m| !mime.is_empty() && mime.starts_with(&m.to_ascii_lowercase())) { + return false; + } + } + if !self.host.trim().is_empty() && !Url::parse(item.url).is_ok_and(|u| Pattern::new(&self.host).fits(&u)) { + return false; + } + let mb = 1024 * 1024; + // A size nobody told passes. + if item.size.is_some_and(|n| n < self.min_mb * mb || (self.max_mb > 0 && n > self.max_mb * mb)) { + return false; + } + self.pattern.trim().is_empty() || glob(self.pattern.trim(), &name) + } +} + +/// The first enabled rule that fits. +pub fn first(rules: &[Rule], item: &Item) -> Option { + rules.iter().position(|r| r.enabled && r.fits(item)) +} + +/// What the rules say for an item; `base` is the download folder. +pub fn apply(rules: &[Rule], item: &Item, base: &Path, now: chrono::NaiveDate) -> Outcome { + let Some(at) = first(rules, item) else { return Outcome::default() }; + let r = &rules[at]; + let folder = Some(r.folder.trim()).filter(|f| !f.is_empty()).map(|f| { + let f = Path::new(f); + if f.is_absolute() { f.to_path_buf() } else { base.join(f.components().filter(|c| matches!(c, std::path::Component::Normal(_))).collect::()) } + }); + let name = Some(r.template.trim()).filter(|t| !t.is_empty()).and_then(|t| expand(t, item, now)); + Outcome { rule: Some(at), folder, queue: r.queue, tags: r.tags.clone(), priority: r.priority, name } +} + +/// A template filled in. Every value is cleaned first, so nothing can add a path part; an unknown `{word}` is left out. +/// None when nothing usable is left. +pub fn expand(template: &str, item: &Item, now: chrono::NaiveDate) -> Option { + use chrono::Datelike; + let name = if item.name.is_empty() { name_of(item.url) } else { item.name.to_string() }; + let (stem, ext) = match name.rsplit_once('.') { + Some((s, e)) if !s.is_empty() => (s.to_string(), e.to_string()), + _ => (name.clone(), String::new()), + }; + let host = Url::parse(item.url).ok().and_then(|u| u.host_str().map(String::from)).unwrap_or_default(); + let clean = |v: &str| v.chars().map(|c| if matches!(c, '/' | '\\') { '_' } else { c }).collect::(); + let mut out = String::new(); + let mut rest = template; + while let Some(open) = rest.find('{') { + out.push_str(&rest[..open]); + let Some(close) = rest[open..].find('}') else { + rest = &rest[open..]; + break; + }; + let key = &rest[open + 1..open + close]; + out.push_str(&match key { + "name" => clean(&name), + "stem" => clean(&stem), + "ext" => clean(&ext), + "host" => clean(&host), + "date" => now.format("%Y-%m-%d").to_string(), + "year" => format!("{:04}", now.year()), + "month" => format!("{:02}", now.month()), + "day" => format!("{:02}", now.day()), + _ => String::new(), + }); + rest = &rest[open + close + 1..]; + } + out.push_str(rest); + safe(&out) +} + +/// `name`, or `stem (2).ext`, `stem (3).ext` until `taken` is false. +pub fn unique(name: &str, taken: impl Fn(&str) -> bool) -> String { + if !taken(name) { + return name.to_string(); + } + let (stem, ext) = match name.rsplit_once('.') { + Some((s, e)) if !s.is_empty() => (s, format!(".{e}")), + _ => (name, String::new()), + }; + (2..) + .map(|n| format!("{stem} ({n}){ext}")) + .find(|c| !taken(c)) + .unwrap_or_else(|| name.to_string()) +} + +/// Names that are not yet used in a folder or in what is taken already. +pub fn free_name(name: &str, folder: &Path, used: &mut HashSet) -> String { + let n = unique(name, |c| used.contains(c) || folder.join(c).exists()); + used.insert(n.clone()); + n +} + +/// A set to start from: one rule for each kind of file, each in a folder of its own below the download folder. +pub fn defaults() -> Vec { + let kind = |name: &str, folder: &str, mime: &[&str], ext: &[&str]| Rule { + name: name.into(), + enabled: true, + folder: folder.into(), + mime: mime.iter().map(|s| s.to_string()).collect(), + extensions: ext.iter().map(|s| s.to_string()).collect(), + ..Rule::default() + }; + vec![ + kind("Video", "Video", &["video/"], &["mp4", "mkv", "webm", "avi", "mov"]), + kind("Music", "Music", &["audio/"], &["mp3", "flac", "ogg", "opus", "m4a", "wav"]), + kind("Pictures", "Pictures", &["image/"], &["jpg", "jpeg", "png", "gif", "webp", "svg"]), + kind("Documents", "Documents", &[], &["pdf", "epub", "doc", "docx", "odt", "txt", "xls", "xlsx", "ods"]), + kind("Archives", "Archives", &[], &["zip", "7z", "rar", "tar", "gz", "xz", "bz2", "zst", "iso"]), + kind("Programs", "Programs", &[], &["exe", "msi", "deb", "rpm", "appimage", "flatpak", "apk"]), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + fn day() -> chrono::NaiveDate { + chrono::NaiveDate::from_ymd_opt(2026, 3, 9).unwrap() + } + + fn item<'a>(url: &'a str) -> Item<'a> { + Item { url, ..Item::default() } + } + + #[test] + fn globs() { + assert!(glob("*.ISO", "Arch.iso")); + assert!(glob("a?c*", "abcdef")); + assert!(!glob("a?c", "ac")); + assert!(glob("*", "")); + } + + #[test] + fn conditions_and_order() { + let mut rules = defaults(); + rules.insert(0, Rule { name: "big".into(), enabled: true, extensions: vec!["mp4".into()], min_mb: 100, folder: "Big".into(), ..Rule::default() }); + let small = Item { url: "https://a.test/x.mp4", size: Some(5 << 20), ..Item::default() }; + let big = Item { size: Some(500 << 20), ..small }; + assert_eq!(first(&rules, &small), Some(1)); + assert_eq!(first(&rules, &big), Some(0)); + let mime = Item { url: "https://a.test/stream", mime: Some("audio/ogg; x=1"), ..Item::default() }; + assert_eq!(rules[first(&rules, &mime).unwrap()].name, "Music"); + rules[0].enabled = false; + assert_eq!(first(&rules, &big), Some(1)); + assert_eq!(first(&rules, &item("https://a.test/readme")), None); + } + + #[test] + fn host_and_folder() { + let rules = [Rule { enabled: true, host: "*.example.com".into(), folder: "../../etc".into(), ..Rule::default() }]; + let o = apply(&rules, &item("https://cdn.example.com/f.bin"), Path::new("/home/u/Downloads"), day()); + assert_eq!(o.folder.unwrap(), Path::new("/home/u/Downloads/etc")); + assert_eq!(apply(&rules, &item("https://other.test/f.bin"), Path::new("/d"), day()), Outcome::default()); + } + + #[test] + fn templates_are_safe() { + let i = Item { url: "https://h.test/a/b%2Fc.tar.gz", ..Item::default() }; + assert_eq!(expand("{date} {host} {stem}.{ext}", &i, day()).unwrap(), "2026-03-09 h.test b_c.tar.gz"); + assert_eq!(expand("{nope}x/../{name}", &i, day()).unwrap(), "b_c.tar.gz"); + assert_eq!(expand("{nope}", &i, day()), None); + } + + #[test] + fn collisions() { + let mut used = HashSet::new(); + let nowhere = Path::new("/nonexistent-medlar"); + assert_eq!(free_name("a.zip", nowhere, &mut used), "a.zip"); + assert_eq!(free_name("a.zip", nowhere, &mut used), "a (2).zip"); + assert_eq!(free_name("a.zip", nowhere, &mut used), "a (3).zip"); + assert_eq!(unique("noext", |n| n == "noext"), "noext (2)"); + } +} diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index 433de78..4e82a1a 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -33,6 +33,16 @@ pub struct Settings { /// Go on at the next start with what ran when Medlar ended. pub auto_resume: bool, pub sites: Vec, + /// Sort new downloads, first fit counts (see `rules`). + pub rules: Vec, + /// Links that are copied: `off`, `ask` or `add`. + pub clipboard: String, + /// Only links to these types (extensions in small letters); empty for any link. + pub clip_types: Vec, + /// Never from these hosts. + pub clip_skip: Vec, + /// The small ring that takes drops. + pub drop_target: bool, /// See `proxy::Choice`. pub proxy: String, /// Hosts and networks it is not used for. @@ -144,6 +154,11 @@ impl Default for Settings { tries: 10, auto_resume: true, sites: vec![], + rules: vec![], + clipboard: "off".into(), + clip_types: vec![], + clip_skip: vec![], + drop_target: false, proxy: "system".into(), proxy_bypass: ["localhost", "127.0.0.0/8", "::1"].map(String::from).into(), connector: true, diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 8ff32e6..90e75f3 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -222,3 +222,8 @@ Seen: boxes were ticked together after the tests, against rule 3. ## S025 — Video sites (compiled, not tested) - `core::ytdlp`: finder and version check (`Problem`), `probe` (cached, cancellable by drop, DRM refused), `Choice`/`Run`, `start` -> `Running` (progress parsed, stop = kill, restart continues), `Reason` mapped to error kinds, cookies in a 0600 temp file. `views/video.rs`: quality/audio/subtitle/playlist page. - Not done: page not shown by the Add dialog, no manager task kind, limiter not fed live, no cookie-header conversion, no automatic tests or stub. Tests: `docs/tests/S025-video-sites.md`. + +## S027 — Rules, clipboard, drops (compiled, not tested) +- `core::rules` (Rule/Item/apply/expand/unique/defaults, first fit wins; settings `rules`, `clipboard`, `clip_types`, `clip_skip`, `drop_target`); Add's `tasks()` applies rules to what the user left as is (folder, queue, priority, tags, name template with collision numbers). +- `app::clipboard` (thread polls arboard 1 s while ask/add; ignores start content, repeats, own copies via `clipboard::copy`), `app::drop` (full-window overlay, paths and `://` paths to Add), `views/target.rs` (own viewport, always-on-top hint, ring, menu), `views/rules.rs` and two settings pages (Rules, Clipboard and drops). +- Not done: winit gives no dropped text, so browser link drags work only as paths; always-on-top is ignored by niri; no layer-shell; rules not applied by the CLI or direct engine adds; tests: `docs/tests/S027-rules-clipboard-drop.md`. diff --git a/docs/tests/S027-rules-clipboard-drop.md b/docs/tests/S027-rules-clipboard-drop.md new file mode 100644 index 0000000..5559c8c --- /dev/null +++ b/docs/tests/S027-rules-clipboard-drop.md @@ -0,0 +1,42 @@ +# S027 — Rules, clipboard, drag and drop, drop target: test file + +Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. + +## Built +- `crates/core/src/rules.rs` · Rule, Item, `first`, `apply`, `expand` (name templates), `unique`/`free_name`, `glob`, `defaults`; unit tests inside. +- `crates/app/src/clipboard.rs` · `links` filter, `Watch` thread (arboard), `copy` marks own copies; one unit test inside. +- `crates/app/src/drop.rs` · `requests` (dropped paths to Add requests), `overlay` (full-window state). +- `crates/app/src/views/target.rs` · floating ring window with menu. `views/rules.rs` · rules page, editor, test box, clipboard note. Settings pages Rules and Clipboard (`views/settings/rows.rs`). `App::extras` wires all. +- `views/add/mod.rs` `tasks()` applies the rules. + +## Checks +| # | Risk | Do this | Expect | How | Result | +|---|---|---|---|---|---| +| 1 | HIGH | `nice cargo test -j 2 -p medlar-core rules` | all rules tests green | unit | — | +| 2 | HIGH | Template `{nope}x/../{name}` on `b%2Fc.tar.gz` | no path part in the result; `b_c.tar.gz` | unit | — | +| 3 | HIGH | Rule folder `../../etc` with base `/home/u/Downloads` | folder is `/home/u/Downloads/etc` | unit | — | +| 4 | MED | Two rules fit; disable the first | the second one counts | unit | — | +| 5 | MED | Size unknown against a rule with min 100 MB | the rule still fits | unit | — | +| 6 | MED | Add three links of the same template name `a.zip` | names `a.zip`, `a (2).zip`, `a (3).zip` | unit | — | +| 7 | MED | `nice cargo test -j 2 -p medlar clipboard` | filters by type and host work | unit | — | +| 8 | HIGH | Clipboard set to Ask, copy `https://a.test/x.zip` (X11/XWayland or data-control) | Add window opens with the link once; copying it again does nothing | by hand | — | +| 9 | HIGH | Clipboard Ask, press copy in Medlar (details value) | no Add window (own copy ignored) | by hand | — | +| 10 | MED | Clipboard Add, copy a link already in the list | nothing is added | by hand | — | +| 11 | MED | Clipboard Off, copy a link, then switch to Ask | the old copy is not offered | by hand | — | +| 12 | MED | Rules page: add default set, edit one, move, disable, delete and undo | list follows; undo brings it back; settings file keeps `rules` | screen | — | +| 13 | MED | Rules test box with `https://x.test/movie.mp4` | shows rule Video and folder below the download folder | screen | — | +| 14 | MED | Add dialog with a link that a rule catches, folder not touched | download lands in the rule's folder, queue and priority | screen | — | +| 15 | MED | Hidden run: drag a `.txt` list over the window | full-window drop state shows; on release Add opens with the list | screen | — | +| 16 | LOW | Drop target switch on, hidden nested niri | small ring window with speed; right click menu; Hide switches the setting off | screen | — | +| 17 | LOW | Old settings file without the new keys | opens with defaults (rules empty, clipboard off) | unit | — | + +## Needs +Throwaway `XDG_*` home; hidden niri via `tools/hidden.sh`; never the user's clipboard history. Clipboard checks need a compositor with data-control or XWayland. + +## Doubts +- Always-on-top is a hint; niri ignores it, no layer-shell used. The ring is an ordinary small window there. +- winit delivers dropped files as paths only; dragging a link from a browser may not arrive at all. +- The clipboard thread polls once a second even when no window is focused; on Wayland without data-control it does nothing and the page says so. +- The ring's menu grows the window instead of a popup (a popup would be clipped); sizes untested. +- Default rule names are English and not in the catalogue; rules apply only in the Add window path (also clipboard add), not CLI. +- Settings undo keys for new rows are by name only; existing settings tests that count pages or rows may need updating.