misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Download windows: a slow drive no longer freezes them; the disk is asked beside the window (#743, #751) (#768)
Ahmed Nefzaoui415725d4c12b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a2c79593..aab09bb8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Fixed+- The download windows no longer freeze while a drive is slow to answer (a hard disk waking up, a USB drive, a network or mapped folder). **Download File Info** asked the disk whether its file's name was taken (to number it `(1)`) on the window's own thread, and so did **Show in folder**, **Open folder**, **Open** and the drag handle in **Download complete**, the question to create a missing folder, the look for files a torrent would write into, and the progress window's check of a folder for **Rename**; the window waited for the disk, 8 seconds and more in the reports. They now ask beside the window. Meanwhile Save As shows the name as it is, without `(1)`, and takes the numbered one when the answer comes; a download started before then is numbered as it starts, so nothing is overwritten ([#743](https://github.com/anefzaoui/misterdownloadmanager/issues/743), [#751](https://github.com/anefzaoui/misterdownloadmanager/issues/751)).- **Sizes for a stream's qualities:** HLS qualities showed no size; each is now estimated from its bitrate and the video's length, in the Download video window and in the download list.- **A video already in the list is no longer downloaded again without a word:** picking the same quality of the same video, from the menu over a video or the Download video window, now follows Options → Downloads ("If a duplicate download link is added": ask, a numbered name, overwrite, or open / resume the one there). Another quality of the same video is not a duplicate.- The progress window's bar glides as the download goes, instead of moving in steps four times a second.diff --git a/ROADMAP.md b/ROADMAP.mdindex 0d5faa74..9bb6c858 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -508,6 +508,11 @@ These ship in the next version.Scheduler's download limit is reached waits([#708](https://github.com/anefzaoui/misterdownloadmanager/issues/708))- ✅ The browser's Download video button in right-to-left languages: its corners and divider follow the text direction, so its outline stays whole+- ✅ A freeze of the download windows on a drive slow to answer (a sleeping disk, a USB drive, a+ network folder): Download File Info's numbered name, Show in folder, Download complete and+ creating a missing folder ask the disk beside the window+ ([#743](https://github.com/anefzaoui/misterdownloadmanager/issues/743),+ [#751](https://github.com/anefzaoui/misterdownloadmanager/issues/751))- ✅ **Deferred Rename** on a download's **Download status** tab: save a new name while downloading to rename the finished file's stem (and video subtitles) or an exclusive finished folder on completion, leaving shared/save or pre-existing folders, split-archive volumes and single-file torrents under their original names ([#655](https://github.com/anefzaoui/misterdownloadmanager/pull/655))- ✅ Links added by hand go with the User-Agent of your default browser, at the version you have(Chrome, Edge, Brave, Opera, Vivaldi, Firefox, Safari), instead of a years-old one; **Automatic**@@ -603,6 +608,10 @@ These ship in a later version, when they're ready.### Bugs being looked into+- 🔍 The main window's own looks at the disk on a drive slow to answer: starting or resuming a+ download that was already under way, a rename or move when one finishes, and links added+ without Download File Info still wait for it (follows+ [#743](https://github.com/anefzaoui/misterdownloadmanager/issues/743))- 🔄 The browser's video button over a video in a feed sending the feed's address, where yt-dlpfinds nothing (LinkedIn, Facebook, and other sites with feeds;[#689](https://github.com/anefzaoui/misterdownloadmanager/issues/689),diff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex c9193c47..15997896 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -1949,6 +1949,7 @@ impl App {);self.name_guessed(id, fi.name_guessed());self.set_direct(id, fi.direct);+ self.number_at_start(id);self.selection.set(id);if matches!(start, Start::Now) {// Later: the answer is closed (its download starts some other time).@@ -1970,10 +1971,13 @@ impl App {if !self.settings.start_immediately || fi.early.is_some() || !fi.probed() {return;}- let dest = fi.dest();- if !dest.parent().is_some_and(std::path::Path::is_dir) {- return; // a folder still to be created waits for the dialog's question+ // Once Save As has been looked at off the window's thread (#743): its name numbered in+ // its folder, and the folder there. A folder still to be created waits for the dialog's+ // question; a look still under way, for its answer.+ if fi.folder_found() != Some(true) {+ return;}+ let dest = fi.dest();let id = self.push_item(fi.url.clone(),dest,@@ -1989,6 +1993,7 @@ impl App {},);self.set_direct(id, fi.direct);+ self.number_at_start(id);fi.early = Some(id);if let Some(k) = fi.take_kept() {self.kept_answers.insert(id, k);@@ -2035,6 +2040,7 @@ impl App {dont_show: false,notices: i.notices.clone(),seen: false,+ opening: None,});}} else if !live {@@ -2096,6 +2102,8 @@ impl App {item.dest = dest;item.downloaded = 0;item.status = Status::Stopped;+ // Download File Info's place, given without waiting for the disk (#743).+ item.number_at_start = true;if start {self.start(id, true);}@@ -2157,6 +2165,15 @@ impl App {}}+ /// Download `id`'s name was given without waiting for its folder to be looked at (Download+ /// File Info, #743): it starts under it, or the next free numbered name if it is taken by+ /// then (`Item::number_at_start`).+ fn number_at_start(&mut self, id: u64) {+ if let Some(item) = self.item(id) {+ item.number_at_start = true;+ }+ }+/// Download `id`'s name is only its address's guess (`guessed`): the server names it when/// it starts (`Item::name_from_url`).fn name_guessed(&mut self, id: u64, guessed: bool) {@@ -3055,13 +3072,19 @@ impl App {// The file's own remembered limit, else the Speed Limiter's.opts.speed_limit = own_limit.or(self.settings.speed_limit());opts.checksum = checksum;- self.claim_place(id);+ // A new download from Download File Info has nothing of its own on the disk yet: nothing+ // to resume, and no place to claim from another row (the engine takes the next free+ // name as it starts). Its start never waits for the disk on the window's thread (#743).+ let fresh = self.item(id).is_some_and(|i| i.number_at_start);+ if !fresh {+ self.claim_place(id);+ }let Some(item) = self.item(id) else { return };let _guard = rt.enter();// Resume whenever there is something to resume. If that fails, say why and keep the// data: starting over would overwrite it, and that is only ever the user's choice.let state = state_path(&item.dest);- let dl = if state.exists() {+ let dl = if !fresh && state.exists() {match Download::resume(state, headers, opts) {Ok(dl) => dl,Err(e) => {@@ -3075,13 +3098,15 @@ impl App {} else {// Nothing to resume. A missing folder is created by the engine; a removed drive is// reported without touching the progress shown for the data on it.- if item.dest.parent().is_none_or(std::path::Path::is_dir) {+ if fresh || item.dest.parent().is_none_or(std::path::Path::is_dir) {item.downloaded = 0;}// A name nobody gave (the address's guess) is the server's to give: into the folder,- // under its Content-Disposition name (#28); the row follows the file made.+ // under its Content-Disposition name (#28); the row follows the file made. A name+ // given before its folder was looked at is numbered on there if it is taken (#743).let dest = match item.dest.parent() {Some(dir) if item.name_from_url => Destination::Dir(dir.to_owned()),+ _ if fresh => Destination::Free(item.dest.clone()),_ => Destination::File(item.dest.clone()),};Download::start_with(@@ -6696,6 +6721,7 @@ impl App {dont_show: false,notices: i.notices.clone(),seen: false,+ opening: None,});}}@@ -8380,6 +8406,7 @@ impl App {dont_show: false,notices: i.notices.clone(),seen: false,+ opening: None,});} else if i.live.is_none() {self.start(id, true);@@ -9827,14 +9854,39 @@ impl App {p.rename_disabled_reason = None;p.rename_guard_stamp = Some(rename_stamp);} else if p.rename_guard_stamp != Some(rename_stamp) {- p.rename_disabled_reason = deferred_rename_disabled_reason_with(- item,- &self.downloads,- &self.settings,- &self.rss,- &self.items,- );- p.rename_guard_stamp = Some(rename_stamp);+ // Looked at off the window's thread (#743), with copies of the rows' places.+ if p.rename_guard+ .as_ref()+ .is_none_or(|(s, _)| *s != rename_stamp)+ {+ let asked = crate::launch::Asked::default();+ let (item, items) = (+ item.place_copy(),+ self.items.iter().map(Item::place_copy).collect::<Vec<_>>(),+ );+ let (downloads, settings, rss) = (+ self.downloads.clone(),+ self.settings.clone(),+ self.rss.clone(),+ );+ let _ = asked.get(+ &rename_stamp,+ Duration::MAX,+ Duration::ZERO,+ Some(ctx),+ move |_| {+ deferred_rename_disabled_reason_with(+ &item, &downloads, &settings, &rss, &items,+ )+ },+ );+ p.rename_guard = Some((rename_stamp, asked));+ }+ if let Some(reason) = p.rename_guard.as_ref().and_then(|(s, a)| a.answer(s)) {+ p.rename_disabled_reason = reason;+ p.rename_guard_stamp = Some(rename_stamp);+ p.rename_guard = None;+ }}actions.push((p.id, p.show(ctx, item, item.snap.as_ref())));}diff --git a/crates/app/src/dialogs.rs b/crates/app/src/dialogs.rsindex c92ed702..34f343fb 100644--- a/crates/app/src/dialogs.rs+++ b/crates/app/src/dialogs.rs@@ -860,6 +860,141 @@ impl AddUrl {// ---- Download File Info (client 570 × 208) -------------------------------------------------+/// What Download File Info asks the disk about Save As (#743).+#[derive(Clone, Debug, PartialEq)]+pub(crate) struct PlaceAsk {+ pub dir: PathBuf,+ pub name: String,+ /// A name MDM gave: numbered on when it is taken there (`naming::destination`). A typed one+ /// only has its folder looked at (its download is numbered as it starts if it is taken).+ pub number: bool,+}++/// The disk's answer: where the download goes, and whether its folder is there.+#[derive(Clone, Debug, PartialEq)]+pub(crate) struct Found {+ pub dest: PathBuf,+ pub folder: bool,+}++/// How the disk is looked at: [`look`], or a test's slow one.+pub(crate) type Look = Arc<dyn Fn(&PlaceAsk) -> Found + Send + Sync>;++/// The engine's naming rules on the disk as it is now; on a thread of its own (it may wait).+fn look(ask: &PlaceAsk) -> Found {+ Found {+ dest: if ask.number {+ mdm_engine::naming::destination(&ask.dir, &ask.name)+ } else {+ ask.dir.join(&ask.name)+ },+ folder: ask.dir.is_dir(),+ }+}++/// Save As's place, looked at off the window's thread (#743, #751): a sleeping hard disk, a USB+/// drive or a network folder can take seconds to answer whether a name is taken, and the window+/// waited for it (the freeze report caught 8 s). Save As shows the name as given meanwhile+/// (fitted, without " (1)"), and takes the numbered one when the answer comes, unless it was+/// typed over. A download started before the answer is numbered as it starts+/// (`Destination::Free`, `Item::number_at_start`): nothing is overwritten either way.+pub(crate) struct SaveAsPlace {+ look: Look,+ repaint: Option<egui::Context>,+ /// The last question, Save As's text it is for (as the answer set it, once taken), and its+ /// answer to come. A new question asks on a thread of its own: one that hangs on a dead+ /// share holds up nothing else.+ asking: Option<(PlaceAsk, String, crate::launch::Asked<PlaceAsk, Found>)>,+}++impl SaveAsPlace {+ /// Looked at on the disk; `repaint` shows the answer when it comes.+ pub fn new(repaint: Option<&egui::Context>) -> Self {+ Self::with(Arc::new(look), repaint)+ }++ /// Looked at with `look` (a test's).+ pub fn with(look: Look, repaint: Option<&egui::Context>) -> Self {+ SaveAsPlace {+ look,+ repaint: repaint.cloned(),+ asking: None,+ }+ }++ /// `name` in `dir` as MDM names it: Save As's text for now (fitted, not numbered: no wait+ /// for the disk), its free numbered name asked for.+ pub fn name_in(&mut self, dir: &Path, name: &str) -> String {+ let shown = display_path(&mdm_engine::naming::guess(dir, name));+ let ask = PlaceAsk {+ dir: dir.to_owned(),+ name: name.to_owned(),+ number: true,+ };+ self.ask(ask, &shown);+ shown+ }++ fn ask(&mut self, ask: PlaceAsk, shown: &str) {+ if self+ .asking+ .as_ref()+ .is_some_and(|(a, s, _)| *a == ask && s == shown)+ {+ return;+ }+ let asked = crate::launch::Asked::default();+ let look = self.look.clone();+ // Never waits: the answer is taken on a later frame (`follow`).+ let _ = asked.get(+ &ask,+ std::time::Duration::MAX,+ std::time::Duration::ZERO,+ self.repaint.as_ref(),+ move |a| look(a),+ );+ self.asking = Some((ask, shown.to_owned(), asked));+ }++ /// Each frame, never waiting: once the answer has come for what Save As (`save_as`) still+ /// shows, a name MDM gave takes its free numbered name; whether its folder is there. None+ /// while it hasn't come, or when Save As was typed over since.+ pub fn follow(&mut self, save_as: &mut String) -> Option<bool> {+ let (ask, shown, asked) = self.asking.as_mut()?;+ if shown != save_as {+ return None;+ }+ let found = asked.answer(ask)?;+ if ask.number {+ *save_as = display_path(&found.dest);+ shown.clone_from(save_as);+ }+ Some(found.folder)+ }++ /// Whether Save As's folder is there, as looked at for the text it shows (None: not known+ /// yet). A path typed in Save As is asked about here, as it is (its folder only).+ pub fn folder(&mut self, save_as: &mut String) -> Option<bool> {+ if let Some(there) = self.follow(save_as) {+ return Some(there);+ }+ if self.asking.as_ref().is_some_and(|(_, s, _)| s == save_as) {+ return None; // asked: the answer is on its way+ }+ let dest = resolve_path(save_as);+ let (Some(dir), Some(name)) = (dest.parent(), dest.file_name()) else {+ return None;+ };+ let ask = PlaceAsk {+ dir: dir.to_owned(),+ name: name.to_string_lossy().into_owned(),+ number: false,+ };+ self.ask(ask, &save_as.clone());+ self.follow(save_as)+ }+}+pub struct FileInfo {pub url: Url,pub login: Option<(String, String)>,@@ -890,8 +1025,8 @@ pub struct FileInfo {category_open: bool,/// Browser request context for the download this dialog adds.pub context: mdm_ipc::Command,- /// Asking to create a missing folder, the dialog's choice held meanwhile.- asking: Option<(CreateFolder, Start)>,+ /// Start or Later held while the folder is looked at, and asked to be created when missing.+ asking: FolderGate<Start>,/// The download already running while the dialog shows (Options → Downloads → "Start/// downloading immediately while displaying Download File Info dialog").pub early: Option<u64>,@@ -919,6 +1054,9 @@ pub struct FileInfo {/// Whether Save As names a folder, looked at off the window's thread: it is asked every/// frame, and a folder on a network share that doesn't answer would freeze the window.dest_dir: crate::launch::Asked<PathBuf, bool>,+ /// Save As's name numbered in its folder, and whether the folder is there, looked at off the+ /// window's thread (#743).+ place: SaveAsPlace,}pub enum Start {@@ -954,7 +1092,8 @@ impl FileInfo {.unwrap_or_else(|| mdm_engine::naming::file_name(None, &new.url));let category = Category::of(&name);let folder = crate::model::category_folder(category, &downloads, &dirs);- let save_as = display_path(&mdm_engine::naming::destination(&folder, &name));+ let mut place = SaveAsPlace::new(Some(ctx));+ let save_as = place.name_in(&folder, &name);let (probe, info) = match from_browser {Some(file_name) => (Arc::new(Mutex::new(None)),@@ -974,6 +1113,7 @@ impl FileInfo {};FileInfo {dest_dir: Default::default(),+ place,url_text: new.url.to_string(),url_bad: false,focused: false,@@ -993,7 +1133,7 @@ impl FileInfo {dirs,category_open: false,context,- asking: None,+ asking: FolderGate::default(),early: None,folders: Vec::new(),folders_open: false,@@ -1050,7 +1190,7 @@ impl FileInfo {self.category = Category::of(&name);let dir =crate::model::category_folder(self.category, &self.downloads, &self.dirs);- self.save_as = display_path(&mdm_engine::naming::destination(&dir, &name));+ self.save_as = self.place.name_in(&dir, &name);}// Another address: the browser's name, size and form are not its own, and on// another site neither are its cookies and page (never sent there).@@ -1088,7 +1228,7 @@ impl FileInfo {.map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();// Fitted to the new folder too (#28): a deeper one leaves a long name less room.- self.save_as = display_path(&mdm_engine::naming::destination(folder, &name));+ self.save_as = self.place.name_in(folder, &name);self.edited = true;}@@ -1140,7 +1280,13 @@ impl FileInfo {.map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();let folder = crate::model::category_folder(c, &self.downloads, &self.dirs);- self.save_as = display_path(&mdm_engine::naming::destination(&folder, &name));+ self.save_as = self.place.name_in(&folder, &name);+ }++ /// Whether Save As's folder is there, as looked at off the window's thread for the name it+ /// shows now (None: not known yet). A name MDM gave has its free numbered name by then.+ pub fn folder_found(&mut self) -> Option<bool> {+ self.place.folder(&mut self.save_as)}/// The dialog; Start (or Download Later) waits for a missing folder to be created.@@ -1196,10 +1342,12 @@ impl FileInfo {if let (Ok(pi), false) = (&res, self.edited) {self.category = Category::of(&pi.file_name);let dir = crate::model::category_folder(self.category, &self.downloads, &self.dirs);- self.save_as = display_path(&mdm_engine::naming::destination(&dir, &pi.file_name));+ self.save_as = self.place.name_in(&dir, &pi.file_name);}self.info = Some(res);}+ // The name numbered in its folder, once the disk has answered (#743).+ self.place.follow(&mut self.save_as);self.follow_route(ctx);// The "Download through" line (#44) takes a row of its own while an account takes the// address: the window grows by it.@@ -1711,6 +1859,9 @@ pub struct Complete {/// Clicked (or activated) once: from then on a window like any other, no longer above every/// program's (it shows above them until then, as IDM's does: #77).pub seen: bool,+ /// Open was pressed: the file is looked for and handed to its program off the window's+ /// thread (#743); the box closes when it opened, and stays (for Open folder) when it didn't.+ pub opening: Option<crate::launch::Asked<PathBuf, bool>>,}impl Complete {@@ -1848,8 +1999,8 @@ impl Complete {if grip.hovered() {ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);}+ // The file is looked for beside the window, with the drag (#743).if grip.drag_started()- && self.path.exists()&& let Err(e) = crate::win32::drag_file_out(crate::i18n::t("Download complete"),&self.path,@@ -1877,10 +2028,26 @@ impl Complete {let dragging = crate::win32::dragging_out();#[cfg(not(windows))]let dragging = false; // the grip is Windows-only- // A file that can't open says why (the box stays for Open folder).+ // A file that can't open says why (the box stays for Open folder). Looked for and+ // handed over off the window's thread (#743): the box closes once it opened.+ let opened = self.opening.as_ref().and_then(|a| a.answer(&self.path));+ if opened.is_some() {+ self.opening = None;+ }if (open.clicked() || (!dragging && winui::enter_pressed(ui)))- && open_file(&self.path)+ && self.opening.is_none(){+ let opening = crate::launch::Asked::default();+ let _ = opening.get(+ &self.path,+ std::time::Duration::MAX,+ std::time::Duration::ZERO,+ Some(ui.ctx()),+ |p| open_file_now(p),+ );+ self.opening = Some(opening);+ }+ if opened == Some(true) {Outcome::Done(())} else if with.clicked() {open_with(&self.path);@@ -2560,10 +2727,19 @@ pub fn told() -> Vec<(&'static str, String)> {}/// Open a downloaded file with its program, or say why not (moved or deleted since, no-/// program for it): it did nothing at all. True when it was handed to the system. Waited for-/// (the `open` crate's launcher, at most 250 ms each on Windows and Linux), unlike-/// crate::launch's: whether it failed decides whether Download complete stays open.-pub fn open_file(path: &Path) -> bool {+/// program for it): on a thread of its own, as the file may be on a drive slow to answer+/// (#743). Returns at once.+pub fn open_file(path: &Path) {+ let path = path.to_owned();+ crate::launch::spawn("open file", move || {+ open_file_now(&path);+ });+}++/// [`open_file`], waited for: true when the file was handed to the system. For a thread other+/// than the window's (Download complete asks it through `launch::Asked`: whether it failed+/// decides whether the box stays open).+pub fn open_file_now(path: &Path) -> bool {let name = crate::i18n::isolate(&path.file_name().unwrap_or_default().to_string_lossy());let failed = if !path.exists() {crate::i18n::fmt(@@ -2585,7 +2761,17 @@ pub fn open_file(path: &Path) -> bool {false}+/// Show the file selected in the file manager (its folder, when the file is gone). Returns at+/// once: whether the file and its folder are there is looked at on a thread of its own, as a+/// sleeping hard disk, a USB drive or a network folder can take seconds to answer (#751: 8 s,+/// on the window's thread, froze it).pub fn show_in_folder(path: &Path) {+ let path = path.to_owned();+ crate::launch::spawn("show in folder", move || show_in_folder_now(&path));+}++/// [`show_in_folder`], on the thread it runs on.+fn show_in_folder_now(path: &Path) {#[cfg(windows)]{use std::os::windows::process::CommandExt;@@ -2967,6 +3153,8 @@ impl DeleteCategory {pub struct CreateFolder {folder: PathBuf,error: Option<String>,+ /// Yes was pressed: the folder is made off the window's thread (#743), its answer to come.+ making: Option<crate::launch::Asked<PathBuf, Result<(), String>>>,}impl CreateFolder {@@ -2974,6 +3162,7 @@ impl CreateFolder {CreateFolder {folder,error: None,+ making: None,}}@@ -3034,20 +3223,33 @@ impl CreateFolder {None,).clicked();+ // Made beside the window (#743): a drive slow to answer doesn't hold it.+ let made = self.making.as_ref().and_then(|m| m.answer(&self.folder));+ if made.is_some() {+ self.making = None;+ }+ if let Some(Err(e)) = &made {+ self.error = Some(crate::i18n::fmt(+ crate::i18n::t("The folder could not be created: {error}"),+ &[("error", e)],+ ));+ }if no || winui::escape_pressed(ui) {Outcome::Closed- } else if yes || winui::enter_pressed(ui) {- match std::fs::create_dir_all(&self.folder) {- Ok(()) => Outcome::Done(()),- Err(e) => {- self.error = Some(crate::i18n::fmt(- crate::i18n::t("The folder could not be created: {error}"),- &[("error", &e.to_string())],- ));- Outcome::Open- }- }+ } else if made == Some(Ok(())) {+ Outcome::Done(())} else {+ if (yes || winui::enter_pressed(ui)) && self.making.is_none() {+ let making = crate::launch::Asked::default();+ let _ = making.get(+ &self.folder,+ std::time::Duration::MAX,+ std::time::Duration::ZERO,+ Some(ui.ctx()),+ |f| std::fs::create_dir_all(f).map_err(|e| e.to_string()),+ );+ self.making = Some(making);+ }Outcome::Open}},@@ -3184,80 +3386,151 @@ impl ExistingFiles {}}-/// Holds a dialog's "start" (`out`) while files the torrent would write into already exist-/// (`found`, looked for once, when the dialog says start): asks [`ExistingFiles`] and keeps the-/// result meanwhile; No goes back to the dialog. `asking` lives in the dialog, across frames.-pub fn ensure_files_free<T>(- ctx: &egui::Context,- asking: &mut Option<(ExistingFiles, T)>,- out: Outcome<T>,- found: impl FnOnce() -> Vec<PathBuf>,-) -> Outcome<T> {- match out {- Outcome::Closed => {- *asking = None;- return Outcome::Closed;+/// A dialog's "start" (`T`) held while what it would start into is looked at on the disk, off+/// the window's thread (#743: a sleeping hard disk, a USB drive or a network folder can take+/// seconds to answer, and the window waited for it; the dialog stays as it is meanwhile), then+/// while a question about it (`Q`) is up. Lives in the dialog, across frames.+pub struct Gate<T, A, Q> {+ held: Option<T>,+ /// Where it was looked at, and the answer (`A`) to come.+ look: Option<(PathBuf, crate::launch::Asked<PathBuf, A>)>,+ question: Option<Q>,+}++/// [`ensure_folder`]'s: whether the folder is there; Create folder.+pub type FolderGate<T> = Gate<T, bool, CreateFolder>;++/// [`ensure_files_free`]'s: the torrent's files found there; Existing files.+pub type FilesGate<T> = Gate<T, Vec<PathBuf>, ExistingFiles>;++impl<T, A, Q> Default for Gate<T, A, Q> {+ fn default() -> Self {+ Gate {+ held: None,+ look: None,+ question: None,}- Outcome::Done(v) if asking.is_none() => {- let found = found();- if found.is_empty() {- return Outcome::Done(v);+ }+}++impl<T, A: Clone + PartialEq + Send + 'static, Q> Gate<T, A, Q> {+ /// The dialog's "start", let go: the gate starts over.+ fn release(&mut self) -> Outcome<T> {+ let held = self.held.take();+ *self = Gate::default();+ held.map_or(Outcome::Open, Outcome::Done)+ }++ /// `out` held until `at` has been looked at with `look` (made only when asked; it runs on+ /// a thread of its own) and the question `ask` makes of the answer (None: nothing to ask)+ /// was answered Yes by `show`. No goes back to the dialog.+ fn pass<L: FnOnce(&PathBuf) -> A + Send + 'static>(+ &mut self,+ ctx: &egui::Context,+ out: Outcome<T>,+ at: &Path,+ look: impl FnOnce() -> L,+ ask: impl FnOnce(A) -> Option<Q>,+ show: impl FnOnce(&mut Q, &egui::Context) -> Outcome<()>,+ ) -> Outcome<T> {+ match out {+ Outcome::Closed => {+ *self = Gate::default();+ return Outcome::Closed;}- *asking = Some((ExistingFiles::new(&found), v));+ Outcome::Done(v) if self.held.is_none() => self.held = Some(v),+ // While it is looked at, or the question is up, the dialog's own "start" waits.+ _ => {}}- _ => {}- }- let Some((ask, _)) = asking.as_mut() else {- return Outcome::Open;- };- match ask.show(ctx) {- Outcome::Open => Outcome::Open,- Outcome::Closed => {- *asking = None;- Outcome::Open+ if self.held.is_none() {+ return Outcome::Open;+ }+ if self.question.is_none() {+ // Asked once for each place (the dialog's folder may change meanwhile); never waited.+ if self.look.as_ref().is_none_or(|(p, _)| p != at) {+ let asked = crate::launch::Asked::default();+ let _ = asked.get(+ &at.to_owned(),+ std::time::Duration::MAX,+ std::time::Duration::ZERO,+ Some(ctx),+ look(),+ );+ self.look = Some((at.to_owned(), asked));+ }+ let found = self.look.as_ref().and_then(|(p, a)| a.answer(p));+ match found.map(ask) {+ None => return Outcome::Open,+ Some(None) => return self.release(),+ Some(question) => self.question = question,+ }+ }+ let Some(question) = self.question.as_mut() else {+ return Outcome::Open;+ };+ match show(question, ctx) {+ Outcome::Open => Outcome::Open,+ Outcome::Closed => {+ *self = Gate::default();+ Outcome::Open+ }+ Outcome::Done(()) => self.release(),}- Outcome::Done(()) => asking- .take()- .map_or(Outcome::Open, |(_, v)| Outcome::Done(v)),}}-/// Holds a dialog's "start" (`out`) until `folder` exists: when it is missing, asks to create-/// it ([`CreateFolder`]) and keeps the dialog's result meanwhile; No goes back to the dialog.-/// `asking` lives in the dialog, across frames.+/// Holds a dialog's "start" (`out`) while files the torrent would write into already exist in+/// `folder` (looked for when the dialog says start, off the window's thread, by what `found`+/// makes): asks [`ExistingFiles`] and keeps the result meanwhile; No goes back to the dialog.+/// `gate` lives in the dialog, across frames.+pub fn ensure_files_free<T, F: FnOnce() -> Vec<PathBuf> + Send + 'static>(+ ctx: &egui::Context,+ gate: &mut FilesGate<T>,+ out: Outcome<T>,+ folder: &Path,+ found: impl FnOnce() -> F,+) -> Outcome<T> {+ gate.pass(+ ctx,+ out,+ folder,+ || {+ let found = found();+ move |_: &PathBuf| found()+ },+ |found| (!found.is_empty()).then(|| ExistingFiles::new(&found)),+ ExistingFiles::show,+ )+}++/// Holds a dialog's "start" (`out`) until `folder` exists: looked at off the window's thread,+/// and when it is missing, asks to create it ([`CreateFolder`]); No goes back to the dialog.+/// `gate` lives in the dialog, across frames.pub fn ensure_folder<T>(ctx: &egui::Context,- asking: &mut Option<(CreateFolder, T)>,+ gate: &mut FolderGate<T>,out: Outcome<T>,folder: &Path,) -> Outcome<T> {- match out {- Outcome::Closed => {- *asking = None;- return Outcome::Closed;- }- Outcome::Done(v) if asking.is_none() => {- if folder.as_os_str().is_empty() || folder.is_dir() {- return Outcome::Done(v);- }- *asking = Some((CreateFolder::new(folder.to_owned()), v));- }- // While the question is up the dialog's own "start" waits for the answer.- _ => {}- }- let Some((ask, _)) = asking.as_mut() else {- return Outcome::Open;- };- match ask.show(ctx) {- Outcome::Open => Outcome::Open,- Outcome::Closed => {- *asking = None;- Outcome::Open- }- Outcome::Done(()) => asking- .take()- .map_or(Outcome::Open, |(_, v)| Outcome::Done(v)),- }+ ensure_folder_with(ctx, gate, out, folder, |f| f.is_dir())+}++/// [`ensure_folder`], the folder looked at with `is_dir` (a test's).+fn ensure_folder_with<T>(+ ctx: &egui::Context,+ gate: &mut FolderGate<T>,+ out: Outcome<T>,+ folder: &Path,+ is_dir: impl FnOnce(&Path) -> bool + Send + 'static,+) -> Outcome<T> {+ gate.pass(+ ctx,+ out,+ folder,+ || move |f: &PathBuf| f.as_os_str().is_empty() || is_dir(f.as_path()),+ |there| (!there).then(|| CreateFolder::new(folder.to_owned())),+ CreateFolder::show,+ )}#[cfg(test)]@@ -3630,4 +3903,181 @@ mod tests {"the pass that closes the dialog paints it as the one before");}++ /// A look at the disk that waits until the test lets it go (a sleeping drive, a network+ /// folder that answers late); then answers as the engine would on `taken` names.+ fn slow_look(taken: &'static [&'static str]) -> (Look, std::sync::mpsc::Sender<()>) {+ let (release, stuck) = std::sync::mpsc::channel::<()>();+ let stuck = Mutex::new(stuck);+ let look: Look = Arc::new(move |ask: &PlaceAsk| {+ // Released once: every look after it answers at once.+ let _ = stuck.lock().unwrap().recv();+ let mut name = ask.name.clone();+ if ask.number {+ let (stem, ext) = ask.name.rsplit_once('.').unwrap_or((ask.name.as_str(), ""));+ let ext = if ext.is_empty() {+ String::new()+ } else {+ format!(".{ext}")+ };+ let mut n = 0;+ while taken.contains(&name.as_str()) {+ n += 1;+ name = format!("{stem} ({n}){ext}");+ }+ }+ Found {+ dest: ask.dir.join(name),+ folder: true,+ }+ });+ (look, release)+ }++ /// Wait (at most 5 s) until `place` answers for `save_as`.+ fn answered(place: &mut SaveAsPlace, save_as: &mut String) -> Option<bool> {+ let until = std::time::Instant::now() + std::time::Duration::from_secs(5);+ while std::time::Instant::now() < until {+ if let Some(there) = place.follow(save_as) {+ return Some(there);+ }+ std::thread::sleep(std::time::Duration::from_millis(2));+ }+ None+ }++ /// #743: a disk that doesn't answer holds up no frame of Download File Info. Save As shows+ /// the name as given (no " (1)": not known yet), and takes the free numbered one when the+ /// answer comes at last.+ #[test]+ fn a_disk_that_never_answers_holds_up_no_frame() {+ let dir = std::env::temp_dir().join("mdm-743-slow");+ let (look, release) = slow_look(&["a.zip"]);+ let mut place = SaveAsPlace::with(look, None);+ let started = std::time::Instant::now();+ let mut save_as = place.name_in(&dir, "a.zip");+ assert_eq!(save_as, display_path(&dir.join("a.zip")), "the guess");+ for _ in 0..1000 {+ assert_eq!(place.follow(&mut save_as), None);+ assert_eq!(place.folder(&mut save_as), None, "not known yet");+ }+ assert!(+ started.elapsed() < std::time::Duration::from_millis(500),+ "{:?} for 1000 frames",+ started.elapsed()+ );+ assert_eq!(save_as, display_path(&dir.join("a.zip")), "still the guess");+ // The disk answers: the name is taken there.+ drop(release);+ assert_eq!(answered(&mut place, &mut save_as), Some(true));+ assert_eq!(save_as, display_path(&dir.join("a (1).zip")));+ // Asked once: the next frames keep it.+ assert_eq!(place.folder(&mut save_as), Some(true));+ assert_eq!(save_as, display_path(&dir.join("a (1).zip")));+ }++ /// An answer comes for the text it was asked for only: Save As typed over meanwhile keeps+ /// what was typed, and a new name asked for (another folder) drops the old question's.+ #[test]+ fn a_late_answer_never_replaces_what_was_typed_or_picked_since() {+ let dir = std::env::temp_dir().join("mdm-743-typed");+ let (look, release) = slow_look(&["a.zip", "b.zip"]);+ let mut place = SaveAsPlace::with(look, None);+ let _guess = place.name_in(&dir, "a.zip");+ // Typed over before the disk answered.+ let mut save_as = display_path(&dir.join("mine.zip"));+ drop(release);+ std::thread::sleep(std::time::Duration::from_millis(50));+ assert_eq!(place.follow(&mut save_as), None);+ assert_eq!(save_as, display_path(&dir.join("mine.zip")), "typed: kept");+ // Typed text has its folder looked at, as typed (never numbered here).+ let mut there = None;+ let until = std::time::Instant::now() + std::time::Duration::from_secs(5);+ while there.is_none() && std::time::Instant::now() < until {+ there = place.folder(&mut save_as);+ std::thread::sleep(std::time::Duration::from_millis(2));+ }+ assert_eq!(there, Some(true));+ assert_eq!(save_as, display_path(&dir.join("mine.zip")));+ // Another name: its own answer, not the last one's.+ let other = dir.join("elsewhere");+ save_as = place.name_in(&other, "b.zip");+ assert_eq!(answered(&mut place, &mut save_as), Some(true));+ assert_eq!(save_as, display_path(&other.join("b (1).zip")));+ }++ /// The real look follows the engine's rules: a name taken on the disk (a file, another+ /// download's part file) is numbered on, the folder said there or not.+ #[test]+ fn the_look_numbers_as_the_engine_does() {+ let d = tempfile::tempdir().unwrap();+ std::fs::write(d.path().join("a.zip"), b"x").unwrap();+ std::fs::write(+ mdm_engine::naming::part_path(&d.path().join("a (1).zip")),+ b"x",+ )+ .unwrap();+ let mut place = SaveAsPlace::new(None);+ let mut save_as = place.name_in(d.path(), "a.zip");+ assert_eq!(answered(&mut place, &mut save_as), Some(true));+ assert_eq!(save_as, display_path(&d.path().join("a (2).zip")));+ assert_eq!(+ resolve_path(&save_as),+ mdm_engine::naming::destination(d.path(), "a.zip")+ );+ let gone = d.path().join("not-there");+ let mut save_as = place.name_in(&gone, "a.zip");+ assert_eq!(answered(&mut place, &mut save_as), Some(false));+ assert_eq!(save_as, display_path(&gone.join("a.zip")));+ }++ /// #743: Start in a dialog whose folder is on a disk slow to answer holds up no frame: the+ /// dialog stays as it is until the answer comes, then goes on with what Start said.+ #[test]+ fn start_waits_for_the_folder_without_holding_up_a_frame() {+ let ctx = egui::Context::default();+ let (release, stuck) = std::sync::mpsc::channel::<()>();+ let mut gate = FolderGate::<u32>::default();+ let folder = std::env::temp_dir().join("mdm-743-gate");+ let started = std::time::Instant::now();+ let is_dir = move |_: &Path| {+ let _ = stuck.recv();+ true+ };+ let first = ensure_folder_with(&ctx, &mut gate, Outcome::Done(7), &folder, is_dir);+ assert!(matches!(first, Outcome::Open));+ for _ in 0..1000 {+ // A second Start meanwhile changes nothing; nor does a frame without one.+ let again = ensure_folder_with(&ctx, &mut gate, Outcome::Done(8), &folder, |_| {+ unreachable!("looked at once")+ });+ assert!(matches!(again, Outcome::Open));+ }+ assert!(+ started.elapsed() < std::time::Duration::from_millis(500),+ "{:?}",+ started.elapsed()+ );+ drop(release);+ let until = std::time::Instant::now() + std::time::Duration::from_secs(5);+ let done = loop {+ match ensure_folder_with(&ctx, &mut gate, Outcome::Open, &folder, |_| {+ unreachable!("looked at once")+ }) {+ Outcome::Done(v) => break Some(v),+ _ if std::time::Instant::now() > until => break None,+ _ => std::thread::sleep(std::time::Duration::from_millis(2)),+ }+ };+ assert_eq!(done, Some(7), "the first Start's");+ // Let go: the next Start is looked at afresh.+ let next = ensure_folder_with(&ctx, &mut gate, Outcome::Done(9), &folder, |_| true);+ let until = std::time::Instant::now() + std::time::Duration::from_secs(5);+ let mut next = next;+ while !matches!(next, Outcome::Done(_)) && std::time::Instant::now() < until {+ std::thread::sleep(std::time::Duration::from_millis(2));+ next = ensure_folder_with(&ctx, &mut gate, Outcome::Open, &folder, |_| true);+ }+ assert!(matches!(next, Outcome::Done(9)));+ }}diff --git a/crates/app/src/gallerydlg.rs b/crates/app/src/gallerydlg.rsindex fdc803c7..ab098ce5 100644--- a/crates/app/src/gallerydlg.rs+++ b/crates/app/src/gallerydlg.rs@@ -35,7 +35,7 @@ pub struct GalleryDialog {checked: Option<(String, bool)>,error: Option<String>,start_now: Option<bool>,- asking: Option<(crate::dialogs::CreateFolder, ())>,+ asking: crate::dialogs::FolderGate<()>,helpers: Option<crate::helpers::Programs>,/// The helper as found (read again after an install or Helpers, not every frame).tool: Option<Option<mdm_tools::Installed>>,@@ -58,7 +58,7 @@ impl GalleryDialog {checked: None,error: None,start_now: None,- asking: None,+ asking: Default::default(),helpers: None,tool: None,}diff --git a/crates/app/src/launch.rs b/crates/app/src/launch.rsindex 9430408b..d1ee548b 100644--- a/crates/app/src/launch.rs+++ b/crates/app/src/launch.rs@@ -38,13 +38,17 @@ pub fn run_detached_with_fallback(/// and Linux, until it exits on macOS).pub fn open(target: impl AsRef<OsStr>) {let target = target.as_ref().to_owned();- let started = std::thread::Builder::new()- .name("launch".into())- .spawn(move || {- let _ = open::that_detached(&target);- });- if let Err(e) = started {- tracing::warn!("open: no thread to run it on: {e}");+ spawn("launch", move || {+ let _ = open::that_detached(&target);+ });+}++/// Run `job` on a thread of its own named `name`, and return at once: for what a window hands+/// over that may wait (a program, a file on a sleeping hard disk, a USB drive or a network+/// folder: #743, #751).+pub fn spawn(name: &str, job: impl FnOnce() + Send + 'static) {+ if let Err(e) = std::thread::Builder::new().name(name.into()).spawn(job) {+ tracing::warn!("{name}: no thread to run it on: {e}");}}@@ -145,6 +149,16 @@ where.0;}}++ /// The answer for `key` if it came; never asks, never waits (a window that asked once, with+ /// [`Asked::get`], and looks for its answer each frame after).+ pub fn answer(&self, key: &K) -> Option<T> {+ let s = self.shared.0.lock().unwrap_or_else(|e| e.into_inner());+ s.answer+ .as_ref()+ .filter(|(k, _, _)| k == key)+ .map(|(_, v, _)| v.clone())+ }}/// Run `cmd` quietly, waiting at most `limit` for it: true when it ran and succeeded. One thatdiff --git a/crates/app/src/model.rs b/crates/app/src/model.rsindex 054e0e53..51f97574 100644--- a/crates/app/src/model.rs+++ b/crates/app/src/model.rs@@ -395,6 +395,12 @@ pub struct Item {/// Content-Disposition), as a browser does (#28). Cleared once the file is made.#[serde(default, skip_serializing_if = "std::ops::Not::not")]pub name_from_url: bool,+ /// Its name was given without waiting for its folder to be looked at (Download File Info:+ /// a sleeping drive or a network folder can take seconds to answer, #743): nothing of its+ /// own is on the disk yet, and it starts under that name or the next free numbered one, as+ /// the engine finds as it starts (`Destination::Free`). Cleared once the file is made.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub number_at_start: bool,/// The Link grabber package it came in (#37): its archives are extracted together once/// every volume is there.#[serde(default, skip_serializing_if = "Option::is_none")]@@ -720,6 +726,22 @@ impl Item {.join("\n")}+ /// What tells where this row's files are (its place, its kind, the files it wrote), for a+ /// look at the disk on a thread other than the window's (#743): no live download, no log.+ pub fn place_copy(&self) -> Item {+ let mut c = Item::new(self.id, self.url.clone(), self.dest.clone(), self.category);+ c.file_name.clone_from(&self.file_name);+ c.status = self.status;+ c.downloaded = self.downloaded;+ c.video.clone_from(&self.video);+ c.torrent.clone_from(&self.torrent);+ c.gallery.clone_from(&self.gallery);+ c.remote.clone_from(&self.remote);+ c.preexisting_folder = self.preexisting_folder;+ c.written_files.clone_from(&self.written_files);+ c+ }+/// A new, not yet started download (queued state, nothing on disk).pub fn new(id: u64, url: Url, dest: PathBuf, category: Category) -> Self {Item {@@ -746,6 +768,7 @@ impl Item {gallery: None,log: Vec::new(),name_from_url: false,+ number_at_start: false,package: None,server: None,direct: false,@@ -801,8 +824,9 @@ impl Item {self.size = size_after(s.state, s.size, s.downloaded, self.size);self.resumable = s.resumable.or(self.resumable);if let Some(f) = &s.file {- // Named now: a later start from scratch keeps this name.+ // Named now: a later start from scratch keeps this name, and its file is its own.let guessed = std::mem::take(&mut self.name_from_url);+ self.number_at_start = false;if *f != self.dest {// The file as saved (a video's real extension, a numbered duplicate, the name// the server gave).diff --git a/crates/app/src/progress.rs b/crates/app/src/progress.rsindex 05fca555..69f0976d 100644--- a/crates/app/src/progress.rs+++ b/crates/app/src/progress.rs@@ -335,6 +335,10 @@ pub struct Progress {/// In-memory state stamp for `rename_disabled_reason`, so disk checks run only when the/// window opens, when a download completes, or when list/folder settings change.pub rename_guard_stamp: Option<u64>,+ /// Those disk checks, under way off the window's thread for a newer stamp (#743): a folder+ /// on a sleeping drive or a network share can take seconds to answer. The reason shown+ /// stays the last one meanwhile (the rename is checked again when it is carried out).+ pub rename_guard: Option<(u64, crate::launch::Asked<u64, Option<&'static str>>)>,}pub enum Action {@@ -402,6 +406,7 @@ impl Progress {pending_rename: None,rename_disabled_reason: None,rename_guard_stamp: None,+ rename_guard: None,}}diff --git a/crates/app/src/torrentdlg.rs b/crates/app/src/torrentdlg.rsindex a8141df6..bb1c1365 100644--- a/crates/app/src/torrentdlg.rs+++ b/crates/app/src/torrentdlg.rs@@ -78,9 +78,9 @@ pub struct TorrentDialog {/// Download in order (#39).in_order: bool,/// Asking to create a missing folder.- asking: Option<(crate::dialogs::CreateFolder, ())>,+ asking: crate::dialogs::FolderGate<()>,/// Asking whether to use files of the torrent's names already in the folder (#40).- asking_files: Option<(crate::dialogs::ExistingFiles, ())>,+ asking_files: crate::dialogs::FilesGate<()>,/// A .torrent on the web (#39, Add URL or the browser): the request it is fetched with/// (the browser's cookies). One typed in the box goes as MDM's own downloads do.remote: Option<crate::torrents::Remote>,@@ -249,8 +249,8 @@ impl TorrentDialog {focused: false,start_now: None,in_order: false,- asking: None,- asking_files: None,+ asking: Default::default(),+ asking_files: Default::default(),remote,clip,};@@ -400,11 +400,13 @@ impl TorrentDialog {let folder = crate::dialogs::resolve_path(&self.folder);let out = crate::dialogs::ensure_folder(ctx, &mut self.asking, out, &folder);// Then: files of the torrent's names already there would be written into (#40).+ // Looked for off the window's thread (#743), with what the torrent holds as it is now.let meta = &self.meta;- let out = crate::dialogs::ensure_files_free(ctx, &mut self.asking_files, out, || {- meta.as_ref()- .map_or_else(Vec::new, |m| m.existing_in(&folder))- });+ let out =+ crate::dialogs::ensure_files_free(ctx, &mut self.asking_files, out, &folder, || {+ let (meta, there) = (meta.clone(), folder.clone());+ move || meta.map_or_else(Vec::new, |m| m.existing_in(&there))+ });match out {Outcome::Open => Outcome::Open,Outcome::Closed => Outcome::Closed,diff --git a/crates/app/src/videodlg.rs b/crates/app/src/videodlg.rsindex 912a15d5..60d13732 100644--- a/crates/app/src/videodlg.rs+++ b/crates/app/src/videodlg.rs@@ -90,7 +90,7 @@ pub struct VideoDialog {/// Look the page up as soon as yt-dlp is there (opened from Add URL).auto_look: bool,/// Asking to create a missing folder.- asking: Option<(crate::dialogs::CreateFolder, ())>,+ asking: crate::dialogs::FolderGate<()>,/// Helpers...: where yt-dlp and ffmpeg come from (#51).helpers: Option<crate::helpers::Programs>,/// The looked-up video's subtitle languages (#68) and the one chosen in the Subtitles list@@ -187,7 +187,7 @@ impl VideoDialog {focused: false,start_now: None,auto_look: false,- asking: None,+ asking: Default::default(),helpers: None,subs: Vec::new(),sub_pick: 0,diff --git a/crates/app/src/win32.rs b/crates/app/src/win32.rsindex c4f15d66..da7dfe35 100644--- a/crates/app/src/win32.rs+++ b/crates/app/src/win32.rs@@ -2552,7 +2552,12 @@ pub fn drag_file_out(title: &str, file: &std::path::Path) -> Result<(), String>if !shared {tracing::warn!("drag out: the window's input isn't shared");}- let result = drag_on_this_thread(hwnd as HWND, &file);+ // Looked for here, beside the window (#743): a drive slow to answer doesn't hold it.+ let result = if file.exists() {+ drag_on_this_thread(hwnd as HWND, &file)+ } else {+ Ok(())+ };if let Ok(mut t) = DRAG_ENDED.lock() {*t = Some(std::time::Instant::now());}diff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rsindex 43027f6f..36de43aa 100644--- a/crates/engine/src/download.rs+++ b/crates/engine/src/download.rs@@ -280,6 +280,10 @@ pub enum Destination {Dir(PathBuf),/// Save exactly here.File(PathBuf),+ /// Save here, or under the next free numbered name in its folder (`naming::unique_path`)+ /// when this one is taken as the download starts: a name given before its folder was looked+ /// at (#743: a window that waits for a sleeping drive freezes), decided here, beside it.+ Free(PathBuf),}#[derive(Clone, Debug)]@@ -1945,11 +1949,13 @@ async fn open_destination() -> Result<(PathBuf, naming::Reservation, File), Error> {// The folder must exist: we create it, but a removed drive or offline share can't be.let folder = match dest {- Destination::File(p) => p.parent().unwrap_or(Path::new("")).to_owned(),+ Destination::File(p) | Destination::Free(p) => {+ p.parent().unwrap_or(Path::new("")).to_owned()+ }Destination::Dir(dir) => dir.clone(),};std::fs::create_dir_all(&folder).map_err(|_| Error::DestinationUnavailable(folder.clone()))?;- if let Destination::File(p) = dest+ if let Destination::File(p) | Destination::Free(p) = dest&& !naming::path_fits(p){return Err(Error::PathTooLong(p.clone()));@@ -1977,24 +1983,12 @@ async fn open_destination(// Shortened to fit Windows' path limit; a folder too deep for any name is an error.let name =naming::fit_name(dir, &name).ok_or_else(|| Error::PathTooLong(dir.join(&name)))?;- let mut attempt = 0;- loop {- let dest = naming::unique_path(dir, &name);- if let Some(r) = naming::reserve(&dest) {- // Read too: reconnecting connections re-read their last bytes (overlap check).- match std::fs::OpenOptions::new()- .read(true)- .write(true)- .create_new(true)- .open(naming::part_path(&dest))- {- Ok(file) => break (dest, r, file),- Err(e) if e.kind() == io::ErrorKind::AlreadyExists && attempt < 100 => {}- Err(e) => return Err(e.into()),- }- }- attempt += 1;- }+ claim_free(dir, &name)?+ }+ Destination::Free(p) => {+ let dir = p.parent().unwrap_or(Path::new(""));+ let name = p.file_name().unwrap_or_default().to_string_lossy();+ claim_free(dir, &name)?}};// Before any data: a mark the hook sets (Mark of the Web, quarantine) is on the file from@@ -2012,6 +2006,29 @@ async fn open_destination(Ok((dest, reservation, file))}+/// `name` in `dir`, or the next free numbered name (`naming::unique_path`): reserved in this+/// process, its part file created exclusively (another program may take the name meanwhile).+fn claim_free(dir: &Path, name: &str) -> Result<(PathBuf, naming::Reservation, File), Error> {+ let mut attempt = 0;+ loop {+ let dest = naming::unique_path(dir, name);+ if let Some(r) = naming::reserve(&dest) {+ // Read too: reconnecting connections re-read their last bytes (overlap check).+ match std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create_new(true)+ .open(naming::part_path(&dest))+ {+ Ok(file) => return Ok((dest, r, file)),+ Err(e) if e.kind() == io::ErrorKind::AlreadyExists && attempt < 100 => {}+ Err(e) => return Err(e.into()),+ }+ }+ attempt += 1;+ }+}+/// The download has its file and is receiving it.fn downloading(shared: &Shared, dest: &Path, size: Option<u64>, ranges: u8) {let mut v = shared.view.lock().unwrap();@@ -3496,7 +3513,7 @@ pub(crate) fn named(h: &HeaderMap) -> bool {/// Where a download is saved under a name of its own (the browser's, the user's), that name.fn dest_name(dest: &Destination) -> Option<&str> {match dest {- Destination::File(p) => p.file_name().and_then(|n| n.to_str()),+ Destination::File(p) | Destination::Free(p) => p.file_name().and_then(|n| n.to_str()),Destination::Dir(_) => None,}}diff --git a/crates/engine/src/naming.rs b/crates/engine/src/naming.rsindex 6a822089..332c2de7 100644--- a/crates/engine/src/naming.rs+++ b/crates/engine/src/naming.rs@@ -240,8 +240,20 @@ pub fn fit_name(dir: &Path, name: &str) -> Option<String> {/// deep for any name keeps it whole, and the download says the path is too long. A name from a/// long address (a token hundreds of characters long, #28) no longer fails the download.pub fn destination(dir: &Path, name: &str) -> PathBuf {- let name = fit_name(dir, name).unwrap_or_else(|| name.to_owned());- unique_path(dir, &name)+ unique_path(dir, &fitted(dir, name))+}++/// `destination` before the folder is looked at: the name fitted to the path limit, not yet+/// numbered. What a window shows while the disk is asked (a sleeping drive or a network folder+/// can take seconds to answer, #743); a download started there is numbered on if the name is+/// taken by then ([`crate::Destination::Free`]). Never touches the disk.+pub fn guess(dir: &Path, name: &str) -> PathBuf {+ dir.join(fitted(dir, name))+}++/// `name` fitted to `dir` (`fit_name`), kept whole when `dir` leaves too little room.+fn fitted(dir: &Path, name: &str) -> String {+ fit_name(dir, name).unwrap_or_else(|| name.to_owned())}/// `destination` for a download whose helper picks the extension and takes any `<stem>.*` it@@ -250,7 +262,7 @@ pub fn destination(dir: &Path, name: &str) -> PathBuf {/// with it and a dot, letter case aside, and `in_use` (the other downloads' stems in `dir`)/// says no.pub fn stem_destination(dir: &Path, name: &str, in_use: impl Fn(&str) -> bool) -> PathBuf {- let name = fit_name(dir, name).unwrap_or_else(|| name.to_owned());+ let name = fitted(dir, name);let (stem, ext) = match name.rfind('.') {Some(i) if i > 0 => (&name[..i], &name[i..]),_ => (name.as_str(), ""),@@ -727,6 +739,25 @@ mod tests {assert_eq!(sanitize("..."), "download");}+ /// #743: the guess a window shows before the disk answers is `destination`'s name, fitted+ /// the same way, never numbered (and never looked up).+ #[test]+ fn the_guess_is_the_destination_before_numbering() {+ let d = tempfile::tempdir().unwrap();+ assert_eq!(guess(d.path(), "a.zip"), destination(d.path(), "a.zip"));+ std::fs::write(d.path().join("a.zip"), b"").unwrap();+ assert_eq!(guess(d.path(), "a.zip"), d.path().join("a.zip"));+ assert_eq!(destination(d.path(), "a.zip"), d.path().join("a (1).zip"));+ let long = format!("{}.zip", "x".repeat(400));+ assert_eq!(+ guess(d.path(), &long),+ d.path().join(fit_name(d.path(), &long).unwrap())+ );+ // A folder that isn't there: nothing to look up, the same name.+ let gone = d.path().join("gone");+ assert_eq!(guess(&gone, "a.zip"), gone.join("a.zip"));+ }+#[test]fn numbered_duplicates() {let d = tempfile::tempdir().unwrap();diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rsindex 10981416..4d1a4ddb 100644--- a/crates/engine/tests/e2e.rs+++ b/crates/engine/tests/e2e.rs@@ -825,6 +825,44 @@ async fn the_view_names_the_file_when_its_place_was_taken_meanwhile() {}}+/// #743: a name given before its folder was looked at (Download File Info doesn't wait for a+/// slow disk) is numbered as the download starts when it is taken by then, by a file or by+/// another download's part file: neither is touched, and the view names the file made.+#[tokio::test]+async fn a_name_given_unlooked_is_numbered_as_it_starts() {+ let s = server("").await;+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("master.mp4");+ std::fs::write(&dest, b"someone else's").unwrap();+ let part = mdm_engine::naming::part_path(&dir.path().join("master (1).mp4"));+ std::fs::write(&part, b"another download's").unwrap();+ let dl = Download::start(+ Request {+ url: s.url("/gen/256K/master.mp4?seed=7").parse().unwrap(),+ headers: Default::default(),+ dest: Destination::Free(dest.clone()),+ },+ fast_opts(),+ );+ let (file, path) = view_and_outcome(dl).await;+ assert_eq!(path, dir.path().join("master (2).mp4"));+ assert_eq!(file.as_deref(), Some(path.as_path()));+ assert_eq!(std::fs::read(&dest).unwrap(), b"someone else's");+ assert_eq!(std::fs::read(&part).unwrap(), b"another download's");+ assert_eq!(std::fs::metadata(&path).unwrap().len(), 256 * 1024);+ // Free, it keeps its name.+ let free = dir.path().join("free.mp4");+ let dl = Download::start(+ Request {+ url: s.url("/gen/64K/free.mp4?seed=8").parse().unwrap(),+ headers: Default::default(),+ dest: Destination::Free(free.clone()),+ },+ fast_opts(),+ );+ assert_eq!(view_and_outcome(dl).await.1, free);+}+/// The same for a resumed download: the row follows, and the resume itself still works.#[tokio::test]async fn the_view_names_the_file_when_a_resume_finds_its_place_taken() {