auto-launch 0.6.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! Auto launch any application or executable at startup. Supports Windows, Mac (via AppleScript or Launch Agent), and Linux.
//!
//! ## Usage
//!
//! The parameters of `AutoLaunch::new` are different on each platform.
//! See the function definition or the demo below for details.
//!
//! Or you can construct the AutoLaunch by using `AutoLaunchBuilder`.
//!
//! ```rust
//! # #[cfg(target_os = "linux")]
//! # mod linux {
//! use auto_launch::{AutoLaunch, LinuxLaunchMode};
//!
//! fn main() {
//!     let app_name = "the-app";
//!     let app_path = "/path/to/the-app";
//!     let args = &["--minimized"];
//!     // Use XDG Autostart by default, or use LinuxLaunchMode::Systemd for systemd
//!     let auto = AutoLaunch::new(app_name, app_path, LinuxLaunchMode::XdgAutostart, args);
//!
//!     // enable the auto launch
//!     auto.enable().is_ok();
//!     auto.is_enabled().unwrap();
//!
//!     // disable the auto launch
//!     auto.disable().is_ok();
//!     auto.is_enabled().unwrap();
//! }
//! # }
//! ```
//!
//! ### macOS
//!
//! macOS supports two ways to achieve auto launch:
//! - **Launch Agent**: Uses plist files in `~/Library/LaunchAgents/` (default)
//! - **AppleScript**: Uses AppleScript to add login items
//!
//! **Note**:
//! - The `app_path` should be a absolute path and exists. Otherwise, it will cause an error when `enable`.
//! - In case using AppleScript, the `app_name` should be same as the basename of `app_path`, or it will be corrected automatically.
//! - In case using AppleScript, only `--hidden` and `--minimized` in `args` are valid, which means that hide the app on launch.
//!
//! ```rust
//! # #[cfg(target_os = "macos")]
//! # mod macos {
//! use auto_launch::{AutoLaunch, MacOSLaunchMode};
//!
//! fn main() {
//!     let app_name = "the-app";
//!     let app_path = "/path/to/the-app.app";
//!     let args = &["--minimized"];
//!     let bundle_identifiers = &["com.github.auto-launch-test"];
//!     // Use Launch Agent by default, or use MacOSLaunchMode::AppleScript
//!     let auto = AutoLaunch::new(app_name, app_path, MacOSLaunchMode::LaunchAgent, args, bundle_identifiers, "");
//!
//!     // enable the auto launch
//!     auto.enable().is_ok();
//!     auto.is_enabled().unwrap();
//!
//!     // disable the auto launch
//!     auto.disable().is_ok();
//!     auto.is_enabled().unwrap();
//! }
//! # }
//! ```
//!
//! ### Windows
//!
//! On Windows, it will add a registry entry under either `\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run` (system-wide) or
//! `\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run` (current user only).
//!
//! By default we try to apply the auto launch to the system registry, which requires admin privileges and applies the auto launch to any user in the system.
//! If there's no permission to do so, we fallback to enabling it to the current user only.
//! To change this behavior, specify the [`WindowsEnableMode`] when creating the [`AutoLaunch`] instance.
//!
//! ```rust
//! # #[cfg(target_os = "windows")]
//! # mod win {
//! use auto_launch::{AutoLaunch, WindowsEnableMode};
//!
//! fn main() {
//!     let app_name = "the-app";
//!     let app_path = "C:\\path\\to\\the-app.exe";
//!     let args = &["--minimized"];
//!     let enable_mode = WindowsEnableMode::CurrentUser;
//!     let auto = AutoLaunch::new(app_name, app_path, enable_mode, args);
//!
//!     // enable the auto launch
//!     auto.enable().is_ok();
//!     auto.is_enabled().unwrap();
//!
//!     // disable the auto launch
//!     auto.disable().is_ok();
//!     auto.is_enabled().unwrap();
//! }
//! # }
//! ```
//!
//! ### Builder
//!
//! AutoLaunch Builder helps to eliminate the constructor difference
//! on various platforms.
//!
//! ```rust
//! use auto_launch::*;
//!
//! # fn example() -> std::result::Result<(), Box<dyn std::error::Error>> {
//! let auto = AutoLaunchBuilder::new()
//!     .set_app_name("the-app")
//!     .set_app_path("/path/to/the-app")
//!     .set_macos_launch_mode(MacOSLaunchMode::LaunchAgent)
//!     .set_args(&["--minimized"])
//!     .build()?;
//!
//! auto.enable()?;
//! auto.is_enabled()?;
//!
//! auto.disable()?;
//! auto.is_enabled()?;
//! # Ok(())
//! # }
//! ```
//!

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("app_name shouldn't be None")]
    AppNameNotSpecified,
    #[error("app_path shouldn't be None")]
    AppPathNotSpecified,
    #[error("app path doesn't exist: {0}")]
    AppPathDoesntExist(std::path::PathBuf),
    #[error("app path is not absolute: {0}")]
    AppPathIsNotAbsolute(std::path::PathBuf),
    #[error("Failed to execute apple script with status: {0}")]
    AppleScriptFailed(i32),
    #[error("Failed to register app with SMAppService with status: {0}")]
    SMAppServiceRegistrationFailed(u32),
    #[error("Failed to unregister app with SMAppService with status: {0}")]
    SMAppServiceUnregistrationFailed(u32),
    #[error("Unsupported target os")]
    UnsupportedOS,
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

pub type Result<T> = std::result::Result<T, Error>;

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "windows")]
mod windows;

/// The parameters of `AutoLaunch::new` are different on each platform.
///
/// ### Linux
///
/// ```rust
/// # #[cfg(target_os = "linux")]
/// # {
/// # use auto_launch::{AutoLaunch, LinuxLaunchMode};
/// # let app_name = "the-app";
/// # let app_path = "/path/to/the-app";
/// # let launch_mode = LinuxLaunchMode::XdgAutostart;
/// # let args = &["--minimized"];
/// AutoLaunch::new(app_name, app_path, launch_mode, args);
/// # }
/// ```
///
/// ### Macos
///
/// ```rust
/// # #[cfg(target_os = "macos")]
/// # {
/// # use auto_launch::{AutoLaunch, MacOSLaunchMode};
/// # let app_name = "the-app";
/// # let app_path = "/path/to/the-app";
/// # let launch_mode = MacOSLaunchMode::LaunchAgent;
/// # let args = &["--minimized"];
/// # let bundle_identifiers = &["com.github.auto-launch-test"];
/// AutoLaunch::new(app_name, app_path, launch_mode, args, bundle_identifiers, "");
/// # }
/// ```
///
/// ### Windows
///
/// ```rust
/// # #[cfg(target_os = "windows")]
/// # {
/// # use auto_launch::{AutoLaunch, WindowsEnableMode};
/// # let app_name = "the-app";
/// # let app_path = "/path/to/the-app";
/// # let args = &["--minimized"];
/// # let enable_mode = WindowsEnableMode::CurrentUser;
/// AutoLaunch::new(app_name, app_path, enable_mode, args);
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AutoLaunch {
    /// The application name
    pub(crate) app_name: String,

    /// The application executable path (absolute path will be better)
    pub(crate) app_path: String,

    /// Args passed to the binary on startup
    pub(crate) args: Vec<String>,

    #[cfg(target_os = "linux")]
    /// Launch mode for Linux (XDG Autostart or systemd)
    pub(crate) launch_mode: LinuxLaunchMode,

    #[cfg(target_os = "macos")]
    /// Launch mode for macOS (Launch Agent or AppleScript)
    pub(crate) launch_mode: MacOSLaunchMode,

    #[cfg(target_os = "macos")]
    /// Bundle identifiers
    pub(crate) bundle_identifiers: Vec<String>,

    #[cfg(target_os = "macos")]
    /// Extra config in plist file for Launch Agent
    pub(crate) agent_extra_config: String,

    #[cfg(windows)]
    pub(crate) enable_mode: WindowsEnableMode,
}

impl AutoLaunch {
    /// check whether it is support the platform
    ///
    /// ## Usage
    ///
    /// ```rust
    /// use auto_launch::AutoLaunch;
    ///
    /// dbg!(AutoLaunch::is_support());
    /// ```
    pub fn is_support() -> bool {
        cfg!(any(
            target_os = "linux",
            target_os = "macos",
            target_os = "windows",
        ))
    }

    /// get the application name
    pub fn get_app_name(&self) -> &str {
        &self.app_name
    }

    /// get the application path
    pub fn get_app_path(&self) -> &str {
        &self.app_path
    }

    /// get the args
    pub fn get_args(&self) -> &[String] {
        &self.args
    }
}

#[derive(Debug, Default, Clone)]
/// AutoLaunch Builder helps to eliminate the constructor difference
/// on various platforms.
///
/// ## Notes
///
/// The builder will not check whether the app_path matches the platform-specify file path.
///
/// ## Usage
///
/// ```rust
/// use auto_launch::*;
///
/// # fn example() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// let auto = AutoLaunchBuilder::new()
///     .set_app_name("the-app")
///     .set_app_path("/path/to/the-app")
///     .set_macos_launch_mode(MacOSLaunchMode::LaunchAgent)
///     .set_args(&["--minimized"])
///     .build()?;
///
/// auto.enable()?;
/// auto.is_enabled()?;
///
/// auto.disable()?;
/// auto.is_enabled()?;
/// # Ok(())
/// # }
/// ```
pub struct AutoLaunchBuilder {
    pub app_name: Option<String>,

    pub app_path: Option<String>,

    pub macos_launch_mode: MacOSLaunchMode,

    pub bundle_identifiers: Option<Vec<String>>,

    pub agent_extra_config: Option<String>,

    pub windows_enable_mode: WindowsEnableMode,

    pub linux_launch_mode: LinuxLaunchMode,

    pub args: Option<Vec<String>>,
}

/// Determines how the auto launch is enabled on Linux.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinuxLaunchMode {
    /// Use XDG Autostart (.desktop file in ~/.config/autostart/)
    XdgAutostart,
    /// Use systemd user service (~/.config/systemd/user/)
    Systemd,
}

impl Default for LinuxLaunchMode {
    fn default() -> Self {
        Self::XdgAutostart
    }
}

/// Determines how the auto launch is enabled on macOS.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacOSLaunchMode {
    /// Use Launch Agent (plist file in ~/Library/LaunchAgents/)
    LaunchAgent,
    /// Use AppleScript to add login item
    AppleScript,
    /// User SMAppService API to enable the auto launch (macOS 13+)
    SMAppService,
}

impl Default for MacOSLaunchMode {
    fn default() -> Self {
        Self::LaunchAgent
    }
}

/// Determines how the auto launch is enabled on Windows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowsEnableMode {
    /// Dynamically tries to enable the auto launch for the system (admin privileges required),
    /// fallbacks to the current user if there is no permission to modify the system registry.
    Dynamic,
    /// Enables the auto launch for the current user only. Does not require admin permissions.
    CurrentUser,
    /// Enables the auto launch for all users. Requires admin permissions.
    System,
}

impl Default for WindowsEnableMode {
    fn default() -> Self {
        Self::Dynamic
    }
}

impl AutoLaunchBuilder {
    pub fn new() -> AutoLaunchBuilder {
        AutoLaunchBuilder::default()
    }

    /// Set the `app_name`
    pub fn set_app_name(&mut self, name: &str) -> &mut Self {
        self.app_name = Some(name.into());
        self
    }

    /// Set the `app_path`
    pub fn set_app_path(&mut self, path: &str) -> &mut Self {
        self.app_path = Some(path.into());
        self
    }

    /// Set the [`MacOSLaunchMode`].
    /// This setting only works on macOS
    pub fn set_macos_launch_mode(&mut self, mode: MacOSLaunchMode) -> &mut Self {
        self.macos_launch_mode = mode;
        self
    }

    /// Set the `use_launch_agent` (deprecated: use `set_macos_launch_mode` instead)
    /// This setting only works on macOS
    #[deprecated(since = "0.6.0", note = "Use `set_macos_launch_mode` instead")]
    pub fn set_use_launch_agent(&mut self, use_launch_agent: bool) -> &mut Self {
        self.macos_launch_mode = if use_launch_agent {
            MacOSLaunchMode::LaunchAgent
        } else {
            MacOSLaunchMode::AppleScript
        };
        self
    }

    /// Set the `bundle_identifiers`
    /// This setting only works on macOS
    pub fn set_bundle_identifiers(&mut self, bundle_identifiers: &[impl AsRef<str>]) -> &mut Self {
        self.bundle_identifiers = Some(
            bundle_identifiers
                .iter()
                .map(|s| s.as_ref().to_string())
                .collect(),
        );
        self
    }

    /// Set the `agent_extra_config`
    /// This setting only works on macOS
    pub fn set_agent_extra_config(&mut self, config: &str) -> &mut Self {
        self.agent_extra_config = Some(config.into());
        self
    }

    /// Set the [`WindowsEnableMode`].
    /// This setting only works on Windows
    pub fn set_windows_enable_mode(&mut self, mode: WindowsEnableMode) -> &mut Self {
        self.windows_enable_mode = mode;
        self
    }

    /// Set the [`LinuxLaunchMode`].
    /// This setting only works on Linux
    pub fn set_linux_launch_mode(&mut self, mode: LinuxLaunchMode) -> &mut Self {
        self.linux_launch_mode = mode;
        self
    }

    /// Set the args
    pub fn set_args(&mut self, args: &[impl AsRef<str>]) -> &mut Self {
        self.args = Some(args.iter().map(|s| s.as_ref().to_string()).collect());
        self
    }

    /// Construct a AutoLaunch instance
    ///
    /// ## Errors
    ///
    /// - `app_name` is none
    /// - `app_path` is none
    /// - Unsupported target OS
    pub fn build(&self) -> Result<AutoLaunch> {
        let default_str = String::new();
        /*
         * When SMAppService is used, app_name and app_path are ignored. This
         * is because the SMAppService API is used to register the running app.
         *
         * We also need to check whether the os version is compatible with SMAppService.
         */
        let (app_name, app_path) = if self.macos_launch_mode == MacOSLaunchMode::SMAppService {
            let info = os_info::get();
            match info.version() {
                os_info::Version::Semantic(major, _, _) => {
                    if *major < 13 {
                        return Err(Error::UnsupportedOS);
                    }
                }
                _ => return Err(Error::UnsupportedOS),
            };

            (
                self.app_name.as_ref().unwrap_or(&default_str),
                self.app_path.as_ref().unwrap_or(&default_str),
            )
        } else {
            (
                self.app_name.as_ref().ok_or(Error::AppNameNotSpecified)?,
                self.app_path.as_ref().ok_or(Error::AppPathNotSpecified)?,
            )
        };
        let args = self.args.clone().unwrap_or_default();
        let bundle_identifiers = self.bundle_identifiers.clone().unwrap_or_default();
        let agent_extra_config = self.agent_extra_config.as_ref().map_or("", |v| v);

        #[cfg(target_os = "linux")]
        return Ok(AutoLaunch::new(
            app_name,
            app_path,
            self.linux_launch_mode,
            &args,
        ));
        #[cfg(target_os = "macos")]
        return Ok(AutoLaunch::new(
            app_name,
            app_path,
            self.macos_launch_mode,
            &args,
            &bundle_identifiers,
            agent_extra_config,
        ));
        #[cfg(target_os = "windows")]
        return Ok(AutoLaunch::new(
            app_name,
            app_path,
            self.windows_enable_mode,
            &args,
        ));

        #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
        return Err(Error::UnsupportedOS);
    }
}