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
feat: open at login for runtime-template apps
Tw9303c170081c99
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 671ad356..5df15a25 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -68,6 +68,7 @@ zbus = "5.14"windows-sys = { version = "0.61.2", features = ["Win32_Foundation","Win32_Globalization",+ "Win32_System_Registry","Win32_UI_Shell","Win32_UI_WindowsAndMessaging",] }diff --git a/src-tauri/src/app/autostart.rs b/src-tauri/src/app/autostart.rsnew file mode 100644index 00000000..0fbf746b--- /dev/null+++ b/src-tauri/src/app/autostart.rs@@ -0,0 +1,259 @@+//! Open at login for apps made from a runtime template.+//!+//! A builder writes `launch_at_login` into pake.json and the app keeps its own+//! login item in step each time it starts, so the item always names where the+//! app really is. Each system gets its own per-user form: a LaunchAgent on+//! macOS, a Run value on Windows, an XDG autostart entry on Linux, all named+//! by the app identifier. Tauri's autostart plugin does the same but needs a+//! newer Tauri than this tree locks.++use std::path::Path;++/// Writes or removes the login item. Failures are logged, never fatal: an app+/// that cannot register itself still has to open.+pub fn reconcile(enabled: bool, identifier: &str, name: &str) {+ let executable = match std::env::current_exe() {+ Ok(path) => path,+ Err(error) => {+ eprintln!("[Pake] Failed to resolve the executable for its login item: {error}");+ return;+ }+ };+ if let Err(error) = platform::reconcile(enabled, identifier, name, &executable) {+ eprintln!("[Pake] Failed to update the login item: {error}");+ }+}++/// Writes `content` only when the file differs, and removes it when `content` is None.+#[cfg(any(target_os = "macos", target_os = "linux", test))]+fn sync_file(path: &Path, content: Option<&str>) -> std::io::Result<()> {+ match content {+ Some(content) => {+ if std::fs::read_to_string(path).is_ok_and(|current| current == content) {+ return Ok(());+ }+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)?;+ }+ std::fs::write(path, content)+ }+ None => match std::fs::remove_file(path) {+ Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),+ _ => Ok(()),+ },+ }+}++#[cfg(any(target_os = "macos", test))]+fn xml_escape(text: &str) -> String {+ text.replace('&', "&")+ .replace('<', "<")+ .replace('>', ">")+}++/// A LaunchAgent that starts the app's own executable once at login.+#[cfg(any(target_os = "macos", test))]+pub(crate) fn launch_agent(identifier: &str, executable: &Path) -> String {+ format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>{}</string>+ <key>ProgramArguments</key>+ <array>+ <string>{}</string>+ </array>+ <key>RunAtLoad</key>+ <true/>+ <key>ProcessType</key>+ <string>Interactive</string>+</dict>+</plist>+"#,+ xml_escape(identifier),+ xml_escape(&executable.to_string_lossy())+ )+}++/// An XDG autostart entry. Exec quotes the path and doubles `%`, which the+/// desktop entry format reads as a field code.+#[cfg(any(target_os = "linux", test))]+pub(crate) fn autostart_entry(name: &str, executable: &Path) -> String {+ let path = executable.to_string_lossy();+ let mut quoted = String::with_capacity(path.len() + 2);+ quoted.push('"');+ for character in path.chars() {+ match character {+ '"' | '`' | '$' | '\\' => {+ quoted.push('\\');+ quoted.push(character);+ }+ '%' => quoted.push_str("%%"),+ _ => quoted.push(character),+ }+ }+ quoted.push('"');+ 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"+ )+}++#[cfg(target_os = "macos")]+mod platform {+ use super::*;++ pub fn reconcile(+ enabled: bool,+ identifier: &str,+ _name: &str,+ executable: &Path,+ ) -> std::io::Result<()> {+ let Some(home) = std::env::var_os("HOME") else {+ return Ok(());+ };+ let path = Path::new(&home)+ .join("Library/LaunchAgents")+ .join(format!("{identifier}.plist"));+ let content = enabled.then(|| launch_agent(identifier, executable));+ sync_file(&path, content.as_deref())+ }+}++#[cfg(target_os = "linux")]+mod platform {+ use super::*;++ pub fn reconcile(+ enabled: bool,+ identifier: &str,+ name: &str,+ executable: &Path,+ ) -> std::io::Result<()> {+ let config = std::env::var_os("XDG_CONFIG_HOME")+ .filter(|value| !value.is_empty())+ .map(std::path::PathBuf::from)+ .or_else(|| std::env::var_os("HOME").map(|home| Path::new(&home).join(".config")));+ let Some(config) = config else {+ return Ok(());+ };+ let path = config+ .join("autostart")+ .join(format!("{identifier}.desktop"));+ let content = enabled.then(|| autostart_entry(name, executable));+ sync_file(&path, content.as_deref())+ }+}++#[cfg(target_os = "windows")]+mod platform {+ use super::*;+ use std::os::windows::ffi::OsStrExt;+ use std::ptr;+ use windows_sys::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_SUCCESS};+ use windows_sys::Win32::System::Registry::{+ RegCloseKey, RegCreateKeyExW, RegDeleteValueW, RegSetValueExW, HKEY, HKEY_CURRENT_USER,+ KEY_SET_VALUE, REG_OPTION_NON_VOLATILE, REG_SZ,+ };++ fn wide(text: &str) -> Vec<u16> {+ text.encode_utf16().chain(std::iter::once(0)).collect()+ }++ pub fn reconcile(+ enabled: bool,+ identifier: &str,+ _name: &str,+ executable: &Path,+ ) -> std::io::Result<()> {+ let subkey = wide(r"Software\Microsoft\Windows\CurrentVersion\Run");+ let value_name = wide(identifier);+ let mut key: HKEY = ptr::null_mut();+ let opened = unsafe {+ RegCreateKeyExW(+ HKEY_CURRENT_USER,+ subkey.as_ptr(),+ 0,+ ptr::null(),+ REG_OPTION_NON_VOLATILE,+ KEY_SET_VALUE,+ ptr::null(),+ &mut key,+ ptr::null_mut(),+ )+ };+ if opened != ERROR_SUCCESS {+ return Err(std::io::Error::from_raw_os_error(opened as i32));+ }+ let status = if enabled {+ // The command line is the quoted path, so a space in it is not an argument break.+ let mut command: Vec<u16> = vec![u16::from(b'"')];+ command.extend(executable.as_os_str().encode_wide());+ command.push(u16::from(b'"'));+ command.push(0);+ unsafe {+ RegSetValueExW(+ key,+ value_name.as_ptr(),+ 0,+ REG_SZ,+ command.as_ptr().cast(),+ (command.len() * 2) as u32,+ )+ }+ } else {+ match unsafe { RegDeleteValueW(key, value_name.as_ptr()) } {+ ERROR_FILE_NOT_FOUND => ERROR_SUCCESS,+ other => other,+ }+ };+ unsafe { RegCloseKey(key) };+ if status != ERROR_SUCCESS {+ return Err(std::io::Error::from_raw_os_error(status as i32));+ }+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_launch_agent_starts_the_apps_own_executable_at_login() {+ let plist = launch_agent(+ "com.pake.a928b2e",+ Path::new("/Applications/Q&A.app/Contents/MacOS/Q&A"),+ );+ assert!(plist.contains("<string>com.pake.a928b2e</string>"));+ assert!(plist.contains("<string>/Applications/Q&A.app/Contents/MacOS/Q&A</string>"));+ assert!(plist.contains("<key>RunAtLoad</key>\n <true/>"));+ }++ #[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"));+ assert!(entry.contains("Name=HackerNews\n"));+ assert!(entry.contains("Exec=\"/home/a b/50%%/com.pake.a1\"\n"));+ assert!(entry.starts_with("[Desktop Entry]\nType=Application\n"));+ }++ #[test]+ fn a_login_item_file_is_written_once_and_removed_when_turned_off() {+ let dir = std::env::temp_dir().join(format!("pake-autostart-{}", std::process::id()));+ let path = dir.join("nested").join("item.plist");+ sync_file(&path, Some("one")).unwrap();+ let written = std::fs::metadata(&path).unwrap().modified().unwrap();+ sync_file(&path, Some("one")).unwrap();+ assert_eq!(+ std::fs::metadata(&path).unwrap().modified().unwrap(),+ written+ );+ sync_file(&path, None).unwrap();+ assert!(!path.exists());+ sync_file(&path, None).unwrap();+ std::fs::remove_dir_all(&dir).unwrap();+ }+}diff --git a/src-tauri/src/app/config.rs b/src-tauri/src/app/config.rsindex ed8bfc74..644d3cc4 100644--- a/src-tauri/src/app/config.rs+++ b/src-tauri/src/app/config.rs@@ -129,6 +129,10 @@ pub struct PakeConfig {pub multi_instance: bool,#[serde(default)]pub multi_window: bool,+ /// Open at login. Read only from a runtime override: the app then keeps its own+ /// login item in step at every start (see `autostart.rs`).+ #[serde(default)]+ pub launch_at_login: bool,/// Replaces the compiled custom.js when a runtime override supplies one.#[serde(skip)]pub runtime_custom_js: Option<String>,diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rsindex 648a4b05..eca8e346 100644--- a/src-tauri/src/app/mod.rs+++ b/src-tauri/src/app/mod.rs@@ -1,5 +1,6 @@#[cfg(target_os = "macos")]pub mod auth;+pub mod autostart;#[cfg(any(target_os = "linux", test))]pub mod color_scheme;pub mod config;diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 5b79d0b5..a656ca51 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -296,6 +296,14 @@ pub fn run_app() {if pake_config.runtime_app {util::set_app_user_model_id(&tauri_config.identifier);}+ // A runtime app's login item follows its own setting; a CLI build has none to keep.+ if pake_config.runtime_app {+ app::autostart::reconcile(+ pake_config.launch_at_login,+ &tauri_config.identifier,+ tauri_config.product_name.as_deref().unwrap_or("Pake"),+ );+ }let mut context = tauri::generate_context!();// Paths, app data and the macOS menu derive from the context, so a runtime// app must not share the template's identity.