From a8c38788e15a0c48b3ab91c2e12eb5c11b14b469 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 26 Nov 2026 12:34:22 -0600 Subject: [PATCH] S046: placeholder names give way to the server's, raise on arrival, copy in fields --- crates/app/src/app.rs | 2 +- crates/app/src/keys.rs | 37 +++++++++++++++++++++++++++- crates/app/src/views/add/draw.rs | 1 + crates/app/src/views/add/mod.rs | 9 +++++++ crates/app/src/views/incoming.rs | 41 ++++++++++++++++++++++++++++---- crates/core/src/http/download.rs | 6 ++++- crates/core/src/http/mod.rs | 2 +- crates/core/src/http/name.rs | 29 ++++++++++++++++++++++ crates/core/tests/http.rs | 18 ++++++++++++++ 9 files changed, 137 insertions(+), 8 deletions(-) diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index fc22644..3d4388f 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -323,7 +323,7 @@ impl App { 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); + crate::views::incoming::raise(ctx); self.main.adding.ask(Request { text: links.join("\n"), literal: true, ..Request::default() }); } } diff --git a/crates/app/src/keys.rs b/crates/app/src/keys.rs index ccd944e..33ffc23 100644 --- a/crates/app/src/keys.rs +++ b/crates/app/src/keys.rs @@ -174,6 +174,11 @@ impl Shortcut { moves.contains(&self.key) && !self.alt || self.key == Key::Tab || self.ctrl && !self.alt && !self.shift && edits.contains(&self.key) } + /// Copy, select all and the other editing keys: a focused text field owns them. + fn edits(self) -> bool { + self.ctrl && !self.alt && [Key::A, Key::C, Key::V, Key::X, Key::Z].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::().is_ok()); @@ -253,7 +258,7 @@ pub fn label(action: Action) -> String { /// 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() { + if (keys.types() || keys.edits()) && ui.ctx().text_edit_focused() { return false; } ui.input_mut(|i| { @@ -282,6 +287,36 @@ mod tests { } } + #[test] + #[allow(deprecated)] + fn a_focused_field_keeps_copy_and_select_all() { + use eframe::egui::{Context, Id, RawInput, TextEdit}; + let ctx = Context::default(); + let mut text = String::from("abc"); + let id = Id::new("field"); + let mut run = |events: Vec, focus: bool| { + let mut got = (false, false); + let input = RawInput { events, ..RawInput::default() }; + let _ = ctx.run_ui(input, |ui| { + let r = ui.add(TextEdit::singleline(&mut text).id(id)); + if focus { + r.request_focus(); + } + got = (pressed(ui, Action::Copy), pressed(ui, Action::SelectAll)); + }); + got + }; + let ctrl = Modifiers::CTRL; + let keys = |k| vec![Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: ctrl }]; + run(vec![], true); + run(vec![], true); + assert_eq!(run(vec![Event::Copy], true), (false, false), "field has focus"); + assert_eq!(run(keys(Key::A), true), (false, false)); + ctx.memory_mut(|m| m.surrender_focus(id)); + run(vec![], false); + assert_eq!(run(vec![Event::Copy], false).0, true, "list copies without a field"); + } + #[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"] { diff --git a/crates/app/src/views/add/draw.rs b/crates/app/src/views/add/draw.rs index a419b52..5fd0518 100644 --- a/crates/app/src/views/add/draw.rs +++ b/crates/app/src/views/add/draw.rs @@ -112,6 +112,7 @@ impl Add { let r = field.show(ui, t, &mut self.name); if r.changed() { self.name_own = !self.name.trim().is_empty(); + self.name_typed = self.name_own; } } self.where_to(ui, t, cx, wrong); diff --git a/crates/app/src/views/add/mod.rs b/crates/app/src/views/add/mod.rs index d9fd6b8..f71248f 100644 --- a/crates/app/src/views/add/mod.rs +++ b/crates/app/src/views/add/mod.rs @@ -341,6 +341,8 @@ pub struct Add { pub name: String, /// The user wrote it. name_own: bool, + /// The user typed the name, so the server never replaces it. + name_typed: bool, rules: Vec, base: PathBuf, pub folder: String, @@ -403,6 +405,7 @@ impl Add { twice: Twice::Skip, name: from.name.clone().unwrap_or_default(), name_own: from.name.is_some(), + name_typed: false, rules: settings.rules.clone(), base: download_folder(settings), folder: download_folder(settings).display().to_string(), @@ -644,6 +647,12 @@ impl Add { pub fn learned(&mut self, found: Probed) { if !self.name_own { self.name = found.name.clone(); + } else if !self.name_typed { + // The name came with the link: a placeholder gives way to the server's. + if let Some(n) = medlar_core::http::prefer_name(self.name.trim(), &found.name) { + self.name = n; + self.name_own = false; + } } self.look = Look::Found(found); } diff --git a/crates/app/src/views/incoming.rs b/crates/app/src/views/incoming.rs index ab438fe..71c8b2d 100644 --- a/crates/app/src/views/incoming.rs +++ b/crates/app/src/views/incoming.rs @@ -9,7 +9,7 @@ use super::add::{Add, Checking, Request}; use super::main::Main; use crate::bridge::Data; use crate::views::connector; -use eframe::egui::{Context, ViewportCommand}; +use eframe::egui::{Context, UserAttentionType, ViewportCommand}; use medlar_core::connector::{Arrival, Connector, Incoming as Link}; use medlar_core::model::TaskId; use medlar_core::relink::{self, NewLink, Strength}; @@ -38,6 +38,16 @@ pub struct Inbox { /// Downloads that wait for a link, and the check of the one that came. waiting: Vec<(TaskId, String, Checking)>, failed: bool, + /// The window asked for attention and has not had focus since. + attention: bool, +} + +/// Brings the window forward, also from the tray. Where focus is refused (Wayland), it asks for attention. +pub fn raise(ctx: &Context) { + ctx.send_viewport_cmd(ViewportCommand::Visible(true)); + ctx.send_viewport_cmd(ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(ViewportCommand::Focus); + ctx.send_viewport_cmd(ViewportCommand::RequestUserAttention(UserAttentionType::Critical)); } impl Inbox { @@ -48,10 +58,15 @@ impl Inbox { /// Once per frame. pub fn tick(&mut self, ctx: &Context, s: &Settings, main: &mut Main) { + if self.attention && ctx.input(|i| i.focused) { + self.attention = false; + ctx.send_viewport_cmd(ViewportCommand::RequestUserAttention(UserAttentionType::Reset)); + } self.port(ctx, s, main); if let Some(args) = &self.args { while let Ok(list) = args.try_recv() { - ctx.send_viewport_cmd(ViewportCommand::Focus); + raise(ctx); + self.attention = true; self.pending.extend(list.iter().filter_map(|a| of_arg(a)).map(Item::Asked)); } } @@ -148,9 +163,14 @@ impl Inbox { self.waiting.retain(|(_, _, c)| c.busy()); } + fn raise(&mut self, ctx: &Context) { + raise(ctx); + self.attention = true; + } + fn ask(&mut self, ctx: &Context, main: &mut Main, request: Request) { if main.adding.now().is_none() { - ctx.send_viewport_cmd(ViewportCommand::Focus); + self.raise(ctx); } main.adding.ask(request); } @@ -200,6 +220,7 @@ impl Inbox { main.bridge.add(tasks, secrets); } main.toasts.info("download", tr!("incoming.added", n = n)); + self.raise(ctx); return; } self.ask(ctx, main, request); @@ -226,7 +247,19 @@ pub fn of_arg(arg: &str) -> Option { #[cfg(test)] mod tests { - use super::of_arg; + use super::{of_arg, raise}; + use eframe::egui::{Context, RawInput, UserAttentionType, ViewportCommand, ViewportId}; + + #[test] + fn raising_shows_focuses_and_asks_for_attention() { + let ctx = Context::default(); + let out = ctx.run_ui(RawInput::default(), |ui| raise(ui.ctx())); + let cmds = &out.viewport_output[&ViewportId::ROOT].commands; + assert!(cmds.contains(&ViewportCommand::Visible(true))); + assert!(cmds.contains(&ViewportCommand::Minimized(false))); + assert!(cmds.contains(&ViewportCommand::Focus)); + assert!(cmds.contains(&ViewportCommand::RequestUserAttention(UserAttentionType::Critical))); + } #[test] fn arguments() { diff --git a/crates/core/src/http/download.rs b/crates/core/src/http/download.rs index ed17d27..c1b5281 100644 --- a/crates/core/src/http/download.rs +++ b/crates/core/src/http/download.rs @@ -293,7 +293,11 @@ fn finished(p: &Part) -> bool { async fn start(shared: &Shared, job: &Job, task: &Task, probe: Probe, link: &Link, stop: &mut Stop) -> Result<(Arc, Vec)> { let hints = hints(shared, task, &probe, link, stop).await?; let parts = vec![Part { start: 0, end: probe.version.size.filter(|_| probe.ranges), done: 0 }]; - let wanted = safe_name(&task.name).unwrap_or(probe.name); + // A sender's name is a hint: the reply's own name wins over a placeholder like `output.bin`. + let wanted = match safe_name(&task.name) { + Some(hint) => name::prefer(&hint, &probe.name).unwrap_or(hint), + None => probe.name, + }; let (id, saved, folder) = (job.id, parts.clone(), task.folder.clone()); let file = job .run(move |store| { diff --git a/crates/core/src/http/mod.rs b/crates/core/src/http/mod.rs index f4a1c12..a9afc90 100644 --- a/crates/core/src/http/mod.rs +++ b/crates/core/src/http/mod.rs @@ -15,7 +15,7 @@ pub(crate) use download::is_page; pub(crate) use fetch::{bytes_at, same_body, small}; pub use fetch::{Link, OVERLAP, compare, fetch, same_bytes}; pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, ServerState, ServerView, Snapshot}; -pub use name::safe as safe_name; +pub use name::{prefer as prefer_name, safe as safe_name}; pub(crate) use piece::piece; pub use probe::{Probe, probe}; diff --git a/crates/core/src/http/name.rs b/crates/core/src/http/name.rs index c8ef1aa..57a3814 100644 --- a/crates/core/src/http/name.rs +++ b/crates/core/src/http/name.rs @@ -85,6 +85,24 @@ pub(super) fn pick(source: &Source, last: &Url, headers: &HeaderMap) -> String { } } +/// A name that says nothing: no extension, a page or script extension, bin, or a known placeholder. +fn placeholder(name: &str) -> bool { + let (stem, ext) = split(name); + let stem = stem.to_lowercase(); + if ["download", "file", "output", "index", "unknown", "get"].contains(&stem.as_str()) && ext.is_none_or(|e| e.eq_ignore_ascii_case("bin")) { + return true; + } + ext.is_none_or(|e| { + let e = e.to_lowercase(); + SCRIPTS.contains(&e.as_str()) || ["bin", "html", "htm", "download"].contains(&e.as_str()) + }) +} + +/// A name a sender gave is a hint. When it says nothing and the reply has a better one, that one. +pub fn prefer(hint: &str, found: &str) -> Option { + (placeholder(hint) && !placeholder(found)).then(|| found.to_string()) +} + /// `type/subtype` in lower case. pub(super) fn mime(headers: &HeaderMap) -> Option { let value = headers.get(CONTENT_TYPE)?.to_str().ok()?; @@ -275,6 +293,17 @@ mod tests { assert_eq!(picked(h, "http://[::1]/", ""), "__1"); } + #[test] + fn hints_give_way() { + assert_eq!(prefer("output.bin", "game.zip").as_deref(), Some("game.zip")); + assert_eq!(prefer("download", "a.iso").as_deref(), Some("a.iso")); + assert_eq!(prefer("get.php", "a.iso").as_deref(), Some("a.iso")); + assert_eq!(prefer("noext", "a.iso").as_deref(), Some("a.iso")); + assert_eq!(prefer("real.zip", "other.zip"), None); + assert_eq!(prefer("output.bin", "host.example.html"), None); + assert_eq!(prefer("output.bin", "file"), None); + } + #[test] fn safe_names() { for (name, want) in [ diff --git a/crates/core/tests/http.rs b/crates/core/tests/http.rs index b35fcf6..f11a01a 100644 --- a/crates/core/tests/http.rs +++ b/crates/core/tests/http.rs @@ -490,3 +490,21 @@ async fn kills_lose_nothing() { println!("{kills} kills, {files} files, {} MB kept over kills", kept / MB); assert!(kept > 0, "no kill came in the middle"); } + +/// S046: the name a sender gave is a hint; the reply's own name replaces a placeholder, never a real name. +#[tokio::test(flavor = "multi_thread")] +async fn a_placeholder_name_gives_way_to_the_servers() { + let b = Bench::new().await; + let add = |path: &str, name: &str| b.store.add_task(Task { url: b.server.url(path), name: name.into(), folder: b.folder(), ..Task::default() }).unwrap(); + let named = add("/data/4/300k/game.zip?disp=attachment", "output.bin"); + let moved = add("/redirect/1?to=/data/5/300k/other.iso", "download"); + let real = add("/data/6/300k/game2.zip?disp=attachment", "mine.bin"); + for id in [named, moved, real] { + b.run(id).await.unwrap(); + } + let name = |id| b.store.task(id).unwrap().name; + assert_eq!(name(named), "game.zip"); + assert_eq!(name(moved), "other.iso"); + assert_eq!(name(real), "mine.bin", "a name without a placeholder stays"); + assert!(b.folder().join("game.zip").exists() && !b.folder().join("output.bin").exists()); +}