Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

feat(linux): ask before a page uses the camera or microphone, and recover from a failed load

Tw93404369a587d9
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 44229e82..82f10b33 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2589,6 +2589,7 @@ version = "3.18.0"
dependencies = [
"block2",
"dispatch",
+ "gtk",
"objc2",
"objc2-app-kit",
"objc2-foundation",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 5776d6c9..671ad356 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -57,6 +57,9 @@ objc2-web-kit = { version = "0.3", default-features = false, features = [
# Version and features must match what wry resolves, or PlatformWebview::inner
# hands back a WebView from a different crate instance.
webkit2gtk = { version = "=2.0.2", features = ["v2_40"] }
+# The camera and microphone question (media_permission.rs). The version wry and
+# tao already lock, so its Window is the one WebView::toplevel hands back.
+gtk = "0.18"
# Reads the freedesktop color-scheme from the settings portal. Same version
# and features that tauri-plugin-opener and single-instance already lock.
zbus = "5.14"
diff --git a/src-tauri/src/app/media_permission.rs b/src-tauri/src/app/media_permission.rs
new file mode 100644
index 00000000..0413c225
--- /dev/null
+++ b/src-tauri/src/app/media_permission.rs
@@ -0,0 +1,175 @@
+//! Camera and microphone for pages on Linux.
+//!
+//! WebKitGTK refuses `getUserMedia` unless the embedder answers its
+//! `permission-request` signal, and neither wry nor Pake did, so a call or
+//! voice page never got a device. Linux has no system prompt for this as
+//! macOS and WebView2 do, so Pake asks once per site and run.
+
+use gtk::prelude::*;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use webkit2gtk::{
+ DeviceInfoPermissionRequest, PermissionRequestExt, SettingsExt, UserMediaPermissionRequest,
+ UserMediaPermissionRequestExt, WebViewExt,
+};
+
+thread_local! {
+ /// The answers given in this run, by host and device kinds.
+ static ANSWERS: RefCell<HashMap<String, bool>> = RefCell::new(HashMap::new());
+}
+
+pub fn install(webview: &tauri::webview::PlatformWebview) {
+ let gtk_webview = webview.inner();
+ if let Some(settings) = WebViewExt::settings(&gtk_webview) {
+ settings.set_enable_media_stream(true);
+ settings.set_enable_webrtc(true);
+ }
+
+ gtk_webview.connect_permission_request(|webview, request| {
+ let host = webview
+ .uri()
+ .and_then(|uri| tauri::Url::parse(uri.as_str()).ok())
+ .and_then(|url| url.host_str().map(str::to_owned))
+ .unwrap_or_default();
+
+ // Device labels in enumerateDevices follow what the site was already allowed.
+ if request.is::<DeviceInfoPermissionRequest>() {
+ if host_was_allowed(&host) {
+ request.allow();
+ } else {
+ request.deny();
+ }
+ return true;
+ }
+
+ let Some(media) = request.downcast_ref::<UserMediaPermissionRequest>() else {
+ return false;
+ };
+ let audio = media.is_for_audio_device();
+ let video = media.is_for_video_device();
+ let key = answer_key(&host, audio, video);
+ if let Some(allowed) = ANSWERS.with(|answers| answers.borrow().get(&key).copied()) {
+ answer(request, allowed);
+ return true;
+ }
+
+ let parent = webview
+ .toplevel()
+ .and_then(|widget| widget.downcast::<gtk::Window>().ok());
+ let (question, deny, allow) = prompt_text(
+ &host,
+ audio,
+ video,
+ crate::util::UiLanguage::system() != crate::util::UiLanguage::English,
+ );
+ let dialog = gtk::MessageDialog::new(
+ parent.as_ref(),
+ gtk::DialogFlags::MODAL,
+ gtk::MessageType::Question,
+ gtk::ButtonsType::None,
+ &question,
+ );
+ dialog.add_button(deny, gtk::ResponseType::Reject);
+ dialog.add_button(allow, gtk::ResponseType::Accept);
+ let request = request.clone();
+ dialog.connect_response(move |dialog, response| {
+ // Closing the dialog without choosing is a refusal that is asked again next time.
+ if matches!(
+ response,
+ gtk::ResponseType::Accept | gtk::ResponseType::Reject
+ ) {
+ let allowed = response == gtk::ResponseType::Accept;
+ ANSWERS.with(|answers| answers.borrow_mut().insert(key.clone(), allowed));
+ answer(&request, allowed);
+ } else {
+ request.deny();
+ }
+ dialog.close();
+ });
+ dialog.show();
+ true
+ });
+}
+
+fn answer(request: &webkit2gtk::PermissionRequest, allowed: bool) {
+ if allowed {
+ request.allow();
+ } else {
+ request.deny();
+ }
+}
+
+fn host_was_allowed(host: &str) -> bool {
+ let prefix = format!("{host}|");
+ ANSWERS.with(|answers| {
+ answers
+ .borrow()
+ .iter()
+ .any(|(key, allowed)| *allowed && key.starts_with(&prefix))
+ })
+}
+
+pub(crate) fn answer_key(host: &str, audio: bool, video: bool) -> String {
+ format!("{host}|{}{}", u8::from(audio), u8::from(video))
+}
+
+/// The question and its two buttons, refusal first.
+pub(crate) fn prompt_text(
+ host: &str,
+ audio: bool,
+ video: bool,
+ chinese: bool,
+) -> (String, &'static str, &'static str) {
+ if chinese {
+ let devices = match (audio, video) {
+ (true, true) => "摄像头和麦克风",
+ (false, true) => "摄像头",
+ _ => "麦克风",
+ };
+ (format!("{host} 想使用{devices}"), "不允许", "允许")
+ } else {
+ let devices = match (audio, video) {
+ (true, true) => "camera and microphone",
+ (false, true) => "camera",
+ _ => "microphone",
+ };
+ (
+ format!("{host} wants to use your {devices}"),
+ "Don't Allow",
+ "Allow",
+ )
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_prompt_names_the_site_and_only_the_devices_asked_for() {
+ assert_eq!(
+ prompt_text("meet.google.com", true, true, false).0,
+ "meet.google.com wants to use your camera and microphone"
+ );
+ assert_eq!(
+ prompt_text("chatgpt.com", true, false, false).0,
+ "chatgpt.com wants to use your microphone"
+ );
+ assert_eq!(
+ prompt_text("meet.google.com", false, true, true),
+ ("meet.google.com 想使用摄像头".to_string(), "不允许", "允许")
+ );
+ }
+
+ #[test]
+ fn an_answer_is_kept_per_site_and_device_kinds() {
+ assert_ne!(
+ answer_key("a.example", true, false),
+ answer_key("a.example", true, true)
+ );
+ assert_ne!(
+ answer_key("a.example", true, true),
+ answer_key("b.example", true, true)
+ );
+ }
+}
diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rs
index 7bccb6ac..648a4b05 100644
--- a/src-tauri/src/app/mod.rs
+++ b/src-tauri/src/app/mod.rs
@@ -6,10 +6,14 @@ pub mod config;
#[cfg(target_os = "windows")]
pub mod download;
pub mod invoke;
+#[cfg(target_os = "linux")]
+pub mod media_permission;
#[cfg(target_os = "macos")]
pub mod menu;
pub mod navigation;
pub mod notification;
+#[cfg(any(target_os = "linux", target_os = "windows", test))]
+pub mod recovery;
pub mod setup;
#[cfg(target_os = "macos")]
pub mod tab_bar;
diff --git a/src-tauri/src/app/recovery.rs b/src-tauri/src/app/recovery.rs
new file mode 100644
index 00000000..60290812
--- /dev/null
+++ b/src-tauri/src/app/recovery.rs
@@ -0,0 +1,122 @@
+//! Getting back from a page that failed to load or a web process that died.
+//!
+//! WebKitGTK shows a bare engine message for a failed load and a dead grey view
+//! after its web process exits; WebView2 has its own error page but leaves a
+//! blank view after a renderer crash. Neither had a way back short of knowing
+//! Ctrl+R. macOS is not covered: Tauri 2.10 exposes neither hook for WKWebView.
+
+#[cfg(target_os = "linux")]
+pub fn install(webview: &tauri::webview::PlatformWebview) {
+ use webkit2gtk::{NetworkError, PluginError, PolicyError, WebViewExt};
+
+ let gtk_webview = webview.inner();
+ gtk_webview.connect_load_failed(|webview, _event, uri, error| {
+ // A cancelled load, a load a download took over and a policy refusal are not failures.
+ if error.kind::<NetworkError>() == Some(NetworkError::Cancelled)
+ || error.is::<PolicyError>()
+ || error.is::<PluginError>()
+ || uri.starts_with("about:")
+ {
+ return false;
+ }
+ let host = tauri::Url::parse(uri)
+ .ok()
+ .and_then(|url| url.host_str().map(str::to_owned))
+ .unwrap_or_default();
+ let chinese = crate::util::UiLanguage::system() != crate::util::UiLanguage::English;
+ // The failed address stays the page's own, so Try Again and Ctrl+R load it again.
+ webview.load_alternate_html(&error_page(&host, chinese), uri, None);
+ true
+ });
+ gtk_webview.connect_web_process_terminated(|webview, _reason| {
+ webview.reload();
+ });
+}
+
+#[cfg(target_os = "windows")]
+pub fn install(webview: &tauri::webview::PlatformWebview) {
+ use webview2_com::{
+ Microsoft::Web::WebView2::Win32::{
+ COREWEBVIEW2_PROCESS_FAILED_KIND,
+ COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_EXITED,
+ },
+ ProcessFailedEventHandler,
+ };
+
+ let result = unsafe {
+ (|| -> windows_core::Result<()> {
+ let core = webview.controller().CoreWebView2()?;
+ let mut token = 0;
+ core.add_ProcessFailed(
+ &ProcessFailedEventHandler::create(Box::new(|core, args| {
+ let (Some(core), Some(args)) = (core, args) else {
+ return Ok(());
+ };
+ let mut kind = COREWEBVIEW2_PROCESS_FAILED_KIND(0);
+ args.ProcessFailedKind(&mut kind)?;
+ // Only a dead renderer leaves a view that a reload brings back.
+ if kind == COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_EXITED {
+ core.Reload()?;
+ }
+ Ok(())
+ })),
+ &mut token,
+ )
+ })()
+ };
+ if let Err(error) = result {
+ eprintln!("[Pake] Failed to watch for a WebView2 renderer crash: {error}");
+ }
+}
+
+/// A self-contained page for a load that failed: what happened, the site, one way back.
+#[cfg(any(target_os = "linux", test))]
+pub(crate) fn error_page(host: &str, chinese: bool) -> String {
+ let (title, hint, retry) = if chinese {
+ ("无法打开此页面", "检查网络后再试一次", "重试")
+ } else {
+ (
+ "Can't open this page",
+ "Check your network, then try again.",
+ "Try Again",
+ )
+ };
+ let host = host
+ .replace('&', "&amp;")
+ .replace('<', "&lt;")
+ .replace('>', "&gt;");
+ format!(
+ r#"<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{title}</title><style>
+html,body{{height:100%;margin:0}}
+body{{display:flex;align-items:center;justify-content:center;font:14px/1.5 system-ui,-apple-system,"Segoe UI","Noto Sans CJK SC",sans-serif;background:#fff;color:#1d1d1f}}
+main{{text-align:center;padding:24px;max-width:420px}}
+h1{{font-size:20px;font-weight:600;margin:0 0 6px}}
+p{{margin:0;color:#6e6e73}}
+.host{{margin-top:2px;word-break:break-all}}
+button{{margin-top:20px;font:inherit;padding:7px 18px;border-radius:8px;border:0;background:#1d1d1f;color:#fff;cursor:pointer}}
+@media (prefers-color-scheme:dark){{body{{background:#1c1c1e;color:#f5f5f7}}p{{color:#98989d}}button{{background:#f5f5f7;color:#1c1c1e}}}}
+</style></head><body><main><h1>{title}</h1><p>{hint}</p><p class="host">{host}</p><button onclick="location.reload()">{retry}</button></main></body></html>"#
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_error_page_names_the_site_and_offers_one_way_back() {
+ let page = error_page("example.com", false);
+ assert!(page.contains("Can't open this page"));
+ assert!(page.contains(r#"<p class="host">example.com</p>"#));
+ assert_eq!(page.matches("<button").count(), 1);
+ assert!(page.contains("location.reload()"));
+ assert!(error_page("example.com", true).contains("无法打开此页面"));
+ }
+
+ #[test]
+ fn a_host_cannot_inject_markup_into_the_error_page() {
+ let page = error_page("<script>alert(1)</script>", false);
+ assert!(!page.contains("<script>"));
+ assert!(page.contains("&lt;script&gt;"));
+ }
+}
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index 6ead56a7..1edbf5eb 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -883,6 +883,22 @@ fn build_window(
#[cfg(target_os = "windows")]
crate::app::download::install(&window, download_target)?;
+ // Every webview is built here, so every one can be asked for the camera and microphone.
+ #[cfg(target_os = "linux")]
+ if let Err(error) = window.with_webview(|webview| {
+ crate::app::media_permission::install(&webview);
+ crate::app::recovery::install(&webview);
+ }) {
+ eprintln!("[Pake] Failed to access WebKitGTK for media permissions and recovery: {error}");
+ }
+
+ #[cfg(target_os = "windows")]
+ if let Err(error) = window.with_webview(|webview| {
+ crate::app::recovery::install(&webview);
+ }) {
+ eprintln!("[Pake] Failed to access WebView2 for crash recovery: {error}");
+ }
+
// 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")]