BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / autostart.rs

autostart.rs

autostart.rs 5.8 KiB Download Raw
1use std::io;
2use std::path::Path;
3
4pub const AUTOSTART_FLAG: &str = "--autostart";
5const BACKGROUND_META_KEY: &str = "startup.open_in_background";
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
8pub struct StartupSettings {
9 pub auto_start: bool,
10 pub open_in_background: bool,
11}
12
13impl StartupSettings {
14 pub fn load(store: &store::Store, read_system: bool) -> StartupSettings {
15 StartupSettings {
16 auto_start: read_system && is_enabled(crate::APP_NAME),
17 open_in_background: store.meta(BACKGROUND_META_KEY).ok().flatten().as_deref()
18 == Some("1"),
19 }
20 }
21
22 pub fn save_background(&self, store: &store::Store) {
23 let _ = store.set_meta(
24 BACKGROUND_META_KEY,
25 if self.open_in_background { "1" } else { "0" },
26 );
27 }
28
29 pub fn starts_hidden(&self, launched_by_autostart: bool) -> bool {
30 launched_by_autostart && self.auto_start && self.open_in_background
31 }
32}
33
34pub fn launch_command(executable: &Path) -> String {
35 format!("\"{}\" {AUTOSTART_FLAG}", executable.display())
36}
37
38pub fn desktop_entry(name: &str, executable: &Path) -> String {
39 format!(
40 "[Desktop Entry]\nType=Application\nName={name}\nExec={}\nX-GNOME-Autostart-enabled=true\n",
41 launch_command(executable)
42 )
43}
44
45pub fn launched_by_autostart(arguments: impl IntoIterator<Item = String>) -> bool {
46 arguments
47 .into_iter()
48 .any(|argument| argument == AUTOSTART_FLAG)
49}
50
51#[cfg(not(windows))]
52fn entry_path(name: &str) -> Option<std::path::PathBuf> {
53 let file_name = format!("{}.desktop", name.to_lowercase().replace(' ', "-"));
54 directories::BaseDirs::new().map(|base| base.config_dir().join("autostart").join(file_name))
55}
56
57#[cfg(not(windows))]
58pub fn is_enabled(name: &str) -> bool {
59 entry_path(name).is_some_and(|path| path.is_file())
60}
61
62#[cfg(not(windows))]
63pub fn set_enabled(name: &str, enabled: bool) -> io::Result<()> {
64 let path = entry_path(name).ok_or_else(|| io::Error::other("no config directory"))?;
65 if !enabled {
66 return match std::fs::remove_file(&path) {
67 Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
68 _ => Ok(()),
69 };
70 }
71 if let Some(directory) = path.parent() {
72 std::fs::create_dir_all(directory)?;
73 }
74 std::fs::write(&path, desktop_entry(name, &std::env::current_exe()?))
75}
76
77#[cfg(windows)]
78const RUN_KEY: &str = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
79
80#[cfg(windows)]
81fn wide(text: &str) -> Vec<u16> {
82 text.encode_utf16().chain(std::iter::once(0)).collect()
83}
84
85#[cfg(windows)]
86pub fn is_enabled(name: &str) -> bool {
87 use windows::Win32::System::Registry::{HKEY_CURRENT_USER, RRF_RT_REG_SZ, RegGetValueW};
88 use windows::core::PCWSTR;
89 let (key, value) = (wide(RUN_KEY), wide(name));
90 unsafe {
91 RegGetValueW(
92 HKEY_CURRENT_USER,
93 PCWSTR(key.as_ptr()),
94 PCWSTR(value.as_ptr()),
95 RRF_RT_REG_SZ,
96 None,
97 None,
98 None,
99 )
100 .is_ok()
101 }
102}
103
104#[cfg(windows)]
105pub fn set_enabled(name: &str, enabled: bool) -> io::Result<()> {
106 use windows::Win32::Foundation::ERROR_FILE_NOT_FOUND;
107 use windows::Win32::System::Registry::{
108 HKEY_CURRENT_USER, REG_SZ, RegDeleteKeyValueW, RegSetKeyValueW,
109 };
110 use windows::core::PCWSTR;
111 let (key, value) = (wide(RUN_KEY), wide(name));
112 let status = if enabled {
113 let command = wide(&launch_command(&std::env::current_exe()?));
114 unsafe {
115 RegSetKeyValueW(
116 HKEY_CURRENT_USER,
117 PCWSTR(key.as_ptr()),
118 PCWSTR(value.as_ptr()),
119 REG_SZ.0,
120 Some(command.as_ptr().cast()),
121 (command.len() * size_of::<u16>()) as u32,
122 )
123 }
124 } else {
125 match unsafe {
126 RegDeleteKeyValueW(HKEY_CURRENT_USER, PCWSTR(key.as_ptr()), PCWSTR(value.as_ptr()))
127 } {
128 ERROR_FILE_NOT_FOUND => return Ok(()),
129 status => status,
130 }
131 };
132 status
133 .ok()
134 .map_err(|error| io::Error::other(error.message()))
135}
136
137#[cfg(test)]
138mod tests {
139 use std::path::Path;
140
141 use super::{
142 AUTOSTART_FLAG, StartupSettings, desktop_entry, launch_command, launched_by_autostart,
143 };
144
145 #[test]
146 fn background_choice_survives_a_restart_and_only_applies_to_autostart() {
147 let store = store::Store::open_in_memory().unwrap();
148 let loaded = StartupSettings::load(&store, false);
149 assert_eq!(loaded, StartupSettings::default());
150 let settings = StartupSettings {
151 auto_start: true,
152 open_in_background: true,
153 };
154 settings.save_background(&store);
155 assert!(StartupSettings::load(&store, false).open_in_background);
156 assert!(settings.starts_hidden(true));
157 assert!(!settings.starts_hidden(false));
158 assert!(
159 !StartupSettings {
160 auto_start: false,
161 ..settings
162 }
163 .starts_hidden(true)
164 );
165 }
166
167 #[test]
168 fn the_start_command_quotes_the_path_and_marks_the_autostart() {
169 let command = launch_command(Path::new("/opt/rusty teams/teams"));
170 assert_eq!(command, format!("\"/opt/rusty teams/teams\" {AUTOSTART_FLAG}"));
171 let entry = desktop_entry("Rusty Teams", Path::new("/opt/teams"));
172 assert!(entry.starts_with("[Desktop Entry]\n"));
173 assert!(entry.contains(&format!("Exec=\"/opt/teams\" {AUTOSTART_FLAG}\n")));
174 assert!(entry.contains("Name=Rusty Teams\n"));
175 }
176
177 #[test]
178 fn only_the_autostart_flag_marks_a_background_start() {
179 assert!(launched_by_autostart(["--demo".into(), AUTOSTART_FLAG.into()]));
180 assert!(!launched_by_autostart(["--demo".to_owned()]));
181 }
182}