BlueGit

ict rusty-teams

Files

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

linux_desktop.rs

linux_desktop.rs 15.0 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
84/// Installed by a deb/rpm (under `/usr` or `/opt`), a Flatpak (under `/app`) or started from
85/// an AppImage, whose runtime sets `APPIMAGE`. Those bring their own menu entry and updates, so the app
86/// does not offer to install itself (and, outside the install folder, never updates itself).
87pub fn is_packaged(executable: &Path, appimage: Option<&std::ffi::OsStr>) -> bool {
88 appimage.is_some_and(|path| !path.is_empty())
89 || executable.starts_with("/usr")
90 || executable.starts_with("/opt")
91 || executable.starts_with("/app")
92}
93
94pub fn should_offer_install(executable: &Path, layout: &Layout, dont_ask: bool) -> bool {
95 !dont_ask && !is_installed(executable, layout)
96}
97
98pub fn dont_ask_again(store: &store::Store) -> bool {
99 store.meta(DONT_ASK_META_KEY).ok().flatten().as_deref() == Some("1")
100}
101
102pub fn set_dont_ask_again(store: &store::Store) {
103 let _ = store.set_meta(DONT_ASK_META_KEY, "1");
104}
105
106/// Brings the install question back on the next start.
107pub fn ask_again(store: &store::Store) {
108 let _ = store.set_meta(DONT_ASK_META_KEY, "0");
109}
110
111/// Removes the menu entry and the installed binary (with a staged update). Sign-in
112/// and cache stay. A running installed copy keeps running.
113pub fn uninstall(layout: &Layout) -> io::Result<()> {
114 let remove = |path: PathBuf| match fs::remove_file(&path) {
115 Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
116 _ => Ok(()),
117 };
118 remove(layout.desktop_file())?;
119 let install_dir = layout.install_dir();
120 remove(layout.installed_binary())?;
121 remove(install_dir.join(format!("{BINARY_FILE_NAME}.old")))?;
122 if install_dir.join("update").is_dir() {
123 fs::remove_dir_all(install_dir.join("update"))?;
124 }
125 for size in ICON_SIZES {
126 remove(layout.icon_file(size))?;
127 }
128 // Only when empty: anything else in there belongs to the user.
129 let _ = fs::remove_dir(&install_dir);
130 refresh_desktop_caches(layout);
131 Ok(())
132}
133
134/// Puts the binary into the install folder (copied when it is build output, moved
135/// otherwise), writes the `.desktop` entry and returns the new path. An older
136/// installed binary is replaced.
137pub fn install_binary(executable: &Path, layout: &Layout) -> io::Result<PathBuf> {
138 let target = layout.installed_binary();
139 fs::create_dir_all(layout.install_dir())?;
140 if fs::canonicalize(executable).ok() != fs::canonicalize(&target).ok() {
141 if is_build_output(executable) {
142 copy_file(executable, &target)?;
143 } else {
144 move_file(executable, &target)?;
145 }
146 }
147 make_executable(&target)?;
148 install_icon(layout, crate::appearance::AppIcon::RustyTeams.png()).map_err(io::Error::other)?;
149 write_desktop_entry(layout, &target)?;
150 refresh_desktop_caches(layout);
151 Ok(target)
152}
153
154/// `rename`, or copy and delete when the source is on another file system.
155fn move_file(from: &Path, to: &Path) -> io::Result<()> {
156 if fs::rename(from, to).is_ok() {
157 return Ok(());
158 }
159 copy_file(from, to)?;
160 let _ = fs::remove_file(from);
161 Ok(())
162}
163
164/// Copies through a temporary file and renames it into place, so a running older
165/// binary at `to` is replaced instead of written over.
166fn copy_file(from: &Path, to: &Path) -> io::Result<()> {
167 let partial = to.with_extension("partial");
168 fs::copy(from, &partial)?;
169 fs::rename(&partial, to).inspect_err(|_| {
170 let _ = fs::remove_file(&partial);
171 })
172}
173
174fn make_executable(path: &Path) -> io::Result<()> {
175 use std::os::unix::fs::PermissionsExt as _;
176 let mut permissions = fs::metadata(path)?.permissions();
177 permissions.set_mode(permissions.mode() | 0o755);
178 fs::set_permissions(path, permissions)
179}
180
181/// Quotes a path for the `Exec` key of a desktop entry.
182fn exec_quoted(path: &Path) -> String {
183 let mut quoted = String::from("\"");
184 for character in path.display().to_string().chars() {
185 if matches!(character, '"' | '`' | '$' | '\\') {
186 quoted.push('\\');
187 }
188 if character == '%' {
189 quoted.push('%');
190 }
191 quoted.push(character);
192 }
193 quoted.push('"');
194 quoted
195}
196
197pub fn desktop_entry(executable: &Path) -> String {
198 format!(
199 "[Desktop Entry]\n\
200 Type=Application\n\
201 Name={name}\n\
202 GenericName=Microsoft Teams client\n\
203 Comment=A fast, native Microsoft Teams chat client\n\
204 Exec={exec}\n\
205 TryExec={try_exec}\n\
206 Icon={ICON_NAME}\n\
207 StartupWMClass={DESKTOP_ID}\n\
208 Terminal=false\n\
209 Categories=Network;InstantMessaging;Chat;\n\
210 Keywords=Teams;Chat;Microsoft;\n",
211 name = crate::APP_NAME,
212 exec = exec_quoted(executable),
213 try_exec = executable.display(),
214 )
215}
216
217pub fn write_desktop_entry(layout: &Layout, executable: &Path) -> io::Result<()> {
218 fs::create_dir_all(layout.applications_dir())?;
219 fs::write(layout.desktop_file(), desktop_entry(executable))
220}
221
222/// Lets the menu and task manager pick up a new entry or icon right away. Every tool
223/// is optional; whatever is missing is skipped.
224pub fn refresh_desktop_caches(layout: &Layout) {
225 let applications = layout.applications_dir();
226 let icons = layout.icons_dir();
227 std::thread::spawn(move || {
228 let run = |program: &str, arguments: &[&std::ffi::OsStr]| {
229 let _ = std::process::Command::new(program)
230 .args(arguments)
231 .stdin(std::process::Stdio::null())
232 .stdout(std::process::Stdio::null())
233 .stderr(std::process::Stdio::null())
234 .status();
235 };
236 run("update-desktop-database", &[applications.as_os_str()]);
237 run(
238 "gtk-update-icon-cache",
239 &["-f".as_ref(), "-t".as_ref(), icons.as_os_str()],
240 );
241 run("kbuildsycoca6", &[]);
242 run("kbuildsycoca5", &[]);
243 });
244}
245
246/// Writes the menu icon into `hicolor` in every size of [`ICON_SIZES`].
247pub fn install_icon(layout: &Layout, bytes: &[u8]) -> Result<(), String> {
248 let decoded = image::load_from_memory(bytes).map_err(|error| error.to_string())?;
249 for size in ICON_SIZES {
250 let resized = decoded.resize_exact(size, size, image::imageops::FilterType::Lanczos3);
251 let mut png = Vec::new();
252 resized
253 .write_to(&mut io::Cursor::new(&mut png), image::ImageFormat::Png)
254 .map_err(|error| error.to_string())?;
255 let path = layout.icon_file(size);
256 if let Some(directory) = path.parent() {
257 fs::create_dir_all(directory).map_err(|error| error.to_string())?;
258 }
259 let partial = path.with_extension("partial");
260 fs::write(&partial, &png).map_err(|error| error.to_string())?;
261 fs::rename(&partial, &path).map_err(|error| error.to_string())?;
262 }
263 Ok(())
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269
270 fn png(size: u32) -> Vec<u8> {
271 let image = image::RgbaImage::from_pixel(size, size, image::Rgba([80, 90, 200, 255]));
272 let mut bytes = Vec::new();
273 image::DynamicImage::ImageRgba8(image)
274 .write_to(&mut io::Cursor::new(&mut bytes), image::ImageFormat::Png)
275 .unwrap();
276 bytes
277 }
278
279 #[test]
280 fn layout_follows_the_xdg_data_folder() {
281 let layout = Layout::new("/home/a/.local/share");
282 assert_eq!(
283 layout.installed_binary(),
284 Path::new("/home/a/.local/share/rusty-teams/teams")
285 );
286 assert_eq!(
287 layout.desktop_file(),
288 Path::new("/home/a/.local/share/applications/rusty-teams.desktop")
289 );
290 assert_eq!(
291 layout.icon_file(48),
292 Path::new("/home/a/.local/share/icons/hicolor/48x48/apps/rusty-teams.png")
293 );
294 }
295
296 #[test]
297 fn package_and_appimage_installs_count_as_packaged() {
298 use std::ffi::OsStr;
299 assert!(is_packaged(Path::new("/usr/bin/teams"), None));
300 assert!(is_packaged(Path::new("/opt/rusty-teams/teams"), None));
301 assert!(is_packaged(Path::new("/app/bin/teams"), None));
302 assert!(is_packaged(
303 Path::new("/tmp/.mount_teamsAbc/usr/bin/teams"),
304 Some(OsStr::new("/home/a/Apps/rusty-teams.AppImage"))
305 ));
306 assert!(!is_packaged(Path::new("/home/a/Downloads/teams"), None));
307 assert!(!is_packaged(
308 Path::new("/home/a/.local/share/rusty-teams/teams"),
309 Some(OsStr::new(""))
310 ));
311 assert!(!is_packaged(Path::new("/usrlocal/teams"), None));
312 }
313
314 #[test]
315 fn the_entry_starts_the_binary_and_matches_the_window() {
316 let entry = desktop_entry(Path::new("/home/a/my apps/te\"a$ms"));
317 assert!(entry.starts_with("[Desktop Entry]\n"));
318 assert!(entry.contains("Exec=\"/home/a/my apps/te\\\"a\\$ms\"\n"));
319 assert!(entry.contains("Icon=rusty-teams\n"));
320 assert!(entry.contains("StartupWMClass=rusty-teams\n"));
321 }
322
323 fn assert_installed(installed: &Path, layout: &Layout, content: &[u8]) {
324 use std::os::unix::fs::PermissionsExt as _;
325 assert_eq!(installed, layout.installed_binary());
326 assert_eq!(fs::read(installed).unwrap(), content);
327 assert_eq!(
328 fs::metadata(installed).unwrap().permissions().mode() & 0o111,
329 0o111
330 );
331 let entry = fs::read_to_string(layout.desktop_file()).unwrap();
332 assert!(entry.contains(&installed.display().to_string()));
333 assert!(!should_offer_install(installed, layout, false));
334 }
335
336 #[test]
337 fn install_moves_a_downloaded_binary_and_writes_the_entry() {
338 let home = tempfile::tempdir().unwrap();
339 let downloads = home.path().join("Downloads");
340 fs::create_dir_all(&downloads).unwrap();
341 let binary = downloads.join("teams");
342 fs::write(&binary, b"v1").unwrap();
343 let layout = Layout::new(home.path().join("share"));
344 assert!(should_offer_install(&binary, &layout, false));
345 assert!(!should_offer_install(&binary, &layout, true));
346
347 let installed = install_binary(&binary, &layout).unwrap();
348
349 assert!(!binary.exists());
350 assert_installed(&installed, &layout, b"v1");
351 assert_eq!(install_binary(&installed, &layout).unwrap(), installed);
352 assert_eq!(fs::read(&installed).unwrap(), b"v1");
353 }
354
355 #[test]
356 fn install_copies_build_output_and_replaces_an_older_install() {
357 let home = tempfile::tempdir().unwrap();
358 let target = home.path().join("repo").join("target");
359 fs::create_dir_all(target.join("release")).unwrap();
360 fs::write(
361 target.join("CACHEDIR.TAG"),
362 b"Signature: 8a477f597d28d172789f06886806bc55",
363 )
364 .unwrap();
365 let binary = target.join("release").join("teams");
366 let layout = Layout::new(home.path().join("share"));
367 fs::write(&binary, b"v1").unwrap();
368 install_binary(&binary, &layout).unwrap();
369 fs::write(&binary, b"v2").unwrap();
370
371 let installed = install_binary(&binary, &layout).unwrap();
372
373 assert!(is_build_output(&binary));
374 assert!(binary.exists());
375 assert_installed(&installed, &layout, b"v2");
376 assert!(!layout.install_dir().join("teams.partial").exists());
377 }
378
379 #[test]
380 fn uninstall_removes_entry_binary_and_update_but_keeps_other_files() {
381 let home = tempfile::tempdir().unwrap();
382 let layout = Layout::new(home.path().join("share"));
383 let downloads = home.path().join("Downloads");
384 fs::create_dir_all(&downloads).unwrap();
385 fs::write(downloads.join("teams"), b"v1").unwrap();
386 install_binary(&downloads.join("teams"), &layout).unwrap();
387 fs::create_dir_all(layout.install_dir().join("update")).unwrap();
388 fs::write(layout.install_dir().join("update").join("teams"), b"v2").unwrap();
389
390 uninstall(&layout).unwrap();
391
392 assert!(!layout.desktop_file().exists());
393 assert!(!layout.install_dir().exists());
394 assert!(!layout.largest_icon().exists());
395 uninstall(&layout).unwrap();
396
397 fs::create_dir_all(layout.install_dir()).unwrap();
398 fs::write(layout.install_dir().join("notes.txt"), b"mine").unwrap();
399 uninstall(&layout).unwrap();
400 assert!(layout.install_dir().join("notes.txt").exists());
401 }
402
403 #[test]
404 fn the_icon_lands_in_every_size() {
405 let home = tempfile::tempdir().unwrap();
406 let layout = Layout::new(home.path());
407 install_icon(&layout, &png(300)).unwrap();
408 for size in ICON_SIZES {
409 let written = image::open(layout.icon_file(size)).unwrap();
410 assert_eq!((written.width(), written.height()), (size, size));
411 }
412 assert!(install_icon(&layout, b"not an image").is_err());
413 }
414}