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: let the page keep its keys, stop endless crash reloads, and escape the autostart entry
Tw9365513dedae38
diff --git a/src-tauri/src/app/autostart.rs b/src-tauri/src/app/autostart.rsindex 0fbf746b..a39e860b 100644--- a/src-tauri/src/app/autostart.rs+++ b/src-tauri/src/app/autostart.rs@@ -77,11 +77,25 @@ pub(crate) fn launch_agent(identifier: &str, executable: &Path) -> String {)}-/// An XDG autostart entry. Exec quotes the path and doubles `%`, which the-/// desktop entry format reads as a field code.+/// A desktop-entry string value: the format unescapes backslash sequences before anything else.#[cfg(any(target_os = "linux", test))]-pub(crate) fn autostart_entry(name: &str, executable: &Path) -> String {+fn entry_value(text: &str) -> String {+ text.replace('\\', "\\\\")+ .replace('\n', "\\n")+ .replace('\r', "\\r")+ .replace('\t', "\\t")+}++/// An XDG autostart entry, or None for a path the Exec key cannot carry (`=`, a control+/// character). The argument is quoted first (a backslash before `"`, a backtick, `$` and `\`,+/// `%` doubled) and then escaped as a string value, since unescaping happens before unquoting.+/// GLib checks argv[0] before it expands `%%`, so a path with `%` is passed to env instead.+#[cfg(any(target_os = "linux", test))]+pub(crate) fn autostart_entry(name: &str, executable: &Path) -> Option<String> {let path = executable.to_string_lossy();+ if path.contains('=') || path.chars().any(char::is_control) {+ return None;+ }let mut quoted = String::with_capacity(path.len() + 2);quoted.push('"');for character in path.chars() {@@ -95,10 +109,16 @@ pub(crate) fn autostart_entry(name: &str, executable: &Path) -> String {}}quoted.push('"');+ let command = if path.contains('%') {+ format!("/usr/bin/env -- {}", entry_value("ed))+ } else {+ entry_value("ed)+ };let name: String = name.chars().filter(|c| !c.is_control()).collect();- format!(- "[Desktop Entry]\nType=Application\nName={name}\nExec={quoted}\nTerminal=false\nX-GNOME-Autostart-enabled=true\n"- )+ Some(format!(+ "[Desktop Entry]\nType=Application\nName={}\nExec={command}\nTerminal=false\nX-GNOME-Autostart-enabled=true\n",+ entry_value(&name)+ ))}#[cfg(target_os = "macos")]@@ -142,7 +162,12 @@ mod platform {let path = config.join("autostart").join(format!("{identifier}.desktop"));- let content = enabled.then(|| autostart_entry(name, executable));+ // A path the entry cannot carry gets no login item rather than a broken one.+ let content = if enabled {+ autostart_entry(name, executable)+ } else {+ None+ };sync_file(&path, content.as_deref())}}@@ -233,11 +258,22 @@ mod tests {}#[test]- fn the_autostart_entry_quotes_the_path_and_doubles_percent() {- let entry = autostart_entry("Hacker\nNews", Path::new("/home/a b/50%/com.pake.a1"));+ fn the_autostart_entry_quotes_then_escapes_the_path() {+ let entry = autostart_entry("Hacker\nNews", Path::new("/home/a b/com.pake.a1")).unwrap();assert!(entry.contains("Name=HackerNews\n"));- assert!(entry.contains("Exec=\"/home/a b/50%%/com.pake.a1\"\n"));+ assert!(entry.contains("Exec=\"/home/a b/com.pake.a1\"\n"));assert!(entry.starts_with("[Desktop Entry]\nType=Application\n"));++ // Quoted first, then escaped as a string value: a `$` gets one backslash, doubled.+ let odd = autostart_entry("A", Path::new("/home/a$b/x")).unwrap();+ assert!(odd.contains("Exec=\"/home/a\\\\$b/x\"\n"), "{odd}");+ // GLib checks argv[0] before expanding %%, so env carries such a path.+ let percent = autostart_entry("A", Path::new("/home/50%/x")).unwrap();+ assert!(+ percent.contains("Exec=/usr/bin/env -- \"/home/50%%/x\"\n"),+ "{percent}"+ );+ assert!(autostart_entry("A", Path::new("/home/a=b/x")).is_none());}#[test]diff --git a/src-tauri/src/app/media_permission.rs b/src-tauri/src/app/media_permission.rsindex 0413c225..62d4ba4c 100644--- a/src-tauri/src/app/media_permission.rs+++ b/src-tauri/src/app/media_permission.rs@@ -64,7 +64,7 @@ pub fn install(webview: &tauri::webview::PlatformWebview) {);let dialog = gtk::MessageDialog::new(parent.as_ref(),- gtk::DialogFlags::MODAL,+ gtk::DialogFlags::MODAL | gtk::DialogFlags::DESTROY_WITH_PARENT,gtk::MessageType::Question,gtk::ButtonsType::None,&question,@@ -72,7 +72,13 @@ pub fn install(webview: &tauri::webview::PlatformWebview) {dialog.add_button(deny, gtk::ResponseType::Reject);dialog.add_button(allow, gtk::ResponseType::Accept);let request = request.clone();+ // The request is answered once: destroying the dialog raises no second response, where+ // close() would send a delete-event and with it another one.+ let answered = std::cell::Cell::new(false);dialog.connect_response(move |dialog, response| {+ if answered.replace(true) {+ return;+ }// Closing the dialog without choosing is a refusal that is asked again next time.if matches!(response,@@ -84,7 +90,7 @@ pub fn install(webview: &tauri::webview::PlatformWebview) {} else {request.deny();}- dialog.close();+ unsafe { dialog.destroy() };});dialog.show();truediff --git a/src-tauri/src/app/recovery.rs b/src-tauri/src/app/recovery.rsindex 60290812..c17ec944 100644--- a/src-tauri/src/app/recovery.rs+++ b/src-tauri/src/app/recovery.rs@@ -5,6 +5,30 @@//! 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.+/// A page that takes its renderer down on every load must not be reloaded for ever: after+/// `MAX_RELOADS` in `RELOAD_WINDOW` the view is left as it is.+const MAX_RELOADS: usize = 2;+const RELOAD_WINDOW: std::time::Duration = std::time::Duration::from_secs(60);++/// True when one more automatic reload is within the limit, and counts it.+pub(crate) fn may_reload(recent: &mut Vec<std::time::Instant>, now: std::time::Instant) -> bool {+ recent.retain(|at| now.duration_since(*at) < RELOAD_WINDOW);+ if recent.len() >= MAX_RELOADS {+ return false;+ }+ recent.push(now);+ true+}++#[cfg(any(target_os = "linux", target_os = "windows"))]+fn reload_allowed() -> bool {+ use std::cell::RefCell;+ thread_local! {+ static RECENT: RefCell<Vec<std::time::Instant>> = const { RefCell::new(Vec::new()) };+ }+ RECENT.with(|recent| may_reload(&mut recent.borrow_mut(), std::time::Instant::now()))+}+#[cfg(target_os = "linux")]pub fn install(webview: &tauri::webview::PlatformWebview) {use webkit2gtk::{NetworkError, PluginError, PolicyError, WebViewExt};@@ -29,7 +53,18 @@ pub fn install(webview: &tauri::webview::PlatformWebview) {true});gtk_webview.connect_web_process_terminated(|webview, _reason| {- webview.reload();+ if reload_allowed() {+ webview.reload();+ return;+ }+ // Past the limit the page gets the same way back as a failed load, and no more reloads.+ let uri = webview.uri().map(|uri| uri.to_string()).unwrap_or_default();+ 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;+ webview.load_alternate_html(&error_page(&host, chinese), &uri, None);});}@@ -55,7 +90,9 @@ pub fn install(webview: &tauri::webview::PlatformWebview) {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 {+ if kind == COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_EXITED+ && reload_allowed()+ {core.Reload()?;}Ok(())@@ -113,6 +150,30 @@ mod tests {assert!(error_page("example.com", true).contains("无法打开此页面"));}+ #[test]+ fn a_page_that_keeps_crashing_is_reloaded_twice_a_minute_at_most() {+ let start = std::time::Instant::now();+ let mut recent = Vec::new();+ assert!(may_reload(&mut recent, start));+ assert!(may_reload(+ &mut recent,+ start + std::time::Duration::from_secs(1)+ ));+ assert!(!may_reload(+ &mut recent,+ start + std::time::Duration::from_secs(2)+ ));+ assert!(!may_reload(+ &mut recent,+ start + std::time::Duration::from_secs(59)+ ));+ // Once the first reload is a minute old there is room for one more.+ assert!(may_reload(+ &mut recent,+ start + std::time::Duration::from_secs(61)+ ));+ }+#[test]fn a_host_cannot_inject_markup_into_the_error_page() {let page = error_page("<script>alert(1)</script>", false);diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.jsindex 3dcbf67b..1319ae2f 100644--- a/src-tauri/src/inject/event.js+++ b/src-tauri/src/inject/event.js@@ -128,28 +128,37 @@ const altShortcuts = {ArrowRight: () => nativeNavigate("forward"),};-function handleWebShortcut(event) {- if (isNonMacDesktop() && event.ctrlKey) {- const plain = !event.shiftKey && !event.altKey && !event.metaKey;- const windowShortcut = plain && windowShortcuts[event.key?.toLowerCase?.()];- if (windowShortcut) {- event.preventDefault();- windowShortcut();- return;- }- handleShortcut(event);+// The page gets these keys first: this listens on window for keydown in the+// bubble phase, after the page's own handlers, and leaves alone a key the page+// prevented. A web terminal or editor that takes Ctrl+W (delete a word), Ctrl+L+// (clear) or Alt+Left (word left) on keydown keeps it, as find.js does for Ctrl+F.+function handleWindowShortcut(event) {+ if (!isNonMacDesktop() || event.defaultPrevented || event.repeat) {return;}- if (- isNonMacDesktop() &&+ let action;+ if (event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey) {+ action = windowShortcuts[event.key?.toLowerCase?.()];+ } else if (event.altKey &&+ !event.ctrlKey &&!event.shiftKey &&- !event.metaKey &&- altShortcuts[event.key]+ !event.metaKey) {- event.preventDefault();- altShortcuts[event.key]();+ action = altShortcuts[event.key];+ }+ if (!action) {+ return;+ }++ event.preventDefault();+ action();+}++function handleWebShortcut(event) {+ if (isNonMacDesktop() && event.ctrlKey) {+ handleShortcut(event);return;}@@ -742,6 +751,7 @@ document.addEventListener("DOMContentLoaded", () => {if (window["pakeConfig"]?.disabled_web_shortcuts !== true) {document.addEventListener("keydown", handleWindowFullscreenShortcut, true);document.addEventListener("keyup", handleWebShortcut);+ window.addEventListener("keydown", handleWindowShortcut);}document.addEventListener("keydown", handleClipboardShortcut, true);diff --git a/tests/unit/event-fullscreen-shortcuts.test.js b/tests/unit/event-fullscreen-shortcuts.test.jsindex c9fd2ebb..baf956d6 100644--- a/tests/unit/event-fullscreen-shortcuts.test.js+++ b/tests/unit/event-fullscreen-shortcuts.test.js@@ -179,6 +179,12 @@ function getFullscreenShortcutHandler(context) {).handler;}+function getWindowShortcutHandler(context) {+ return context.eventListeners.keydown.find(+ ({ handler }) => handler.name === "handleWindowShortcut",+ ).handler;+}+function getWebShortcutHandler(context) {return context.eventListeners.keyup.find(({ handler }) => handler.name === "handleWebShortcut",@@ -245,7 +251,7 @@ describe("event fullscreen shortcuts", () => {},};context.window.location = { href: "https://example.com/page" };- const handler = getWebShortcutHandler(context);+ const handler = getWindowShortcutHandler(context);handler(createKeyEvent("w", { ctrlKey: true }));expect(context.closeCalls).toEqual(["close"]);@@ -263,7 +269,7 @@ describe("event fullscreen shortcuts", () => {it("goes back and forward on Alt+Left and Alt+Right on Windows and Linux", () => {const context = loadEventHelpers();- const handler = getWebShortcutHandler(context);+ const handler = getWindowShortcutHandler(context);handler(createKeyEvent("ArrowLeft", { altKey: true }));handler(createKeyEvent("ArrowRight", { altKey: true }));@@ -278,7 +284,7 @@ describe("event fullscreen shortcuts", () => {"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15",platform: "MacIntel",});- const handler = getWebShortcutHandler(context);+ const handler = getWindowShortcutHandler(context);handler(createKeyEvent("w", { ctrlKey: true }));handler(createKeyEvent("ArrowLeft", { altKey: true }));@@ -287,6 +293,24 @@ describe("event fullscreen shortcuts", () => {expect(context.navigateCalls).toEqual([]);});+ it("leaves a window shortcut to a page that handled the key itself", () => {+ const context = loadEventHelpers();+ const handler = getWindowShortcutHandler(context);++ // A web terminal takes Ctrl+W on keydown and prevents the default.+ handler(createKeyEvent("w", { ctrlKey: true, defaultPrevented: true }));+ handler(+ createKeyEvent("ArrowLeft", { altKey: true, defaultPrevented: true }),+ );+ handler(createKeyEvent("w", { ctrlKey: true, repeat: true }));+ // AltGr on European layouts reports Ctrl and Alt together.+ handler(createKeyEvent("q", { ctrlKey: true, altKey: true }));++ expect(context.closeCalls).toEqual([]);+ expect(context.navigateCalls).toEqual([]);+ expect(context.invokeCalls).not.toContain("quit_app");+ });+it("keeps macOS scroll-to-edge shortcuts in the webview", () => {const context = loadEventHelpers({userAgent: