auto_launch/
linux.rs

1use crate::AutoLaunch;
2use crate::Result;
3use std::fs;
4use std::io::Write;
5use std::path::PathBuf;
6
7/// Linux implement
8impl AutoLaunch {
9    /// Create a new AutoLaunch instance
10    /// - `app_name`: application name
11    /// - `app_path`: application path
12    /// - `args`: startup args passed to the binary
13    ///
14    /// ## Notes
15    ///
16    /// The parameters of `AutoLaunch::new` are different on each platform.
17    pub fn new(app_name: &str, app_path: &str, args: &[impl AsRef<str>]) -> AutoLaunch {
18        AutoLaunch {
19            app_name: app_name.into(),
20            app_path: app_path.into(),
21            args: args.iter().map(|s| s.as_ref().to_string()).collect(),
22        }
23    }
24
25    /// Enable the AutoLaunch setting
26    ///
27    /// ## Errors
28    ///
29    /// - failed to create dir `~/.config/autostart`
30    /// - failed to create file `~/.config/autostart/{app_name}.desktop`
31    /// - failed to write bytes to the file
32    pub fn enable(&self) -> Result<()> {
33        let data = format!(
34            "[Desktop Entry]\n\
35            Type=Application\n\
36            Version=1.0\n\
37            Name={}\n\
38            Comment={}startup script\n\
39            Exec={} {}\n\
40            StartupNotify=false\n\
41            Terminal=false",
42            self.app_name,
43            self.app_name,
44            self.app_path,
45            self.args.join(" ")
46        );
47
48        let dir = get_dir();
49        if !dir.exists() {
50            fs::create_dir(&dir)?;
51        }
52        fs::File::create(self.get_file())?.write(data.as_bytes())?;
53        Ok(())
54    }
55
56    /// Disable the AutoLaunch setting
57    ///
58    /// ## Errors
59    ///
60    /// - failed to remove file `~/.config/autostart/{app_name}.desktop`
61    pub fn disable(&self) -> Result<()> {
62        let file = self.get_file();
63        if file.exists() {
64            fs::remove_file(file)?;
65        }
66        Ok(())
67    }
68
69    /// Check whether the AutoLaunch setting is enabled
70    pub fn is_enabled(&self) -> Result<bool> {
71        Ok(self.get_file().exists())
72    }
73
74    /// Get the desktop entry file path
75    fn get_file(&self) -> PathBuf {
76        get_dir().join(format!("{}.desktop", self.app_name))
77    }
78}
79
80/// Get the autostart dir
81fn get_dir() -> PathBuf {
82    dirs::home_dir().unwrap().join(".config").join("autostart")
83}