Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
fix: restore native WebView2 download UI on Windows
WaveYof672b91c3bc8
diff --git a/src-tauri/src/app/download.rs b/src-tauri/src/app/download.rsnew file mode 100644index 00000000..217997ec--- /dev/null+++ b/src-tauri/src/app/download.rs@@ -0,0 +1,77 @@+//! WebView2 downloads keep the browser session and its default download UI.++use crate::util::{+ check_file_or_append, get_download_dir, get_download_message_with_lang,+ sanitize_download_filename, show_toast, MessageType,+};+use std::path::PathBuf;+use tauri::{Manager, WebviewWindow};+use webview2_com::{+ take_pwstr, DownloadStartingEventHandler, Microsoft::Web::WebView2::Win32::ICoreWebView2_4,+};+use windows_core::{Interface, HSTRING, PWSTR};++pub fn install(window: &WebviewWindow, target: Option<tauri::Url>) -> tauri::Result<()> {+ let owner = window.clone();+ window.with_webview(move |webview| {+ let result = unsafe {+ (|| -> windows_core::Result<()> {+ let core = webview.controller().CoreWebView2()?;+ let downloads = core.cast::<ICoreWebView2_4>()?;+ let download_window = owner.clone();+ let mut token = 0;+ downloads.add_DownloadStarting(+ &DownloadStartingEventHandler::create(Box::new(move |_, args| {+ let Some(args) = args else { return Ok(()) };+ // Fail closed if changing the destination fails: never fall+ // back to a different folder or overwrite an existing file.+ args.SetCancel(true)?;+ let destination = (|| -> Result<PathBuf, String> {+ let mut path = PWSTR::null();+ args.ResultFilePath(&mut path).map_err(|e| e.to_string())?;+ let path = PathBuf::from(take_pwstr(path));+ let filename = path+ .file_name()+ .and_then(|name| name.to_str())+ .unwrap_or("download");+ let path = get_download_dir(download_window.app_handle())?+ .join(sanitize_download_filename(filename));+ let path = path+ .to_str()+ .ok_or("Download destination is not valid UTF-8")?;+ Ok(PathBuf::from(check_file_or_append(path)))+ })();+ match destination {+ Ok(path) => {+ args.SetResultFilePath(&HSTRING::from(path.as_os_str()))?;+ // Unlike Wry's requested callback, leave WebView2's UI visible.+ args.SetHandled(false)?;+ args.SetCancel(false)?;+ }+ Err(error) => {+ args.SetCancel(true)?;+ eprintln!("[Pake] Failed to resolve download destination: {error}");+ show_toast(+ &download_window,+ &get_download_message_with_lang(+ MessageType::DirectoryFailure,+ None,+ ),+ );+ }+ }+ Ok(())+ })),+ &mut token,+ )?;+ if let Some(target) = target {+ core.Navigate(&HSTRING::from(target.as_str()))?;+ }+ Ok(())+ })()+ };+ if let Err(error) = result {+ eprintln!("[Pake] Failed to initialize native Windows downloads: {error}");+ }+ })+}diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rsindex 37dabb67..7bccb6ac 100644--- a/src-tauri/src/app/mod.rs+++ b/src-tauri/src/app/mod.rs@@ -3,6 +3,8 @@ pub mod auth;#[cfg(any(target_os = "linux", test))]pub mod color_scheme;pub mod config;+#[cfg(target_os = "windows")]+pub mod download;pub mod invoke;#[cfg(target_os = "macos")]pub mod menu;diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rsindex 7d4add98..35c33949 100644--- a/src-tauri/src/app/window.rs+++ b/src-tauri/src/app/window.rs@@ -1,10 +1,12 @@use crate::app::config::PakeConfig;#[cfg(target_os = "windows")]use crate::app::navigation::set_password_autosave;+#[cfg(not(target_os = "windows"))]use crate::util::{- check_file_or_append, data_dir_name, get_data_dir, get_download_dir,- get_download_message_with_lang, sanitize_download_filename, show_toast, MessageType,+ check_file_or_append, get_download_dir, get_download_message_with_lang,+ sanitize_download_filename, show_toast, MessageType,};+use crate::util::{data_dir_name, get_data_dir};#[cfg(target_os = "macos")]use dispatch::Queue;#[cfg(target_os = "macos")]@@ -18,8 +20,10 @@ use std::{str::FromStr,sync::atomic::{AtomicU32, Ordering},};+#[cfg(not(target_os = "windows"))]+use tauri::webview::DownloadEvent;use tauri::{- webview::{DownloadEvent, NewWindowFeatures, NewWindowResponse},+ webview::{NewWindowFeatures, NewWindowResponse},AppHandle, Config, Manager, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder,};@@ -466,6 +470,28 @@ fn build_window(let url = restored_url.map(WebviewUrl::External).unwrap_or(url);+ // Install the native download handler before a remote entry page can respond+ // with an attachment. about:blank popups still keep their own WindowProxy.+ #[cfg(target_os = "windows")]+ let download_target = match &url {+ WebviewUrl::External(target) if matches!(target.scheme(), "http" | "https") => {+ Some(target.clone())+ }+ WebviewUrl::App(path) => path+ .to_str()+ .and_then(|path| Url::parse(path).ok())+ .filter(|target| matches!(target.scheme(), "http" | "https")),+ _ => None,+ };+ #[cfg(target_os = "windows")]+ let url = if download_target.is_some() {+ WebviewUrl::CustomProtocol(Url::parse("about:blank").map_err(|error| {+ tauri::Error::Io(std::io::Error::new(std::io::ErrorKind::InvalidInput, error))+ })?)+ } else {+ url+ };+// The delegate must be installed before the first TLS challenge. Start on// a neutral page, then navigate from the with_webview callback below.#[cfg(target_os = "macos")]@@ -483,6 +509,9 @@ fn build_window("window.pakeConfig = {}",serde_json::to_string(&window_config).unwrap_or_else(|_| "{}".to_string()));+ // A host-provided marker avoids relying on a site's overridden user agent.+ #[cfg(target_os = "windows")]+ let config_script = format!("{config_script}; window.pakeNativeDownloads = true;");// Platform-specific title: macOS prefers empty, others fallback to product namelet effective_title = window_config.title.as_deref().unwrap_or_else(|| {@@ -763,6 +792,7 @@ fn build_window(// through the JS bridge, and downloads triggered from a sandboxed iframe// can't reach the IPC either. Letting the browser download natively and// catching it here is independent of the page CSP and the IPC channel.+ #[cfg(not(target_os = "windows"))]{let download_handle = app.clone();window_builder = window_builder.on_download(move |webview, event| match event {@@ -843,6 +873,9 @@ fn build_window(}}+ #[cfg(target_os = "windows")]+ crate::app::download::install(&window, download_target)?;+// Every webview is built here (main window, Cmd+N clones, --new-window and// blank two-stage popups), so trackpad history swipes match in all of them.#[cfg(target_os = "macos")]