BlueGit

ict rusty-teams

Files

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

autostart.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
autostart.rs 5.9 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(
127 HKEY_CURRENT_USER,
128 PCWSTR(key.as_ptr()),
129 PCWSTR(value.as_ptr()),
130 )
131 } {
132 ERROR_FILE_NOT_FOUND => return Ok(()),
133 status => status,
134 }
135 };
136 status
137 .ok()
138 .map_err(|error| io::Error::other(error.message()))
139}
140
141#[cfg(test)]
142mod tests {
143 use std::path::Path;
144
145 use super::{
146 AUTOSTART_FLAG, StartupSettings, desktop_entry, launch_command, launched_by_autostart,
147 };
148
149 #[test]
150 fn background_choice_survives_a_restart_and_only_applies_to_autostart() {
151 let store = store::Store::open_in_memory().unwrap();
152 let loaded = StartupSettings::load(&store, false);
153 assert_eq!(loaded, StartupSettings::default());
154 let settings = StartupSettings {
155 auto_start: true,
156 open_in_background: true,
157 };
158 settings.save_background(&store);
159 assert!(StartupSettings::load(&store, false).open_in_background);
160 assert!(settings.starts_hidden(true));
161 assert!(!settings.starts_hidden(false));
162 assert!(
163 !StartupSettings {
164 auto_start: false,
165 ..settings
166 }
167 .starts_hidden(true)
168 );
169 }
170
171 #[test]
172 fn the_start_command_quotes_the_path_and_marks_the_autostart() {
173 let command = launch_command(Path::new("/opt/rusty teams/teams"));
174 assert_eq!(
175 command,
176 format!("\"/opt/rusty teams/teams\" {AUTOSTART_FLAG}")
177 );
178 let entry = desktop_entry("Rusty Teams", Path::new("/opt/teams"));
179 assert!(entry.starts_with("[Desktop Entry]\n"));
180 assert!(entry.contains(&format!("Exec=\"/opt/teams\" {AUTOSTART_FLAG}\n")));
181 assert!(entry.contains("Name=Rusty Teams\n"));
182 }
183
184 #[test]
185 fn only_the_autostart_flag_marks_a_background_start() {
186 assert!(launched_by_autostart([
187 "--demo".into(),
188 AUTOSTART_FLAG.into()
189 ]));
190 assert!(!launched_by_autostart(["--demo".to_owned()]));
191 }
192}