BlueGit

ict rusty-teams

Files

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

linux_desktop.rs

linux_desktop.rs 17.4 KiB Download Raw
1//! Desktop integration on Linux: the install folder
2//! (`~/.local/share/applications/teams`), the `.desktop` entry and the Teams icon,
3//! which is downloaded from Microsoft instead of shipped.
4
5use std::fs;
6use std::io;
7use std::path::{Path, PathBuf};
8use std::sync::RwLock;
9
10use futures_util::AsyncReadExt as _;
11use gpui_kit::{App, Task};
12
13/// Matches the window's app id, so KDE pairs the window with the entry.
14pub const DESKTOP_ID: &str = "rusty-teams";
15/// Name the `.desktop` entry, the tray and `hicolor` use for the icon.
16pub const ICON_NAME: &str = "rusty-teams";
17pub const BINARY_FILE_NAME: &str = "teams";
18/// Same icon the Teams web page shows in its tab.
19pub const TEAMS_ICON_URL: &str = "https://teams.public.onecdn.static.microsoft/evergreen-assets/icons/microsoft_teams_logo_refresh_v2025.ico";
20/// Fallback when [`TEAMS_ICON_URL`] moves: the page names its current favicon.
21pub const TEAMS_PAGE_URL: &str = "https://teams.cloud.microsoft/";
22pub const ICON_SIZES: [u32; 5] = [256, 128, 64, 48, 32];
23const INSTALL_FOLDER: &str = "teams";
24const DONT_ASK_META_KEY: &str = "linux.install.dont_ask";
25const FAVICON_ID: &str = "id=\"teams-favicon\"";
26
27/// Cargo marks its target folder with `CACHEDIR.TAG`; a binary in
28/// `target/<profile>/` is build output and is copied, not moved, on install.
29pub fn is_build_output(executable: &Path) -> bool {
30 executable
31 .parent()
32 .and_then(Path::parent)
33 .is_some_and(|target| target.join("CACHEDIR.TAG").is_file())
34}
35
36/// Paths below the XDG data folder (`~/.local/share`).
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Layout {
39 data_dir: PathBuf,
40}
41
42impl Layout {
43 pub fn new(data_dir: impl Into<PathBuf>) -> Layout {
44 Layout {
45 data_dir: data_dir.into(),
46 }
47 }
48
49 pub fn current() -> Option<Layout> {
50 directories::BaseDirs::new().map(|base| Layout::new(base.data_dir()))
51 }
52
53 pub fn applications_dir(&self) -> PathBuf {
54 self.data_dir.join("applications")
55 }
56
57 pub fn install_dir(&self) -> PathBuf {
58 self.applications_dir().join(INSTALL_FOLDER)
59 }
60
61 pub fn installed_binary(&self) -> PathBuf {
62 self.install_dir().join(BINARY_FILE_NAME)
63 }
64
65 pub fn desktop_file(&self) -> PathBuf {
66 self.applications_dir()
67 .join(format!("{DESKTOP_ID}.desktop"))
68 }
69
70 pub fn icons_dir(&self) -> PathBuf {
71 self.data_dir.join("icons").join("hicolor")
72 }
73
74 pub fn icon_file(&self, size: u32) -> PathBuf {
75 self.icons_dir()
76 .join(format!("{size}x{size}"))
77 .join("apps")
78 .join(format!("{ICON_NAME}.png"))
79 }
80
81 pub fn largest_icon(&self) -> PathBuf {
82 self.icon_file(ICON_SIZES[0])
83 }
84}
85
86pub fn is_installed(executable: &Path, layout: &Layout) -> bool {
87 let install_dir = layout.install_dir();
88 let canonical = |path: &Path| fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
89 executable
90 .parent()
91 .is_some_and(|parent| canonical(parent) == canonical(&install_dir))
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/// cache and the downloaded icon 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 // Only when empty: anything else in there belongs to the user.
126 let _ = fs::remove_dir(&install_dir);
127 refresh_desktop_caches(layout);
128 Ok(())
129}
130
131/// Puts the binary into the install folder (copied when it is build output, moved
132/// otherwise), writes the `.desktop` entry and returns the new path. An older
133/// installed binary is replaced.
134pub fn install_binary(executable: &Path, layout: &Layout) -> io::Result<PathBuf> {
135 let target = layout.installed_binary();
136 fs::create_dir_all(layout.install_dir())?;
137 if fs::canonicalize(executable).ok() != fs::canonicalize(&target).ok() {
138 if is_build_output(executable) {
139 copy_file(executable, &target)?;
140 } else {
141 move_file(executable, &target)?;
142 }
143 }
144 make_executable(&target)?;
145 write_desktop_entry(layout, &target)?;
146 refresh_desktop_caches(layout);
147 Ok(target)
148}
149
150/// `rename`, or copy and delete when the source is on another file system.
151fn move_file(from: &Path, to: &Path) -> io::Result<()> {
152 if fs::rename(from, to).is_ok() {
153 return Ok(());
154 }
155 copy_file(from, to)?;
156 fs::remove_file(from)
157}
158
159/// Copies through a temporary file and renames it into place, so a running older
160/// binary at `to` is replaced instead of written over.
161fn copy_file(from: &Path, to: &Path) -> io::Result<()> {
162 let partial = to.with_extension("partial");
163 fs::copy(from, &partial)?;
164 fs::rename(&partial, to).inspect_err(|_| {
165 let _ = fs::remove_file(&partial);
166 })
167}
168
169fn make_executable(path: &Path) -> io::Result<()> {
170 use std::os::unix::fs::PermissionsExt as _;
171 let mut permissions = fs::metadata(path)?.permissions();
172 permissions.set_mode(permissions.mode() | 0o755);
173 fs::set_permissions(path, permissions)
174}
175
176/// Quotes a path for the `Exec` key of a desktop entry.
177fn exec_quoted(path: &Path) -> String {
178 let mut quoted = String::from("\"");
179 for character in path.display().to_string().chars() {
180 if matches!(character, '"' | '`' | '$' | '\\') {
181 quoted.push('\\');
182 }
183 quoted.push(character);
184 }
185 quoted.push('"');
186 quoted
187}
188
189pub fn desktop_entry(executable: &Path) -> String {
190 format!(
191 "[Desktop Entry]\n\
192 Type=Application\n\
193 Name={name}\n\
194 GenericName=Microsoft Teams client\n\
195 Comment=A fast, native Microsoft Teams chat client\n\
196 Exec={exec}\n\
197 TryExec={try_exec}\n\
198 Icon={ICON_NAME}\n\
199 StartupWMClass={DESKTOP_ID}\n\
200 Terminal=false\n\
201 Categories=Network;InstantMessaging;Chat;\n\
202 Keywords=Teams;Chat;Microsoft;\n",
203 name = crate::APP_NAME,
204 exec = exec_quoted(executable),
205 try_exec = executable.display(),
206 )
207}
208
209pub fn write_desktop_entry(layout: &Layout, executable: &Path) -> io::Result<()> {
210 fs::create_dir_all(layout.applications_dir())?;
211 fs::write(layout.desktop_file(), desktop_entry(executable))
212}
213
214/// Lets the menu and task manager pick up a new entry or icon right away. Every tool
215/// is optional; whatever is missing is skipped.
216pub fn refresh_desktop_caches(layout: &Layout) {
217 let applications = layout.applications_dir();
218 let icons = layout.icons_dir();
219 std::thread::spawn(move || {
220 let run = |program: &str, arguments: &[&std::ffi::OsStr]| {
221 let _ = std::process::Command::new(program)
222 .args(arguments)
223 .stdin(std::process::Stdio::null())
224 .stdout(std::process::Stdio::null())
225 .stderr(std::process::Stdio::null())
226 .status();
227 };
228 run("update-desktop-database", &[applications.as_os_str()]);
229 run(
230 "gtk-update-icon-cache",
231 &["-f".as_ref(), "-t".as_ref(), icons.as_os_str()],
232 );
233 run("kbuildsycoca6", &[]);
234 run("kbuildsycoca5", &[]);
235 });
236}
237
238/// Writes the Teams icon into `hicolor` in every size of [`ICON_SIZES`].
239/// `bytes` is an `.ico` or a `.png`.
240pub fn install_icon(layout: &Layout, bytes: &[u8]) -> Result<(), String> {
241 let decoded = image::load_from_memory(bytes).map_err(|error| error.to_string())?;
242 for size in ICON_SIZES {
243 let resized = decoded.resize_exact(size, size, image::imageops::FilterType::Lanczos3);
244 let mut png = Vec::new();
245 resized
246 .write_to(&mut io::Cursor::new(&mut png), image::ImageFormat::Png)
247 .map_err(|error| error.to_string())?;
248 let path = layout.icon_file(size);
249 if let Some(directory) = path.parent() {
250 fs::create_dir_all(directory).map_err(|error| error.to_string())?;
251 }
252 let partial = path.with_extension("partial");
253 fs::write(&partial, &png).map_err(|error| error.to_string())?;
254 fs::rename(&partial, &path).map_err(|error| error.to_string())?;
255 }
256 Ok(())
257}
258
259pub fn has_icon(layout: &Layout) -> bool {
260 layout.largest_icon().is_file()
261}
262
263/// The `href` of `<link id="teams-favicon" ...>` in the Teams page.
264pub fn favicon_url(html: &str) -> Option<String> {
265 let start = html.find(FAVICON_ID)?;
266 let tag_start = html[..start].rfind('<')?;
267 let tag_end = start + html[start..].find('>')?;
268 let tag = &html[tag_start..tag_end];
269 let href = tag.find("href=\"")? + "href=\"".len();
270 let length = tag[href..].find('"')?;
271 let url = &tag[href..href + length];
272 url.starts_with("https://").then(|| url.to_owned())
273}
274
275/// Downloads the Teams icon into `hicolor` and returns the 256 px PNG.
276pub fn download_icon(layout: Layout, cx: &App) -> Task<Result<Vec<u8>, String>> {
277 let client = cx.http_client();
278 cx.background_executor().spawn(async move {
279 let get = |url: String| {
280 let client = client.clone();
281 async move {
282 let mut response = client
283 .get(&url, ().into(), true)
284 .await
285 .map_err(|error| error.to_string())?;
286 let mut body = Vec::new();
287 response
288 .body_mut()
289 .read_to_end(&mut body)
290 .await
291 .map_err(|error| error.to_string())?;
292 if !response.status().is_success() {
293 return Err(format!("{url}: status {}", response.status()));
294 }
295 Ok::<_, String>(body)
296 }
297 };
298 let bytes = match get(TEAMS_ICON_URL.to_owned()).await {
299 Ok(bytes) => bytes,
300 Err(first) => {
301 let page = get(TEAMS_PAGE_URL.to_owned()).await?;
302 let url = favicon_url(&String::from_utf8_lossy(&page))
303 .ok_or_else(|| format!("{first}; no favicon on the Teams page"))?;
304 get(url).await?
305 }
306 };
307 install_icon(&layout, &bytes)?;
308 refresh_desktop_caches(&layout);
309 fs::read(layout.largest_icon()).map_err(|error| error.to_string())
310 })
311}
312
313static TEAMS_ICON: RwLock<Option<&'static [u8]>> = RwLock::new(None);
314
315/// The downloaded Teams icon as PNG, once it is on disk.
316pub fn teams_icon() -> Option<&'static [u8]> {
317 *TEAMS_ICON
318 .read()
319 .unwrap_or_else(|poisoned| poisoned.into_inner())
320}
321
322pub fn set_teams_icon(png: Vec<u8>) {
323 if !png.starts_with(b"\x89PNG") {
324 return;
325 }
326 let mut slot = TEAMS_ICON
327 .write()
328 .unwrap_or_else(|poisoned| poisoned.into_inner());
329 // Set once or twice per run (start and after a download); the leak is bounded.
330 *slot = Some(Box::leak(png.into_boxed_slice()));
331}
332
333/// Loads the icon a previous run downloaded.
334pub fn load_teams_icon(layout: &Layout) {
335 if let Ok(png) = fs::read(layout.largest_icon()) {
336 set_teams_icon(png);
337 }
338}
339
340#[cfg(test)]
341mod tests {
342 use super::*;
343
344 fn png(size: u32) -> Vec<u8> {
345 let image = image::RgbaImage::from_pixel(size, size, image::Rgba([80, 90, 200, 255]));
346 let mut bytes = Vec::new();
347 image::DynamicImage::ImageRgba8(image)
348 .write_to(&mut io::Cursor::new(&mut bytes), image::ImageFormat::Png)
349 .unwrap();
350 bytes
351 }
352
353 #[test]
354 fn layout_follows_the_xdg_data_folder() {
355 let layout = Layout::new("/home/a/.local/share");
356 assert_eq!(
357 layout.installed_binary(),
358 Path::new("/home/a/.local/share/applications/teams/teams")
359 );
360 assert_eq!(
361 layout.desktop_file(),
362 Path::new("/home/a/.local/share/applications/rusty-teams.desktop")
363 );
364 assert_eq!(
365 layout.icon_file(48),
366 Path::new("/home/a/.local/share/icons/hicolor/48x48/apps/rusty-teams.png")
367 );
368 }
369
370 #[test]
371 fn the_entry_starts_the_binary_and_matches_the_window() {
372 let entry = desktop_entry(Path::new("/home/a/my apps/te\"a$ms"));
373 assert!(entry.starts_with("[Desktop Entry]\n"));
374 assert!(entry.contains("Exec=\"/home/a/my apps/te\\\"a\\$ms\"\n"));
375 assert!(entry.contains("Icon=rusty-teams\n"));
376 assert!(entry.contains("StartupWMClass=rusty-teams\n"));
377 }
378
379 fn assert_installed(installed: &Path, layout: &Layout, content: &[u8]) {
380 use std::os::unix::fs::PermissionsExt as _;
381 assert_eq!(installed, layout.installed_binary());
382 assert_eq!(fs::read(installed).unwrap(), content);
383 assert_eq!(
384 fs::metadata(installed).unwrap().permissions().mode() & 0o111,
385 0o111
386 );
387 let entry = fs::read_to_string(layout.desktop_file()).unwrap();
388 assert!(entry.contains(&installed.display().to_string()));
389 assert!(!should_offer_install(installed, layout, false));
390 }
391
392 #[test]
393 fn install_moves_a_downloaded_binary_and_writes_the_entry() {
394 let home = tempfile::tempdir().unwrap();
395 let downloads = home.path().join("Downloads");
396 fs::create_dir_all(&downloads).unwrap();
397 let binary = downloads.join("teams");
398 fs::write(&binary, b"v1").unwrap();
399 let layout = Layout::new(home.path().join("share"));
400 assert!(should_offer_install(&binary, &layout, false));
401 assert!(!should_offer_install(&binary, &layout, true));
402
403 let installed = install_binary(&binary, &layout).unwrap();
404
405 assert!(!binary.exists());
406 assert_installed(&installed, &layout, b"v1");
407 assert_eq!(install_binary(&installed, &layout).unwrap(), installed);
408 assert_eq!(fs::read(&installed).unwrap(), b"v1");
409 }
410
411 #[test]
412 fn install_copies_build_output_and_replaces_an_older_install() {
413 let home = tempfile::tempdir().unwrap();
414 let target = home.path().join("repo").join("target");
415 fs::create_dir_all(target.join("release")).unwrap();
416 fs::write(
417 target.join("CACHEDIR.TAG"),
418 b"Signature: 8a477f597d28d172789f06886806bc55",
419 )
420 .unwrap();
421 let binary = target.join("release").join("teams");
422 let layout = Layout::new(home.path().join("share"));
423 fs::write(&binary, b"v1").unwrap();
424 install_binary(&binary, &layout).unwrap();
425 fs::write(&binary, b"v2").unwrap();
426
427 let installed = install_binary(&binary, &layout).unwrap();
428
429 assert!(is_build_output(&binary));
430 assert!(binary.exists());
431 assert_installed(&installed, &layout, b"v2");
432 assert!(!layout.install_dir().join("teams.partial").exists());
433 }
434
435 #[test]
436 fn uninstall_removes_entry_binary_and_update_but_keeps_other_files() {
437 let home = tempfile::tempdir().unwrap();
438 let layout = Layout::new(home.path().join("share"));
439 let downloads = home.path().join("Downloads");
440 fs::create_dir_all(&downloads).unwrap();
441 fs::write(downloads.join("teams"), b"v1").unwrap();
442 install_binary(&downloads.join("teams"), &layout).unwrap();
443 fs::create_dir_all(layout.install_dir().join("update")).unwrap();
444 fs::write(layout.install_dir().join("update").join("teams"), b"v2").unwrap();
445
446 uninstall(&layout).unwrap();
447
448 assert!(!layout.desktop_file().exists());
449 assert!(!layout.install_dir().exists());
450 uninstall(&layout).unwrap();
451
452 fs::create_dir_all(layout.install_dir()).unwrap();
453 fs::write(layout.install_dir().join("notes.txt"), b"mine").unwrap();
454 uninstall(&layout).unwrap();
455 assert!(layout.install_dir().join("notes.txt").exists());
456 }
457
458 #[test]
459 fn the_icon_lands_in_every_size() {
460 let home = tempfile::tempdir().unwrap();
461 let layout = Layout::new(home.path());
462 assert!(!has_icon(&layout));
463 install_icon(&layout, &png(300)).unwrap();
464 for size in ICON_SIZES {
465 let written = image::open(layout.icon_file(size)).unwrap();
466 assert_eq!((written.width(), written.height()), (size, size));
467 }
468 assert!(has_icon(&layout));
469 assert!(install_icon(&layout, b"not an image").is_err());
470 }
471
472 #[test]
473 fn the_favicon_comes_from_the_teams_page() {
474 let html = r#"<head><link rel="shortcut icon" type="image/x-icon" id="teams-favicon" href="https://cdn.example/icons/teams.ico"/></head>"#;
475 assert_eq!(
476 favicon_url(html).as_deref(),
477 Some("https://cdn.example/icons/teams.ico")
478 );
479 assert_eq!(favicon_url("<html></html>"), None);
480 assert_eq!(
481 favicon_url(r#"<link id="teams-favicon" href="http://insecure/x.ico">"#),
482 None
483 );
484 }
485}