Skip to content

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

Windows: Open with shows Windows' own chooser, for paths with spaces too (fixes #720) (#864)

Ahmed Nefzaoui2cf20874dae9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f7319432..80f4a1cd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- Windows: **Open with...**, in a finished download's right-click menu and in **Download complete**, shows Windows' own **Select an app to open this file** again. It showed nothing when the file's name or folder had a space in it: MDM handed the file to Windows' old `OpenAs_RunDLL` command, which takes everything after it for the file's name, the quotes round a name with spaces included, and found no such file. MDM now asks Windows for the chooser itself, as Explorer's **Open with → Choose another app** does, beside the window, and a file moved or deleted since then says so, as **Open** does ([#720](https://github.com/anefzaoui/misterdownloadmanager/issues/720)).
- A file host that answers with its own web page (DropMeFiles, dailyuploads, datavaults: a page that counts down, asks you to solve a captcha or to press a button before the file) no longer leaves a "corrupted" archive of a few kilobytes marked as finished. MDM saved that page under the archive's name whenever the site sent it as the file's own type, under the file's name, or without a type, and the download looked complete. Now the download stops before anything is saved and says the site sent a web page instead of the file: open the link in your browser, finish there, and the download comes back to MDM (through MDM's browser extension). The progress window's **Open in browser** opens it. MDM tells the page by its first bytes as well as by its type, wherever an archive, a program, a disk image, a PDF, a picture, audio or video was expected (from its name, the browser's type for it, or the size the browser announced), and a download resumed onto such a page stops the same way, its data on disk kept as it was. A page you download on purpose (`.html`, a page's link) is saved as before, and so is a report "exported to Excel" as a page under an `.xls` name. A link the browser handed over that now gives the page is also asked once where the browser's own download ended, as one the site refuses is ([#701](https://github.com/anefzaoui/misterdownloadmanager/issues/701), [#692](https://github.com/anefzaoui/misterdownloadmanager/issues/692)).
- A YouTube video that lists only **Audio only** (and maybe one low quality) now says why: yt-dlp needs a JavaScript runtime (Deno, Node.js or Bun) to solve YouTube's challenges, and without one it finds only part of the video's qualities. The Download video window, the menu over a video and the command line now say **YouTube needs a JavaScript runtime to list its video qualities: install Node.js or Deno, then look it up again**, with a link to the [help page's section](docs/video.md#javascript-runtime) that gives the command for Windows, Ubuntu and Debian, Fedora, Arch and macOS. MDM notices a runtime installed while it runs at the next look-up, and also finds Deno from its own installer (`~/.deno/bin`) and, on Windows, Deno or Node.js just installed with winget or Node.js's installer ([#852](https://github.com/anefzaoui/misterdownloadmanager/issues/852)).
- Linux: the window no longer freezes where the session bus doesn't answer (a session started without D-Bus, some minimal window managers, a bus that hangs). MDM made its tray icon on the window's own thread, and the tray library waits for the bus as the icon is made, so the window waited too, and reported "The window stopped responding". The icon is now set up beside the window, which opens at once and behaves meanwhile as it does with no tray (closing quits). A bus that answers later, however late, still brings the icon, and closing then hides the window in it ([#828](https://github.com/anefzaoui/misterdownloadmanager/issues/828)).
diff --git a/ROADMAP.md b/ROADMAP.md
index 51628faf..fa1afa8b 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -557,6 +557,9 @@ Bug fixes from the first days of 0.5.0, a Safari extension, and more file types.
These ship in the next version.
+- ✅ Windows: **Open with...** shows Windows' "Select an app to open this file" again, for
+ files whose name or folder has a space too
+ ([#720](https://github.com/anefzaoui/misterdownloadmanager/issues/720))
- ✅ A file host's web page (a countdown, a captcha, DropMeFiles', dailyuploads') is never saved
under the archive's name and called finished: the download stops, says the site sent its page
and to finish in the browser, and the progress window's **Open in browser** opens the link
diff --git a/crates/app/src/dialogs.rs b/crates/app/src/dialogs.rs
index d7adfa89..a5b6d64a 100644
--- a/crates/app/src/dialogs.rs
+++ b/crates/app/src/dialogs.rs
@@ -3042,6 +3042,13 @@ pub fn open_file(path: &Path) {
/// 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 {
+ hand_over(path, |p| open::that_detached(p).map_err(|e| e.to_string()))
+}
+
+/// Hand the downloaded file `path` to `hand` (which opens it, or shows a chooser for it), or say
+/// why not: moved or deleted since, or `hand`'s error. True when it was handed over. Waits for
+/// `hand`, so it runs on a thread other than the window's.
+fn hand_over(path: &Path, hand: impl FnOnce(&Path) -> Result<(), String>) -> bool {
let name = crate::i18n::isolate(&path.file_name().unwrap_or_default().to_string_lossy());
let failed = if !path.exists() {
crate::i18n::fmt(
@@ -3050,10 +3057,10 @@ pub fn open_file_now(path: &Path) -> bool {
),
&[("file", &name)],
)
- } else if let Err(e) = open::that_detached(path) {
+ } else if let Err(e) = hand(path) {
crate::i18n::fmt(
crate::i18n::t("{file} could not be opened: {error}"),
- &[("file", &name), ("error", &e.to_string())],
+ &[("file", &name), ("error", &e)],
)
} else {
return true;
@@ -3106,18 +3113,30 @@ fn show_in_folder_now(path: &Path) {
crate::unix::show_in_folder(path);
}
+/// "Open with": the system's chooser of programs for the downloaded file `path`, or a message
+/// saying why not (moved or deleted since). Returns at once: the chooser is shown, and waited
+/// for, on a thread of its own, as is the look at the file (#743, #751).
pub fn open_with(path: &Path) {
- #[cfg(windows)]
- {
- let _ = std::process::Command::new("rundll32")
- .arg("shell32.dll,OpenAs_RunDLL")
- .arg(path)
- .spawn();
- }
- #[cfg(not(windows))]
- {
- crate::launch::open(path);
- }
+ let path = path.to_owned();
+ crate::launch::spawn("open with", move || {
+ hand_over(&path, |p| {
+ // Windows' own "How do you want to open this file?", as Explorer shows it (#720).
+ #[cfg(windows)]
+ {
+ crate::win32::open_with_dialog(p).map_err(|hr| {
+ tracing::warn!("open with: SHOpenWithDialog failed, {hr:#010x}");
+ std::io::Error::from_raw_os_error(hr).to_string()
+ })
+ }
+ // Linux and macOS have no chooser MDM can call for a file: the desktop's opener
+ // (xdg-open, which goes through the desktop portal in a sandbox, or macOS's `open`)
+ // opens it with the program set for its type, which the user changes there.
+ #[cfg(not(windows))]
+ {
+ open::that_detached(p).map_err(|e| e.to_string())
+ }
+ });
+ });
}
/// "Duplicate download link": the address is already in the list (Options → Downloads → "If a
diff --git a/crates/app/src/win32.rs b/crates/app/src/win32.rs
index f261acaf..5104cc77 100644
--- a/crates/app/src/win32.rs
+++ b/crates/app/src/win32.rs
@@ -5580,6 +5580,77 @@ mod classic_text {
}
}
+/// What Explorer's "Open with → Choose another app" asks of the chooser: the "Always use this
+/// app" choice may be saved for the file's type (`ALLOW_REGISTRATION`, `REGISTER_EXT`), and the
+/// app chosen opens the file (`EXEC`; without it the chooser only records the choice).
+const OPEN_WITH_FLAGS: windows_sys::Win32::UI::Shell::OPEN_AS_INFO_FLAGS = {
+ use windows_sys::Win32::UI::Shell::{OAIF_ALLOW_REGISTRATION, OAIF_EXEC, OAIF_REGISTER_EXT};
+ OAIF_ALLOW_REGISTRATION | OAIF_REGISTER_EXT | OAIF_EXEC
+};
+
+/// `path` as `SHOpenWithDialog` reads it: the path itself, wide and NUL-ended, with no quotes
+/// round it (a path with spaces is one string here, not a command line).
+fn open_with_file(path: &std::path::Path) -> Vec<u16> {
+ use std::os::windows::ffi::OsStrExt;
+ path.as_os_str().encode_wide().chain(Some(0)).collect()
+}
+
+/// Windows' own "Open with" chooser for the file `path` ("How do you want to open this file?"),
+/// as Explorer shows it: the app chosen there opens the file (#720). It waits until the chooser
+/// is closed, so it is called on a thread of its own (with COM, apartment-threaded, as the shell
+/// expects). `Err(HRESULT)` when Windows couldn't show it; closing the chooser without a choice
+/// is `Ok`.
+///
+/// It used to run `rundll32 shell32.dll,OpenAs_RunDLL <path>`, which takes the rest of its
+/// command line as the path, quotes included: the quotes a path with a space gets made it a file
+/// that isn't there, and the chooser never showed.
+pub fn open_with_dialog(path: &std::path::Path) -> Result<(), i32> {
+ use windows_sys::Win32::Foundation::ERROR_CANCELLED;
+ use windows_sys::Win32::UI::Shell::{OPENASINFO, SHOpenWithDialog};
+ com_on_this_thread();
+ let file = open_with_file(path);
+ let info = OPENASINFO {
+ pcszFile: file.as_ptr(),
+ pcszClass: std::ptr::null(),
+ oaifInFlags: OPEN_WITH_FLAGS,
+ };
+ // SAFETY: `info` and the NUL-ended `file` it points to outlive the call, which only reads
+ // them. No owner window: the window's thread isn't this one, and an owner would tie the two
+ // threads' input together while the chooser is open.
+ let hr = unsafe { SHOpenWithDialog(std::ptr::null_mut(), &info) };
+ // HRESULT_FROM_WIN32(ERROR_CANCELLED): the chooser closed without a choice.
+ let cancelled = (0x8007_0000 | ERROR_CANCELLED) as i32;
+ if hr >= 0 || hr == cancelled {
+ Ok(())
+ } else {
+ Err(hr)
+ }
+}
+
+#[cfg(test)]
+mod open_with_tests {
+ use super::*;
+
+ #[test]
+ fn the_chooser_opens_the_file_chosen() {
+ use windows_sys::Win32::UI::Shell::{OAIF_EXEC, OAIF_REGISTER_EXT};
+ assert_eq!(OPEN_WITH_FLAGS & OAIF_EXEC, OAIF_EXEC);
+ assert_eq!(OPEN_WITH_FLAGS & OAIF_REGISTER_EXT, OAIF_REGISTER_EXT);
+ }
+
+ #[test]
+ fn a_path_with_spaces_is_given_whole_and_unquoted() {
+ let path = std::path::Path::new(r"C:\Users\A B\Downloads\my file.zip");
+ let wide = open_with_file(path);
+ assert_eq!(wide.last(), Some(&0));
+ assert_eq!(
+ String::from_utf16(&wide[..wide.len() - 1]).unwrap(),
+ r"C:\Users\A B\Downloads\my file.zip"
+ );
+ assert!(!wide.contains(&u16::from(b'"')));
+ }
+}
+
/// The program Windows runs to open folders, when that isn't Explorer (a file manager such as
/// Directory Opus set up to replace it, #446); None for Explorer, or when Windows doesn't say.
pub fn folder_opener() -> Option<String> {