Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: make the browser's right-click downloads work on macOS (#13003)

Michael Han3afc66d7e076
diff --git a/studio/frontend/src/features/browser/download-approval-queue.ts b/studio/frontend/src/features/browser/download-approval-queue.ts
index 2d6ed54e3e5..6086a4297ff 100644
--- a/studio/frontend/src/features/browser/download-approval-queue.ts
+++ b/studio/frontend/src/features/browser/download-approval-queue.ts
@@ -47,9 +47,20 @@ export function approveDownload(url: string, name: string, site: string = url):
if (!dangerous && (remembered === "allow" || !useBrowserPrefsStore.getState().askBeforeDownloading)) {
return Promise.resolve(true);
}
+ return ask(origin, label, shown, dangerous);
+}
+
+/** Picked from the context menu: no site answer applies, and only a file that runs code asks (with nothing to remember). */
+export function approveChosenDownload(url: string, name: string): Promise<boolean> {
+ const shown = safeDownloadName(name);
+ if (!isDangerousDownload(shown)) return Promise.resolve(true);
+ return ask("", hostOf(url) || url.slice(0, 80), shown, true);
+}
+
+function ask(origin: string, label: string, name: string, dangerous: boolean): Promise<boolean> {
return new Promise((resolve) =>
useApprovalStore.setState((state) => ({
- queue: [...state.queue, { origin, label, name: shown, dangerous, resolve }],
+ queue: [...state.queue, { origin, label, name, dangerous, resolve }],
})),
);
}
diff --git a/studio/frontend/src/features/browser/native-view.ts b/studio/frontend/src/features/browser/native-view.ts
index ef069fb526a..43730234aec 100644
--- a/studio/frontend/src/features/browser/native-view.ts
+++ b/studio/frontend/src/features/browser/native-view.ts
@@ -10,7 +10,7 @@ import { openExternalLink } from "@/lib/open-link";
import { toast } from "@/lib/toast";
import { BROWSER_PAGE_INSET_VAR, CHAT_SETTINGS_INSET_VAR } from "@/lib/toast-offset";
import { hostOf } from "./address";
-import { approveDownload, downloadSiteOf } from "./download-approval-queue";
+import { approveChosenDownload, approveDownload, downloadSiteOf } from "./download-approval-queue";
import { abandonDownload, beginDownload, finishDownload, useDownloadActivity } from "./download-activity";
import { proxiedFavicon } from "./favicon";
import { useBrowserHistoryStore } from "./history-store";
@@ -56,7 +56,7 @@ type NativeEvent =
/** The downloadPrompt `id` it was asked under; null when refused before asking. */
promptId?: string | null;
}
- | { kind: "downloadPrompt"; tabId: string; url: string; site: string; name: string; id: string }
+ | { kind: "downloadPrompt"; tabId: string; url: string; site: string; name: string; id: string; saveAs: boolean }
| { kind: "downloadCancelled"; tabId: string; url: string; promptId: string };
type Bounds = { x: number; y: number; width: number; height: number; viewportWidth: number };
@@ -127,17 +127,23 @@ const downloadKey = (promptId: string) => `native:${promptId}`;
/** Always answered: an unanswered download would sit in staging until the app quits. */
function onDownloadPrompt(event: Extract<NativeEvent, { kind: "downloadPrompt" }>, tab: BrowserTab | undefined): void {
- const { id, url, site, name } = event;
+ const { id, url, site, name, saveAs } = event;
const entry = tab ? currentEntry(tab) : null;
// The site asking is the page that started it, taken then (a later site's answer must not cover it); blob: counts as its creator. With no web origin yet, the opener or the address asked for.
const asking = downloadSiteOf(site) ? site : entry?.kind === "web" ? entry.from || entry.url : "";
- const decided = entry?.kind === "web" ? approveDownload(url, name, asking) : Promise.resolve(false);
+ // Picked from the context menu: the save dialog is the prompt, whatever the site's remembered answer.
+ const decided =
+ entry?.kind !== "web"
+ ? Promise.resolve(false)
+ : saveAs
+ ? approveChosenDownload(url, name)
+ : approveDownload(url, name, asking);
const key = downloadKey(id);
void decided
.then(async (allow) => {
// Begun before deciding: a file that finished while the prompt was open lands at once.
if (allow) beginDownload(key, name);
- await decideNativeDownload(id, allow, useBrowserPrefsStore.getState().askWhereToSave);
+ await decideNativeDownload(id, allow, saveAs || useBrowserPrefsStore.getState().askWhereToSave);
// Still running: one that landed during the decide call has already said so.
const { active, buttons } = useDownloadActivity.getState();
if (allow && buttons === 0 && key in active) toast(t("browser.native.downloading", { name }));
diff --git a/studio/frontend/tests/browser-settings.test.ts b/studio/frontend/tests/browser-settings.test.ts
index ab2e911f66a..28691b6803f 100644
--- a/studio/frontend/tests/browser-settings.test.ts
+++ b/studio/frontend/tests/browser-settings.test.ts
@@ -316,6 +316,28 @@ test("a remembered answer settles the site's other waiting downloads", async ()
useDownloadSitesStore.getState().setSite("https://a.example", null);
});
+test("a context menu download skips a site's block, and a file that runs code still asks", async () => {
+ const { approveChosenDownload, answerDownload, useApprovalStore } = await import(
+ "../src/features/browser/download-approval-queue.ts"
+ );
+ const { useDownloadSitesStore } = await import("../src/features/browser/download-sites-store.ts");
+ useDownloadSitesStore.getState().setSite("https://e.example", "block");
+ try {
+ assert.equal(await approveChosenDownload("https://e.example/cat.png", "cat.png"), true);
+ const setup = approveChosenDownload("https://e.example/setup.exe", "setup.exe");
+ // No origin: the prompt offers nothing to remember.
+ assert.deepEqual(
+ useApprovalStore.getState().queue.map(({ origin, label, dangerous }) => [origin, label, dangerous]),
+ [["", "e.example", true]],
+ );
+ answerDownload(useApprovalStore.getState().queue[0], true, true);
+ assert.equal(await setup, true);
+ assert.equal(useDownloadSitesStore.getState().sites["https://e.example"], "block");
+ } finally {
+ useDownloadSitesStore.getState().setSite("https://e.example", null);
+ }
+});
+
test("a file that runs code asks whatever the site's remembered answer or the ask setting", async () => {
const { approveDownload, answerDownload, useApprovalStore } = await import(
"../src/features/browser/download-approval-queue.ts"
diff --git a/studio/frontend/tests/helpers/native-view-resolver.mjs b/studio/frontend/tests/helpers/native-view-resolver.mjs
index cad37035f5a..59fb9a696d7 100644
--- a/studio/frontend/tests/helpers/native-view-resolver.mjs
+++ b/studio/frontend/tests/helpers/native-view-resolver.mjs
@@ -40,7 +40,9 @@ const STUBS = {
"export const decideNativeDownload = async (...args) => { globalThis.nativeViewDecide?.(...args); };",
),
"./download-approval-queue": stub(
- "export const approveDownload = async () => Boolean(globalThis.nativeViewApprove); export const downloadSiteOf = () => '';",
+ "export const approveDownload = async () => Boolean(globalThis.nativeViewApprove);" +
+ " export const approveChosenDownload = async () => Boolean(globalThis.nativeViewApprove);" +
+ " export const downloadSiteOf = () => '';",
),
"./history-store": stub(
"export const useBrowserHistoryStore = { getState: () => ({ recordVisit() {}," +
diff --git a/studio/src-tauri/Cargo.toml b/studio/src-tauri/Cargo.toml
index 18751a68cdd..f4a42dc6dfb 100644
--- a/studio/src-tauri/Cargo.toml
+++ b/studio/src-tauri/Cargo.toml
@@ -61,10 +61,11 @@ tokio = { version = "1", features = ["test-util"] }
objc2 = { version = "0.6", features = ["exception"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSAppearance", "NSButton", "NSControl", "NSResponder", "NSStatusBarButton", "NSStatusItem", "NSView", "NSBitmapImageRep", "NSImage", "NSImageRep", "NSPrintInfo", "NSPrintOperation", "NSWindow"] }
-objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSError", "NSDictionary", "NSKeyValueCoding", "NSKeyValueObserving", "NSObject", "NSProcessInfo", "NSString", "NSURL", "NSData", "NSGeometry"] }
+objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSError", "NSDictionary", "NSKeyValueCoding", "NSKeyValueObserving", "NSObject", "NSProcessInfo", "NSString", "NSURL", "NSURLRequest", "NSURLResponse", "NSData", "NSGeometry"] }
# The browser panel's content rules (browser_webview.rs), snapshots and printing
-# (browser_capture.rs); wry already builds this crate.
-objc2-web-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "WKContentRuleList", "WKContentRuleListStore", "WKUserContentController", "WKWebView", "WKWebViewConfiguration", "WKWebsiteDataStore", "WKSnapshotConfiguration", "objc2-app-kit", "objc2-core-foundation"] }
+# (browser_capture.rs) and context menu downloads (browser_context_downloads.rs); wry already
+# builds this crate.
+objc2-web-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "WKContentRuleList", "WKContentRuleListStore", "WKDownload", "WKDownloadDelegate", "WKNavigationDelegate", "WKUserContentController", "WKWebView", "WKWebViewConfiguration", "WKWebsiteDataStore", "WKSnapshotConfiguration", "objc2-app-kit", "objc2-core-foundation"] }
block2 = "0.6"
[target.'cfg(target_os = "linux")'.dependencies]
diff --git a/studio/src-tauri/src/browser_context_downloads.rs b/studio/src-tauri/src/browser_context_downloads.rs
new file mode 100644
index 00000000000..39715c6cd9d
--- /dev/null
+++ b/studio/src-tauri/src/browser_context_downloads.rs
@@ -0,0 +1,189 @@
+//! macOS context menu downloads (Download Image, Download Linked File, Download Video). WebKit
+//! hands them to a navigation delegate callback wry lacks, so they never started. Route them
+//! through the panel's download path as a save-as.
+
+use std::{cell::RefCell, collections::HashMap, path::PathBuf, ptr, rc::Rc};
+
+use objc2::{
+ define_class, ffi, msg_send,
+ rc::Retained,
+ runtime::{AnyObject, Imp, NSObject, ProtocolObject, Sel},
+ sel, MainThreadOnly,
+};
+use objc2_foundation::{
+ MainThreadMarker, NSData, NSError, NSObjectProtocol, NSString, NSURLResponse, NSURL,
+};
+use objc2_web_kit::{WKDownload, WKDownloadDelegate, WKWebView};
+use tauri::{Manager, Runtime, Webview};
+use url::Url;
+
+use crate::browser_webview::{download_finished, download_requested};
+
+/// Stages a tab's download; false refuses it.
+type Request = Rc<dyn Fn(Url, &mut PathBuf, bool) -> bool>;
+/// Settles a finished download. Holds no view, which may close first.
+type Finish = Rc<dyn Fn(Url, PathBuf, bool)>;
+type Hook = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut WKWebView, *mut WKDownload);
+
+thread_local! {
+ /// Tab views by WKWebView address.
+ static VIEWS: RefCell<HashMap<usize, (Request, Finish)>> = RefCell::new(HashMap::new());
+ /// Downloads in flight: how to settle them, their address and destination.
+ static ACTIVE: RefCell<HashMap<usize, (Finish, Url, PathBuf)>> = RefCell::new(HashMap::new());
+ /// A download keeps only a weak reference to its delegate.
+ static DELEGATE: RefCell<Option<Retained<ContextDownloadDelegate>>> = const { RefCell::new(None) };
+}
+
+define_class!(
+ #[unsafe(super(NSObject))]
+ #[thread_kind = MainThreadOnly]
+ struct ContextDownloadDelegate;
+
+ unsafe impl NSObjectProtocol for ContextDownloadDelegate {}
+
+ unsafe impl WKDownloadDelegate for ContextDownloadDelegate {
+ #[unsafe(method(download:decideDestinationUsingResponse:suggestedFilename:completionHandler:))]
+ fn decide(
+ &self,
+ download: &WKDownload,
+ _response: &NSURLResponse,
+ suggested: &NSString,
+ done: &block2::DynBlock<dyn Fn(*mut NSURL)>,
+ ) {
+ match start(download, suggested) {
+ Some(path) => {
+ let path = NSString::from_str(&path.to_string_lossy());
+ let url = NSURL::fileURLWithPath_isDirectory(&path, false);
+ done.call((Retained::as_ptr(&url).cast_mut(),));
+ }
+ None => done.call((ptr::null_mut(),)),
+ }
+ }
+
+ #[unsafe(method(downloadDidFinish:))]
+ fn did_finish(&self, download: &WKDownload) {
+ finish(download, true);
+ }
+
+ #[unsafe(method(download:didFailWithError:resumeData:))]
+ fn did_fail(&self, download: &WKDownload, _error: &NSError, _resume: Option<&NSData>) {
+ finish(download, false);
+ }
+ }
+);
+
+/// Send this tab's context menu downloads down the panel's download path.
+pub(crate) fn watch<R: Runtime>(webview: &Webview<R>, tab: &str) {
+ let app = webview.app_handle().clone();
+ let (label, tab) = (webview.label().to_string(), tab.to_string());
+ let _ = webview.with_webview(move |platform| {
+ // Safety: wry's live view, on the main thread.
+ let Some(view) = (unsafe { (platform.inner() as *const WKWebView).as_ref() }) else {
+ return;
+ };
+ let Some(navigation) = (unsafe { view.navigationDelegate() }) else {
+ return;
+ };
+ add_hook((*navigation).as_ref());
+ // WebKit caches which callbacks a delegate has when it is set: set it again.
+ unsafe { view.setNavigationDelegate(Some(&navigation)) };
+ let request_app = app.clone();
+ let request: Request = Rc::new(move |url, destination, save_as| {
+ let Some(page) = request_app.get_webview(&label) else {
+ return false;
+ };
+ download_requested(&page, &tab, url, destination, save_as)
+ });
+ let finish: Finish =
+ Rc::new(move |url, path, success| download_finished(&app, url, Some(path), success));
+ VIEWS.with(|views| views.borrow_mut().insert(key(view), (request, finish)));
+ });
+}
+
+/// Drop a closing view's entry; runs before the close. Its downloads still settle via `ACTIVE`.
+pub(crate) fn forget<R: Runtime>(webview: &Webview<R>) {
+ let _ = webview.with_webview(|platform| {
+ let view = platform.inner() as usize;
+ VIEWS.with(|views| views.borrow_mut().remove(&view));
+ });
+}
+
+fn key<T>(object: &T) -> usize {
+ object as *const T as usize
+}
+
+/// Give wry's navigation delegate class the private callback WebKit calls for context menu downloads.
+fn add_hook(ui: &AnyObject) {
+ let class = ui.class();
+ let name = sel!(_webView:contextMenuDidCreateDownload:);
+ if class.responds_to(name) {
+ return;
+ }
+ let hook: Hook = context_menu_did_create_download;
+ // Safety: the signature matches the "v@:@@" encoding.
+ unsafe {
+ ffi::class_addMethod(
+ (class as *const objc2::runtime::AnyClass).cast_mut(),
+ name,
+ std::mem::transmute::<Hook, Imp>(hook),
+ c"v@:@@".as_ptr(),
+ );
+ }
+}
+
+unsafe extern "C-unwind" fn context_menu_did_create_download(
+ _this: *mut AnyObject,
+ _cmd: Sel,
+ view: *mut WKWebView,
+ download: *mut WKDownload,
+) {
+ // Safety: WebKit passes live objects on the main thread.
+ let (Some(view), Some(download)) = (unsafe { view.as_ref() }, unsafe { download.as_ref() })
+ else {
+ return;
+ };
+ if !VIEWS.with(|views| views.borrow().contains_key(&key(view))) {
+ return;
+ }
+ let Some(mtm) = MainThreadMarker::new() else {
+ return;
+ };
+ DELEGATE.with(|cell| {
+ let delegate = cell
+ .borrow_mut()
+ .get_or_insert_with(|| unsafe {
+ msg_send![mtm.alloc::<ContextDownloadDelegate>(), init]
+ })
+ .clone();
+ unsafe { download.setDelegate(Some(ProtocolObject::from_ref(&*delegate))) };
+ });
+}
+
+/// Stage the download as a save-as. None refuses it.
+fn start(download: &WKDownload, suggested: &NSString) -> Option<PathBuf> {
+ let view = unsafe { download.webView() }?;
+ let (request, finish) = VIEWS.with(|views| views.borrow().get(&key(&*view)).cloned())?;
+ let address = unsafe { download.originalRequest() }?
+ .URL()?
+ .absoluteString()?;
+ let url = Url::parse(&address.to_string()).ok()?;
+ let mut destination = PathBuf::from(suggested.to_string());
+ if !request(url.clone(), &mut destination, true) {
+ return None;
+ }
+ ACTIVE.with(|active| {
+ active
+ .borrow_mut()
+ .insert(key(download), (finish, url, destination.clone()))
+ });
+ Some(destination)
+}
+
+fn finish(download: &WKDownload, success: bool) {
+ let Some((finish, url, path)) =
+ ACTIVE.with(|active| active.borrow_mut().remove(&key(download)))
+ else {
+ return;
+ };
+ finish(url, path, success);
+}
diff --git a/studio/src-tauri/src/browser_webview.rs b/studio/src-tauri/src/browser_webview.rs
index 0e870fb601f..ed5f9634fa8 100644
--- a/studio/src-tauri/src/browser_webview.rs
+++ b/studio/src-tauri/src/browser_webview.rs
@@ -257,6 +257,8 @@ enum BrowserEvent {
site: String,
name: String,
id: String,
+ /// Started from the page's context menu: the user asked for it, so save it via a dialog.
+ save_as: bool,
},
}
@@ -947,6 +949,136 @@ async fn poll_url<R: Runtime>(app: AppHandle<R>) {
}
}
+/// Stage a tab's download and ask about it. False refuses it.
+pub(crate) fn download_requested<R: Runtime>(
+ webview: &Webview<R>,
+ download_tab: &str,
+ url: Url,
+ destination: &mut PathBuf,
+ save_as: bool,
+) -> bool {
+ let app = webview.app_handle();
+ if crate::browser_downloads::unanswered(app, download_tab)
+ >= crate::browser_downloads::MAX_UNANSWERED_PER_TAB
+ {
+ let name = destination
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ emit_download_failed(app, download_tab, &url, &name, None);
+ return false;
+ }
+ let Some((id, staging)) = crate::browser_downloads::staging_dir(app) else {
+ return false;
+ };
+ let path = {
+ let state = app.state::<BrowserViews>();
+ let mut inner = state.inner.lock().unwrap();
+ // macOS reports no path when a download finishes, so two of one URL at
+ // once couldn't be told apart: one at a time.
+ let busy = cfg!(target_os = "macos") && inner.downloads.contains_key(url.as_str());
+ let in_flight = inner.downloads.values().map(Vec::len).sum();
+ let starts = inner
+ .download_starts
+ .entry(download_tab.to_string())
+ .or_default();
+ if busy || !download_allowed(in_flight, starts, Instant::now()) {
+ drop(inner);
+ let _ = std::fs::remove_dir_all(&staging);
+ if !busy {
+ let name = destination
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ emit_download_failed(app, download_tab, &url, &name, None);
+ }
+ return false;
+ }
+ let path = download_destination(&staging, destination, &HashSet::new());
+ inner
+ .downloads
+ .entry(url.to_string())
+ .or_default()
+ .push(path.clone());
+ path
+ };
+ let name = path
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ *destination = path.clone();
+ crate::browser_downloads::add_pending(
+ app,
+ id.clone(),
+ download_tab.to_string(),
+ url.clone(),
+ path,
+ );
+ // "" before the view showed its own page: the frontend knows the tab's address or opener.
+ let committed = app
+ .state::<BrowserViews>()
+ .inner
+ .lock()
+ .unwrap()
+ .committed
+ .contains(download_tab);
+ let site = match webview.url() {
+ Ok(page) if committed => page.to_string(),
+ _ => String::new(),
+ };
+ emit(
+ app,
+ BrowserEvent::DownloadPrompt {
+ tab_id: download_tab.to_string(),
+ url: url.to_string(),
+ site,
+ name,
+ id,
+ save_as,
+ },
+ );
+ true
+}
+
+/// Settle a finished download. Needs no view: its tab may have closed meanwhile.
+pub(crate) fn download_finished<R: Runtime>(
+ app: &AppHandle<R>,
+ url: Url,
+ path: Option<PathBuf>,
+ success: bool,
+) {
+ let (recorded, retired) = {
+ let state = app.state::<BrowserViews>();
+ let mut inner = state.inner.lock().unwrap();
+ let ViewsState {
+ downloads,
+ unexplained_finishes,
+ ..
+ } = &mut *inner;
+ let key = url.to_string();
+ let mut unexplained = unexplained_finishes.remove(&key).unwrap_or(0);
+ let pending = downloads.entry(key.clone()).or_default();
+ let taken = take_finished(pending, &mut unexplained, path.as_deref());
+ if pending.is_empty() {
+ downloads.remove(&key);
+ } else if unexplained > 0 {
+ unexplained_finishes.insert(key, unexplained);
+ }
+ taken
+ };
+ // The reserved path first: the engine may report another spelling of it.
+ crate::browser_downloads::finished(app, [recorded.as_deref(), path.as_deref()], success);
+ for staged in retired {
+ crate::browser_downloads::finished(app, [Some(&staged), None], false);
+ }
+}
+
+fn close_view<R: Runtime>(page: &Webview<R>) -> tauri::Result<()> {
+ #[cfg(target_os = "macos")]
+ crate::browser_context_downloads::forget(page);
+ page.close()
+}
+
fn create_view<R: Runtime>(
caller: &Webview<R>,
tab_id: &str,
@@ -1061,124 +1193,15 @@ fn create_view<R: Runtime>(
}
NewWindowResponse::Deny
})
- .on_download(move |webview, event| {
- let app = webview.app_handle();
- match event {
- DownloadEvent::Requested { url, destination } => {
- if crate::browser_downloads::unanswered(app, &download_tab)
- >= crate::browser_downloads::MAX_UNANSWERED_PER_TAB
- {
- let name = destination
- .file_name()
- .map(|name| name.to_string_lossy().into_owned())
- .unwrap_or_default();
- emit_download_failed(app, &download_tab, &url, &name, None);
- return false;
- }
- let Some((id, staging)) = crate::browser_downloads::staging_dir(app) else {
- return false;
- };
- let path = {
- let state = app.state::<BrowserViews>();
- let mut inner = state.inner.lock().unwrap();
- // macOS reports no path when a download finishes, so two of one URL at
- // once couldn't be told apart: one at a time.
- let busy =
- cfg!(target_os = "macos") && inner.downloads.contains_key(url.as_str());
- let in_flight = inner.downloads.values().map(Vec::len).sum();
- let starts = inner
- .download_starts
- .entry(download_tab.clone())
- .or_default();
- if busy || !download_allowed(in_flight, starts, Instant::now()) {
- drop(inner);
- let _ = std::fs::remove_dir_all(&staging);
- if !busy {
- let name = destination
- .file_name()
- .map(|name| name.to_string_lossy().into_owned())
- .unwrap_or_default();
- emit_download_failed(app, &download_tab, &url, &name, None);
- }
- return false;
- }
- let path = download_destination(&staging, destination, &HashSet::new());
- inner
- .downloads
- .entry(url.to_string())
- .or_default()
- .push(path.clone());
- path
- };
- let name = path
- .file_name()
- .map(|name| name.to_string_lossy().into_owned())
- .unwrap_or_default();
- *destination = path.clone();
- crate::browser_downloads::add_pending(
- app,
- id.clone(),
- download_tab.clone(),
- url.clone(),
- path,
- );
- // "" before the view showed its own page: the frontend knows the tab's address or opener.
- let committed = app
- .state::<BrowserViews>()
- .inner
- .lock()
- .unwrap()
- .committed
- .contains(&download_tab);
- let site = match webview.url() {
- Ok(page) if committed => page.to_string(),
- _ => String::new(),
- };
- emit(
- app,
- BrowserEvent::DownloadPrompt {
- tab_id: download_tab.clone(),
- url: url.to_string(),
- site,
- name,
- id,
- },
- );
- true
- }
- DownloadEvent::Finished { url, path, success } => {
- let (recorded, retired) = {
- let state = app.state::<BrowserViews>();
- let mut inner = state.inner.lock().unwrap();
- let ViewsState {
- downloads,
- unexplained_finishes,
- ..
- } = &mut *inner;
- let key = url.to_string();
- let mut unexplained = unexplained_finishes.remove(&key).unwrap_or(0);
- let pending = downloads.entry(key.clone()).or_default();
- let taken = take_finished(pending, &mut unexplained, path.as_deref());
- if pending.is_empty() {
- downloads.remove(&key);
- } else if unexplained > 0 {
- unexplained_finishes.insert(key, unexplained);
- }
- taken
- };
- // The reserved path first: the engine may report another spelling of it.
- crate::browser_downloads::finished(
- app,
- [recorded.as_deref(), path.as_deref()],
- success,
- );
- for staged in retired {
- crate::browser_downloads::finished(app, [Some(&staged), None], false);
- }
- true
- }
- _ => false,
+ .on_download(move |webview, event| match event {
+ DownloadEvent::Requested { url, destination } => {
+ download_requested(&webview, &download_tab, url, destination, false)
}
+ DownloadEvent::Finished { url, path, success } => {
+ download_finished(webview.app_handle(), url, path, success);
+ true
+ }
+ _ => false,
})
.zoom_hotkeys_enabled(false)
.devtools(cfg!(debug_assertions))
@@ -1190,6 +1213,8 @@ fn create_view<R: Runtime>(
let webview = window
.add_child(builder, position, size)
.map_err(|error| error.to_string())?;
+ #[cfg(target_os = "macos")]
+ crate::browser_context_downloads::watch(&webview, &tab);
// A muted tab whose view closed (four at most stay open) opens muted again.
if app.state::<BrowserViews>().inner.lock().unwrap().muted.contains(&tab) {
let _ = apply_mute(&webview, true);
@@ -1652,7 +1677,7 @@ pub fn browser_view_close<R: Runtime>(
}
}
if let Ok(page) = view(webview.app_handle(), &tab_id) {
- page.close().map_err(|error| error.to_string())?;
+ close_view(&page).map_err(|error| error.to_string())?;
}
Ok(())
}
@@ -1675,7 +1700,7 @@ pub async fn browser_view_clear_data<R: Runtime>(
set_shown(&state, &mut inner, None);
}
for page in browser_views(&app) {
- let _ = page.close();
+ let _ = close_view(&page);
}
}
let live = if closing {
@@ -1709,7 +1734,7 @@ pub async fn browser_view_clear_data<R: Runtime>(
};
let result = clear_profile(&page).await;
if hidden {
- let _ = page.close();
+ let _ = close_view(&page);
}
result
}
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index 844d6d30620..dd6d8b913dd 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -3,6 +3,8 @@
mod app_layout;
mod app_menu;
mod browser_capture;
+#[cfg(target_os = "macos")]
+mod browser_context_downloads;
mod browser_downloads;
mod browser_proxy;
mod browser_webview;