auto-launcher 1.1.0

Auto launch any application or executable at startup. Supports Windows, macOS, and Linux.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use crate::{AutoLaunch, Error, MacOSLaunchMode, Result};
use plist::{Dictionary, Value};
use smappservice_rs::{AppService, ServiceStatus, ServiceType};
use std::{
    fs,
    path::{Path, PathBuf},
    process::{Command, Output},
};

/// macOS implement
impl AutoLaunch {
    /// Create a new AutoLaunch instance
    /// - `app_name`: application name
    /// - `app_path`: application path
    /// - `launch_mode`: launch mode (Launch Agent, AppleScript, or SMAppService)
    /// - `args`: startup args passed to the binary
    /// - `bundle_identifiers`: bundle identifiers (only used for LaunchAgent modes)
    /// - `agent_extra_config`: extra config for Launch Agent / Launch Daemon (unused currently)
    ///
    /// ## Notes
    ///
    /// The parameters of `AutoLaunch::new` are different on each platform.
    ///
    /// The `app_name` should be same as the basename of the `app_path`
    ///     when using AppleScript mode, or it will be corrected automatically.
    ///
    /// The `app_path` should be the **absolute path** and **exists**,
    ///     otherwise it will cause an error when `enable`.
    ///
    /// In case using AppleScript,
    ///     only `"--hidden"` and `"--minimized"` in `args` are valid.
    ///
    /// In case using SMAppService (macOS 13+), `app_name` and `app_path` can be empty strings
    ///     as it registers the running application.
    pub fn new(
        app_name: &str,
        app_path: &str,
        launch_mode: MacOSLaunchMode,
        args: &[impl AsRef<str>],
        bundle_identifiers: &[impl AsRef<str>],
        agent_extra_config: &str,
    ) -> AutoLaunch {
        let mut name = app_name;
        if launch_mode == MacOSLaunchMode::AppleScript {
            // the app_name should be same as the executable's name
            // when using login item
            let end = if app_path.ends_with(".app") { 4 } else { 0 };
            let end = app_path.len() - end;
            let begin = match app_path.rfind('/') {
                Some(i) => i + 1,
                None => 0,
            };
            name = &app_path[begin..end];
        }

        AutoLaunch {
            app_name: name.into(),
            app_path: app_path.into(),
            launch_mode,
            args: args.iter().map(|s| s.as_ref().to_string()).collect(),
            bundle_identifiers: bundle_identifiers
                .iter()
                .map(|s| s.as_ref().to_string())
                .collect(),
            agent_extra_config: agent_extra_config.into(),
        }
    }

    /// Enable the AutoLaunch setting
    ///
    /// ## Errors
    ///
    /// - `app_path` does not exist
    /// - `app_path` is not absolute
    ///
    /// #### LaunchAgent / LaunchDaemon
    ///
    /// - failed to create the plist directory
    /// - failed to serialize or write the plist file
    ///
    /// #### AppleScript
    ///
    /// - failed to execute the `osascript` command, check the exit status or stderr for details
    ///
    /// #### SMAppService
    ///
    /// - failed to register app with SMAppService API (macOS 13+)
    pub fn enable(&self) -> Result<()> {
        if self.launch_mode == MacOSLaunchMode::SMAppService {
            let app_service = AppService::new(ServiceType::MainApp);
            match app_service.register() {
                Ok(()) => return Ok(()),
                Err(e) => return Err(Error::SMAppServiceRegistrationFailed(e.code())),
            }
        }

        let path = Path::new(&self.app_path);

        if !path.exists() {
            return Err(Error::AppPathDoesntExist(path.to_path_buf()));
        }

        if !path.is_absolute() {
            return Err(Error::AppPathIsNotAbsolute(path.to_path_buf()));
        }

        match self.launch_mode {
            MacOSLaunchMode::LaunchAgentUser | MacOSLaunchMode::LaunchAgentSystem => self
                .write_plist(build_launch_agent_plist(
                    &self.app_name,
                    &self.app_path,
                    &self.args,
                    &self.bundle_identifiers,
                )),
            MacOSLaunchMode::LaunchDaemonSystem => self.write_plist(build_launch_daemon_plist(
                &self.app_name,
                &self.app_path,
                &self.args,
            )),
            MacOSLaunchMode::AppleScript => self.enable_applescript(),
            MacOSLaunchMode::SMAppService => unreachable!("SMAppService mode handled above"),
        }
    }

    /// Write a plist `Dictionary` to the appropriate file path.
    fn write_plist(&self, dict: Dictionary) -> Result<()> {
        let dir = get_dir(self.launch_mode)?;
        if !dir.exists() {
            fs::create_dir_all(&dir)?;
        }
        let file = self.get_file()?;
        let f = fs::File::create(file)?;
        plist::to_writer_xml(f, &Value::Dictionary(dict)).map_err(std::io::Error::other)?;
        Ok(())
    }

    /// Enable using AppleScript
    fn enable_applescript(&self) -> Result<()> {
        let hidden = self
            .args
            .iter()
            .find(|arg| *arg == "--hidden" || *arg == "--minimized");

        let props = format!(
            "{{name:\"{}\",path:\"{}\",hidden:{}}}",
            self.app_name,
            self.app_path,
            hidden.is_some()
        );
        let command = format!("make login item at end with properties {props}");
        let output = exec_apple_script(&command)?;
        if !output.status.success() {
            return Err(Error::AppleScriptFailed(output.status.code().unwrap_or(1)));
        }
        Ok(())
    }

    /// Disable the AutoLaunch setting
    ///
    /// ## Errors
    ///
    /// #### LaunchAgent / LaunchDaemon
    ///
    /// - failed to remove the plist file
    ///
    /// #### AppleScript
    ///
    /// - failed to execute the `osascript` command, check the exit status or stderr for details
    ///
    /// #### SMAppService
    ///
    /// - failed to unregister app with SMAppService API (macOS 13+)
    pub fn disable(&self) -> Result<()> {
        match self.launch_mode {
            MacOSLaunchMode::LaunchAgentUser
            | MacOSLaunchMode::LaunchAgentSystem
            | MacOSLaunchMode::LaunchDaemonSystem => self.disable_plist(),
            MacOSLaunchMode::AppleScript => self.disable_applescript(),
            MacOSLaunchMode::SMAppService => self.disable_smappservice(),
        }
    }

    /// Disable SMAppService
    fn disable_smappservice(&self) -> Result<()> {
        let app_service = AppService::new(ServiceType::MainApp);
        match app_service.unregister() {
            Ok(()) => Ok(()),
            Err(e) => Err(Error::SMAppServiceUnregistrationFailed(e.code())),
        }
    }

    /// Remove the plist file (used by both LaunchAgent and LaunchDaemon modes)
    fn disable_plist(&self) -> Result<()> {
        let file = self.get_file()?;
        if file.exists() {
            fs::remove_file(file)?;
        }
        Ok(())
    }

    /// Disable AppleScript login item
    fn disable_applescript(&self) -> Result<()> {
        let command = format!("delete login item \"{}\"", self.app_name);
        let output = exec_apple_script(&command)?;
        if !output.status.success() {
            return Err(Error::AppleScriptFailed(output.status.code().unwrap_or(1)));
        }
        Ok(())
    }

    /// Check whether the AutoLaunch setting is enabled
    pub fn is_enabled(&self) -> Result<bool> {
        match self.launch_mode {
            MacOSLaunchMode::LaunchAgentUser
            | MacOSLaunchMode::LaunchAgentSystem
            | MacOSLaunchMode::LaunchDaemonSystem => Ok(self.get_file()?.exists()),
            MacOSLaunchMode::AppleScript => self.is_applescript_enabled(),
            MacOSLaunchMode::SMAppService => self.is_smappservice_enabled(),
        }
    }

    /// Check if SMAppService is enabled
    fn is_smappservice_enabled(&self) -> Result<bool> {
        let app_service = AppService::new(ServiceType::MainApp);
        Ok(app_service.status() == ServiceStatus::Enabled)
    }

    /// Check if AppleScript login item is enabled
    fn is_applescript_enabled(&self) -> Result<bool> {
        let command = "get the name of every login item";
        let output = exec_apple_script(command)?;
        let enable = if output.status.success() {
            let stdout = std::str::from_utf8(&output.stdout).unwrap_or("");
            stdout
                .split(',')
                .map(|x| x.trim())
                .any(|x| x == self.app_name)
        } else {
            false
        };
        Ok(enable)
    }

    /// Read the registered `app_path` from the on-disk plist file.
    ///
    /// Returns `Ok(None)` when the registration does not exist.
    /// Returns `Ok(Some(path))` with the first element of `ProgramArguments`.
    ///
    /// AppleScript and SMAppService modes do not store a path on disk and
    /// always return `Ok(None)`.
    pub fn get_registered_app_path(&self) -> Result<Option<String>> {
        match self.launch_mode {
            MacOSLaunchMode::LaunchAgentUser
            | MacOSLaunchMode::LaunchAgentSystem
            | MacOSLaunchMode::LaunchDaemonSystem => {
                let file = self.get_file()?;
                if !file.exists() {
                    return Ok(None);
                }
                let value: Value = plist::from_file(&file).map_err(std::io::Error::other)?;
                let path = value
                    .as_dictionary()
                    .and_then(|d| d.get("ProgramArguments"))
                    .and_then(|v| v.as_array())
                    .and_then(|args| args.first())
                    .and_then(|v| v.as_string())
                    .map(|s| s.to_string());
                Ok(path)
            }
            MacOSLaunchMode::AppleScript | MacOSLaunchMode::SMAppService => Ok(None),
        }
    }

    /// Get the plist file path for the current launch mode
    fn get_file(&self) -> Result<PathBuf> {
        Ok(get_dir(self.launch_mode)?.join(format!("{}.plist", self.app_name)))
    }
}

/// Return the directory where the plist file should be placed.
fn get_dir(mode: MacOSLaunchMode) -> Result<PathBuf> {
    match mode {
        MacOSLaunchMode::LaunchAgentUser => {
            let home_dir = dirs::home_dir().ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "Failed to find home directory",
                )
            })?;
            Ok(home_dir.join("Library").join("LaunchAgents"))
        }
        MacOSLaunchMode::LaunchAgentSystem => Ok(PathBuf::from("/Library/LaunchAgents")),
        MacOSLaunchMode::LaunchDaemonSystem => Ok(PathBuf::from("/Library/LaunchDaemons")),
        MacOSLaunchMode::AppleScript | MacOSLaunchMode::SMAppService => {
            unreachable!("AppleScript/SMAppService do not use a plist directory")
        }
    }
}

/// Execute the specific AppleScript
fn exec_apple_script(cmd_suffix: &str) -> Result<Output> {
    let command = format!("tell application \"System Events\" to {cmd_suffix}");
    let output = Command::new("osascript")
        .args(vec!["-e", &command])
        .output()?;
    Ok(output)
}

/// Build a plist `Dictionary` for a **LaunchAgent** (user or system).
///
/// LaunchAgent-specific fields:
/// - `AssociatedBundleIdentifiers`: links this agent to an app bundle for display in
///   System Settings > General > Login Items. Not supported by LaunchDaemon.
///
/// The plist is written to `~/Library/LaunchAgents/` (user) or
/// `/Library/LaunchAgents/` (system). The process runs as the **logged-in user**.
fn build_launch_agent_plist(
    app_name: &str,
    app_path: &str,
    args: &[String],
    bundle_identifiers: &[String],
) -> Dictionary {
    let mut program_args: Vec<Value> = vec![Value::String(app_path.into())];
    program_args.extend(args.iter().map(|a| Value::String(a.clone())));

    let mut dict = Dictionary::new();
    dict.insert("Label".into(), Value::String(app_name.into()));

    // AssociatedBundleIdentifiers: LaunchAgent-only — links agent to an app bundle.
    if !bundle_identifiers.is_empty() {
        let ids: Vec<Value> = bundle_identifiers
            .iter()
            .map(|id| Value::String(id.clone()))
            .collect();
        dict.insert("AssociatedBundleIdentifiers".into(), Value::Array(ids));
    }

    dict.insert("ProgramArguments".into(), Value::Array(program_args));
    dict.insert("RunAtLoad".into(), Value::Boolean(true));
    dict
}

/// Build a plist `Dictionary` for a **LaunchDaemon** (system-level, runs as root).
///
/// Key differences from LaunchAgent:
/// - No `AssociatedBundleIdentifiers` (unsupported by launchd for daemons).
/// - `SessionCreate = true`: gives the daemon its own security session, required
///   for accessing system services (e.g. Keychain, audio) without a user session.
///
/// The plist is written to `/Library/LaunchDaemons/`. Writing that directory
/// and loading the daemon both require **root / sudo** privileges.
fn build_launch_daemon_plist(app_name: &str, app_path: &str, args: &[String]) -> Dictionary {
    let mut program_args: Vec<Value> = vec![Value::String(app_path.into())];
    program_args.extend(args.iter().map(|a| Value::String(a.clone())));

    let mut dict = Dictionary::new();
    dict.insert("Label".into(), Value::String(app_name.into()));
    dict.insert("ProgramArguments".into(), Value::Array(program_args));
    dict.insert("RunAtLoad".into(), Value::Boolean(true));
    // SessionCreate: LaunchDaemon-specific — creates a security session for the daemon.
    dict.insert("SessionCreate".into(), Value::Boolean(true));
    dict
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_build_launch_agent_plist() {
        let dict = build_launch_agent_plist(
            "TestApp",
            "/Applications/TestApp.app",
            &["--flag".into()],
            &["com.example.testapp".into()],
        );

        // Serialize to XML for assertion
        let mut buf = Vec::new();
        plist::to_writer_xml(&mut buf, &Value::Dictionary(dict)).unwrap();
        let xml = String::from_utf8(buf).unwrap();

        assert!(xml.contains("<string>TestApp</string>"));
        assert!(xml.contains("AssociatedBundleIdentifiers"));
        assert!(xml.contains("<string>com.example.testapp</string>"));
        assert!(xml.contains("<string>/Applications/TestApp.app</string>"));
        assert!(xml.contains("<string>--flag</string>"));
        assert!(xml.contains("RunAtLoad"));
        assert!(xml.contains("<true/>"));
        // Agent must NOT have SessionCreate
        assert!(!xml.contains("SessionCreate"));
    }

    #[test]
    fn test_build_launch_daemon_plist() {
        let dict = build_launch_daemon_plist(
            "TestDaemon",
            "/usr/local/bin/test-daemon",
            &["--flag".into()],
        );

        let mut buf = Vec::new();
        plist::to_writer_xml(&mut buf, &Value::Dictionary(dict)).unwrap();
        let xml = String::from_utf8(buf).unwrap();

        assert!(xml.contains("<string>TestDaemon</string>"));
        assert!(xml.contains("<string>/usr/local/bin/test-daemon</string>"));
        assert!(xml.contains("<string>--flag</string>"));
        assert!(xml.contains("RunAtLoad"));
        assert!(xml.contains("<true/>"));
        // Daemon must NOT have AssociatedBundleIdentifiers
        assert!(!xml.contains("AssociatedBundleIdentifiers"));
        // Daemon MUST have SessionCreate
        assert!(xml.contains("SessionCreate"));
    }
}