BlueGit

ict rusty-teams

Files

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

linux_desktop.rs

fix: open points after the PR merges
metis Daniel Däschle · pushed by metis · 2 weeks ago
bc6f4c9e History
linux_desktop.rs 13.7 KiB Download Raw
1//! Desktop integration on Linux: the install folder (`~/.local/share/rusty-teams`),
2//! the `.desktop` entry and the menu icon.
3
4use std::fs;
5use std::io;
6use std::path::{Path, PathBuf};
7
8/// Matches the window's app id, so KDE pairs the window with the entry.
9pub const DESKTOP_ID: &str = "rusty-teams";
10/// Name the `.desktop` entry, the tray and `hicolor` use for the icon.
11pub const ICON_NAME: &str = "rusty-teams";
12pub const BINARY_FILE_NAME: &str = "teams";
13pub const ICON_SIZES: [u32; 5] = [256, 128, 64, 48, 32];
14const INSTALL_FOLDER: &str = "rusty-teams";
15const DONT_ASK_META_KEY: &str = "linux.install.dont_ask";
16
17/// Cargo marks its target folder with `CACHEDIR.TAG`; a binary in
18/// `target/<profile>/` is build output and is copied, not moved, on install.
19pub fn is_build_output(executable: &Path) -> bool {
20 executable
21 .parent()
22 .and_then(Path::parent)
23 .is_some_and(|target| target.join("CACHEDIR.TAG").is_file())
24}
25
26/// Paths below the XDG data folder (`~/.local/share`).
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct Layout {
29 data_dir: PathBuf,
30}
31
32impl Layout {
33 pub fn new(data_dir: impl Into<PathBuf>) -> Layout {
34 Layout {
35 data_dir: data_dir.into(),
36 }
37 }
38
39 pub fn current() -> Option<Layout> {
40 directories::BaseDirs::new().map(|base| Layout::new(base.data_dir()))
41 }
42
43 pub fn applications_dir(&self) -> PathBuf {
44 self.data_dir.join("applications")
45 }
46
47 pub fn install_dir(&self) -> PathBuf {
48 self.data_dir.join(INSTALL_FOLDER)
49 }
50
51 pub fn installed_binary(&self) -> PathBuf {
52 self.install_dir().join(BINARY_FILE_NAME)
53 }
54
55 pub fn desktop_file(&self) -> PathBuf {
56 self.applications_dir()
57 .join(format!("{DESKTOP_ID}.desktop"))
58 }
59
60 pub fn icons_dir(&self) -> PathBuf {
61 self.data_dir.join("icons").join("hicolor")
62 }
63
64 pub fn icon_file(&self, size: u32) -> PathBuf {
65 self.icons_dir()
66 .join(format!("{size}x{size}"))
67 .join("apps")
68 .join(format!("{ICON_NAME}.png"))
69 }
70
71 pub fn largest_icon(&self) -> PathBuf {
72 self.icon_file(ICON_SIZES[0])
73 }
74}
75
76pub fn is_installed(executable: &Path, layout: &Layout) -> bool {
77 let install_dir = layout.install_dir();
78 let canonical = |path: &Path| fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
79 executable
80 .parent()
81 .is_some_and(|parent| canonical(parent) == canonical(&install_dir))
82}
83
84pub fn should_offer_install(executable: &Path, layout: &Layout, dont_ask: bool) -> bool {
85 !dont_ask && !is_installed(executable, layout)
86}
87
88pub fn dont_ask_again(store: &store::Store) -> bool {
89 store.meta(DONT_ASK_META_KEY).ok().flatten().as_deref() == Some("1")
90}
91
92pub fn set_dont_ask_again(store: &store::Store) {
93 let _ = store.set_meta(DONT_ASK_META_KEY, "1");
94}
95
96/// Brings the install question back on the next start.
97pub fn ask_again(store: &store::Store) {
98 let _ = store.set_meta(DONT_ASK_META_KEY, "0");
99}
100
101/// Removes the menu entry and the installed binary (with a staged update). Sign-in
102/// and cache stay. A running installed copy keeps running.
103pub fn uninstall(layout: &Layout) -> io::Result<()> {
104 let remove = |path: PathBuf| match fs::remove_file(&path) {
105 Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
106 _ => Ok(()),
107 };
108 remove(layout.desktop_file())?;
109 let install_dir = layout.install_dir();
110 remove(layout.installed_binary())?;
111 remove(install_dir.join(format!("{BINARY_FILE_NAME}.old")))?;
112 if install_dir.join("update").is_dir() {
113 fs::remove_dir_all(install_dir.join("update"))?;
114 }
115 for size in ICON_SIZES {
116 remove(layout.icon_file(size))?;
117 }
118 // Only when empty: anything else in there belongs to the user.
119 let _ = fs::remove_dir(&install_dir);
120 refresh_desktop_caches(layout);
121 Ok(())
122}
123
124/// Puts the binary into the install folder (copied when it is build output, moved
125/// otherwise), writes the `.desktop` entry and returns the new path. An older
126/// installed binary is replaced.
127pub fn install_binary(executable: &Path, layout: &Layout) -> io::Result<PathBuf> {
128 let target = layout.installed_binary();
129 fs::create_dir_all(layout.install_dir())?;
130 if fs::canonicalize(executable).ok() != fs::canonicalize(&target).ok() {
131 if is_build_output(executable) {
132 copy_file(executable, &target)?;
133 } else {
134 move_file(executable, &target)?;
135 }
136 }
137 make_executable(&target)?;
138 install_icon(layout, crate::appearance::AppIcon::RustyTeams.png()).map_err(io::Error::other)?;
139 write_desktop_entry(layout, &target)?;
140 refresh_desktop_caches(layout);
141 Ok(target)
142}
143
144/// `rename`, or copy and delete when the source is on another file system.
145fn move_file(from: &Path, to: &Path) -> io::Result<()> {
146 if fs::rename(from, to).is_ok() {
147 return Ok(());
148 }
149 copy_file(from, to)?;
150 let _ = fs::remove_file(from);
151 Ok(())
152}
153
154/// Copies through a temporary file and renames it into place, so a running older
155/// binary at `to` is replaced instead of written over.
156fn copy_file(from: &Path, to: &Path) -> io::Result<()> {
157 let partial = to.with_extension("partial");
158 fs::copy(from, &partial)?;
159 fs::rename(&partial, to).inspect_err(|_| {
160 let _ = fs::remove_file(&partial);
161 })
162}
163
164fn make_executable(path: &Path) -> io::Result<()> {
165 use std::os::unix::fs::PermissionsExt as _;
166 let mut permissions = fs::metadata(path)?.permissions();
167 permissions.set_mode(permissions.mode() | 0o755);
168 fs::set_permissions(path, permissions)
169}
170
171/// Quotes a path for the `Exec` key of a desktop entry.
172fn exec_quoted(path: &Path) -> String {
173 let mut quoted = String::from("\"");
174 for character in path.display().to_string().chars() {
175 if matches!(character, '"' | '`' | '$' | '\\') {
176 quoted.push('\\');
177 }
178 if character == '%' {
179 quoted.push('%');
180 }
181 quoted.push(character);
182 }
183 quoted.push('"');
184 quoted
185}
186
187pub fn desktop_entry(executable: &Path) -> String {
188 format!(
189 "[Desktop Entry]\n\
190 Type=Application\n\
191 Name={name}\n\
192 GenericName=Microsoft Teams client\n\
193 Comment=A fast, native Microsoft Teams chat client\n\
194 Exec={exec}\n\
195 TryExec={try_exec}\n\
196 Icon={ICON_NAME}\n\
197 StartupWMClass={DESKTOP_ID}\n\
198 Terminal=false\n\
199 Categories=Network;InstantMessaging;Chat;\n\
200 Keywords=Teams;Chat;Microsoft;\n",
201 name = crate::APP_NAME,
202 exec = exec_quoted(executable),
203 try_exec = executable.display(),
204 )
205}
206
207pub fn write_desktop_entry(layout: &Layout, executable: &Path) -> io::Result<()> {
208 fs::create_dir_all(layout.applications_dir())?;
209 fs::write(layout.desktop_file(), desktop_entry(executable))
210}
211
212/// Lets the menu and task manager pick up a new entry or icon right away. Every tool
213/// is optional; whatever is missing is skipped.
214pub fn refresh_desktop_caches(layout: &Layout) {
215 let applications = layout.applications_dir();
216 let icons = layout.icons_dir();
217 std::thread::spawn(move || {
218 let run = |program: &str, arguments: &[&std::ffi::OsStr]| {
219 let _ = std::process::Command::new(program)
220 .args(arguments)
221 .stdin(std::process::Stdio::null())
222 .stdout(std::process::Stdio::null())
223 .stderr(std::process::Stdio::null())
224 .status();
225 };
226 run("update-desktop-database", &[applications.as_os_str()]);
227 run(
228 "gtk-update-icon-cache",
229 &["-f".as_ref(), "-t".as_ref(), icons.as_os_str()],
230 );
231 run("kbuildsycoca6", &[]);
232 run("kbuildsycoca5", &[]);
233 });
234}
235
236/// Writes the menu icon into `hicolor` in every size of [`ICON_SIZES`].
237pub fn install_icon(layout: &Layout, bytes: &[u8]) -> Result<(), String> {
238 let decoded = image::load_from_memory(bytes).map_err(|error| error.to_string())?;
239 for size in ICON_SIZES {
240 let resized = decoded.resize_exact(size, size, image::imageops::FilterType::Lanczos3);
241 let mut png = Vec::new();
242 resized
243 .write_to(&mut io::Cursor::new(&mut png), image::ImageFormat::Png)
244 .map_err(|error| error.to_string())?;
245 let path = layout.icon_file(size);
246 if let Some(directory) = path.parent() {
247 fs::create_dir_all(directory).map_err(|error| error.to_string())?;
248 }
249 let partial = path.with_extension("partial");
250 fs::write(&partial, &png).map_err(|error| error.to_string())?;
251 fs::rename(&partial, &path).map_err(|error| error.to_string())?;
252 }
253 Ok(())
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259
260 fn png(size: u32) -> Vec<u8> {
261 let image = image::RgbaImage::from_pixel(size, size, image::Rgba([80, 90, 200, 255]));
262 let mut bytes = Vec::new();
263 image::DynamicImage::ImageRgba8(image)
264 .write_to(&mut io::Cursor::new(&mut bytes), image::ImageFormat::Png)
265 .unwrap();
266 bytes
267 }
268
269 #[test]
270 fn layout_follows_the_xdg_data_folder() {
271 let layout = Layout::new("/home/a/.local/share");
272 assert_eq!(
273 layout.installed_binary(),
274 Path::new("/home/a/.local/share/rusty-teams/teams")
275 );
276 assert_eq!(
277 layout.desktop_file(),
278 Path::new("/home/a/.local/share/applications/rusty-teams.desktop")
279 );
280 assert_eq!(
281 layout.icon_file(48),
282 Path::new("/home/a/.local/share/icons/hicolor/48x48/apps/rusty-teams.png")
283 );
284 }
285
286 #[test]
287 fn the_entry_starts_the_binary_and_matches_the_window() {
288 let entry = desktop_entry(Path::new("/home/a/my apps/te\"a$ms"));
289 assert!(entry.starts_with("[Desktop Entry]\n"));
290 assert!(entry.contains("Exec=\"/home/a/my apps/te\\\"a\\$ms\"\n"));
291 assert!(entry.contains("Icon=rusty-teams\n"));
292 assert!(entry.contains("StartupWMClass=rusty-teams\n"));
293 }
294
295 fn assert_installed(installed: &Path, layout: &Layout, content: &[u8]) {
296 use std::os::unix::fs::PermissionsExt as _;
297 assert_eq!(installed, layout.installed_binary());
298 assert_eq!(fs::read(installed).unwrap(), content);
299 assert_eq!(
300 fs::metadata(installed).unwrap().permissions().mode() & 0o111,
301 0o111
302 );
303 let entry = fs::read_to_string(layout.desktop_file()).unwrap();
304 assert!(entry.contains(&installed.display().to_string()));
305 assert!(!should_offer_install(installed, layout, false));
306 }
307
308 #[test]
309 fn install_moves_a_downloaded_binary_and_writes_the_entry() {
310 let home = tempfile::tempdir().unwrap();
311 let downloads = home.path().join("Downloads");
312 fs::create_dir_all(&downloads).unwrap();
313 let binary = downloads.join("teams");
314 fs::write(&binary, b"v1").unwrap();
315 let layout = Layout::new(home.path().join("share"));
316 assert!(should_offer_install(&binary, &layout, false));
317 assert!(!should_offer_install(&binary, &layout, true));
318
319 let installed = install_binary(&binary, &layout).unwrap();
320
321 assert!(!binary.exists());
322 assert_installed(&installed, &layout, b"v1");
323 assert_eq!(install_binary(&installed, &layout).unwrap(), installed);
324 assert_eq!(fs::read(&installed).unwrap(), b"v1");
325 }
326
327 #[test]
328 fn install_copies_build_output_and_replaces_an_older_install() {
329 let home = tempfile::tempdir().unwrap();
330 let target = home.path().join("repo").join("target");
331 fs::create_dir_all(target.join("release")).unwrap();
332 fs::write(
333 target.join("CACHEDIR.TAG"),
334 b"Signature: 8a477f597d28d172789f06886806bc55",
335 )
336 .unwrap();
337 let binary = target.join("release").join("teams");
338 let layout = Layout::new(home.path().join("share"));
339 fs::write(&binary, b"v1").unwrap();
340 install_binary(&binary, &layout).unwrap();
341 fs::write(&binary, b"v2").unwrap();
342
343 let installed = install_binary(&binary, &layout).unwrap();
344
345 assert!(is_build_output(&binary));
346 assert!(binary.exists());
347 assert_installed(&installed, &layout, b"v2");
348 assert!(!layout.install_dir().join("teams.partial").exists());
349 }
350
351 #[test]
352 fn uninstall_removes_entry_binary_and_update_but_keeps_other_files() {
353 let home = tempfile::tempdir().unwrap();
354 let layout = Layout::new(home.path().join("share"));
355 let downloads = home.path().join("Downloads");
356 fs::create_dir_all(&downloads).unwrap();
357 fs::write(downloads.join("teams"), b"v1").unwrap();
358 install_binary(&downloads.join("teams"), &layout).unwrap();
359 fs::create_dir_all(layout.install_dir().join("update")).unwrap();
360 fs::write(layout.install_dir().join("update").join("teams"), b"v2").unwrap();
361
362 uninstall(&layout).unwrap();
363
364 assert!(!layout.desktop_file().exists());
365 assert!(!layout.install_dir().exists());
366 assert!(!layout.largest_icon().exists());
367 uninstall(&layout).unwrap();
368
369 fs::create_dir_all(layout.install_dir()).unwrap();
370 fs::write(layout.install_dir().join("notes.txt"), b"mine").unwrap();
371 uninstall(&layout).unwrap();
372 assert!(layout.install_dir().join("notes.txt").exists());
373 }
374
375 #[test]
376 fn the_icon_lands_in_every_size() {
377 let home = tempfile::tempdir().unwrap();
378 let layout = Layout::new(home.path());
379 install_icon(&layout, &png(300)).unwrap();
380 for size in ICON_SIZES {
381 let written = image::open(layout.icon_file(size)).unwrap();
382 assert_eq!((written.width(), written.height()), (size, size));
383 }
384 assert!(install_icon(&layout, b"not an image").is_err());
385 }
386}