Skip to main content

quickgui_system/
autostart.rs

1use std::path::PathBuf;
2
3#[cfg(target_os = "linux")]
4use auto_launch::LinuxLaunchMode;
5#[cfg(target_os = "macos")]
6use auto_launch::MacOSLaunchMode;
7#[cfg(target_os = "windows")]
8use auto_launch::WindowsEnableMode;
9use auto_launch::{AutoLaunch, AutoLaunchBuilder};
10
11#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
12use crate::SystemIntegrationError;
13use crate::{Result, invalid, platform, validate_text};
14
15pub const MAX_AUTOSTART_ARGUMENTS: usize = 64;
16pub const MAX_AUTOSTART_ARGUMENT_BYTES: usize = 8 * 1024;
17
18/// Explicit platform strategy for login launch registration.
19#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
20pub enum AutoStartMode {
21    /// SMAppService on macOS, the current-user Run key on Windows, and XDG Autostart on Linux.
22    #[default]
23    Native,
24    MacOsLaunchAgent,
25    MacOsAppleScript,
26    LinuxSystemd,
27    WindowsSystem,
28}
29
30#[derive(Clone, Debug, Eq, PartialEq)]
31pub struct AutoStartOptions {
32    pub app_name: String,
33    pub executable: PathBuf,
34    pub arguments: Vec<String>,
35    pub mode: AutoStartMode,
36    pub bundle_identifier: Option<String>,
37}
38
39impl AutoStartOptions {
40    pub fn new(app_name: impl Into<String>) -> Result<Self> {
41        let executable = std::env::current_exe().map_err(platform)?;
42        Ok(Self {
43            app_name: app_name.into(),
44            executable,
45            arguments: Vec::new(),
46            mode: AutoStartMode::Native,
47            bundle_identifier: None,
48        })
49    }
50}
51
52/// A reusable configuration for the user's native login-launch facility.
53#[derive(Clone, Debug)]
54pub struct AutoStart {
55    native: AutoLaunch,
56}
57
58impl AutoStart {
59    pub fn new(options: AutoStartOptions) -> Result<Self> {
60        validate_options(&options)?;
61        let executable = options
62            .executable
63            .to_str()
64            .ok_or_else(|| invalid("the autostart executable path must be valid UTF-8"))?;
65        let mut builder = AutoLaunchBuilder::new();
66        builder
67            .set_app_name(&options.app_name)
68            .set_app_path(executable)
69            .set_args(&options.arguments);
70
71        #[cfg(target_os = "macos")]
72        {
73            let mode = match options.mode {
74                AutoStartMode::Native => MacOSLaunchMode::SMAppService,
75                AutoStartMode::MacOsLaunchAgent => MacOSLaunchMode::LaunchAgent,
76                AutoStartMode::MacOsAppleScript => MacOSLaunchMode::AppleScript,
77                _ => {
78                    return Err(invalid(
79                        "the requested autostart mode does not apply to macOS",
80                    ));
81                }
82            };
83            builder.set_macos_launch_mode(mode);
84            if let Some(identifier) = &options.bundle_identifier {
85                builder.set_bundle_identifiers(&[identifier]);
86            }
87        }
88        #[cfg(target_os = "windows")]
89        builder.set_windows_enable_mode(match options.mode {
90            AutoStartMode::Native => WindowsEnableMode::CurrentUser,
91            AutoStartMode::WindowsSystem => WindowsEnableMode::System,
92            _ => {
93                return Err(invalid(
94                    "the requested autostart mode does not apply to Windows",
95                ));
96            }
97        });
98        #[cfg(target_os = "linux")]
99        builder.set_linux_launch_mode(match options.mode {
100            AutoStartMode::Native => LinuxLaunchMode::XdgAutostart,
101            AutoStartMode::LinuxSystemd => LinuxLaunchMode::Systemd,
102            _ => {
103                return Err(invalid(
104                    "the requested autostart mode does not apply to Linux",
105                ));
106            }
107        });
108        #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
109        return Err(SystemIntegrationError::Unsupported);
110
111        builder
112            .build()
113            .map(|native| Self { native })
114            .map_err(platform)
115    }
116
117    pub const fn is_supported() -> bool {
118        cfg!(any(
119            target_os = "macos",
120            target_os = "windows",
121            target_os = "linux"
122        ))
123    }
124
125    pub fn enable(&self) -> Result<()> {
126        self.native.enable().map_err(platform)
127    }
128
129    pub fn disable(&self) -> Result<()> {
130        self.native.disable().map_err(platform)
131    }
132
133    pub fn is_enabled(&self) -> Result<bool> {
134        self.native.is_enabled().map_err(platform)
135    }
136}
137
138fn validate_options(options: &AutoStartOptions) -> Result<()> {
139    validate_text(&options.app_name, "the autostart application name", 128)?;
140    if !options
141        .app_name
142        .bytes()
143        .next()
144        .is_some_and(|byte| byte.is_ascii_alphanumeric())
145        || !options
146            .app_name
147            .bytes()
148            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
149    {
150        return Err(invalid(
151            "the autostart application name must be a portable identifier containing only ASCII letters, digits, dots, underscores, and hyphens",
152        ));
153    }
154    if !options.executable.is_absolute() {
155        return Err(invalid("the autostart executable path must be absolute"));
156    }
157    if options
158        .executable
159        .to_str()
160        .is_none_or(|path| path.contains(['\0', '\r', '\n']))
161    {
162        return Err(invalid(
163            "the autostart executable path must be valid UTF-8, NUL-free, and single-line",
164        ));
165    }
166    if options.arguments.len() > MAX_AUTOSTART_ARGUMENTS {
167        return Err(invalid("autostart accepts at most 64 arguments"));
168    }
169    let mut bytes = 0_usize;
170    for argument in &options.arguments {
171        if argument.contains('\0') {
172            return Err(invalid("autostart arguments must be NUL-free"));
173        }
174        bytes = bytes.saturating_add(argument.len());
175    }
176    if bytes > MAX_AUTOSTART_ARGUMENT_BYTES {
177        return Err(invalid(
178            "autostart arguments cannot exceed 8192 aggregate UTF-8 bytes",
179        ));
180    }
181    if let Some(identifier) = &options.bundle_identifier {
182        validate_text(identifier, "the bundle identifier", 1_024)?;
183        if identifier.contains(['\r', '\n']) {
184            return Err(invalid("the bundle identifier must be single-line"));
185        }
186    }
187    Ok(())
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn rejects_relative_executable_and_unbounded_arguments() {
196        let invalid_path = AutoStartOptions {
197            app_name: "Example".to_owned(),
198            executable: PathBuf::from("example"),
199            arguments: Vec::new(),
200            mode: AutoStartMode::Native,
201            bundle_identifier: None,
202        };
203        assert!(validate_options(&invalid_path).is_err());
204
205        let mut too_many = invalid_path;
206        too_many.executable = std::env::current_exe().unwrap();
207        too_many.arguments = vec![String::new(); MAX_AUTOSTART_ARGUMENTS + 1];
208        assert!(validate_options(&too_many).is_err());
209    }
210
211    #[test]
212    fn rejects_unsafe_registration_names() {
213        for name in ["../Example", "Example App", "Example\nHidden"] {
214            let options = AutoStartOptions {
215                app_name: name.to_owned(),
216                executable: std::env::current_exe().unwrap(),
217                arguments: Vec::new(),
218                mode: AutoStartMode::Native,
219                bundle_identifier: None,
220            };
221            assert!(validate_options(&options).is_err(), "accepted {name:?}");
222        }
223    }
224}