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
use crate::{AutoLaunch, LinuxLaunchMode, Result};
use std::{fs, io::Write, path::PathBuf};

/// Linux implement
impl AutoLaunch {
    /// Create a new AutoLaunch instance
    /// - `app_name`: application name
    /// - `app_path`: application path
    /// - `launch_mode`: launch mode (XDG Autostart or systemd)
    /// - `args`: startup args passed to the binary
    ///
    /// ## Notes
    ///
    /// The parameters of `AutoLaunch::new` are different on each platform.
    pub fn new(
        app_name: &str,
        app_path: &str,
        launch_mode: LinuxLaunchMode,
        args: &[impl AsRef<str>],
    ) -> AutoLaunch {
        AutoLaunch {
            app_name: app_name.into(),
            app_path: app_path.into(),
            launch_mode,
            args: args.iter().map(|s| s.as_ref().to_string()).collect(),
        }
    }

    /// Enable the AutoLaunch setting
    ///
    /// ## Errors
    ///
    /// - failed to create directory
    /// - failed to create file
    /// - failed to write bytes to the file
    /// - failed to enable systemd service (if using systemd mode)
    pub fn enable(&self) -> Result<()> {
        match self.launch_mode {
            LinuxLaunchMode::XdgAutostart => self.enable_xdg_autostart(),
            LinuxLaunchMode::SystemdUser | LinuxLaunchMode::SystemdSystem => self.enable_systemd(),
        }
    }

    /// Enable using XDG Autostart (.desktop file)
    fn enable_xdg_autostart(&self) -> Result<()> {
        let data = build_xdg_autostart_data(&self.app_name, &self.app_path, &self.args);

        let dir = get_xdg_autostart_dir()?;
        if !dir.exists() {
            fs::create_dir_all(&dir).or_else(|e| {
                if e.kind() == std::io::ErrorKind::AlreadyExists {
                    Ok(())
                } else {
                    Err(e)
                }
            })?;
        }
        let file_path = self.get_xdg_desktop_file()?;
        let mut file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(file_path)?;
        file.write_all(data.as_bytes())?;
        Ok(())
    }

    /// Enable using systemd service
    fn enable_systemd(&self) -> Result<()> {
        // Create systemd service file content
        let data = build_systemd_service_data(
            &self.app_name,
            &self.app_path,
            &self.args,
            self.launch_mode,
        );

        // Create systemd directory
        let dir = get_systemd_dir(self.launch_mode)?;
        if !dir.exists() {
            fs::create_dir_all(&dir).or_else(|e| {
                if e.kind() == std::io::ErrorKind::AlreadyExists {
                    Ok(())
                } else {
                    Err(e)
                }
            })?;
        }

        // Write service file
        let service_file = self.get_systemd_service_file()?;
        let mut file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&service_file)?;
        file.write_all(data.as_bytes())?;

        // Reload systemd daemon so it picks up the new service file
        let daemon_reload_args: &[&str] = match self.launch_mode {
            LinuxLaunchMode::SystemdUser => &["--user", "daemon-reload"],
            LinuxLaunchMode::SystemdSystem => &["daemon-reload"],
            LinuxLaunchMode::XdgAutostart => unreachable!("XDG mode does not use systemctl"),
        };
        let _ = std::process::Command::new("systemctl")
            .args(daemon_reload_args)
            .output();

        // Enable and start the service using systemctl
        self.systemctl_enable()?;

        Ok(())
    }

    /// Run systemctl enable command.
    fn systemctl_enable(&self) -> Result<()> {
        let service_name = format!("{}.service", self.app_name);
        let args: &[&str] = match self.launch_mode {
            LinuxLaunchMode::SystemdUser => &["--user", "enable", &service_name],
            LinuxLaunchMode::SystemdSystem => &["enable", &service_name],
            LinuxLaunchMode::XdgAutostart => unreachable!("XDG mode does not use systemctl"),
        };
        let output = std::process::Command::new("systemctl")
            .args(args)
            .output()?;

        if !output.status.success() {
            return Err(std::io::Error::other(format!(
                "Failed to enable systemd service: {}",
                String::from_utf8_lossy(&output.stderr)
            ))
            .into());
        }

        Ok(())
    }

    /// Disable the AutoLaunch setting
    ///
    /// ## Errors
    ///
    /// - failed to remove file
    /// - failed to disable systemd service (if using systemd mode)
    pub fn disable(&self) -> Result<()> {
        match self.launch_mode {
            LinuxLaunchMode::XdgAutostart => self.disable_xdg_autostart(),
            LinuxLaunchMode::SystemdUser | LinuxLaunchMode::SystemdSystem => self.disable_systemd(),
        }
    }

    /// Disable XDG Autostart
    fn disable_xdg_autostart(&self) -> Result<()> {
        let file = self.get_xdg_desktop_file()?;
        if file.exists() {
            fs::remove_file(file)?;
        }
        Ok(())
    }

    /// Disable systemd service
    fn disable_systemd(&self) -> Result<()> {
        // Disable the service
        self.systemctl_disable()?;

        // Remove service file
        let service_file = self.get_systemd_service_file()?;
        if service_file.exists() {
            fs::remove_file(service_file)?;
        }

        // Reload systemd daemon
        let daemon_reload_args: &[&str] = match self.launch_mode {
            LinuxLaunchMode::SystemdUser => &["--user", "daemon-reload"],
            LinuxLaunchMode::SystemdSystem => &["daemon-reload"],
            LinuxLaunchMode::XdgAutostart => unreachable!("XDG mode does not use systemctl"),
        };
        let _ = std::process::Command::new("systemctl")
            .args(daemon_reload_args)
            .output();

        Ok(())
    }

    /// Run systemctl disable command.
    fn systemctl_disable(&self) -> Result<()> {
        let service_name = format!("{}.service", self.app_name);
        let args: &[&str] = match self.launch_mode {
            LinuxLaunchMode::SystemdUser => &["--user", "disable", &service_name],
            LinuxLaunchMode::SystemdSystem => &["disable", &service_name],
            LinuxLaunchMode::XdgAutostart => unreachable!("XDG mode does not use systemctl"),
        };
        let output = std::process::Command::new("systemctl")
            .args(args)
            .output()?;

        // Don't fail if the service is not enabled
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if !stderr.contains("No such file or directory") && !stderr.contains("not loaded") {
                let err_msg = format!("Failed to disable systemd service: {}", stderr);
                return Err(std::io::Error::other(err_msg).into());
            }
        }

        Ok(())
    }

    /// Check whether the AutoLaunch setting is enabled
    pub fn is_enabled(&self) -> Result<bool> {
        match self.launch_mode {
            LinuxLaunchMode::XdgAutostart => Ok(self.get_xdg_desktop_file()?.exists()),
            LinuxLaunchMode::SystemdUser | LinuxLaunchMode::SystemdSystem => {
                self.is_systemd_enabled()
            }
        }
    }

    /// Check if systemd service is enabled
    fn is_systemd_enabled(&self) -> Result<bool> {
        let service_name = format!("{}.service", self.app_name);
        let args: &[&str] = match self.launch_mode {
            LinuxLaunchMode::SystemdUser => &["--user", "is-enabled", &service_name],
            LinuxLaunchMode::SystemdSystem => &["is-enabled", &service_name],
            LinuxLaunchMode::XdgAutostart => unreachable!("XDG mode does not use systemctl"),
        };
        let output = std::process::Command::new("systemctl")
            .args(args)
            .output()?;

        // systemctl is-enabled returns:
        // - "enabled" with exit code 0 if enabled
        // - "disabled" with exit code 1 if disabled
        // - other states or errors with other exit codes
        Ok(output.status.success())
    }

    /// Read the registered `app_path` from the on-disk service/desktop file.
    ///
    /// Returns `Ok(None)` when the registration does not exist.
    /// For systemd, extracts the binary from the `ExecStart=` line.
    /// For XDG autostart, extracts it from the `Exec=` line.
    pub fn get_registered_app_path(&self) -> Result<Option<String>> {
        let file = match self.launch_mode {
            LinuxLaunchMode::XdgAutostart => self.get_xdg_desktop_file()?,
            LinuxLaunchMode::SystemdUser | LinuxLaunchMode::SystemdSystem => {
                self.get_systemd_service_file()?
            }
        };
        if !file.exists() {
            return Ok(None);
        }
        let content = fs::read_to_string(file)?;
        let key = match self.launch_mode {
            LinuxLaunchMode::XdgAutostart => "Exec=",
            _ => "ExecStart=",
        };
        let path = content
            .lines()
            .find_map(|line| {
                let trimmed = line.trim();
                trimmed.strip_prefix(key).map(|rest| {
                    // ExecStart=/path/to/bin arg1 arg2
                    // Take the first whitespace-delimited token.
                    rest.split_whitespace().next().map(|s| s.to_string())
                })
            })
            .flatten();
        Ok(path)
    }

    /// Get the XDG desktop entry file path
    fn get_xdg_desktop_file(&self) -> Result<PathBuf> {
        Ok(get_xdg_autostart_dir()?.join(format!("{}.desktop", self.app_name)))
    }

    /// Get the systemd service file path
    fn get_systemd_service_file(&self) -> Result<PathBuf> {
        Ok(get_systemd_dir(self.launch_mode)?.join(format!("{}.service", self.app_name)))
    }
}

fn build_xdg_autostart_data(app_name: &str, app_path: &str, args: &[String]) -> String {
    format!(
        "[Desktop Entry]\n\
        Type=Application\n\
        Version=1.0\n\
        Name={}\n\
        Comment={} startup script\n\
        Exec={} {}\n\
        StartupNotify=false\n\
        Terminal=false",
        app_name,
        app_name,
        app_path,
        args.join(" ")
    )
}

fn build_systemd_service_data(
    app_name: &str,
    app_path: &str,
    args: &[String],
    mode: LinuxLaunchMode,
) -> String {
    let args_str = if args.is_empty() {
        String::new()
    } else {
        format!(" {}", args.join(" "))
    };

    // system services should target multi-user.target; user services use default.target
    let wanted_by = match mode {
        LinuxLaunchMode::SystemdSystem => "multi-user.target",
        _ => "default.target",
    };

    format!(
        "[Unit]\n\
        Description={}\n\
        After={}\n\
        \n\
        [Service]\n\
        Type=simple\n\
        ExecStart={}{}\n\
        Restart=on-failure\n\
        RestartSec=10\n\
        \n\
        [Install]\n\
        WantedBy={}",
        app_name, wanted_by, app_path, args_str, wanted_by
    )
}

/// Get the XDG autostart directory
fn get_xdg_autostart_dir() -> Result<PathBuf> {
    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(".config").join("autostart"))
}

/// Get the systemd service directory.
fn get_systemd_dir(mode: LinuxLaunchMode) -> Result<PathBuf> {
    match mode {
        LinuxLaunchMode::SystemdSystem => Ok(PathBuf::from("/etc/systemd/system")),
        LinuxLaunchMode::SystemdUser => {
            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(".config").join("systemd").join("user"))
        }
        LinuxLaunchMode::XdgAutostart => unreachable!("XDG mode does not use systemd dir"),
    }
}

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

    #[test]
    fn test_build_xdg_autostart_data() {
        let data = build_xdg_autostart_data(
            "TestApp",
            "/opt/test-app",
            &["--flag".into(), "value".into()],
        );

        assert!(data.contains("Type=Application"));
        assert!(data.contains("Name=TestApp"));
        assert!(data.contains("Comment=TestApp startup script"));
        assert!(data.contains("Exec=/opt/test-app --flag value"));
        assert!(data.contains("StartupNotify=false"));
        assert!(data.contains("Terminal=false"));
    }

    #[test]
    fn test_build_systemd_service_data() {
        let data = build_systemd_service_data(
            "TestApp",
            "/opt/test-app",
            &["--flag".into()],
            LinuxLaunchMode::SystemdUser,
        );

        assert!(data.contains("Description=TestApp"));
        assert!(data.contains("After=default.target"));
        assert!(data.contains("ExecStart=/opt/test-app --flag"));
        assert!(data.contains("Restart=on-failure"));
        assert!(data.contains("WantedBy=default.target"));
    }

    #[test]
    fn test_build_systemd_service_data_system() {
        let data = build_systemd_service_data(
            "TestApp",
            "/opt/test-app",
            &["--flag".into()],
            LinuxLaunchMode::SystemdSystem,
        );

        assert!(data.contains("After=multi-user.target"));
        assert!(data.contains("WantedBy=multi-user.target"));
    }
}