Skip to content

misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux

Move/Rename works on several selected downloads (#333) (#399)

Ahmed Nefzaoui9acad274c7d7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7134739d..1ea2b0f1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- **Move/Rename** was greyed out with several downloads selected, for example a set just added to a queue. It now asks for a folder and moves them all there ([#333](https://github.com/anefzaoui/misterdownloadmanager/issues/333)).
- The extension no longer asks you to update MDM when only a bug-fix version separates them, which it did even when there was no update to get.
- **Download video** shows a plain file's size, from its server, instead of "size unknown" ([#320](https://github.com/anefzaoui/misterdownloadmanager/issues/320)).
- **Download video** finds the video on pages whose player loads a `.mpd` or `.m3u8` address that answers something else first, as SVT Play does ([#377](https://github.com/anefzaoui/misterdownloadmanager/issues/377)).
diff --git a/ROADMAP.md b/ROADMAP.md
index 955de2ca..21f028fc 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -13,6 +13,8 @@ Everything below ships together, in version 0.5.0.
### Done
+- ✅ **Move/Rename** works on several selected downloads at once: pick a folder and they all go there
+ ([#333](https://github.com/anefzaoui/misterdownloadmanager/issues/333))
- ✅ Download video shows the size of a plain file (what the server says), not "size unknown"
(part of [#320](https://github.com/anefzaoui/misterdownloadmanager/issues/320))
- ✅ Download video on pages whose player first loads a manifest's address answering something else
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index b7cea726..959c7889 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -214,6 +214,43 @@ fn move_file(from: &std::path::Path, to: &std::path::Path) -> Result<(), String>
})
}
+/// Whether Move/Rename can take a download now: a finished file, or nothing of it come in yet.
+fn can_move(i: &Item) -> bool {
+ i.live.is_none() && (i.status == Status::Complete || i.downloaded == 0)
+}
+
+/// What is said when a download can't move, or stays while the others of a selection move.
+fn cant_move_notice() -> (&'static str, String) {
+ (
+ crate::i18n::mark("Move/Rename"),
+ crate::i18n::t(
+ "Only a finished download, or one not started yet, can be moved. Stop it and finish it first.",
+ )
+ .to_owned(),
+ )
+}
+
+/// Where one download of a selection goes in `dir`: a name free there (on disk, what
+/// `naming::destination` checks) and not one the selection has taken (two not started under one
+/// name have no file yet to be seen).
+fn place_in(
+ dir: &std::path::Path,
+ name: &str,
+ taken: &mut std::collections::HashSet<PathBuf>,
+) -> PathBuf {
+ let (stem, ext) = match name.rfind('.') {
+ Some(i) if i > 0 => (&name[..i], &name[i..]),
+ _ => (name, ""),
+ };
+ let mut at = mdm_engine::naming::destination(dir, name);
+ let mut n = 1u32;
+ while !taken.insert(at.clone()) {
+ at = mdm_engine::naming::destination(dir, &format!("{stem} ({n}){ext}"));
+ n += 1;
+ }
+ at
+}
+
/// A download's new place (its name from it). A name the user gave is no longer the address's
/// guess (`Item::name_from_url`); another folder alone keeps the server's say.
fn take_place(item: &mut Item, target: PathBuf) {
@@ -341,6 +378,8 @@ pub struct App {
list_view: View,
/// The download Move/Rename's dialog is for (winui::start_pick answers later).
move_rename_for: Option<u64>,
+ /// The downloads Move/Rename's folder dialog is for, several selected (#333).
+ move_many_for: Vec<u64>,
/// The Categories tree has the keys (else the list; Tab moves between them).
tree_keys: bool,
/// The app's context, to reach its windows from anywhere (bring one to the front).
@@ -909,6 +948,7 @@ impl App {
ui_ctx: ctx.clone(),
tree_keys: false,
move_rename_for: None,
+ move_many_for: Vec::new(),
list_view: view,
add_url: None,
about: None,
@@ -1912,6 +1952,7 @@ impl App {
self.extension = Some(offer);
}
"language" => self.run(Cmd::ChooseLanguage, None, ctx),
+ "move-rename" => self.run(Cmd::MoveRename, None, ctx),
"shortcuts" => self.run(Cmd::Shortcuts, None, ctx),
// The Help menu's windows and Download a gallery, for screenshots (#192). updates
// asks GitHub, as Help → Check for updates does.
@@ -1977,6 +2018,14 @@ impl App {
chrome::open_sub_at(ctx, &format!("menu-{index}"), at);
}
}
+ // Every download selected and the right-click menu open on them (Move/Rename, #333).
+ "context" if tab == "all" => {
+ self.run(Cmd::SelectAll, None, ctx);
+ self.open_menu = None;
+ if let Some(id) = self.shown_ids().first().copied() {
+ self.open_popup(Popup::Item(Some(id)), egui::pos2(360.0, 220.0));
+ }
+ }
// A finished archive's right-click menu (Extract, #37), for screenshots.
"context" => {
let archive = self
@@ -5084,7 +5133,9 @@ impl App {
}
}
Cmd::MoveRename => {
- if let Some(id) = target {
+ if many.len() > 1 {
+ self.move_many(many);
+ } else if let Some(id) = target {
self.move_rename(id);
}
}
@@ -5758,7 +5809,8 @@ impl App {
.chain([I("Create new queue", Cmd::NewQueue, true, false)])
.collect();
let open = self.settings.double_click_open;
- let movable = it.is_some_and(|i| !live && (done || i.downloaded == 0));
+ // Several selected: enabled when one of them can go; the others are said to stay (#333).
+ let movable = chosen.iter().any(|i| can_move(i));
let redo = it.is_some_and(|i| self.can_redownload(i.id));
let extractable = chosen.iter().any(|i| {
i.status == Status::Complete
@@ -7151,6 +7203,10 @@ impl App {
{
self.start_move(id, target);
}
+ if let Some(dir) = winui::picked(ctx, "app-move-many") {
+ let ids = std::mem::take(&mut self.move_many_for);
+ self.move_many_to(ids, dir);
+ }
}
/// View → Theme → Add a theme file, answered: the file copied into the themes folder and
@@ -7356,16 +7412,9 @@ impl App {
let Some(item) = self.items.iter().find(|i| i.id == id) else {
return;
};
- let complete = item.status == Status::Complete;
- if item.live.is_some() || !(complete || item.downloaded == 0) {
+ if !can_move(item) {
// Said, not silently ignored (F2, Ctrl+M on a download that can't move).
- self.notice = Some((
- crate::i18n::mark("Move/Rename"),
- crate::i18n::t(
- "Only a finished download, or one not started yet, can be moved. Stop it and finish it first.",
- )
- .to_owned(),
- ));
+ self.notice = Some(cant_move_notice());
return;
}
let title = crate::i18n::t("Move/Rename").to_owned();
@@ -7385,6 +7434,60 @@ impl App {
});
}
+ /// Move/Rename with several downloads selected (#333): their folder is asked for, not a name
+ /// each.
+ fn move_many(&mut self, ids: Vec<u64>) {
+ let can = ids
+ .iter()
+ .filter_map(|id| self.items.iter().find(|i| i.id == *id))
+ .find(|i| can_move(i));
+ let Some(first) = can else {
+ self.notice = Some(cant_move_notice());
+ return;
+ };
+ let title = crate::i18n::t("Move/Rename").to_owned();
+ let from = first
+ .dest
+ .parent()
+ .unwrap_or(std::path::Path::new("."))
+ .to_path_buf();
+ self.move_many_for = ids;
+ winui::start_pick(&self.ui_ctx, "app-move-many", move || {
+ // Off-screen test runs have no folder dialog to answer.
+ if let Some(dir) = std::env::var_os("MDM_TEST_MOVE_TO") {
+ return Some(PathBuf::from(dir));
+ }
+ rfd::FileDialog::new()
+ .set_title(title)
+ .set_directory(from)
+ .pick_folder()
+ });
+ }
+
+ /// The several downloads' new folder: each that can go goes there, under its own name.
+ fn move_many_to(&mut self, ids: Vec<u64>, dir: PathBuf) {
+ let mut taken = std::collections::HashSet::new();
+ let mut stay = false;
+ for id in ids {
+ let Some(item) = self.items.iter().find(|i| i.id == id) else {
+ continue;
+ };
+ if !can_move(item) {
+ stay = true;
+ continue;
+ }
+ if item.dest.parent() == Some(dir.as_path()) {
+ continue;
+ }
+ let target = place_in(&dir, &item.file_name, &mut taken);
+ self.start_move(id, target);
+ }
+ self.dirty = true;
+ if stay {
+ self.notice = Some(cant_move_notice());
+ }
+ }
+
/// Delete a queue of the user's (not the two built-in ones); its downloads stay in the list.
fn delete_queue(&mut self, q: usize) {
if q < 2 || q >= self.queues.len() {
@@ -8486,6 +8589,32 @@ fn share(cap: u64, other: f64) -> u64 {
rest.max(half).max(1024)
}
+#[cfg(test)]
+mod move_many_tests {
+ use super::place_in;
+
+ /// #333: a selection moved to one folder keeps each its own name, or the next free one when
+ /// several would land on the same name (not started: no file yet) or one is on the disk.
+ #[test]
+ fn a_selection_gets_a_free_name_each() {
+ let dir = tempfile::tempdir().unwrap();
+ let d = dir.path();
+ std::fs::write(d.join("a.zip"), b"x").unwrap();
+ let mut taken = std::collections::HashSet::new();
+ let names: Vec<String> = ["a.zip", "a.zip", "b.bin", "b.bin"]
+ .iter()
+ .map(|n| {
+ place_in(d, n, &mut taken)
+ .file_name()
+ .unwrap()
+ .to_string_lossy()
+ .into_owned()
+ })
+ .collect();
+ assert_eq!(names, ["a (1).zip", "a (2).zip", "b.bin", "b (1).bin"]);
+ }
+}
+
#[cfg(test)]
mod at_login_tests {
use super::{AtLogin, TRAY_GRACE, at_login};
diff --git a/crates/app/tests/move_many.rs b/crates/app/tests/move_many.rs
new file mode 100644
index 00000000..b8670f68
--- /dev/null
+++ b/crates/app/tests/move_many.rs
@@ -0,0 +1,137 @@
+//! #333: Move/Rename with several downloads selected. The real app, off the screens, with a data
+//! folder and a download folder of its own: every row selected (`/show context:all`), then the
+//! command (`/show move-rename`), the folder dialog answered by MDM_TEST_MOVE_TO. What can go goes
+//! there under its own name (two not started under one name get a free one each), a part-way
+//! download stays where its pieces are.
+//!
+//! It opens windows, which needs OpenGL or Direct3D, so it runs on request:
+//! `cargo test -p mdm-app --test move_many -- --ignored`.
+
+use std::path::Path;
+use std::process::Command;
+use std::time::{Duration, Instant};
+
+const APP: &str = env!("CARGO_BIN_EXE_misterdownloadmanager");
+
+fn item(id: u64, name: &str, status: &str, downloaded: u64, dir: &Path) -> serde_json::Value {
+ serde_json::json!({
+ "id": id, "url": format!("https://files.example/{name}"), "file_name": name,
+ "dest": dir.join(name), "size": 1000, "downloaded": downloaded, "status": status,
+ "category": "Compressed", "description": "", "last_try": null, "error": null,
+ "resumable": null,
+ })
+}
+
+fn log(data: &Path) -> String {
+ std::fs::read_to_string(data.join("logs").join("mdm.log")).unwrap_or_default()
+}
+
+fn second_launch(data: &Path, downloads: &Path, what: &str) {
+ let status = Command::new(APP)
+ .args(["/show", what])
+ .env("MDM_DATA_DIR", data)
+ .env("MDM_OFFSCREEN", "1")
+ .env("MDM_DOWNLOADS", downloads)
+ .status()
+ .unwrap();
+ assert!(status.success(), "/show {what}: {status}");
+}
+
+fn wait_for(what: &str, data: &Path, done: impl Fn() -> bool) {
+ let until = Instant::now() + Duration::from_secs(45);
+ while !done() {
+ assert!(Instant::now() < until, "no {what}:\n{}", log(data));
+ std::thread::sleep(Duration::from_millis(100));
+ }
+}
+
+/// A download's saved place: its path relative to `root`, with forward slashes.
+fn saved_place(j: &serde_json::Value, id: u64, root: &Path) -> String {
+ let it = j["items"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|i| i["id"] == id)
+ .unwrap();
+ Path::new(it["dest"].as_str().unwrap())
+ .strip_prefix(root)
+ .unwrap()
+ .to_string_lossy()
+ .replace('\\', "/")
+}
+
+#[test]
+#[ignore = "opens windows; run on request"]
+fn a_selection_moves_to_one_folder() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path();
+ let (data, dl, to) = (root.join("data"), root.join("dl"), root.join("to"));
+ for d in [&data, &dl, &to] {
+ std::fs::create_dir_all(d).unwrap();
+ }
+ for name in ["done-1.bin", "done-2.bin"] {
+ std::fs::write(dl.join(name), [b'x'; 1000]).unwrap();
+ }
+ let items = [
+ item(1, "waiting.zip", "Queued", 0, &dl),
+ item(2, "same.zip", "Queued", 0, &dl),
+ item(3, "same.zip", "Queued", 0, &dl),
+ item(4, "done-1.bin", "Complete", 1000, &dl),
+ item(5, "done-2.bin", "Complete", 1000, &dl),
+ item(6, "partial.bin", "Stopped", 300, &dl),
+ ];
+ let settings = serde_json::json!({
+ "language": "en", "update_check": false, "helpers_asked": true, "language_asked": true,
+ "extension_never_ask": true, "clipboard_autostart": false,
+ });
+ std::fs::write(
+ data.join("downloads.json"),
+ serde_json::json!({ "next_id": 7, "items": items, "version": 2, "settings": settings })
+ .to_string(),
+ )
+ .unwrap();
+ let mut app = Command::new(APP)
+ .env("MDM_DATA_DIR", &data)
+ .env("MDM_OFFSCREEN", "1")
+ .env("MDM_DOWNLOADS", &dl)
+ .env("MDM_TEST_MOVE_TO", &to)
+ .spawn()
+ .unwrap();
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ wait_for("main window", &data, || {
+ log(&data).contains("window opened: main")
+ });
+ second_launch(&data, &dl, "context:all");
+ wait_for("Select all", &data, || {
+ log(&data).contains("command SelectAll")
+ });
+ second_launch(&data, &dl, "move-rename");
+ wait_for("finished files in the new folder", &data, || {
+ to.join("done-1.bin").exists() && to.join("done-2.bin").exists()
+ });
+ // Saved within a second or so of the change.
+ wait_for("the new places saved", &data, || {
+ std::fs::read_to_string(data.join("downloads.json"))
+ .is_ok_and(|t| t.contains("same (1).zip"))
+ });
+ }));
+ let _ = app.kill();
+ let _ = app.wait();
+ if let Err(e) = result {
+ std::panic::resume_unwind(e);
+ }
+ let j: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(data.join("downloads.json")).unwrap())
+ .unwrap();
+ assert_eq!(saved_place(&j, 1, root), "to/waiting.zip");
+ assert_eq!(saved_place(&j, 2, root), "to/same.zip");
+ assert_eq!(saved_place(&j, 3, root), "to/same (1).zip");
+ assert_eq!(saved_place(&j, 4, root), "to/done-1.bin");
+ assert_eq!(saved_place(&j, 5, root), "to/done-2.bin");
+ assert_eq!(
+ saved_place(&j, 6, root),
+ "dl/partial.bin",
+ "part-way: it stays"
+ );
+ assert!(!dl.join("done-1.bin").exists());
+}
diff --git a/docs/download-list.md b/docs/download-list.md
index dbb16e33..29333778 100644
--- a/docs/download-list.md
+++ b/docs/download-list.md
@@ -107,7 +107,7 @@ The right-click menu has everything you can do with a download: **Open**, **Open
![File Properties: the file's name, address, folder, size, status and description](images/help/properties.webp)
*File Properties: change the address or the folder of a download.*
-**Move/Rename** (**Ctrl+M**) moves or renames the file of a finished download, or of one that hasn't started yet.
+**Move/Rename** (**Ctrl+M**) moves or renames the file of a finished download, or of one that hasn't started yet. With several downloads selected it asks for a folder and moves them all there, each under its own name.
## Verify checksum