BlueGit

ict rusty-teams

Merge pull request #35: feat(linux): tray, close to tray, self-install and updates

metis Daniel Däschle · pushed by metis

Authored 2026-11-14 · 2 weeks ago

Hash
2c2f081bef90a2f4378582b8ba5ff22e5aba17c8
21 files changed +1645 −64
.github/workflows/build.yml +2 −0
@@ -127,6 +127,8 @@ jobs:
127 127 mkdir release
128 128 chmod +x dist/teams-linux-amd64/teams
129 129 tar -czf "release/rusty-teams-$TAG-linux-amd64.tar.gz" -C dist/teams-linux-amd64 teams
130 # The bare binary is what the Linux self-update downloads (release_feed.rs).
131 cp dist/teams-linux-amd64/teams "release/rusty-teams-$TAG-linux-amd64"
130 132 cp dist/teams-windows-amd64/teams.exe "release/rusty-teams-$TAG-windows-amd64.exe"
131 133 cp dist/teams-macos/teams-macos.zip "release/rusty-teams-$TAG-macos-universal.zip"
132 134
@@ -127,6 +127,8 @@ jobs:
127 mkdir release
127 mkdir release
128 chmod +x dist/teams-linux-amd64/teams
128 chmod +x dist/teams-linux-amd64/teams
129 tar -czf "release/rusty-teams-$TAG-linux-amd64.tar.gz" -C dist/teams-linux-amd64 teams
129 tar -czf "release/rusty-teams-$TAG-linux-amd64.tar.gz" -C dist/teams-linux-amd64 teams
130 # The bare binary is what the Linux self-update downloads (release_feed.rs).
131 cp dist/teams-linux-amd64/teams "release/rusty-teams-$TAG-linux-amd64"
130 cp dist/teams-windows-amd64/teams.exe "release/rusty-teams-$TAG-windows-amd64.exe"
132 cp dist/teams-windows-amd64/teams.exe "release/rusty-teams-$TAG-windows-amd64.exe"
131 cp dist/teams-macos/teams-macos.zip "release/rusty-teams-$TAG-macos-universal.zip"
133 cp dist/teams-macos/teams-macos.zip "release/rusty-teams-$TAG-macos-universal.zip"
132
134
README.md +2 −2
@@ -81,7 +81,7 @@
81 81
82 82 **App**
83 83 - Dark theme, opens instantly from the cache
84 - Self-update from an update folder
84 - Self-update from GitHub releases (Windows, and the installed Linux binary)
85 85 - Single instance: a second start brings the window to the front
86 86
87 87 ## Status
@@ -89,7 +89,7 @@
89 89 | Platform | State |
90 90 |---|---|
91 91 | 🪟 Windows | Main target. Login through an embedded WebView2 |
92 | 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. Copy `crates/app/assets/linux/rusty-teams.desktop` to `~/.local/share/applications/` and `crates/app/assets/icon/teams-fast-256.png` to `~/.local/share/icons/hicolor/256x256/apps/rusty-teams.png` so the dock can match it. Tray icon through StatusNotifierItem (KDE Plasma natively, GNOME with the AppIndicator extension); with "Close to tray" the window closes and the app keeps running in the tray, which opens a new window. Built-in login without Chrome is planned |
92 | 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. On start the app offers to install itself to `~/.local/share/applications/teams/teams` (moved, or copied when started from a cargo `target` folder) and writes `~/.local/share/applications/rusty-teams.desktop`; starting a newer build offers to replace the installed one, and Settings > General can install, replace, remove or bring the question back. The installed copy of a release build looks for new GitHub releases (Settings > General > Automatic updates) and asks before it downloads and restarts. The Microsoft Teams icon is downloaded from Microsoft's CDN into `~/.local/share/icons/hicolor` instead of being shipped. Tray icon through StatusNotifierItem (KDE Plasma natively, GNOME with the AppIndicator extension); with "Close to tray" the window closes and the app keeps running in the tray, which opens a new window. Built-in login without Chrome is planned |
93 93 | 🍎 macOS | Starts Google Chrome or Chromium on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
94 94
95 95 The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
@@ -81,7 +81,7 @@
81
81
82**App**
82**App**
83- Dark theme, opens instantly from the cache
83- Dark theme, opens instantly from the cache
84- Self-update from an update folder
84- Self-update from GitHub releases (Windows, and the installed Linux binary)
85- Single instance: a second start brings the window to the front
85- Single instance: a second start brings the window to the front
86
86
87## Status
87## Status
@@ -89,7 +89,7 @@
89| Platform | State |
89| Platform | State |
90|---|---|
90|---|---|
91| 🪟 Windows | Main target. Login through an embedded WebView2 |
91| 🪟 Windows | Main target. Login through an embedded WebView2 |
92| 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. Copy `crates/app/assets/linux/rusty-teams.desktop` to `~/.local/share/applications/` and `crates/app/assets/icon/teams-fast-256.png` to `~/.local/share/icons/hicolor/256x256/apps/rusty-teams.png` so the dock can match it. Tray icon through StatusNotifierItem (KDE Plasma natively, GNOME with the AppIndicator extension); with "Close to tray" the window closes and the app keeps running in the tray, which opens a new window. Built-in login without Chrome is planned |
92| 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. On start the app offers to install itself to `~/.local/share/applications/teams/teams` (moved, or copied when started from a cargo `target` folder) and writes `~/.local/share/applications/rusty-teams.desktop`; starting a newer build offers to replace the installed one, and Settings > General can install, replace, remove or bring the question back. The installed copy of a release build looks for new GitHub releases (Settings > General > Automatic updates) and asks before it downloads and restarts. The Microsoft Teams icon is downloaded from Microsoft's CDN into `~/.local/share/icons/hicolor` instead of being shipped. Tray icon through StatusNotifierItem (KDE Plasma natively, GNOME with the AppIndicator extension); with "Close to tray" the window closes and the app keeps running in the tray, which opens a new window. Built-in login without Chrome is planned |
93| 🍎 macOS | Starts Google Chrome or Chromium on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
93| 🍎 macOS | Starts Google Chrome or Chromium on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
94
94
95The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
95The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
ROADMAP.md +1 −0
@@ -35,6 +35,7 @@ Feature parity with the Microsoft Teams desktop client.
35 35 | Start from the local cache, no spinner | Done | |
36 36 | Self-update | Done | |
37 37 | Tray icon, close to tray | Done | Linux: StatusNotifierItem tray (KDE, GNOME with AppIndicator); close really closes the window and the tray opens a new one, since GPUI cannot hide a Wayland window |
38 | Linux install, menu entry and self-update | Done | Offers to install itself to `~/.local/share/applications/teams` with a `.desktop` entry (Settings > General to install, replace, remove or ask again); the installed release build offers new GitHub releases in a dialog (download with progress, then Restart now); the Teams icon is downloaded from Microsoft, not shipped |
38 39 | Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |
39 40 | Single instance, second start brings the window to front | Done | |
40 41 | Sign in on macOS without starting Chrome by hand | Done | Same managed Chrome as on Linux, profile in Application Support |
@@ -35,6 +35,7 @@ Feature parity with the Microsoft Teams desktop client.
35| Start from the local cache, no spinner | Done | |
35| Start from the local cache, no spinner | Done | |
36| Self-update | Done | |
36| Self-update | Done | |
37| Tray icon, close to tray | Done | Linux: StatusNotifierItem tray (KDE, GNOME with AppIndicator); close really closes the window and the tray opens a new one, since GPUI cannot hide a Wayland window |
37| Tray icon, close to tray | Done | Linux: StatusNotifierItem tray (KDE, GNOME with AppIndicator); close really closes the window and the tray opens a new one, since GPUI cannot hide a Wayland window |
38| Linux install, menu entry and self-update | Done | Offers to install itself to `~/.local/share/applications/teams` with a `.desktop` entry (Settings > General to install, replace, remove or ask again); the installed release build offers new GitHub releases in a dialog (download with progress, then Restart now); the Teams icon is downloaded from Microsoft, not shipped |
38| Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |
39| Sign in on Linux without starting Chrome by hand | Done | The app starts Chrome or Chromium headless with its own profile, shows the window for the login and hides it again afterwards; a watchdog restarts a dead or hung Chrome |
39| Single instance, second start brings the window to front | Done | |
40| Single instance, second start brings the window to front | Done | |
40| Sign in on macOS without starting Chrome by hand | Done | Same managed Chrome as on Linux, profile in Application Support |
41| Sign in on macOS without starting Chrome by hand | Done | Same managed Chrome as on Linux, profile in Application Support |
crates/app-base/Cargo.toml +1 −1
@@ -26,7 +26,7 @@ session.workspace = true
26 26 store.workspace = true
27 27 teams-core.workspace = true
28 28 tokio.workspace = true
29 image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
29 image = { version = "0.25", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }
30 30 raw-window-handle = "0.6"
31 31 sha2 = "0.10"
32 32 sys-locale = "0.3"
@@ -26,7 +26,7 @@ session.workspace = true
26store.workspace = true
26store.workspace = true
27teams-core.workspace = true
27teams-core.workspace = true
28tokio.workspace = true
28tokio.workspace = true
29image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
29image = { version = "0.25", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }
30raw-window-handle = "0.6"
30raw-window-handle = "0.6"
31sha2 = "0.10"
31sha2 = "0.10"
32sys-locale = "0.3"
32sys-locale = "0.3"
crates/app-base/locales/app.yml +103 −0
@@ -388,6 +388,109 @@ tray:
388 388 mute_sound:
389 389 en: Mute sound
390 390 de: Ton stumm schalten
391 install:
392 title:
393 en: Install Rusty Teams?
394 de: Rusty Teams installieren?
395 body:
396 en: "Put Rusty Teams into %{folder} and add it to the application menu?"
397 de: "Rusty Teams nach %{folder} legen und ins Anwendungsmenü aufnehmen?"
398 move:
399 en: Install
400 de: Installieren
401 not_now:
402 en: Not now
403 de: Nicht jetzt
404 dont_ask:
405 en: Don't ask again
406 de: Nicht mehr fragen
407 failed:
408 en: "Could not install: %{detail}"
409 de: "Installation fehlgeschlagen: %{detail}"
410 removed:
411 en: Removed from the application menu
412 de: Aus dem Anwendungsmenü entfernt
413 remove_failed:
414 en: "Could not remove: %{detail}"
415 de: "Entfernen fehlgeschlagen: %{detail}"
416 menu_title:
417 en: Application menu
418 de: Anwendungsmenü
419 installed_detail:
420 en: "Installed in %{folder}"
421 de: "Installiert in %{folder}"
422 other_copy_detail:
423 en: "Another build is installed in %{folder}"
424 de: "In %{folder} ist ein anderer Build installiert"
425 not_installed_detail:
426 en: Not installed. Install puts Rusty Teams into the application menu
427 de: Nicht installiert. Installieren nimmt Rusty Teams ins Anwendungsmenü auf
428 replace:
429 en: Replace with this build
430 de: Durch diesen Build ersetzen
431 remove:
432 en: Remove
433 de: Entfernen
434 ask_on_start:
435 en: Ask to install on start
436 de: Beim Start nach Installation fragen
437 updates_title:
438 en: Updates
439 de: Updates
440 updates_detail:
441 en: "%{version}, updates from GitHub releases"
442 de: "%{version}, Updates über GitHub-Releases"
443 updates_detail_not_installed:
444 en: "%{version}. Install Rusty Teams above to get updates"
445 de: "%{version}. Installiere Rusty Teams oben, um Updates zu erhalten"
446 updates_need_install:
447 en: Install Rusty Teams first (Application menu > Install), then it can update itself
448 de: Installiere Rusty Teams zuerst (Anwendungsmenü > Installieren), dann kann es sich selbst aktualisieren
449 check_now:
450 en: Check now
451 de: Jetzt prüfen
452 update_checking:
453 en: Checking for updates...
454 de: Suche nach Updates...
455 auto_updates:
456 en: Automatic updates
457 de: Automatische Updates
458 auto_updates_detail:
459 en: Look for new releases and ask before installing
460 de: Nach neuen Releases suchen und vor der Installation fragen
461 update_available_title:
462 en: Update available
463 de: Update verfügbar
464 update_available_body:
465 en: "Rusty Teams %{version} is available. You have %{current}. Update now?"
466 de: "Rusty Teams %{version} ist verfügbar. Installiert ist %{current}. Jetzt aktualisieren?"
467 update_now:
468 en: Update
469 de: Aktualisieren
470 update_downloading:
471 en: "Downloading %{version}... %{percent}%"
472 de: "%{version} wird heruntergeladen... %{percent} %"
473 hide:
474 en: Hide
475 de: Ausblenden
476 update_ready_title:
477 en: Update ready
478 de: Update bereit
479 update_ready_body:
480 en: "%{version} is downloaded. Restart Rusty Teams to finish the update."
481 de: "%{version} ist heruntergeladen. Starte Rusty Teams neu, um das Update abzuschließen."
482 later:
483 en: Later
484 de: Später
485 restart_now:
486 en: Restart now
487 de: Jetzt neu starten
488 up_to_date:
489 en: Rusty Teams is up to date
490 de: Rusty Teams ist aktuell
491 update_failed:
492 en: "Update check failed: %{detail}"
493 de: "Update-Prüfung fehlgeschlagen: %{detail}"
391 494 calls:
392 495 notice:
393 496 not_connected:
@@ -388,6 +388,109 @@ tray:
388 mute_sound:
388 mute_sound:
389 en: Mute sound
389 en: Mute sound
390 de: Ton stumm schalten
390 de: Ton stumm schalten
391install:
392 title:
393 en: Install Rusty Teams?
394 de: Rusty Teams installieren?
395 body:
396 en: "Put Rusty Teams into %{folder} and add it to the application menu?"
397 de: "Rusty Teams nach %{folder} legen und ins Anwendungsmenü aufnehmen?"
398 move:
399 en: Install
400 de: Installieren
401 not_now:
402 en: Not now
403 de: Nicht jetzt
404 dont_ask:
405 en: Don't ask again
406 de: Nicht mehr fragen
407 failed:
408 en: "Could not install: %{detail}"
409 de: "Installation fehlgeschlagen: %{detail}"
410 removed:
411 en: Removed from the application menu
412 de: Aus dem Anwendungsmenü entfernt
413 remove_failed:
414 en: "Could not remove: %{detail}"
415 de: "Entfernen fehlgeschlagen: %{detail}"
416 menu_title:
417 en: Application menu
418 de: Anwendungsmenü
419 installed_detail:
420 en: "Installed in %{folder}"
421 de: "Installiert in %{folder}"
422 other_copy_detail:
423 en: "Another build is installed in %{folder}"
424 de: "In %{folder} ist ein anderer Build installiert"
425 not_installed_detail:
426 en: Not installed. Install puts Rusty Teams into the application menu
427 de: Nicht installiert. Installieren nimmt Rusty Teams ins Anwendungsmenü auf
428 replace:
429 en: Replace with this build
430 de: Durch diesen Build ersetzen
431 remove:
432 en: Remove
433 de: Entfernen
434 ask_on_start:
435 en: Ask to install on start
436 de: Beim Start nach Installation fragen
437 updates_title:
438 en: Updates
439 de: Updates
440 updates_detail:
441 en: "%{version}, updates from GitHub releases"
442 de: "%{version}, Updates über GitHub-Releases"
443 updates_detail_not_installed:
444 en: "%{version}. Install Rusty Teams above to get updates"
445 de: "%{version}. Installiere Rusty Teams oben, um Updates zu erhalten"
446 updates_need_install:
447 en: Install Rusty Teams first (Application menu > Install), then it can update itself
448 de: Installiere Rusty Teams zuerst (Anwendungsmenü > Installieren), dann kann es sich selbst aktualisieren
449 check_now:
450 en: Check now
451 de: Jetzt prüfen
452 update_checking:
453 en: Checking for updates...
454 de: Suche nach Updates...
455 auto_updates:
456 en: Automatic updates
457 de: Automatische Updates
458 auto_updates_detail:
459 en: Look for new releases and ask before installing
460 de: Nach neuen Releases suchen und vor der Installation fragen
461 update_available_title:
462 en: Update available
463 de: Update verfügbar
464 update_available_body:
465 en: "Rusty Teams %{version} is available. You have %{current}. Update now?"
466 de: "Rusty Teams %{version} ist verfügbar. Installiert ist %{current}. Jetzt aktualisieren?"
467 update_now:
468 en: Update
469 de: Aktualisieren
470 update_downloading:
471 en: "Downloading %{version}... %{percent}%"
472 de: "%{version} wird heruntergeladen... %{percent} %"
473 hide:
474 en: Hide
475 de: Ausblenden
476 update_ready_title:
477 en: Update ready
478 de: Update bereit
479 update_ready_body:
480 en: "%{version} is downloaded. Restart Rusty Teams to finish the update."
481 de: "%{version} ist heruntergeladen. Starte Rusty Teams neu, um das Update abzuschließen."
482 later:
483 en: Later
484 de: Später
485 restart_now:
486 en: Restart now
487 de: Jetzt neu starten
488 up_to_date:
489 en: Rusty Teams is up to date
490 de: Rusty Teams ist aktuell
491 update_failed:
492 en: "Update check failed: %{detail}"
493 de: "Update-Prüfung fehlgeschlagen: %{detail}"
391calls:
494calls:
392 notice:
495 notice:
393 not_connected:
496 not_connected:
crates/app-base/src/appearance.rs +30 −2
@@ -12,16 +12,29 @@ pub const ZOOM_STEPS: [f32; 14] = [
12 12 ];
13 13 pub const DEFAULT_ZOOM: f32 = 1.;
14 14 const RUSTY_TEAMS_ICON_PNG: &[u8] = include_bytes!("../../app/assets/icon/teams-fast-256.png");
15 // Linux builds leave the Microsoft logo out; the app downloads it from Microsoft
16 // on first start (see `linux_desktop`).
17 #[cfg(not(target_os = "linux"))]
15 18 const MICROSOFT_TEAMS_ICON_PNG: &[u8] =
16 19 include_bytes!("../../app/assets/icon/microsoft-teams-256.png");
17 20
18 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
19 22 pub enum AppIcon {
20 #[default]
21 23 RustyTeams,
22 24 MicrosoftTeams,
23 25 }
24 26
27 impl Default for AppIcon {
28 /// On Linux the downloaded Teams icon is the default once it is there.
29 fn default() -> Self {
30 #[cfg(target_os = "linux")]
31 if crate::linux_desktop::teams_icon().is_some() {
32 return AppIcon::MicrosoftTeams;
33 }
34 AppIcon::RustyTeams
35 }
36 }
37
25 38 impl AppIcon {
26 39 pub const ALL: [AppIcon; 2] = [AppIcon::RustyTeams, AppIcon::MicrosoftTeams];
27 40
@@ -46,7 +59,12 @@ impl AppIcon {
46 59 pub fn png(self) -> &'static [u8] {
47 60 match self {
48 61 AppIcon::RustyTeams => RUSTY_TEAMS_ICON_PNG,
62 #[cfg(not(target_os = "linux"))]
49 63 AppIcon::MicrosoftTeams => MICROSOFT_TEAMS_ICON_PNG,
64 #[cfg(target_os = "linux")]
65 AppIcon::MicrosoftTeams => {
66 crate::linux_desktop::teams_icon().unwrap_or(RUSTY_TEAMS_ICON_PNG)
67 }
50 68 }
51 69 }
52 70 }
@@ -190,6 +208,16 @@ pub fn load(store: &Store) -> AppearanceSettings {
190 208 .unwrap_or_default()
191 209 }
192 210
211 /// Whether an icon was ever saved, by the user or by an earlier default.
212 pub fn icon_saved(store: &Store) -> bool {
213 store.meta(META_KEY).ok().flatten().is_some_and(|text| {
214 text.lines().any(|line| {
215 line.split_once('=')
216 .is_some_and(|(key, _)| key == APP_ICON_KEY)
217 })
218 })
219 }
220
193 221 pub fn save(store: &Store, settings: &AppearanceSettings) {
194 222 let _ = store.set_meta(META_KEY, &serialize(settings));
195 223 }
@@ -12,16 +12,29 @@ pub const ZOOM_STEPS: [f32; 14] = [
12];
12];
13pub const DEFAULT_ZOOM: f32 = 1.;
13pub const DEFAULT_ZOOM: f32 = 1.;
14const RUSTY_TEAMS_ICON_PNG: &[u8] = include_bytes!("../../app/assets/icon/teams-fast-256.png");
14const RUSTY_TEAMS_ICON_PNG: &[u8] = include_bytes!("../../app/assets/icon/teams-fast-256.png");
15// Linux builds leave the Microsoft logo out; the app downloads it from Microsoft
16// on first start (see `linux_desktop`).
17#[cfg(not(target_os = "linux"))]
15const MICROSOFT_TEAMS_ICON_PNG: &[u8] =
18const MICROSOFT_TEAMS_ICON_PNG: &[u8] =
16 include_bytes!("../../app/assets/icon/microsoft-teams-256.png");
19 include_bytes!("../../app/assets/icon/microsoft-teams-256.png");
17
20
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum AppIcon {
22pub enum AppIcon {
20 #[default]
21 RustyTeams,
23 RustyTeams,
22 MicrosoftTeams,
24 MicrosoftTeams,
23}
25}
24
26
27impl Default for AppIcon {
28 /// On Linux the downloaded Teams icon is the default once it is there.
29 fn default() -> Self {
30 #[cfg(target_os = "linux")]
31 if crate::linux_desktop::teams_icon().is_some() {
32 return AppIcon::MicrosoftTeams;
33 }
34 AppIcon::RustyTeams
35 }
36}
37
25impl AppIcon {
38impl AppIcon {
26 pub const ALL: [AppIcon; 2] = [AppIcon::RustyTeams, AppIcon::MicrosoftTeams];
39 pub const ALL: [AppIcon; 2] = [AppIcon::RustyTeams, AppIcon::MicrosoftTeams];
27
40
@@ -46,7 +59,12 @@ impl AppIcon {
46 pub fn png(self) -> &'static [u8] {
59 pub fn png(self) -> &'static [u8] {
47 match self {
60 match self {
48 AppIcon::RustyTeams => RUSTY_TEAMS_ICON_PNG,
61 AppIcon::RustyTeams => RUSTY_TEAMS_ICON_PNG,
62 #[cfg(not(target_os = "linux"))]
49 AppIcon::MicrosoftTeams => MICROSOFT_TEAMS_ICON_PNG,
63 AppIcon::MicrosoftTeams => MICROSOFT_TEAMS_ICON_PNG,
64 #[cfg(target_os = "linux")]
65 AppIcon::MicrosoftTeams => {
66 crate::linux_desktop::teams_icon().unwrap_or(RUSTY_TEAMS_ICON_PNG)
67 }
50 }
68 }
51 }
69 }
52}
70}
@@ -190,6 +208,16 @@ pub fn load(store: &Store) -> AppearanceSettings {
190 .unwrap_or_default()
208 .unwrap_or_default()
191}
209}
192
210
211/// Whether an icon was ever saved, by the user or by an earlier default.
212pub fn icon_saved(store: &Store) -> bool {
213 store.meta(META_KEY).ok().flatten().is_some_and(|text| {
214 text.lines().any(|line| {
215 line.split_once('=')
216 .is_some_and(|(key, _)| key == APP_ICON_KEY)
217 })
218 })
219}
220
193pub fn save(store: &Store, settings: &AppearanceSettings) {
221pub fn save(store: &Store, settings: &AppearanceSettings) {
194 let _ = store.set_meta(META_KEY, &serialize(settings));
222 let _ = store.set_meta(META_KEY, &serialize(settings));
195}
223}
crates/app-base/src/lib.rs +2 −0
@@ -23,6 +23,8 @@ pub mod image_clipboard;
23 23 pub mod image_view_math;
24 24 pub mod inline_image;
25 25 #[cfg(target_os = "linux")]
26 pub mod linux_desktop;
27 #[cfg(target_os = "linux")]
26 28 pub mod linux_fonts;
27 29 pub mod native_dumps;
28 30 pub mod notify;
@@ -23,6 +23,8 @@ pub mod image_clipboard;
23pub mod image_view_math;
23pub mod image_view_math;
24pub mod inline_image;
24pub mod inline_image;
25#[cfg(target_os = "linux")]
25#[cfg(target_os = "linux")]
26pub mod linux_desktop;
27#[cfg(target_os = "linux")]
26pub mod linux_fonts;
28pub mod linux_fonts;
27pub mod native_dumps;
29pub mod native_dumps;
28pub mod notify;
30pub mod notify;
crates/app-base/src/linux_desktop.rs added +485 −0
@@ -0,0 +1,485 @@
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
5 use std::fs;
6 use std::io;
7 use std::path::{Path, PathBuf};
8 use std::sync::RwLock;
9
10 use futures_util::AsyncReadExt as _;
11 use gpui_kit::{App, Task};
12
13 /// Matches the window's app id, so KDE pairs the window with the entry.
14 pub const DESKTOP_ID: &str = "rusty-teams";
15 /// Name the `.desktop` entry, the tray and `hicolor` use for the icon.
16 pub const ICON_NAME: &str = "rusty-teams";
17 pub const BINARY_FILE_NAME: &str = "teams";
18 /// Same icon the Teams web page shows in its tab.
19 pub 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.
21 pub const TEAMS_PAGE_URL: &str = "https://teams.cloud.microsoft/";
22 pub const ICON_SIZES: [u32; 5] = [256, 128, 64, 48, 32];
23 const INSTALL_FOLDER: &str = "teams";
24 const DONT_ASK_META_KEY: &str = "linux.install.dont_ask";
25 const 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.
29 pub 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)]
38 pub struct Layout {
39 data_dir: PathBuf,
40 }
41
42 impl 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
86 pub 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
94 pub fn should_offer_install(executable: &Path, layout: &Layout, dont_ask: bool) -> bool {
95 !dont_ask && !is_installed(executable, layout)
96 }
97
98 pub fn dont_ask_again(store: &store::Store) -> bool {
99 store.meta(DONT_ASK_META_KEY).ok().flatten().as_deref() == Some("1")
100 }
101
102 pub 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.
107 pub 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.
113 pub 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.
134 pub 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.
151 fn 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.
161 fn 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
169 fn 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.
177 fn 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
189 pub 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
209 pub 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.
216 pub 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`.
240 pub 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
259 pub 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.
264 pub 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.
276 pub 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
313 static TEAMS_ICON: RwLock<Option<&'static [u8]>> = RwLock::new(None);
314
315 /// The downloaded Teams icon as PNG, once it is on disk.
316 pub fn teams_icon() -> Option<&'static [u8]> {
317 *TEAMS_ICON
318 .read()
319 .unwrap_or_else(|poisoned| poisoned.into_inner())
320 }
321
322 pub 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.
334 pub 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)]
341 mod 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 }
@@ -0,0 +1,485 @@
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}
crates/app-base/src/notify/platform/linux_tray.rs +1 −3
@@ -9,9 +9,7 @@ use ksni::menu::{CheckmarkItem, StandardItem};
9 9 use ksni::{Category, Icon, MenuItem, ToolTip};
10 10
11 11 use super::TrayCommand;
12
13 /// The window and desktop entry id (`rusty-teams.desktop`).
14 const DESKTOP_ID: &str = "rusty-teams";
12 use crate::linux_desktop::DESKTOP_ID;
15 13
16 14 const TRAY_ICON_SIZES: [u32; 3] = [22, 32, 64];
17 15 const DOT_COLOR: [u8; 4] = [0xef, 0x44, 0x44, 0xff];
@@ -9,9 +9,7 @@ use ksni::menu::{CheckmarkItem, StandardItem};
9use ksni::{Category, Icon, MenuItem, ToolTip};
9use ksni::{Category, Icon, MenuItem, ToolTip};
10
10
11use super::TrayCommand;
11use super::TrayCommand;
12
12use crate::linux_desktop::DESKTOP_ID;
13/// The window and desktop entry id (`rusty-teams.desktop`).
14const DESKTOP_ID: &str = "rusty-teams";
15
13
16const TRAY_ICON_SIZES: [u32; 3] = [22, 32, 64];
14const TRAY_ICON_SIZES: [u32; 3] = [22, 32, 64];
17const DOT_COLOR: [u8; 4] = [0xef, 0x44, 0x44, 0xff];
15const DOT_COLOR: [u8; 4] = [0xef, 0x44, 0x44, 0xff];
crates/app-base/src/release_feed.rs +165 −45
@@ -1,7 +1,8 @@
1 #![cfg_attr(not(windows), allow(dead_code))]
1 #![cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))]
2 2
3 3 use std::cmp::Ordering;
4 4 use std::fs;
5 use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
5 6 use std::time::Duration;
6 7
7 8 use futures_util::AsyncReadExt as _;
@@ -15,8 +16,17 @@ pub const FIRST_CHECK_DELAY: Duration = Duration::from_secs(60);
15 16 pub const CHECK_INTERVAL: Duration = Duration::from_secs(6 * 60 * 60);
16 17 const RELEASES_URL: &str =
17 18 "https://api.github.com/repos/danieldaeschle/rusty-teams/releases?per_page=10";
18 const WINDOWS_ASSET_SUFFIX: &str = "-windows-amd64.exe";
19 /// The release asset this platform installs, and the magic bytes it must start with.
20 #[cfg(not(target_os = "linux"))]
21 const ASSET_SUFFIX: &str = "-windows-amd64.exe";
22 #[cfg(not(target_os = "linux"))]
23 const EXECUTABLE_MAGIC: &[u8] = b"MZ";
24 #[cfg(target_os = "linux")]
25 const ASSET_SUFFIX: &str = "-linux-amd64";
26 #[cfg(target_os = "linux")]
27 const EXECUTABLE_MAGIC: &[u8] = b"\x7fELF";
19 28 const PARTIAL_SUFFIX: &str = ".partial";
29 const DOWNLOAD_CHUNK: usize = 64 * 1024;
20 30 const SHA256_PREFIX: &str = "sha256:";
21 31
22 32 #[derive(Debug, Clone, Deserialize)]
@@ -30,7 +40,7 @@ pub struct Release {
30 40 pub assets: Vec<ReleaseAsset>,
31 41 }
32 42
33 #[derive(Debug, Clone, Deserialize)]
43 #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
34 44 pub struct ReleaseAsset {
35 45 pub name: String,
36 46 pub browser_download_url: String,
@@ -95,6 +105,14 @@ impl PartialOrd for ReleaseVersion {
95 105 }
96 106 }
97 107
108 /// Whether release `tag` is newer than `running_tag`.
109 pub fn is_newer(tag: &str, running_tag: &str) -> bool {
110 matches!(
111 (parse_version(tag), parse_version(running_tag)),
112 (Some(tag), Some(running)) if tag > running
113 )
114 }
115
98 116 /// Pre-releases are offered only to a build that runs a pre-release itself.
99 117 pub fn newest_update<'a>(
100 118 running_tag: &str,
@@ -110,7 +128,7 @@ pub fn newest_update<'a>(
110 128 let asset = release
111 129 .assets
112 130 .iter()
113 .find(|asset| asset.name.ends_with(WINDOWS_ASSET_SUFFIX))?;
131 .find(|asset| asset.name.ends_with(ASSET_SUFFIX))?;
114 132 Some((version, release, asset))
115 133 })
116 134 .max_by(|left, right| left.0.cmp(&right.0))
@@ -121,8 +139,8 @@ pub fn verify_download(asset: &ReleaseAsset, bytes: &[u8]) -> Result<(), String>
121 139 if bytes.len() as u64 != asset.size {
122 140 return Err(format!("size {} instead of {}", bytes.len(), asset.size));
123 141 }
124 if !bytes.starts_with(b"MZ") {
125 return Err("not a Windows executable".to_owned());
142 if !bytes.starts_with(EXECUTABLE_MAGIC) {
143 return Err("not an executable for this platform".to_owned());
126 144 }
127 145 let Some(expected) = asset
128 146 .digest
@@ -141,6 +159,12 @@ pub fn verify_download(asset: &ReleaseAsset, bytes: &[u8]) -> Result<(), String>
141 159 Ok(())
142 160 }
143 161
162 fn partial_path(path: &std::path::Path) -> std::path::PathBuf {
163 let mut name = path.file_name().unwrap_or_default().to_owned();
164 name.push(PARTIAL_SUFFIX);
165 path.with_file_name(name)
166 }
167
144 168 fn already_staged(paths: &UpdatePaths, tag: &str) -> bool {
145 169 paths.update_exe.exists()
146 170 && fs::read_to_string(&paths.version_file).is_ok_and(|staged| staged.trim() == tag)
@@ -153,53 +177,115 @@ fn stage(paths: &UpdatePaths, tag: &str, bytes: &[u8]) -> Result<(), String> {
153 177 .ok_or_else(|| "no update directory".to_owned())?;
154 178 fs::create_dir_all(directory).map_err(|error| error.to_string())?;
155 179 let _ = fs::remove_file(&paths.version_file);
156 let partial = paths
157 .update_exe
158 .with_extension(format!("exe{PARTIAL_SUFFIX}"));
180 let partial = partial_path(&paths.update_exe);
159 181 fs::write(&partial, bytes).map_err(|error| error.to_string())?;
182 #[cfg(unix)]
183 {
184 use std::os::unix::fs::PermissionsExt as _;
185 fs::set_permissions(&partial, fs::Permissions::from_mode(0o755))
186 .map_err(|error| error.to_string())?;
187 }
160 188 fs::rename(&partial, &paths.update_exe).map_err(|error| error.to_string())?;
161 189 fs::write(&paths.version_file, tag).map_err(|error| error.to_string())
162 190 }
163 191
192 /// A newer release this platform can install.
193 #[derive(Debug, Clone, PartialEq, Eq)]
194 pub struct AvailableUpdate {
195 pub tag: String,
196 pub asset: ReleaseAsset,
197 }
198
199 type HttpClient = std::sync::Arc<dyn gpui_kit::http_client::HttpClient>;
200
201 /// GETs `url`. `progress` counts the body bytes as they arrive.
202 async fn get(
203 client: &HttpClient,
204 url: &str,
205 progress: Option<&AtomicU64>,
206 ) -> Result<Vec<u8>, String> {
207 let mut response = client
208 .get(url, ().into(), true)
209 .await
210 .map_err(|error| error.to_string())?;
211 if !response.status().is_success() {
212 return Err(format!("status {}", response.status()));
213 }
214 let mut body = Vec::new();
215 let mut chunk = vec![0; DOWNLOAD_CHUNK];
216 loop {
217 let read = response
218 .body_mut()
219 .read(&mut chunk)
220 .await
221 .map_err(|error| error.to_string())?;
222 if read == 0 {
223 return Ok(body);
224 }
225 body.extend_from_slice(&chunk[..read]);
226 if let Some(progress) = progress {
227 progress.store(body.len() as u64, AtomicOrdering::Relaxed);
228 }
229 }
230 }
231
232 /// Looks for a release newer than `running_tag`, without downloading it.
233 pub fn find_update(
234 running_tag: &'static str,
235 cx: &App,
236 ) -> Task<Result<Option<AvailableUpdate>, String>> {
237 let client = cx.http_client();
238 cx.background_executor().spawn(async move {
239 let releases: Vec<Release> =
240 serde_json::from_slice(&get(&client, RELEASES_URL, None).await?)
241 .map_err(|error| error.to_string())?;
242 Ok(
243 newest_update(running_tag, &releases).map(|(release, asset)| AvailableUpdate {
244 tag: release.tag_name.clone(),
245 asset: asset.clone(),
246 }),
247 )
248 })
249 }
250
251 /// Downloads and verifies `update` into the update folder, counting bytes in `progress`.
252 pub fn download_update(
253 update: AvailableUpdate,
254 paths: UpdatePaths,
255 progress: std::sync::Arc<AtomicU64>,
256 cx: &App,
257 ) -> Task<Result<(), String>> {
258 let client = cx.http_client();
259 cx.background_executor().spawn(async move {
260 if already_staged(&paths, &update.tag) {
261 progress.store(update.asset.size, AtomicOrdering::Relaxed);
262 return Ok(());
263 }
264 let bytes = get(&client, &update.asset.browser_download_url, Some(&progress)).await?;
265 verify_download(&update.asset, &bytes)?;
266 stage(&paths, &update.tag, &bytes)
267 })
268 }
269
164 270 /// Downloads a newer GitHub release into the update folder; the regular update poll installs it.
165 271 pub fn fetch_update(
166 272 running_tag: &'static str,
167 273 paths: UpdatePaths,
168 274 cx: &App,
169 275 ) -> Task<Result<Option<String>, String>> {
276 let find = find_update(running_tag, cx);
170 277 let client = cx.http_client();
171 278 cx.background_executor().spawn(async move {
172 let get = |url: String| {
173 let client = client.clone();
174 async move {
175 let mut response = client
176 .get(&url, ().into(), true)
177 .await
178 .map_err(|error| error.to_string())?;
179 let mut body = Vec::new();
180 response
181 .body_mut()
182 .read_to_end(&mut body)
183 .await
184 .map_err(|error| error.to_string())?;
185 if !response.status().is_success() {
186 return Err(format!("status {}", response.status()));
187 }
188 Ok::<_, String>(body)
189 }
190 };
191 let releases: Vec<Release> = serde_json::from_slice(&get(RELEASES_URL.to_owned()).await?)
192 .map_err(|error| error.to_string())?;
193 let Some((release, asset)) = newest_update(running_tag, &releases) else {
279 let Some(update) = find.await? else {
194 280 return Ok(None);
195 281 };
196 if already_staged(&paths, &release.tag_name) {
282 if already_staged(&paths, &update.tag) {
197 283 return Ok(None);
198 284 }
199 let bytes = get(asset.browser_download_url.clone()).await?;
200 verify_download(asset, &bytes)?;
201 stage(&paths, &release.tag_name, &bytes)?;
202 Ok(Some(release.tag_name.clone()))
285 let bytes = get(&client, &update.asset.browser_download_url, None).await?;
286 verify_download(&update.asset, &bytes)?;
287 stage(&paths, &update.tag, &bytes)?;
288 Ok(Some(update.tag))
203 289 })
204 290 }
205 291
@@ -215,9 +301,9 @@ mod tests {
215 301 draft: false,
216 302 prerelease,
217 303 assets: vec![ReleaseAsset {
218 name: format!("rusty-teams-{tag}{WINDOWS_ASSET_SUFFIX}"),
304 name: format!("rusty-teams-{tag}{ASSET_SUFFIX}"),
219 305 browser_download_url: format!("https://example.test/{tag}.exe"),
220 size: 2,
306 size: EXECUTABLE_MAGIC.len() as u64,
221 307 digest: None,
222 308 }],
223 309 }
@@ -243,7 +329,7 @@ mod tests {
243 329 ];
244 330 let (found, asset) = newest_update("v0.1.0", &releases).unwrap();
245 331 assert_eq!(found.tag_name, "v0.2.0");
246 assert!(asset.name.ends_with(WINDOWS_ASSET_SUFFIX));
332 assert!(asset.name.ends_with(ASSET_SUFFIX));
247 333 assert!(newest_update("v0.2.0", &releases).is_none());
248 334 let (found, _) = newest_update("v0.2.0-rc.1", &releases).unwrap();
249 335 assert_eq!(found.tag_name, "v0.3.0-rc.1");
@@ -259,7 +345,7 @@ mod tests {
259 345
260 346 #[test]
261 347 fn a_download_must_match_size_header_and_digest() {
262 let bytes = b"MZ";
348 let bytes = EXECUTABLE_MAGIC;
263 349 let digest: String = Sha256::digest(bytes)
264 350 .iter()
265 351 .map(|byte| format!("{byte:02x}"))
@@ -269,18 +355,52 @@ mod tests {
269 355 asset.digest = Some(format!("{SHA256_PREFIX}{digest}"));
270 356 assert!(verify_download(&asset, bytes).is_ok());
271 357 assert!(verify_download(&asset, b"XY").is_err());
272 assert!(verify_download(&asset, b"MZ!").is_err());
358 assert!(verify_download(&asset, &[EXECUTABLE_MAGIC, b"!"].concat()).is_err());
359 }
360
361 #[test]
362 fn newer_compares_release_versions() {
363 assert!(is_newer("v0.5.0", "v0.4.0"));
364 assert!(is_newer("v0.5.0", "v0.5.0-rc.1"));
365 assert!(!is_newer("v0.4.0", "v0.4.0"));
366 assert!(!is_newer("v0.3.9", "v0.4.0"));
367 assert!(!is_newer("garbage", "v0.4.0"));
368 }
369
370 #[cfg(target_os = "linux")]
371 #[test]
372 fn linux_takes_the_plain_binary_not_the_tarball() {
373 let mut release = release("v0.5.0", false);
374 let binary = release.assets.remove(0);
375 let tarball = ReleaseAsset {
376 name: "rusty-teams-v0.5.0-linux-amd64.tar.gz".to_owned(),
377 ..binary.clone()
378 };
379 release.assets = vec![tarball.clone()];
380 assert!(newest_update("v0.4.0", std::slice::from_ref(&release)).is_none());
381 release.assets = vec![tarball, binary];
382 let (_, asset) = newest_update("v0.4.0", std::slice::from_ref(&release)).unwrap();
383 assert_eq!(asset.name, "rusty-teams-v0.5.0-linux-amd64");
273 384 }
274 385
275 386 #[test]
276 387 fn staging_writes_the_exe_before_the_version() {
277 388 let directory = tempfile::tempdir().unwrap();
278 let paths = UpdatePaths::beside(&directory.path().join("teams.exe"));
389 let paths = UpdatePaths::beside(&directory.path().join("teams"));
279 390 assert!(!already_staged(&paths, "v0.2.0"));
280 stage(&paths, "v0.2.0", b"MZ").unwrap();
281 assert_eq!(fs::read(&paths.update_exe).unwrap(), b"MZ");
391 stage(&paths, "v0.2.0", EXECUTABLE_MAGIC).unwrap();
392 assert_eq!(fs::read(&paths.update_exe).unwrap(), EXECUTABLE_MAGIC);
393 #[cfg(unix)]
394 {
395 use std::os::unix::fs::PermissionsExt as _;
396 let mode = fs::metadata(&paths.update_exe)
397 .unwrap()
398 .permissions()
399 .mode();
400 assert_eq!(mode & 0o111, 0o111);
401 }
282 402 assert!(already_staged(&paths, "v0.2.0"));
283 403 assert!(!already_staged(&paths, "v0.3.0"));
284 assert!(!Path::new(&paths.update_exe.with_extension("exe.partial")).exists());
404 assert!(!partial_path(&paths.update_exe).exists());
285 405 }
286 406 }
@@ -1,7 +1,8 @@
1#![cfg_attr(not(windows), allow(dead_code))]
1#![cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))]
2
2
3use std::cmp::Ordering;
3use std::cmp::Ordering;
4use std::fs;
4use std::fs;
5use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
5use std::time::Duration;
6use std::time::Duration;
6
7
7use futures_util::AsyncReadExt as _;
8use futures_util::AsyncReadExt as _;
@@ -15,8 +16,17 @@ pub const FIRST_CHECK_DELAY: Duration = Duration::from_secs(60);
15pub const CHECK_INTERVAL: Duration = Duration::from_secs(6 * 60 * 60);
16pub const CHECK_INTERVAL: Duration = Duration::from_secs(6 * 60 * 60);
16const RELEASES_URL: &str =
17const RELEASES_URL: &str =
17 "https://api.github.com/repos/danieldaeschle/rusty-teams/releases?per_page=10";
18 "https://api.github.com/repos/danieldaeschle/rusty-teams/releases?per_page=10";
18const WINDOWS_ASSET_SUFFIX: &str = "-windows-amd64.exe";
19/// The release asset this platform installs, and the magic bytes it must start with.
20#[cfg(not(target_os = "linux"))]
21const ASSET_SUFFIX: &str = "-windows-amd64.exe";
22#[cfg(not(target_os = "linux"))]
23const EXECUTABLE_MAGIC: &[u8] = b"MZ";
24#[cfg(target_os = "linux")]
25const ASSET_SUFFIX: &str = "-linux-amd64";
26#[cfg(target_os = "linux")]
27const EXECUTABLE_MAGIC: &[u8] = b"\x7fELF";
19const PARTIAL_SUFFIX: &str = ".partial";
28const PARTIAL_SUFFIX: &str = ".partial";
29const DOWNLOAD_CHUNK: usize = 64 * 1024;
20const SHA256_PREFIX: &str = "sha256:";
30const SHA256_PREFIX: &str = "sha256:";
21
31
22#[derive(Debug, Clone, Deserialize)]
32#[derive(Debug, Clone, Deserialize)]
@@ -30,7 +40,7 @@ pub struct Release {
30 pub assets: Vec<ReleaseAsset>,
40 pub assets: Vec<ReleaseAsset>,
31}
41}
32
42
33#[derive(Debug, Clone, Deserialize)]
43#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
34pub struct ReleaseAsset {
44pub struct ReleaseAsset {
35 pub name: String,
45 pub name: String,
36 pub browser_download_url: String,
46 pub browser_download_url: String,
@@ -95,6 +105,14 @@ impl PartialOrd for ReleaseVersion {
95 }
105 }
96}
106}
97
107
108/// Whether release `tag` is newer than `running_tag`.
109pub fn is_newer(tag: &str, running_tag: &str) -> bool {
110 matches!(
111 (parse_version(tag), parse_version(running_tag)),
112 (Some(tag), Some(running)) if tag > running
113 )
114}
115
98/// Pre-releases are offered only to a build that runs a pre-release itself.
116/// Pre-releases are offered only to a build that runs a pre-release itself.
99pub fn newest_update<'a>(
117pub fn newest_update<'a>(
100 running_tag: &str,
118 running_tag: &str,
@@ -110,7 +128,7 @@ pub fn newest_update<'a>(
110 let asset = release
128 let asset = release
111 .assets
129 .assets
112 .iter()
130 .iter()
113 .find(|asset| asset.name.ends_with(WINDOWS_ASSET_SUFFIX))?;
131 .find(|asset| asset.name.ends_with(ASSET_SUFFIX))?;
114 Some((version, release, asset))
132 Some((version, release, asset))
115 })
133 })
116 .max_by(|left, right| left.0.cmp(&right.0))
134 .max_by(|left, right| left.0.cmp(&right.0))
@@ -121,8 +139,8 @@ pub fn verify_download(asset: &ReleaseAsset, bytes: &[u8]) -> Result<(), String>
121 if bytes.len() as u64 != asset.size {
139 if bytes.len() as u64 != asset.size {
122 return Err(format!("size {} instead of {}", bytes.len(), asset.size));
140 return Err(format!("size {} instead of {}", bytes.len(), asset.size));
123 }
141 }
124 if !bytes.starts_with(b"MZ") {
142 if !bytes.starts_with(EXECUTABLE_MAGIC) {
125 return Err("not a Windows executable".to_owned());
143 return Err("not an executable for this platform".to_owned());
126 }
144 }
127 let Some(expected) = asset
145 let Some(expected) = asset
128 .digest
146 .digest
@@ -141,6 +159,12 @@ pub fn verify_download(asset: &ReleaseAsset, bytes: &[u8]) -> Result<(), String>
141 Ok(())
159 Ok(())
142}
160}
143
161
162fn partial_path(path: &std::path::Path) -> std::path::PathBuf {
163 let mut name = path.file_name().unwrap_or_default().to_owned();
164 name.push(PARTIAL_SUFFIX);
165 path.with_file_name(name)
166}
167
144fn already_staged(paths: &UpdatePaths, tag: &str) -> bool {
168fn already_staged(paths: &UpdatePaths, tag: &str) -> bool {
145 paths.update_exe.exists()
169 paths.update_exe.exists()
146 && fs::read_to_string(&paths.version_file).is_ok_and(|staged| staged.trim() == tag)
170 && fs::read_to_string(&paths.version_file).is_ok_and(|staged| staged.trim() == tag)
@@ -153,53 +177,115 @@ fn stage(paths: &UpdatePaths, tag: &str, bytes: &[u8]) -> Result<(), String> {
153 .ok_or_else(|| "no update directory".to_owned())?;
177 .ok_or_else(|| "no update directory".to_owned())?;
154 fs::create_dir_all(directory).map_err(|error| error.to_string())?;
178 fs::create_dir_all(directory).map_err(|error| error.to_string())?;
155 let _ = fs::remove_file(&paths.version_file);
179 let _ = fs::remove_file(&paths.version_file);
156 let partial = paths
180 let partial = partial_path(&paths.update_exe);
157 .update_exe
158 .with_extension(format!("exe{PARTIAL_SUFFIX}"));
159 fs::write(&partial, bytes).map_err(|error| error.to_string())?;
181 fs::write(&partial, bytes).map_err(|error| error.to_string())?;
182 #[cfg(unix)]
183 {
184 use std::os::unix::fs::PermissionsExt as _;
185 fs::set_permissions(&partial, fs::Permissions::from_mode(0o755))
186 .map_err(|error| error.to_string())?;
187 }
160 fs::rename(&partial, &paths.update_exe).map_err(|error| error.to_string())?;
188 fs::rename(&partial, &paths.update_exe).map_err(|error| error.to_string())?;
161 fs::write(&paths.version_file, tag).map_err(|error| error.to_string())
189 fs::write(&paths.version_file, tag).map_err(|error| error.to_string())
162}
190}
163
191
192/// A newer release this platform can install.
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct AvailableUpdate {
195 pub tag: String,
196 pub asset: ReleaseAsset,
197}
198
199type HttpClient = std::sync::Arc<dyn gpui_kit::http_client::HttpClient>;
200
201/// GETs `url`. `progress` counts the body bytes as they arrive.
202async fn get(
203 client: &HttpClient,
204 url: &str,
205 progress: Option<&AtomicU64>,
206) -> Result<Vec<u8>, String> {
207 let mut response = client
208 .get(url, ().into(), true)
209 .await
210 .map_err(|error| error.to_string())?;
211 if !response.status().is_success() {
212 return Err(format!("status {}", response.status()));
213 }
214 let mut body = Vec::new();
215 let mut chunk = vec![0; DOWNLOAD_CHUNK];
216 loop {
217 let read = response
218 .body_mut()
219 .read(&mut chunk)
220 .await
221 .map_err(|error| error.to_string())?;
222 if read == 0 {
223 return Ok(body);
224 }
225 body.extend_from_slice(&chunk[..read]);
226 if let Some(progress) = progress {
227 progress.store(body.len() as u64, AtomicOrdering::Relaxed);
228 }
229 }
230}
231
232/// Looks for a release newer than `running_tag`, without downloading it.
233pub fn find_update(
234 running_tag: &'static str,
235 cx: &App,
236) -> Task<Result<Option<AvailableUpdate>, String>> {
237 let client = cx.http_client();
238 cx.background_executor().spawn(async move {
239 let releases: Vec<Release> =
240 serde_json::from_slice(&get(&client, RELEASES_URL, None).await?)
241 .map_err(|error| error.to_string())?;
242 Ok(
243 newest_update(running_tag, &releases).map(|(release, asset)| AvailableUpdate {
244 tag: release.tag_name.clone(),
245 asset: asset.clone(),
246 }),
247 )
248 })
249}
250
251/// Downloads and verifies `update` into the update folder, counting bytes in `progress`.
252pub fn download_update(
253 update: AvailableUpdate,
254 paths: UpdatePaths,
255 progress: std::sync::Arc<AtomicU64>,
256 cx: &App,
257) -> Task<Result<(), String>> {
258 let client = cx.http_client();
259 cx.background_executor().spawn(async move {
260 if already_staged(&paths, &update.tag) {
261 progress.store(update.asset.size, AtomicOrdering::Relaxed);
262 return Ok(());
263 }
264 let bytes = get(&client, &update.asset.browser_download_url, Some(&progress)).await?;
265 verify_download(&update.asset, &bytes)?;
266 stage(&paths, &update.tag, &bytes)
267 })
268}
269
164/// Downloads a newer GitHub release into the update folder; the regular update poll installs it.
270/// Downloads a newer GitHub release into the update folder; the regular update poll installs it.
165pub fn fetch_update(
271pub fn fetch_update(
166 running_tag: &'static str,
272 running_tag: &'static str,
167 paths: UpdatePaths,
273 paths: UpdatePaths,
168 cx: &App,
274 cx: &App,
169) -> Task<Result<Option<String>, String>> {
275) -> Task<Result<Option<String>, String>> {
276 let find = find_update(running_tag, cx);
170 let client = cx.http_client();
277 let client = cx.http_client();
171 cx.background_executor().spawn(async move {
278 cx.background_executor().spawn(async move {
172 let get = |url: String| {
279 let Some(update) = find.await? else {
173 let client = client.clone();
174 async move {
175 let mut response = client
176 .get(&url, ().into(), true)
177 .await
178 .map_err(|error| error.to_string())?;
179 let mut body = Vec::new();
180 response
181 .body_mut()
182 .read_to_end(&mut body)
183 .await
184 .map_err(|error| error.to_string())?;
185 if !response.status().is_success() {
186 return Err(format!("status {}", response.status()));
187 }
188 Ok::<_, String>(body)
189 }
190 };
191 let releases: Vec<Release> = serde_json::from_slice(&get(RELEASES_URL.to_owned()).await?)
192 .map_err(|error| error.to_string())?;
193 let Some((release, asset)) = newest_update(running_tag, &releases) else {
194 return Ok(None);
280 return Ok(None);
195 };
281 };
196 if already_staged(&paths, &release.tag_name) {
282 if already_staged(&paths, &update.tag) {
197 return Ok(None);
283 return Ok(None);
198 }
284 }
199 let bytes = get(asset.browser_download_url.clone()).await?;
285 let bytes = get(&client, &update.asset.browser_download_url, None).await?;
200 verify_download(asset, &bytes)?;
286 verify_download(&update.asset, &bytes)?;
201 stage(&paths, &release.tag_name, &bytes)?;
287 stage(&paths, &update.tag, &bytes)?;
202 Ok(Some(release.tag_name.clone()))
288 Ok(Some(update.tag))
203 })
289 })
204}
290}
205
291
@@ -215,9 +301,9 @@ mod tests {
215 draft: false,
301 draft: false,
216 prerelease,
302 prerelease,
217 assets: vec![ReleaseAsset {
303 assets: vec![ReleaseAsset {
218 name: format!("rusty-teams-{tag}{WINDOWS_ASSET_SUFFIX}"),
304 name: format!("rusty-teams-{tag}{ASSET_SUFFIX}"),
219 browser_download_url: format!("https://example.test/{tag}.exe"),
305 browser_download_url: format!("https://example.test/{tag}.exe"),
220 size: 2,
306 size: EXECUTABLE_MAGIC.len() as u64,
221 digest: None,
307 digest: None,
222 }],
308 }],
223 }
309 }
@@ -243,7 +329,7 @@ mod tests {
243 ];
329 ];
244 let (found, asset) = newest_update("v0.1.0", &releases).unwrap();
330 let (found, asset) = newest_update("v0.1.0", &releases).unwrap();
245 assert_eq!(found.tag_name, "v0.2.0");
331 assert_eq!(found.tag_name, "v0.2.0");
246 assert!(asset.name.ends_with(WINDOWS_ASSET_SUFFIX));
332 assert!(asset.name.ends_with(ASSET_SUFFIX));
247 assert!(newest_update("v0.2.0", &releases).is_none());
333 assert!(newest_update("v0.2.0", &releases).is_none());
248 let (found, _) = newest_update("v0.2.0-rc.1", &releases).unwrap();
334 let (found, _) = newest_update("v0.2.0-rc.1", &releases).unwrap();
249 assert_eq!(found.tag_name, "v0.3.0-rc.1");
335 assert_eq!(found.tag_name, "v0.3.0-rc.1");
@@ -259,7 +345,7 @@ mod tests {
259
345
260 #[test]
346 #[test]
261 fn a_download_must_match_size_header_and_digest() {
347 fn a_download_must_match_size_header_and_digest() {
262 let bytes = b"MZ";
348 let bytes = EXECUTABLE_MAGIC;
263 let digest: String = Sha256::digest(bytes)
349 let digest: String = Sha256::digest(bytes)
264 .iter()
350 .iter()
265 .map(|byte| format!("{byte:02x}"))
351 .map(|byte| format!("{byte:02x}"))
@@ -269,18 +355,52 @@ mod tests {
269 asset.digest = Some(format!("{SHA256_PREFIX}{digest}"));
355 asset.digest = Some(format!("{SHA256_PREFIX}{digest}"));
270 assert!(verify_download(&asset, bytes).is_ok());
356 assert!(verify_download(&asset, bytes).is_ok());
271 assert!(verify_download(&asset, b"XY").is_err());
357 assert!(verify_download(&asset, b"XY").is_err());
272 assert!(verify_download(&asset, b"MZ!").is_err());
358 assert!(verify_download(&asset, &[EXECUTABLE_MAGIC, b"!"].concat()).is_err());
359 }
360
361 #[test]
362 fn newer_compares_release_versions() {
363 assert!(is_newer("v0.5.0", "v0.4.0"));
364 assert!(is_newer("v0.5.0", "v0.5.0-rc.1"));
365 assert!(!is_newer("v0.4.0", "v0.4.0"));
366 assert!(!is_newer("v0.3.9", "v0.4.0"));
367 assert!(!is_newer("garbage", "v0.4.0"));
368 }
369
370 #[cfg(target_os = "linux")]
371 #[test]
372 fn linux_takes_the_plain_binary_not_the_tarball() {
373 let mut release = release("v0.5.0", false);
374 let binary = release.assets.remove(0);
375 let tarball = ReleaseAsset {
376 name: "rusty-teams-v0.5.0-linux-amd64.tar.gz".to_owned(),
377 ..binary.clone()
378 };
379 release.assets = vec![tarball.clone()];
380 assert!(newest_update("v0.4.0", std::slice::from_ref(&release)).is_none());
381 release.assets = vec![tarball, binary];
382 let (_, asset) = newest_update("v0.4.0", std::slice::from_ref(&release)).unwrap();
383 assert_eq!(asset.name, "rusty-teams-v0.5.0-linux-amd64");
273 }
384 }
274
385
275 #[test]
386 #[test]
276 fn staging_writes_the_exe_before_the_version() {
387 fn staging_writes_the_exe_before_the_version() {
277 let directory = tempfile::tempdir().unwrap();
388 let directory = tempfile::tempdir().unwrap();
278 let paths = UpdatePaths::beside(&directory.path().join("teams.exe"));
389 let paths = UpdatePaths::beside(&directory.path().join("teams"));
279 assert!(!already_staged(&paths, "v0.2.0"));
390 assert!(!already_staged(&paths, "v0.2.0"));
280 stage(&paths, "v0.2.0", b"MZ").unwrap();
391 stage(&paths, "v0.2.0", EXECUTABLE_MAGIC).unwrap();
281 assert_eq!(fs::read(&paths.update_exe).unwrap(), b"MZ");
392 assert_eq!(fs::read(&paths.update_exe).unwrap(), EXECUTABLE_MAGIC);
393 #[cfg(unix)]
394 {
395 use std::os::unix::fs::PermissionsExt as _;
396 let mode = fs::metadata(&paths.update_exe)
397 .unwrap()
398 .permissions()
399 .mode();
400 assert_eq!(mode & 0o111, 0o111);
401 }
282 assert!(already_staged(&paths, "v0.2.0"));
402 assert!(already_staged(&paths, "v0.2.0"));
283 assert!(!already_staged(&paths, "v0.3.0"));
403 assert!(!already_staged(&paths, "v0.3.0"));
284 assert!(!Path::new(&paths.update_exe.with_extension("exe.partial")).exists());
404 assert!(!partial_path(&paths.update_exe).exists());
285 }
405 }
286}
406}
crates/app-base/src/updater.rs +23 −4
@@ -1,4 +1,4 @@
1 #![cfg_attr(not(windows), allow(dead_code))]
1 #![cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))]
2 2
3 3 use std::io;
4 4 use std::path::{Path, PathBuf};
@@ -8,8 +8,14 @@ use std::time::Duration;
8 8 pub const POLL_INTERVAL: Duration = Duration::from_secs(15);
9 9
10 10 const UPDATE_DIRECTORY: &str = "update";
11 #[cfg(windows)]
11 12 const EXE_NAME: &str = "teams.exe";
13 #[cfg(windows)]
12 14 const OLD_EXE_NAME: &str = "teams.old.exe";
15 #[cfg(not(windows))]
16 const EXE_NAME: &str = "teams";
17 #[cfg(not(windows))]
18 const OLD_EXE_NAME: &str = "teams.old";
13 19 const PDB_NAME: &str = "teams.pdb";
14 20 const VERSION_FILE_NAME: &str = "version.txt";
15 21 pub const RELAUNCH_ENV: &str = "RUSTY_TEAMS_RELAUNCH";
@@ -254,6 +260,19 @@ mod platform {
254 260 pub fn terminate_current() {}
255 261 }
256 262
263 /// Whether this build may replace itself from GitHub releases. On Linux only the copy
264 /// installed in `~/.local/share/applications/teams` updates; a binary run from a
265 /// build folder or a package location is left alone.
266 pub fn self_update_allowed() -> bool {
267 #[cfg(target_os = "linux")]
268 return std::env::current_exe().is_ok_and(|executable| {
269 crate::linux_desktop::Layout::current()
270 .is_some_and(|layout| crate::linux_desktop::is_installed(&executable, &layout))
271 });
272 #[cfg(not(target_os = "linux"))]
273 true
274 }
275
257 276 /// Reading the new exe once lets the virus scanner finish before the restart, which otherwise blocks process start for seconds.
258 277 pub fn prescan(update_exe: &Path) {
259 278 if let Ok(mut file) = std::fs::File::open(update_exe) {
@@ -319,8 +338,8 @@ mod tests {
319 338
320 339 #[test]
321 340 fn plan_lists_the_operations_in_order() {
322 let paths = UpdatePaths::beside(Path::new("/app/teams.exe"));
323 assert_eq!(paths.update_exe, Path::new("/app/update/teams.exe"));
341 let paths = UpdatePaths::beside(&Path::new("/app").join(EXE_NAME));
342 assert_eq!(paths.update_exe, Path::new("/app/update").join(EXE_NAME));
324 343 let plan = swap_plan(&paths);
325 344 assert_eq!(plan.len(), 5);
326 345 assert_eq!(
@@ -340,7 +359,7 @@ mod tests {
340 359 }
341 360
342 361 fn install(directory: &Path) -> UpdatePaths {
343 let paths = UpdatePaths::beside(&directory.join("teams.exe"));
362 let paths = UpdatePaths::beside(&directory.join(EXE_NAME));
344 363 fs::create_dir_all(paths.update_exe.parent().unwrap()).unwrap();
345 364 fs::write(&paths.exe, "old").unwrap();
346 365 fs::write(&paths.update_exe, "new").unwrap();
@@ -1,4 +1,4 @@
1#![cfg_attr(not(windows), allow(dead_code))]
1#![cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))]
2
2
3use std::io;
3use std::io;
4use std::path::{Path, PathBuf};
4use std::path::{Path, PathBuf};
@@ -8,8 +8,14 @@ use std::time::Duration;
8pub const POLL_INTERVAL: Duration = Duration::from_secs(15);
8pub const POLL_INTERVAL: Duration = Duration::from_secs(15);
9
9
10const UPDATE_DIRECTORY: &str = "update";
10const UPDATE_DIRECTORY: &str = "update";
11#[cfg(windows)]
11const EXE_NAME: &str = "teams.exe";
12const EXE_NAME: &str = "teams.exe";
13#[cfg(windows)]
12const OLD_EXE_NAME: &str = "teams.old.exe";
14const OLD_EXE_NAME: &str = "teams.old.exe";
15#[cfg(not(windows))]
16const EXE_NAME: &str = "teams";
17#[cfg(not(windows))]
18const OLD_EXE_NAME: &str = "teams.old";
13const PDB_NAME: &str = "teams.pdb";
19const PDB_NAME: &str = "teams.pdb";
14const VERSION_FILE_NAME: &str = "version.txt";
20const VERSION_FILE_NAME: &str = "version.txt";
15pub const RELAUNCH_ENV: &str = "RUSTY_TEAMS_RELAUNCH";
21pub const RELAUNCH_ENV: &str = "RUSTY_TEAMS_RELAUNCH";
@@ -254,6 +260,19 @@ mod platform {
254 pub fn terminate_current() {}
260 pub fn terminate_current() {}
255}
261}
256
262
263/// Whether this build may replace itself from GitHub releases. On Linux only the copy
264/// installed in `~/.local/share/applications/teams` updates; a binary run from a
265/// build folder or a package location is left alone.
266pub fn self_update_allowed() -> bool {
267 #[cfg(target_os = "linux")]
268 return std::env::current_exe().is_ok_and(|executable| {
269 crate::linux_desktop::Layout::current()
270 .is_some_and(|layout| crate::linux_desktop::is_installed(&executable, &layout))
271 });
272 #[cfg(not(target_os = "linux"))]
273 true
274}
275
257/// Reading the new exe once lets the virus scanner finish before the restart, which otherwise blocks process start for seconds.
276/// Reading the new exe once lets the virus scanner finish before the restart, which otherwise blocks process start for seconds.
258pub fn prescan(update_exe: &Path) {
277pub fn prescan(update_exe: &Path) {
259 if let Ok(mut file) = std::fs::File::open(update_exe) {
278 if let Ok(mut file) = std::fs::File::open(update_exe) {
@@ -319,8 +338,8 @@ mod tests {
319
338
320 #[test]
339 #[test]
321 fn plan_lists_the_operations_in_order() {
340 fn plan_lists_the_operations_in_order() {
322 let paths = UpdatePaths::beside(Path::new("/app/teams.exe"));
341 let paths = UpdatePaths::beside(&Path::new("/app").join(EXE_NAME));
323 assert_eq!(paths.update_exe, Path::new("/app/update/teams.exe"));
342 assert_eq!(paths.update_exe, Path::new("/app/update").join(EXE_NAME));
324 let plan = swap_plan(&paths);
343 let plan = swap_plan(&paths);
325 assert_eq!(plan.len(), 5);
344 assert_eq!(plan.len(), 5);
326 assert_eq!(
345 assert_eq!(
@@ -340,7 +359,7 @@ mod tests {
340 }
359 }
341
360
342 fn install(directory: &Path) -> UpdatePaths {
361 fn install(directory: &Path) -> UpdatePaths {
343 let paths = UpdatePaths::beside(&directory.join("teams.exe"));
362 let paths = UpdatePaths::beside(&directory.join(EXE_NAME));
344 fs::create_dir_all(paths.update_exe.parent().unwrap()).unwrap();
363 fs::create_dir_all(paths.update_exe.parent().unwrap()).unwrap();
345 fs::write(&paths.exe, "old").unwrap();
364 fs::write(&paths.exe, "old").unwrap();
346 fs::write(&paths.update_exe, "new").unwrap();
365 fs::write(&paths.update_exe, "new").unwrap();
crates/app/src/linux_install.rs added +253 −0
@@ -0,0 +1,253 @@
1 //! Linux desktop integration on start: offer to install the binary into
2 //! `~/.local/share/applications/teams` with a menu entry, and fetch the Teams icon
3 //! from Microsoft (it is not shipped with the app).
4
5 use std::collections::HashMap;
6 use std::path::{Path, PathBuf};
7
8 use app_base::linux_desktop::{self, Layout};
9 use gpui_kit::component::button::{Button, ButtonVariants as _};
10 use gpui_kit::component::dialog::{Dialog, DialogFooter};
11 use gpui_kit::component::{WindowExt as _, v_flex};
12 use gpui_kit::*;
13
14 use crate::app_state::AppHandle;
15 use crate::appearance::AppIcon;
16 use crate::i18n::{tr, tr_args};
17 use crate::theme;
18
19 const DIALOG_WIDTH: f32 = 460.;
20
21 /// Loads an icon a previous run downloaded, before the first window picks its icon.
22 pub fn load_icon() {
23 if let Some(layout) = Layout::current() {
24 linux_desktop::load_teams_icon(&layout);
25 }
26 }
27
28 pub fn start(cx: &mut App) {
29 let (Ok(executable), Some(layout)) = (std::env::current_exe(), Layout::current()) else {
30 return;
31 };
32 if !linux_desktop::has_icon(&layout) {
33 download_icon(layout.clone(), cx);
34 }
35 if linux_desktop::is_installed(&executable, &layout) {
36 // Keeps the menu entry pointing at this file, e.g. after it was deleted by hand.
37 if !layout.desktop_file().is_file()
38 && linux_desktop::write_desktop_entry(&layout, &executable).is_ok()
39 {
40 linux_desktop::refresh_desktop_caches(&layout);
41 }
42 return;
43 }
44 let dont_ask = cx
45 .try_global::<AppHandle>()
46 .is_some_and(|handle| linux_desktop::dont_ask_again(&handle.0.read(cx).store));
47 if linux_desktop::should_offer_install(&executable, &layout, dont_ask) {
48 // After the shell's first frame, so the dialog sits on top of the splash.
49 cx.defer(move |cx| offer_install(executable, layout, cx));
50 }
51 }
52
53 fn download_icon(layout: Layout, cx: &mut App) {
54 let download = linux_desktop::download_icon(layout, cx);
55 cx.spawn(async move |cx| match download.await {
56 Ok(png) => {
57 linux_desktop::set_teams_icon(png);
58 cx.update(|cx| {
59 // First run: the Teams icon becomes the default unless one was chosen.
60 if let Some(store) = cx
61 .try_global::<AppHandle>()
62 .map(|handle| handle.0.read(cx).store.clone())
63 && !crate::appearance::icon_saved(&store)
64 {
65 crate::active_appearance::set_app_icon(AppIcon::MicrosoftTeams, &store, cx);
66 }
67 crate::views::shell::refresh_app_icon(cx);
68 });
69 }
70 Err(error) => log::warn!("Teams icon download failed: {error}"),
71 })
72 .detach();
73 }
74
75 fn offer_install(executable: PathBuf, layout: Layout, cx: &mut App) {
76 let Some(window) = crate::main_window::current(cx) else {
77 return;
78 };
79 let folder = layout.install_dir();
80 let mut args = HashMap::new();
81 args.insert("folder".to_owned(), display_home(&folder));
82 let body = tr_args("install.body", &args);
83 window
84 .update(cx, move |_, window, cx| {
85 window.open_dialog(cx, move |dialog: Dialog, _, _| {
86 let (install_from, install_layout) = (executable.clone(), layout.clone());
87 let footer = DialogFooter::new()
88 .child(
89 Button::new("install-dont-ask")
90 .label(tr("install.dont_ask"))
91 .on_click(|_, window, cx| {
92 if let Some(handle) = cx.try_global::<AppHandle>() {
93 linux_desktop::set_dont_ask_again(&handle.0.read(cx).store);
94 }
95 window.close_dialog(cx);
96 }),
97 )
98 .child(
99 Button::new("install-not-now")
100 .label(tr("install.not_now"))
101 .on_click(|_, window, cx| window.close_dialog(cx)),
102 )
103 .child(
104 Button::new("install-move")
105 .primary()
106 .label(tr("install.move"))
107 .on_click(move |_, window, cx| {
108 window.close_dialog(cx);
109 install(&install_from, &install_layout, cx);
110 }),
111 );
112 dialog
113 .title(tr("install.title"))
114 .w(px(DIALOG_WIDTH))
115 .child(
116 v_flex()
117 .gap(px(8.))
118 .text_color(theme::text())
119 .child(body.clone()),
120 )
121 .footer(footer)
122 });
123 })
124 .ok();
125 }
126
127 fn install(executable: &Path, layout: &Layout, cx: &mut App) {
128 match linux_desktop::install_binary(executable, layout) {
129 Ok(installed) => relaunch(&installed, cx),
130 Err(error) => {
131 log::warn!("install failed: {error}");
132 notice(failure("install.failed", &error.to_string()), cx);
133 }
134 }
135 }
136
137 fn failure(key: &str, detail: &str) -> String {
138 let mut args = HashMap::new();
139 args.insert("detail".to_owned(), detail.to_owned());
140 tr_args(key, &args)
141 }
142
143 fn notice(text: String, cx: &mut App) {
144 if let Some(handle) = cx.try_global::<AppHandle>() {
145 handle
146 .0
147 .clone()
148 .update(cx, |state, cx| state.raise_notice(text, None, cx));
149 }
150 }
151
152 /// Where this process stands relative to `~/.local/share/applications/teams`.
153 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
154 pub enum Installation {
155 /// This process is the installed copy.
156 Running,
157 /// Another binary is installed; this one runs from elsewhere.
158 OtherCopy,
159 NotInstalled,
160 }
161
162 pub fn installation() -> Installation {
163 let (Ok(executable), Some(layout)) = (std::env::current_exe(), Layout::current()) else {
164 return Installation::NotInstalled;
165 };
166 if linux_desktop::is_installed(&executable, &layout) {
167 Installation::Running
168 } else if layout.installed_binary().is_file() {
169 Installation::OtherCopy
170 } else {
171 Installation::NotInstalled
172 }
173 }
174
175 pub fn install_folder() -> String {
176 Layout::current()
177 .map(|layout| display_home(&layout.install_dir()))
178 .unwrap_or_default()
179 }
180
181 /// Settings > General: installs (or replaces the installed copy with) this binary.
182 pub fn install_now(cx: &mut App) {
183 let (Ok(executable), Some(layout)) = (std::env::current_exe(), Layout::current()) else {
184 return;
185 };
186 if let Some(handle) = cx.try_global::<AppHandle>() {
187 linux_desktop::ask_again(&handle.0.read(cx).store);
188 }
189 install(&executable, &layout, cx);
190 }
191
192 /// Settings > General: removes the menu entry and the installed binary.
193 pub fn remove(cx: &mut App) {
194 let Some(layout) = Layout::current() else {
195 return;
196 };
197 match linux_desktop::uninstall(&layout) {
198 Ok(()) => notice(tr("install.removed"), cx),
199 Err(error) => notice(failure("install.remove_failed", &error.to_string()), cx),
200 }
201 cx.refresh_windows();
202 }
203
204 pub fn asks_on_start(cx: &App) -> bool {
205 cx.try_global::<AppHandle>()
206 .is_some_and(|handle| !linux_desktop::dont_ask_again(&handle.0.read(cx).store))
207 }
208
209 pub fn set_asks_on_start(ask: bool, cx: &mut App) {
210 if let Some(handle) = cx.try_global::<AppHandle>() {
211 let store = &handle.0.read(cx).store;
212 if ask {
213 linux_desktop::ask_again(store);
214 } else {
215 linux_desktop::set_dont_ask_again(store);
216 }
217 }
218 cx.refresh_windows();
219 }
220
221 /// The release this build counts as: its tag in CI release builds, the workspace
222 /// version (kept equal to the latest release) in a local build.
223 pub fn running_release() -> &'static str {
224 app_base::version::release_tag().unwrap_or(concat!("v", env!("CARGO_PKG_VERSION")))
225 }
226
227 /// The release to update from, when this process is the installed copy.
228 pub fn updatable_release() -> Option<&'static str> {
229 crate::updater::self_update_allowed().then(running_release)
230 }
231
232 /// Starts the installed copy and quits; the new process waits for this one to let go
233 /// of the single-instance socket.
234 fn relaunch(installed: &Path, cx: &mut App) {
235 let started = std::process::Command::new(installed)
236 .env(crate::updater::RELAUNCH_ENV, std::process::id().to_string())
237 .spawn();
238 match started {
239 Ok(_) => cx.quit(),
240 Err(error) => log::warn!("could not start {}: {error}", installed.display()),
241 }
242 }
243
244 fn display_home(path: &Path) -> String {
245 match directories::BaseDirs::new().and_then(|base| {
246 path.strip_prefix(base.home_dir())
247 .ok()
248 .map(Path::to_path_buf)
249 }) {
250 Some(relative) => format!("~/{}", relative.display()),
251 None => path.display().to_string(),
252 }
253 }
@@ -0,0 +1,253 @@
1//! Linux desktop integration on start: offer to install the binary into
2//! `~/.local/share/applications/teams` with a menu entry, and fetch the Teams icon
3//! from Microsoft (it is not shipped with the app).
4
5use std::collections::HashMap;
6use std::path::{Path, PathBuf};
7
8use app_base::linux_desktop::{self, Layout};
9use gpui_kit::component::button::{Button, ButtonVariants as _};
10use gpui_kit::component::dialog::{Dialog, DialogFooter};
11use gpui_kit::component::{WindowExt as _, v_flex};
12use gpui_kit::*;
13
14use crate::app_state::AppHandle;
15use crate::appearance::AppIcon;
16use crate::i18n::{tr, tr_args};
17use crate::theme;
18
19const DIALOG_WIDTH: f32 = 460.;
20
21/// Loads an icon a previous run downloaded, before the first window picks its icon.
22pub fn load_icon() {
23 if let Some(layout) = Layout::current() {
24 linux_desktop::load_teams_icon(&layout);
25 }
26}
27
28pub fn start(cx: &mut App) {
29 let (Ok(executable), Some(layout)) = (std::env::current_exe(), Layout::current()) else {
30 return;
31 };
32 if !linux_desktop::has_icon(&layout) {
33 download_icon(layout.clone(), cx);
34 }
35 if linux_desktop::is_installed(&executable, &layout) {
36 // Keeps the menu entry pointing at this file, e.g. after it was deleted by hand.
37 if !layout.desktop_file().is_file()
38 && linux_desktop::write_desktop_entry(&layout, &executable).is_ok()
39 {
40 linux_desktop::refresh_desktop_caches(&layout);
41 }
42 return;
43 }
44 let dont_ask = cx
45 .try_global::<AppHandle>()
46 .is_some_and(|handle| linux_desktop::dont_ask_again(&handle.0.read(cx).store));
47 if linux_desktop::should_offer_install(&executable, &layout, dont_ask) {
48 // After the shell's first frame, so the dialog sits on top of the splash.
49 cx.defer(move |cx| offer_install(executable, layout, cx));
50 }
51}
52
53fn download_icon(layout: Layout, cx: &mut App) {
54 let download = linux_desktop::download_icon(layout, cx);
55 cx.spawn(async move |cx| match download.await {
56 Ok(png) => {
57 linux_desktop::set_teams_icon(png);
58 cx.update(|cx| {
59 // First run: the Teams icon becomes the default unless one was chosen.
60 if let Some(store) = cx
61 .try_global::<AppHandle>()
62 .map(|handle| handle.0.read(cx).store.clone())
63 && !crate::appearance::icon_saved(&store)
64 {
65 crate::active_appearance::set_app_icon(AppIcon::MicrosoftTeams, &store, cx);
66 }
67 crate::views::shell::refresh_app_icon(cx);
68 });
69 }
70 Err(error) => log::warn!("Teams icon download failed: {error}"),
71 })
72 .detach();
73}
74
75fn offer_install(executable: PathBuf, layout: Layout, cx: &mut App) {
76 let Some(window) = crate::main_window::current(cx) else {
77 return;
78 };
79 let folder = layout.install_dir();
80 let mut args = HashMap::new();
81 args.insert("folder".to_owned(), display_home(&folder));
82 let body = tr_args("install.body", &args);
83 window
84 .update(cx, move |_, window, cx| {
85 window.open_dialog(cx, move |dialog: Dialog, _, _| {
86 let (install_from, install_layout) = (executable.clone(), layout.clone());
87 let footer = DialogFooter::new()
88 .child(
89 Button::new("install-dont-ask")
90 .label(tr("install.dont_ask"))
91 .on_click(|_, window, cx| {
92 if let Some(handle) = cx.try_global::<AppHandle>() {
93 linux_desktop::set_dont_ask_again(&handle.0.read(cx).store);
94 }
95 window.close_dialog(cx);
96 }),
97 )
98 .child(
99 Button::new("install-not-now")
100 .label(tr("install.not_now"))
101 .on_click(|_, window, cx| window.close_dialog(cx)),
102 )
103 .child(
104 Button::new("install-move")
105 .primary()
106 .label(tr("install.move"))
107 .on_click(move |_, window, cx| {
108 window.close_dialog(cx);
109 install(&install_from, &install_layout, cx);
110 }),
111 );
112 dialog
113 .title(tr("install.title"))
114 .w(px(DIALOG_WIDTH))
115 .child(
116 v_flex()
117 .gap(px(8.))
118 .text_color(theme::text())
119 .child(body.clone()),
120 )
121 .footer(footer)
122 });
123 })
124 .ok();
125}
126
127fn install(executable: &Path, layout: &Layout, cx: &mut App) {
128 match linux_desktop::install_binary(executable, layout) {
129 Ok(installed) => relaunch(&installed, cx),
130 Err(error) => {
131 log::warn!("install failed: {error}");
132 notice(failure("install.failed", &error.to_string()), cx);
133 }
134 }
135}
136
137fn failure(key: &str, detail: &str) -> String {
138 let mut args = HashMap::new();
139 args.insert("detail".to_owned(), detail.to_owned());
140 tr_args(key, &args)
141}
142
143fn notice(text: String, cx: &mut App) {
144 if let Some(handle) = cx.try_global::<AppHandle>() {
145 handle
146 .0
147 .clone()
148 .update(cx, |state, cx| state.raise_notice(text, None, cx));
149 }
150}
151
152/// Where this process stands relative to `~/.local/share/applications/teams`.
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum Installation {
155 /// This process is the installed copy.
156 Running,
157 /// Another binary is installed; this one runs from elsewhere.
158 OtherCopy,
159 NotInstalled,
160}
161
162pub fn installation() -> Installation {
163 let (Ok(executable), Some(layout)) = (std::env::current_exe(), Layout::current()) else {
164 return Installation::NotInstalled;
165 };
166 if linux_desktop::is_installed(&executable, &layout) {
167 Installation::Running
168 } else if layout.installed_binary().is_file() {
169 Installation::OtherCopy
170 } else {
171 Installation::NotInstalled
172 }
173}
174
175pub fn install_folder() -> String {
176 Layout::current()
177 .map(|layout| display_home(&layout.install_dir()))
178 .unwrap_or_default()
179}
180
181/// Settings > General: installs (or replaces the installed copy with) this binary.
182pub fn install_now(cx: &mut App) {
183 let (Ok(executable), Some(layout)) = (std::env::current_exe(), Layout::current()) else {
184 return;
185 };
186 if let Some(handle) = cx.try_global::<AppHandle>() {
187 linux_desktop::ask_again(&handle.0.read(cx).store);
188 }
189 install(&executable, &layout, cx);
190}
191
192/// Settings > General: removes the menu entry and the installed binary.
193pub fn remove(cx: &mut App) {
194 let Some(layout) = Layout::current() else {
195 return;
196 };
197 match linux_desktop::uninstall(&layout) {
198 Ok(()) => notice(tr("install.removed"), cx),
199 Err(error) => notice(failure("install.remove_failed", &error.to_string()), cx),
200 }
201 cx.refresh_windows();
202}
203
204pub fn asks_on_start(cx: &App) -> bool {
205 cx.try_global::<AppHandle>()
206 .is_some_and(|handle| !linux_desktop::dont_ask_again(&handle.0.read(cx).store))
207}
208
209pub fn set_asks_on_start(ask: bool, cx: &mut App) {
210 if let Some(handle) = cx.try_global::<AppHandle>() {
211 let store = &handle.0.read(cx).store;
212 if ask {
213 linux_desktop::ask_again(store);
214 } else {
215 linux_desktop::set_dont_ask_again(store);
216 }
217 }
218 cx.refresh_windows();
219}
220
221/// The release this build counts as: its tag in CI release builds, the workspace
222/// version (kept equal to the latest release) in a local build.
223pub fn running_release() -> &'static str {
224 app_base::version::release_tag().unwrap_or(concat!("v", env!("CARGO_PKG_VERSION")))
225}
226
227/// The release to update from, when this process is the installed copy.
228pub fn updatable_release() -> Option<&'static str> {
229 crate::updater::self_update_allowed().then(running_release)
230}
231
232/// Starts the installed copy and quits; the new process waits for this one to let go
233/// of the single-instance socket.
234fn relaunch(installed: &Path, cx: &mut App) {
235 let started = std::process::Command::new(installed)
236 .env(crate::updater::RELAUNCH_ENV, std::process::id().to_string())
237 .spawn();
238 match started {
239 Ok(_) => cx.quit(),
240 Err(error) => log::warn!("could not start {}: {error}", installed.display()),
241 }
242}
243
244fn display_home(path: &Path) -> String {
245 match directories::BaseDirs::new().and_then(|base| {
246 path.strip_prefix(base.home_dir())
247 .ok()
248 .map(Path::to_path_buf)
249 }) {
250 Some(relative) => format!("~/{}", relative.display()),
251 None => path.display().to_string(),
252 }
253}
crates/app/src/linux_update.rs added +401 −0
@@ -0,0 +1,401 @@
1 //! Linux self-update, always with consent: a newer GitHub release is offered in a
2 //! dialog; "Update" downloads it with progress and "Restart now" swaps the binary
3 //! and relaunches. Nothing restarts without a click. Settings > General turns the
4 //! periodic check off; "Check now" works either way.
5
6 use std::collections::HashMap;
7 use std::sync::Arc;
8 use std::sync::atomic::{AtomicU64, Ordering};
9 use std::time::Duration;
10
11 use app_base::release_feed::{self, AvailableUpdate};
12 use gpui_kit::component::button::{Button, ButtonVariants as _};
13 use gpui_kit::component::dialog::{Dialog, DialogFooter};
14 use gpui_kit::component::{WindowExt as _, v_flex};
15 use gpui_kit::*;
16
17 use crate::app_state::AppHandle;
18 use crate::i18n::{tr, tr_args};
19 use crate::theme;
20 use crate::updater;
21
22 const ENABLED_META_KEY: &str = "linux.updates.enabled";
23 /// How often an offer waits for a main window closed into the tray to come back.
24 const WINDOW_WAIT: Duration = Duration::from_secs(30);
25 /// How often the progress dialog redraws while downloading.
26 const PROGRESS_REDRAW: Duration = Duration::from_millis(250);
27 const DIALOG_WIDTH: f32 = 460.;
28
29 #[derive(Clone)]
30 enum Stage {
31 Idle,
32 Offer(AvailableUpdate),
33 Downloading {
34 update: AvailableUpdate,
35 progress: Arc<AtomicU64>,
36 },
37 Ready(String),
38 Failed(String),
39 }
40
41 struct LinuxUpdates {
42 stage: Stage,
43 dialog_open: bool,
44 /// "Not now" holds for this run only; the next start asks again.
45 declined: Option<String>,
46 }
47
48 impl Global for LinuxUpdates {}
49
50 fn stage(cx: &App) -> Stage {
51 cx.try_global::<LinuxUpdates>()
52 .map(|updates| updates.stage.clone())
53 .unwrap_or(Stage::Idle)
54 }
55
56 fn set_stage(stage: Stage, cx: &mut App) {
57 if cx.has_global::<LinuxUpdates>() {
58 cx.global_mut::<LinuxUpdates>().stage = stage;
59 }
60 cx.refresh_windows();
61 }
62
63 fn with_store<R>(cx: &App, read: impl FnOnce(&store::Store) -> R) -> Option<R> {
64 cx.try_global::<AppHandle>()
65 .map(|handle| read(&handle.0.read(cx).store))
66 }
67
68 /// The periodic check; on by default.
69 pub fn enabled(cx: &App) -> bool {
70 with_store(cx, |store| {
71 store.meta(ENABLED_META_KEY).ok().flatten().as_deref() != Some("0")
72 })
73 .unwrap_or(true)
74 }
75
76 pub fn set_enabled(enabled: bool, cx: &mut App) {
77 with_store(cx, |store| {
78 let _ = store.set_meta(ENABLED_META_KEY, if enabled { "1" } else { "0" });
79 });
80 cx.refresh_windows();
81 }
82
83 fn declined(cx: &App) -> Option<String> {
84 cx.try_global::<LinuxUpdates>()
85 .and_then(|updates| updates.declined.clone())
86 }
87
88 fn decline(tag: &str, cx: &mut App) {
89 if cx.has_global::<LinuxUpdates>() {
90 cx.global_mut::<LinuxUpdates>().declined = Some(tag.to_owned());
91 }
92 }
93
94 /// A newer release a previous run downloaded but did not install ("Later").
95 fn staged_update(running_tag: &str) -> Option<String> {
96 let paths = updater::current_paths()?;
97 if !updater::check(&paths) {
98 return None;
99 }
100 let tag = std::fs::read_to_string(&paths.version_file).ok()?;
101 let tag = tag.trim();
102 if release_feed::is_newer(tag, running_tag) {
103 return Some(tag.to_owned());
104 }
105 // Same or older than this build, e.g. after installing a release by hand.
106 let _ = std::fs::remove_file(&paths.version_file);
107 let _ = std::fs::remove_file(&paths.update_exe);
108 None
109 }
110
111 fn args(name: &str, value: impl Into<String>) -> HashMap<String, String> {
112 HashMap::from([(name.to_owned(), value.into())])
113 }
114
115 fn notice(text: String, cx: &mut App) {
116 if let Some(handle) = cx.try_global::<AppHandle>() {
117 handle
118 .0
119 .clone()
120 .update(cx, |state, cx| state.raise_notice(text, None, cx));
121 }
122 }
123
124 fn ensure_state(cx: &mut App) {
125 if !cx.has_global::<LinuxUpdates>() {
126 cx.set_global(LinuxUpdates {
127 stage: Stage::Idle,
128 dialog_open: false,
129 declined: None,
130 });
131 }
132 }
133
134 /// Starts the periodic check. Only the installed copy of a release build updates.
135 pub fn start(cx: &mut App) {
136 if crate::linux_install::updatable_release().is_none() {
137 return;
138 }
139 ensure_state(cx);
140 if let Some(running_tag) = crate::linux_install::updatable_release()
141 && let Some(tag) = staged_update(running_tag)
142 {
143 set_stage(Stage::Ready(tag), cx);
144 show_when_window_is_open(cx);
145 }
146 cx.spawn(async move |cx| {
147 cx.background_executor()
148 .timer(release_feed::FIRST_CHECK_DELAY)
149 .await;
150 loop {
151 let waiting = cx.update(|cx| matches!(stage(cx), Stage::Ready(_)));
152 if !waiting && cx.update(|cx| enabled(cx)) {
153 cx.update(|cx| check(false, cx));
154 }
155 cx.background_executor()
156 .timer(release_feed::CHECK_INTERVAL)
157 .await;
158 }
159 })
160 .detach();
161 }
162
163 /// Looks for a newer release. `manual` (Settings > Check now) also offers a version
164 /// declined with "Not now" in this run and reports "up to date" and errors.
165 pub fn check(manual: bool, cx: &mut App) {
166 let Some(running_tag) = crate::linux_install::updatable_release() else {
167 if manual {
168 notice(tr("install.updates_need_install"), cx);
169 }
170 return;
171 };
172 ensure_state(cx);
173 match stage(cx) {
174 Stage::Downloading { .. } | Stage::Ready(_) => {
175 open_dialog(cx);
176 return;
177 }
178 Stage::Idle | Stage::Offer(_) | Stage::Failed(_) => {}
179 }
180 if manual {
181 notice(tr("install.update_checking"), cx);
182 }
183 let find = release_feed::find_update(running_tag, cx);
184 cx.spawn(async move |cx| {
185 let found = find.await;
186 cx.update(|cx| match found {
187 Ok(Some(update)) if manual || declined(cx).as_deref() != Some(&update.tag) => {
188 offer(update, cx)
189 }
190 Ok(Some(_)) => {}
191 Ok(None) if manual => notice(tr("install.up_to_date"), cx),
192 Ok(None) => {}
193 Err(error) if manual => {
194 notice(tr_args("install.update_failed", &args("detail", error)), cx)
195 }
196 Err(error) => log::warn!("update check failed: {error}"),
197 });
198 })
199 .detach();
200 }
201
202 fn offer(update: AvailableUpdate, cx: &mut App) {
203 set_stage(Stage::Offer(update), cx);
204 show_when_window_is_open(cx);
205 }
206
207 /// Opens the dialog for the current stage, waiting for the main window if it is
208 /// closed into the tray.
209 fn show_when_window_is_open(cx: &mut App) {
210 cx.spawn(async move |cx| {
211 while cx.update(|cx| crate::main_window::current(cx).is_none()) {
212 cx.background_executor().timer(WINDOW_WAIT).await;
213 }
214 cx.update(|cx| {
215 if matches!(stage(cx), Stage::Offer(_) | Stage::Ready(_)) {
216 open_dialog(cx);
217 }
218 });
219 })
220 .detach();
221 }
222
223 fn download(update: AvailableUpdate, cx: &mut App) {
224 let Some(paths) = updater::current_paths() else {
225 return;
226 };
227 let progress = Arc::new(AtomicU64::new(0));
228 set_stage(
229 Stage::Downloading {
230 update: update.clone(),
231 progress: progress.clone(),
232 },
233 cx,
234 );
235 let tag = update.tag.clone();
236 let task = release_feed::download_update(update, paths, progress, cx);
237 cx.spawn(async move |cx| {
238 let redraw = cx.spawn(async move |cx| {
239 loop {
240 cx.background_executor().timer(PROGRESS_REDRAW).await;
241 cx.update(|cx| cx.refresh_windows());
242 }
243 });
244 let result = task.await;
245 drop(redraw);
246 cx.update(|cx| {
247 match result {
248 Ok(()) => set_stage(Stage::Ready(tag), cx),
249 Err(error) => {
250 log::warn!("update download failed: {error}");
251 set_stage(Stage::Failed(error), cx);
252 }
253 }
254 open_dialog(cx);
255 });
256 })
257 .detach();
258 }
259
260 fn restart(cx: &mut App) {
261 let Some(paths) = updater::current_paths() else {
262 return;
263 };
264 match updater::install_and_relaunch(&paths) {
265 Ok(()) => cx.quit(),
266 Err(error) => set_stage(Stage::Failed(error), cx),
267 }
268 }
269
270 /// Opens the update dialog on the main window unless it is already open. It redraws
271 /// from the current stage, so one dialog walks through offer, progress and restart.
272 fn open_dialog(cx: &mut App) {
273 let Some(window) = crate::main_window::current(cx) else {
274 return;
275 };
276 if !cx.has_global::<LinuxUpdates>() || cx.global::<LinuxUpdates>().dialog_open {
277 return;
278 }
279 cx.global_mut::<LinuxUpdates>().dialog_open = true;
280 let opened = window.update(cx, |_, window, cx| {
281 window.open_dialog(cx, |dialog: Dialog, _, cx| build_dialog(dialog, cx));
282 });
283 if opened.is_err() {
284 cx.global_mut::<LinuxUpdates>().dialog_open = false;
285 }
286 }
287
288 fn close_dialog(window: &mut Window, cx: &mut App) {
289 if cx.has_global::<LinuxUpdates>() {
290 cx.global_mut::<LinuxUpdates>().dialog_open = false;
291 }
292 window.close_dialog(cx);
293 }
294
295 fn percent(progress: &AtomicU64, size: u64) -> u64 {
296 (progress.load(Ordering::Relaxed) * 100)
297 .checked_div(size)
298 .unwrap_or(0)
299 .min(100)
300 }
301
302 fn build_dialog(dialog: Dialog, cx: &App) -> Dialog {
303 let running = app_base::version::release_tag().unwrap_or_default();
304 let (title, body, footer) = match stage(cx) {
305 Stage::Offer(update) => {
306 let mut text_args = args("version", update.tag.clone());
307 text_args.insert("current".to_owned(), running.to_owned());
308 let tag = update.tag.clone();
309 (
310 tr("install.update_available_title"),
311 tr_args("install.update_available_body", &text_args),
312 DialogFooter::new()
313 .child(
314 Button::new("update-not-now")
315 .label(tr("install.not_now"))
316 .on_click(move |_, window, cx| {
317 decline(&tag, cx);
318 set_stage(Stage::Idle, cx);
319 close_dialog(window, cx);
320 }),
321 )
322 .child(
323 Button::new("update-start")
324 .primary()
325 .label(tr("install.update_now"))
326 .on_click(move |_, _, cx| download(update.clone(), cx)),
327 ),
328 )
329 }
330 Stage::Downloading { update, progress } => {
331 let mut text_args = args("version", update.tag.clone());
332 text_args.insert(
333 "percent".to_owned(),
334 percent(&progress, update.asset.size).to_string(),
335 );
336 (
337 tr("install.update_available_title"),
338 tr_args("install.update_downloading", &text_args),
339 DialogFooter::new().child(
340 Button::new("update-hide")
341 .label(tr("install.hide"))
342 .on_click(|_, window, cx| close_dialog(window, cx)),
343 ),
344 )
345 }
346 Stage::Ready(tag) => (
347 tr("install.update_ready_title"),
348 tr_args("install.update_ready_body", &args("version", tag)),
349 DialogFooter::new()
350 .child(
351 Button::new("update-later")
352 .label(tr("install.later"))
353 .on_click(|_, window, cx| close_dialog(window, cx)),
354 )
355 .child(
356 Button::new("update-restart")
357 .primary()
358 .label(tr("install.restart_now"))
359 .on_click(|_, _, cx| restart(cx)),
360 ),
361 ),
362 Stage::Failed(error) => (
363 tr("install.update_available_title"),
364 tr_args("install.update_failed", &args("detail", error)),
365 DialogFooter::new().child(
366 Button::new("update-close")
367 .label(tr("common.close"))
368 .on_click(|_, window, cx| {
369 set_stage(Stage::Idle, cx);
370 close_dialog(window, cx);
371 }),
372 ),
373 ),
374 Stage::Idle => (String::new(), String::new(), DialogFooter::new()),
375 };
376 // Only the buttons close it, so the stage and the open flag stay in step.
377 dialog
378 .title(title)
379 .w(px(DIALOG_WIDTH))
380 .keyboard(false)
381 .overlay_closable(false)
382 .close_button(false)
383 .child(v_flex().gap(px(8.)).text_color(theme::text()).child(body))
384 .footer(footer)
385 }
386
387 #[cfg(test)]
388 mod tests {
389 use std::sync::atomic::{AtomicU64, Ordering};
390
391 use super::percent;
392
393 #[test]
394 fn percent_is_clamped_and_safe_without_a_size() {
395 let progress = AtomicU64::new(50);
396 assert_eq!(percent(&progress, 200), 25);
397 assert_eq!(percent(&progress, 0), 0);
398 progress.store(500, Ordering::Relaxed);
399 assert_eq!(percent(&progress, 200), 100);
400 }
401 }
@@ -0,0 +1,401 @@
1//! Linux self-update, always with consent: a newer GitHub release is offered in a
2//! dialog; "Update" downloads it with progress and "Restart now" swaps the binary
3//! and relaunches. Nothing restarts without a click. Settings > General turns the
4//! periodic check off; "Check now" works either way.
5
6use std::collections::HashMap;
7use std::sync::Arc;
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::time::Duration;
10
11use app_base::release_feed::{self, AvailableUpdate};
12use gpui_kit::component::button::{Button, ButtonVariants as _};
13use gpui_kit::component::dialog::{Dialog, DialogFooter};
14use gpui_kit::component::{WindowExt as _, v_flex};
15use gpui_kit::*;
16
17use crate::app_state::AppHandle;
18use crate::i18n::{tr, tr_args};
19use crate::theme;
20use crate::updater;
21
22const ENABLED_META_KEY: &str = "linux.updates.enabled";
23/// How often an offer waits for a main window closed into the tray to come back.
24const WINDOW_WAIT: Duration = Duration::from_secs(30);
25/// How often the progress dialog redraws while downloading.
26const PROGRESS_REDRAW: Duration = Duration::from_millis(250);
27const DIALOG_WIDTH: f32 = 460.;
28
29#[derive(Clone)]
30enum Stage {
31 Idle,
32 Offer(AvailableUpdate),
33 Downloading {
34 update: AvailableUpdate,
35 progress: Arc<AtomicU64>,
36 },
37 Ready(String),
38 Failed(String),
39}
40
41struct LinuxUpdates {
42 stage: Stage,
43 dialog_open: bool,
44 /// "Not now" holds for this run only; the next start asks again.
45 declined: Option<String>,
46}
47
48impl Global for LinuxUpdates {}
49
50fn stage(cx: &App) -> Stage {
51 cx.try_global::<LinuxUpdates>()
52 .map(|updates| updates.stage.clone())
53 .unwrap_or(Stage::Idle)
54}
55
56fn set_stage(stage: Stage, cx: &mut App) {
57 if cx.has_global::<LinuxUpdates>() {
58 cx.global_mut::<LinuxUpdates>().stage = stage;
59 }
60 cx.refresh_windows();
61}
62
63fn with_store<R>(cx: &App, read: impl FnOnce(&store::Store) -> R) -> Option<R> {
64 cx.try_global::<AppHandle>()
65 .map(|handle| read(&handle.0.read(cx).store))
66}
67
68/// The periodic check; on by default.
69pub fn enabled(cx: &App) -> bool {
70 with_store(cx, |store| {
71 store.meta(ENABLED_META_KEY).ok().flatten().as_deref() != Some("0")
72 })
73 .unwrap_or(true)
74}
75
76pub fn set_enabled(enabled: bool, cx: &mut App) {
77 with_store(cx, |store| {
78 let _ = store.set_meta(ENABLED_META_KEY, if enabled { "1" } else { "0" });
79 });
80 cx.refresh_windows();
81}
82
83fn declined(cx: &App) -> Option<String> {
84 cx.try_global::<LinuxUpdates>()
85 .and_then(|updates| updates.declined.clone())
86}
87
88fn decline(tag: &str, cx: &mut App) {
89 if cx.has_global::<LinuxUpdates>() {
90 cx.global_mut::<LinuxUpdates>().declined = Some(tag.to_owned());
91 }
92}
93
94/// A newer release a previous run downloaded but did not install ("Later").
95fn staged_update(running_tag: &str) -> Option<String> {
96 let paths = updater::current_paths()?;
97 if !updater::check(&paths) {
98 return None;
99 }
100 let tag = std::fs::read_to_string(&paths.version_file).ok()?;
101 let tag = tag.trim();
102 if release_feed::is_newer(tag, running_tag) {
103 return Some(tag.to_owned());
104 }
105 // Same or older than this build, e.g. after installing a release by hand.
106 let _ = std::fs::remove_file(&paths.version_file);
107 let _ = std::fs::remove_file(&paths.update_exe);
108 None
109}
110
111fn args(name: &str, value: impl Into<String>) -> HashMap<String, String> {
112 HashMap::from([(name.to_owned(), value.into())])
113}
114
115fn notice(text: String, cx: &mut App) {
116 if let Some(handle) = cx.try_global::<AppHandle>() {
117 handle
118 .0
119 .clone()
120 .update(cx, |state, cx| state.raise_notice(text, None, cx));
121 }
122}
123
124fn ensure_state(cx: &mut App) {
125 if !cx.has_global::<LinuxUpdates>() {
126 cx.set_global(LinuxUpdates {
127 stage: Stage::Idle,
128 dialog_open: false,
129 declined: None,
130 });
131 }
132}
133
134/// Starts the periodic check. Only the installed copy of a release build updates.
135pub fn start(cx: &mut App) {
136 if crate::linux_install::updatable_release().is_none() {
137 return;
138 }
139 ensure_state(cx);
140 if let Some(running_tag) = crate::linux_install::updatable_release()
141 && let Some(tag) = staged_update(running_tag)
142 {
143 set_stage(Stage::Ready(tag), cx);
144 show_when_window_is_open(cx);
145 }
146 cx.spawn(async move |cx| {
147 cx.background_executor()
148 .timer(release_feed::FIRST_CHECK_DELAY)
149 .await;
150 loop {
151 let waiting = cx.update(|cx| matches!(stage(cx), Stage::Ready(_)));
152 if !waiting && cx.update(|cx| enabled(cx)) {
153 cx.update(|cx| check(false, cx));
154 }
155 cx.background_executor()
156 .timer(release_feed::CHECK_INTERVAL)
157 .await;
158 }
159 })
160 .detach();
161}
162
163/// Looks for a newer release. `manual` (Settings > Check now) also offers a version
164/// declined with "Not now" in this run and reports "up to date" and errors.
165pub fn check(manual: bool, cx: &mut App) {
166 let Some(running_tag) = crate::linux_install::updatable_release() else {
167 if manual {
168 notice(tr("install.updates_need_install"), cx);
169 }
170 return;
171 };
172 ensure_state(cx);
173 match stage(cx) {
174 Stage::Downloading { .. } | Stage::Ready(_) => {
175 open_dialog(cx);
176 return;
177 }
178 Stage::Idle | Stage::Offer(_) | Stage::Failed(_) => {}
179 }
180 if manual {
181 notice(tr("install.update_checking"), cx);
182 }
183 let find = release_feed::find_update(running_tag, cx);
184 cx.spawn(async move |cx| {
185 let found = find.await;
186 cx.update(|cx| match found {
187 Ok(Some(update)) if manual || declined(cx).as_deref() != Some(&update.tag) => {
188 offer(update, cx)
189 }
190 Ok(Some(_)) => {}
191 Ok(None) if manual => notice(tr("install.up_to_date"), cx),
192 Ok(None) => {}
193 Err(error) if manual => {
194 notice(tr_args("install.update_failed", &args("detail", error)), cx)
195 }
196 Err(error) => log::warn!("update check failed: {error}"),
197 });
198 })
199 .detach();
200}
201
202fn offer(update: AvailableUpdate, cx: &mut App) {
203 set_stage(Stage::Offer(update), cx);
204 show_when_window_is_open(cx);
205}
206
207/// Opens the dialog for the current stage, waiting for the main window if it is
208/// closed into the tray.
209fn show_when_window_is_open(cx: &mut App) {
210 cx.spawn(async move |cx| {
211 while cx.update(|cx| crate::main_window::current(cx).is_none()) {
212 cx.background_executor().timer(WINDOW_WAIT).await;
213 }
214 cx.update(|cx| {
215 if matches!(stage(cx), Stage::Offer(_) | Stage::Ready(_)) {
216 open_dialog(cx);
217 }
218 });
219 })
220 .detach();
221}
222
223fn download(update: AvailableUpdate, cx: &mut App) {
224 let Some(paths) = updater::current_paths() else {
225 return;
226 };
227 let progress = Arc::new(AtomicU64::new(0));
228 set_stage(
229 Stage::Downloading {
230 update: update.clone(),
231 progress: progress.clone(),
232 },
233 cx,
234 );
235 let tag = update.tag.clone();
236 let task = release_feed::download_update(update, paths, progress, cx);
237 cx.spawn(async move |cx| {
238 let redraw = cx.spawn(async move |cx| {
239 loop {
240 cx.background_executor().timer(PROGRESS_REDRAW).await;
241 cx.update(|cx| cx.refresh_windows());
242 }
243 });
244 let result = task.await;
245 drop(redraw);
246 cx.update(|cx| {
247 match result {
248 Ok(()) => set_stage(Stage::Ready(tag), cx),
249 Err(error) => {
250 log::warn!("update download failed: {error}");
251 set_stage(Stage::Failed(error), cx);
252 }
253 }
254 open_dialog(cx);
255 });
256 })
257 .detach();
258}
259
260fn restart(cx: &mut App) {
261 let Some(paths) = updater::current_paths() else {
262 return;
263 };
264 match updater::install_and_relaunch(&paths) {
265 Ok(()) => cx.quit(),
266 Err(error) => set_stage(Stage::Failed(error), cx),
267 }
268}
269
270/// Opens the update dialog on the main window unless it is already open. It redraws
271/// from the current stage, so one dialog walks through offer, progress and restart.
272fn open_dialog(cx: &mut App) {
273 let Some(window) = crate::main_window::current(cx) else {
274 return;
275 };
276 if !cx.has_global::<LinuxUpdates>() || cx.global::<LinuxUpdates>().dialog_open {
277 return;
278 }
279 cx.global_mut::<LinuxUpdates>().dialog_open = true;
280 let opened = window.update(cx, |_, window, cx| {
281 window.open_dialog(cx, |dialog: Dialog, _, cx| build_dialog(dialog, cx));
282 });
283 if opened.is_err() {
284 cx.global_mut::<LinuxUpdates>().dialog_open = false;
285 }
286}
287
288fn close_dialog(window: &mut Window, cx: &mut App) {
289 if cx.has_global::<LinuxUpdates>() {
290 cx.global_mut::<LinuxUpdates>().dialog_open = false;
291 }
292 window.close_dialog(cx);
293}
294
295fn percent(progress: &AtomicU64, size: u64) -> u64 {
296 (progress.load(Ordering::Relaxed) * 100)
297 .checked_div(size)
298 .unwrap_or(0)
299 .min(100)
300}
301
302fn build_dialog(dialog: Dialog, cx: &App) -> Dialog {
303 let running = app_base::version::release_tag().unwrap_or_default();
304 let (title, body, footer) = match stage(cx) {
305 Stage::Offer(update) => {
306 let mut text_args = args("version", update.tag.clone());
307 text_args.insert("current".to_owned(), running.to_owned());
308 let tag = update.tag.clone();
309 (
310 tr("install.update_available_title"),
311 tr_args("install.update_available_body", &text_args),
312 DialogFooter::new()
313 .child(
314 Button::new("update-not-now")
315 .label(tr("install.not_now"))
316 .on_click(move |_, window, cx| {
317 decline(&tag, cx);
318 set_stage(Stage::Idle, cx);
319 close_dialog(window, cx);
320 }),
321 )
322 .child(
323 Button::new("update-start")
324 .primary()
325 .label(tr("install.update_now"))
326 .on_click(move |_, _, cx| download(update.clone(), cx)),
327 ),
328 )
329 }
330 Stage::Downloading { update, progress } => {
331 let mut text_args = args("version", update.tag.clone());
332 text_args.insert(
333 "percent".to_owned(),
334 percent(&progress, update.asset.size).to_string(),
335 );
336 (
337 tr("install.update_available_title"),
338 tr_args("install.update_downloading", &text_args),
339 DialogFooter::new().child(
340 Button::new("update-hide")
341 .label(tr("install.hide"))
342 .on_click(|_, window, cx| close_dialog(window, cx)),
343 ),
344 )
345 }
346 Stage::Ready(tag) => (
347 tr("install.update_ready_title"),
348 tr_args("install.update_ready_body", &args("version", tag)),
349 DialogFooter::new()
350 .child(
351 Button::new("update-later")
352 .label(tr("install.later"))
353 .on_click(|_, window, cx| close_dialog(window, cx)),
354 )
355 .child(
356 Button::new("update-restart")
357 .primary()
358 .label(tr("install.restart_now"))
359 .on_click(|_, _, cx| restart(cx)),
360 ),
361 ),
362 Stage::Failed(error) => (
363 tr("install.update_available_title"),
364 tr_args("install.update_failed", &args("detail", error)),
365 DialogFooter::new().child(
366 Button::new("update-close")
367 .label(tr("common.close"))
368 .on_click(|_, window, cx| {
369 set_stage(Stage::Idle, cx);
370 close_dialog(window, cx);
371 }),
372 ),
373 ),
374 Stage::Idle => (String::new(), String::new(), DialogFooter::new()),
375 };
376 // Only the buttons close it, so the stage and the open flag stay in step.
377 dialog
378 .title(title)
379 .w(px(DIALOG_WIDTH))
380 .keyboard(false)
381 .overlay_closable(false)
382 .close_button(false)
383 .child(v_flex().gap(px(8.)).text_color(theme::text()).child(body))
384 .footer(footer)
385}
386
387#[cfg(test)]
388mod tests {
389 use std::sync::atomic::{AtomicU64, Ordering};
390
391 use super::percent;
392
393 #[test]
394 fn percent_is_clamped_and_safe_without_a_size() {
395 let progress = AtomicU64::new(50);
396 assert_eq!(percent(&progress, 200), 25);
397 assert_eq!(percent(&progress, 0), 0);
398 progress.store(500, Ordering::Relaxed);
399 assert_eq!(percent(&progress, 200), 100);
400 }
401}
crates/app/src/main.rs +12 −1
@@ -14,6 +14,10 @@ mod inline_video;
14 14 mod layout_guard;
15 15 #[cfg(any(target_os = "linux", target_os = "macos"))]
16 16 mod linux_browser;
17 #[cfg(target_os = "linux")]
18 mod linux_install;
19 #[cfg(target_os = "linux")]
20 mod linux_update;
17 21 mod main_window;
18 22 pub mod notify;
19 23 mod settings;
@@ -194,6 +198,8 @@ fn main() {
194 198 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
195 199 #[cfg(target_os = "linux")]
196 200 app_base::linux_fonts::hide_system_color_emoji();
201 #[cfg(target_os = "linux")]
202 linux_install::load_icon();
197 203 let arguments = parse_arguments();
198 204 if !arguments.demo && arguments.database.is_none() {
199 205 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
@@ -212,7 +218,7 @@ fn main() {
212 218 return;
213 219 }
214 220 }
215 #[cfg(windows)]
221 #[cfg(any(windows, target_os = "linux"))]
216 222 updater::clean_up_old_binary();
217 223 let mode = Mode {
218 224 demo: arguments.demo,
@@ -356,6 +362,11 @@ fn main() {
356 362 }
357 363 })
358 364 .detach();
365 #[cfg(target_os = "linux")]
366 if !arguments.demo {
367 linux_install::start(cx);
368 linux_update::start(cx);
369 }
359 370 if !arguments.autostart {
360 371 cx.activate(true);
361 372 }
@@ -14,6 +14,10 @@ mod inline_video;
14mod layout_guard;
14mod layout_guard;
15#[cfg(any(target_os = "linux", target_os = "macos"))]
15#[cfg(any(target_os = "linux", target_os = "macos"))]
16mod linux_browser;
16mod linux_browser;
17#[cfg(target_os = "linux")]
18mod linux_install;
19#[cfg(target_os = "linux")]
20mod linux_update;
17mod main_window;
21mod main_window;
18pub mod notify;
22pub mod notify;
19mod settings;
23mod settings;
@@ -194,6 +198,8 @@ fn main() {
194 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
198 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
195 #[cfg(target_os = "linux")]
199 #[cfg(target_os = "linux")]
196 app_base::linux_fonts::hide_system_color_emoji();
200 app_base::linux_fonts::hide_system_color_emoji();
201 #[cfg(target_os = "linux")]
202 linux_install::load_icon();
197 let arguments = parse_arguments();
203 let arguments = parse_arguments();
198 if !arguments.demo && arguments.database.is_none() {
204 if !arguments.demo && arguments.database.is_none() {
199 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
205 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
@@ -212,7 +218,7 @@ fn main() {
212 return;
218 return;
213 }
219 }
214 }
220 }
215 #[cfg(windows)]
221 #[cfg(any(windows, target_os = "linux"))]
216 updater::clean_up_old_binary();
222 updater::clean_up_old_binary();
217 let mode = Mode {
223 let mode = Mode {
218 demo: arguments.demo,
224 demo: arguments.demo,
@@ -356,6 +362,11 @@ fn main() {
356 }
362 }
357 })
363 })
358 .detach();
364 .detach();
365 #[cfg(target_os = "linux")]
366 if !arguments.demo {
367 linux_install::start(cx);
368 linux_update::start(cx);
369 }
359 if !arguments.autostart {
370 if !arguments.autostart {
360 cx.activate(true);
371 cx.activate(true);
361 }
372 }
crates/app/src/notify/center.rs +10 −2
@@ -1223,10 +1223,18 @@ impl NotificationCenter {
1223 1223 .ok();
1224 1224 }
1225 1225
1226 /// Applies the icon again even if the choice is unchanged: its image changed.
1227 pub fn reapply_app_icon(&mut self, cx: &mut Context<Self>) {
1228 self.show_app_icon(active_appearance::current(cx).app_icon, cx);
1229 }
1230
1226 1231 fn apply_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1227 if icon == self.app_icon {
1228 return;
1232 if icon != self.app_icon {
1233 self.show_app_icon(icon, cx);
1229 1234 }
1235 }
1236
1237 fn show_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1230 1238 self.app_icon = icon;
1231 1239 let mention = !self.unread_mentions.is_empty();
1232 1240 if let Some(tray) = &mut self.tray {
@@ -1223,10 +1223,18 @@ impl NotificationCenter {
1223 .ok();
1223 .ok();
1224 }
1224 }
1225
1225
1226 /// Applies the icon again even if the choice is unchanged: its image changed.
1227 pub fn reapply_app_icon(&mut self, cx: &mut Context<Self>) {
1228 self.show_app_icon(active_appearance::current(cx).app_icon, cx);
1229 }
1230
1226 fn apply_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1231 fn apply_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1227 if icon == self.app_icon {
1232 if icon != self.app_icon {
1228 return;
1233 self.show_app_icon(icon, cx);
1229 }
1234 }
1235 }
1236
1237 fn show_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1230 self.app_icon = icon;
1238 self.app_icon = icon;
1231 let mention = !self.unread_mentions.is_empty();
1239 let mention = !self.unread_mentions.is_empty();
1232 if let Some(tray) = &mut self.tray {
1240 if let Some(tray) = &mut self.tray {
crates/app/src/settings/general.rs +92 −0
@@ -79,6 +79,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
79 79 }),
80 80 )
81 81 .children(external_browser_rows(app, cx))
82 .children(install_rows(cx))
82 83 .child(caption(tr("settings.caption.compose_box")))
83 84 .child(account_select(
84 85 app,
@@ -95,6 +96,97 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
95 96 .children(translation_rows(app, cx))
96 97 }
97 98
99 /// Linux only: the application menu install, the install question and updates.
100 fn install_rows(cx: &App) -> Vec<AnyElement> {
101 #[cfg(not(target_os = "linux"))]
102 {
103 let _ = cx;
104 Vec::new()
105 }
106 #[cfg(target_os = "linux")]
107 {
108 use std::collections::HashMap;
109
110 use super::rows::{control_row, text_button};
111 use crate::i18n::tr_args;
112 use crate::linux_install::{self, Installation};
113
114 let with = |key: &str, name: &str, value: String| {
115 let mut args = HashMap::new();
116 args.insert(name.to_owned(), value);
117 tr_args(key, &args)
118 };
119 let folder = linux_install::install_folder();
120 let installation = linux_install::installation();
121 let detail = match installation {
122 Installation::Running => with("install.installed_detail", "folder", folder),
123 Installation::OtherCopy => with("install.other_copy_detail", "folder", folder),
124 Installation::NotInstalled => tr("install.not_installed_detail"),
125 };
126 let mut buttons = h_flex().gap(px(8.)).flex_none();
127 if installation != Installation::Running {
128 let label = match installation {
129 Installation::OtherCopy => tr("install.replace"),
130 _ => tr("install.move"),
131 };
132 buttons = buttons.child(
133 text_button("settings-install", label)
134 .on_click(|_, _, cx| linux_install::install_now(cx)),
135 );
136 }
137 if installation != Installation::NotInstalled {
138 buttons = buttons.child(
139 text_button("settings-install-remove", tr("install.remove"))
140 .on_click(|_, _, cx| linux_install::remove(cx)),
141 );
142 }
143 let mut rows =
144 vec![control_row(tr("install.menu_title"), detail, buttons).into_any_element()];
145 if installation != Installation::Running {
146 let asks = linux_install::asks_on_start(cx);
147 rows.push(
148 toggle_row(
149 "settings-install-ask",
150 tr("install.ask_on_start"),
151 "",
152 theme::text_muted(),
153 asks,
154 )
155 .on_click(move |_, _, cx| linux_install::set_asks_on_start(!asks, cx))
156 .into_any_element(),
157 );
158 }
159 let automatic = crate::linux_update::enabled(cx);
160 rows.push(
161 toggle_row(
162 "settings-auto-updates",
163 tr("install.auto_updates"),
164 tr("install.auto_updates_detail"),
165 theme::text_muted(),
166 automatic,
167 )
168 .on_click(move |_, _, cx| crate::linux_update::set_enabled(!automatic, cx))
169 .into_any_element(),
170 );
171 let version = linux_install::running_release().to_owned();
172 let updates_detail = if linux_install::updatable_release().is_some() {
173 with("install.updates_detail", "version", version)
174 } else {
175 with("install.updates_detail_not_installed", "version", version)
176 };
177 rows.push(
178 control_row(
179 tr("install.updates_title"),
180 updates_detail,
181 text_button("settings-check-updates", tr("install.check_now"))
182 .on_click(|_, _, cx| crate::linux_update::check(true, cx)),
183 )
184 .into_any_element(),
185 );
186 rows
187 }
188 }
189
98 190 fn external_browser_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
99 191 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
100 192 {
@@ -79,6 +79,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
79 }),
79 }),
80 )
80 )
81 .children(external_browser_rows(app, cx))
81 .children(external_browser_rows(app, cx))
82 .children(install_rows(cx))
82 .child(caption(tr("settings.caption.compose_box")))
83 .child(caption(tr("settings.caption.compose_box")))
83 .child(account_select(
84 .child(account_select(
84 app,
85 app,
@@ -95,6 +96,97 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
95 .children(translation_rows(app, cx))
96 .children(translation_rows(app, cx))
96}
97}
97
98
99/// Linux only: the application menu install, the install question and updates.
100fn install_rows(cx: &App) -> Vec<AnyElement> {
101 #[cfg(not(target_os = "linux"))]
102 {
103 let _ = cx;
104 Vec::new()
105 }
106 #[cfg(target_os = "linux")]
107 {
108 use std::collections::HashMap;
109
110 use super::rows::{control_row, text_button};
111 use crate::i18n::tr_args;
112 use crate::linux_install::{self, Installation};
113
114 let with = |key: &str, name: &str, value: String| {
115 let mut args = HashMap::new();
116 args.insert(name.to_owned(), value);
117 tr_args(key, &args)
118 };
119 let folder = linux_install::install_folder();
120 let installation = linux_install::installation();
121 let detail = match installation {
122 Installation::Running => with("install.installed_detail", "folder", folder),
123 Installation::OtherCopy => with("install.other_copy_detail", "folder", folder),
124 Installation::NotInstalled => tr("install.not_installed_detail"),
125 };
126 let mut buttons = h_flex().gap(px(8.)).flex_none();
127 if installation != Installation::Running {
128 let label = match installation {
129 Installation::OtherCopy => tr("install.replace"),
130 _ => tr("install.move"),
131 };
132 buttons = buttons.child(
133 text_button("settings-install", label)
134 .on_click(|_, _, cx| linux_install::install_now(cx)),
135 );
136 }
137 if installation != Installation::NotInstalled {
138 buttons = buttons.child(
139 text_button("settings-install-remove", tr("install.remove"))
140 .on_click(|_, _, cx| linux_install::remove(cx)),
141 );
142 }
143 let mut rows =
144 vec![control_row(tr("install.menu_title"), detail, buttons).into_any_element()];
145 if installation != Installation::Running {
146 let asks = linux_install::asks_on_start(cx);
147 rows.push(
148 toggle_row(
149 "settings-install-ask",
150 tr("install.ask_on_start"),
151 "",
152 theme::text_muted(),
153 asks,
154 )
155 .on_click(move |_, _, cx| linux_install::set_asks_on_start(!asks, cx))
156 .into_any_element(),
157 );
158 }
159 let automatic = crate::linux_update::enabled(cx);
160 rows.push(
161 toggle_row(
162 "settings-auto-updates",
163 tr("install.auto_updates"),
164 tr("install.auto_updates_detail"),
165 theme::text_muted(),
166 automatic,
167 )
168 .on_click(move |_, _, cx| crate::linux_update::set_enabled(!automatic, cx))
169 .into_any_element(),
170 );
171 let version = linux_install::running_release().to_owned();
172 let updates_detail = if linux_install::updatable_release().is_some() {
173 with("install.updates_detail", "version", version)
174 } else {
175 with("install.updates_detail_not_installed", "version", version)
176 };
177 rows.push(
178 control_row(
179 tr("install.updates_title"),
180 updates_detail,
181 text_button("settings-check-updates", tr("install.check_now"))
182 .on_click(|_, _, cx| crate::linux_update::check(true, cx)),
183 )
184 .into_any_element(),
185 );
186 rows
187 }
188}
189
98fn external_browser_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
190fn external_browser_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
99 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
191 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
100 {
192 {
crates/app/src/settings/nav.rs +4 −0
@@ -34,6 +34,10 @@ fn search_terms(section: SettingsSection) -> Vec<String> {
34 34 tr("settings.general.open_in_background"),
35 35 tr("settings.general.close_to_tray"),
36 36 tr("settings.general.external_browser"),
37 #[cfg(target_os = "linux")]
38 tr("install.menu_title"),
39 #[cfg(target_os = "linux")]
40 tr("install.updates_title"),
37 41 tr("settings.general.up_arrow"),
38 42 tr("settings.general.translate_into"),
39 43 tr("settings.general.behavior_title"),
@@ -34,6 +34,10 @@ fn search_terms(section: SettingsSection) -> Vec<String> {
34 tr("settings.general.open_in_background"),
34 tr("settings.general.open_in_background"),
35 tr("settings.general.close_to_tray"),
35 tr("settings.general.close_to_tray"),
36 tr("settings.general.external_browser"),
36 tr("settings.general.external_browser"),
37 #[cfg(target_os = "linux")]
38 tr("install.menu_title"),
39 #[cfg(target_os = "linux")]
40 tr("install.updates_title"),
37 tr("settings.general.up_arrow"),
41 tr("settings.general.up_arrow"),
38 tr("settings.general.translate_into"),
42 tr("settings.general.translate_into"),
39 tr("settings.general.behavior_title"),
43 tr("settings.general.behavior_title"),
crates/app/src/views/shell.rs +13 −3
@@ -176,6 +176,14 @@ struct KeptParts {
176 176
177 177 impl Global for KeptParts {}
178 178
179 /// Re-applies the app icon to the tray and window, e.g. after the Teams icon arrived.
180 pub fn refresh_app_icon(cx: &mut App) {
181 if let Some(kept) = cx.try_global::<KeptParts>().cloned() {
182 kept.notifications
183 .update(cx, |notifications, cx| notifications.reapply_app_icon(cx));
184 }
185 }
186
179 187 pub struct AppShell {
180 188 state: Entity<AppState>,
181 189 rail: Entity<RailView>,
@@ -505,7 +513,7 @@ impl AppShell {
505 513 });
506 514 });
507 515 }
508 #[cfg(windows)]
516 #[cfg(any(windows, target_os = "linux"))]
509 517 cx.spawn_in(window, async move |this, cx| {
510 518 loop {
511 519 cx.background_executor().timer(updater::POLL_INTERVAL).await;
@@ -518,6 +526,7 @@ impl AppShell {
518 526 }
519 527 })
520 528 .detach();
529 // Linux asks before downloading (`linux_update`); Windows downloads quietly.
521 530 #[cfg(windows)]
522 531 if let Some(running_tag) = app_base::version::release_tag() {
523 532 watch_releases(running_tag, cx);
@@ -525,7 +534,7 @@ impl AppShell {
525 534 shell
526 535 }
527 536
528 #[cfg_attr(not(windows), allow(dead_code))]
537 #[cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))]
529 538 fn poll_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
530 539 if matches!(
531 540 self.update,
@@ -551,7 +560,8 @@ impl AppShell {
551 560 composer_empty: conversation.composer_is_empty(cx),
552 561 send_in_flight: conversation.send_in_flight(),
553 562 });
554 if idle {
563 // On Linux only the user restarts: the update dialog or the title bar button.
564 if idle && cfg!(not(target_os = "linux")) {
555 565 self.restart_into_update(cx);
556 566 }
557 567 cx.notify();
@@ -176,6 +176,14 @@ struct KeptParts {
176
176
177impl Global for KeptParts {}
177impl Global for KeptParts {}
178
178
179/// Re-applies the app icon to the tray and window, e.g. after the Teams icon arrived.
180pub fn refresh_app_icon(cx: &mut App) {
181 if let Some(kept) = cx.try_global::<KeptParts>().cloned() {
182 kept.notifications
183 .update(cx, |notifications, cx| notifications.reapply_app_icon(cx));
184 }
185}
186
179pub struct AppShell {
187pub struct AppShell {
180 state: Entity<AppState>,
188 state: Entity<AppState>,
181 rail: Entity<RailView>,
189 rail: Entity<RailView>,
@@ -505,7 +513,7 @@ impl AppShell {
505 });
513 });
506 });
514 });
507 }
515 }
508 #[cfg(windows)]
516 #[cfg(any(windows, target_os = "linux"))]
509 cx.spawn_in(window, async move |this, cx| {
517 cx.spawn_in(window, async move |this, cx| {
510 loop {
518 loop {
511 cx.background_executor().timer(updater::POLL_INTERVAL).await;
519 cx.background_executor().timer(updater::POLL_INTERVAL).await;
@@ -518,6 +526,7 @@ impl AppShell {
518 }
526 }
519 })
527 })
520 .detach();
528 .detach();
529 // Linux asks before downloading (`linux_update`); Windows downloads quietly.
521 #[cfg(windows)]
530 #[cfg(windows)]
522 if let Some(running_tag) = app_base::version::release_tag() {
531 if let Some(running_tag) = app_base::version::release_tag() {
523 watch_releases(running_tag, cx);
532 watch_releases(running_tag, cx);
@@ -525,7 +534,7 @@ impl AppShell {
525 shell
534 shell
526 }
535 }
527
536
528 #[cfg_attr(not(windows), allow(dead_code))]
537 #[cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))]
529 fn poll_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
538 fn poll_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
530 if matches!(
539 if matches!(
531 self.update,
540 self.update,
@@ -551,7 +560,8 @@ impl AppShell {
551 composer_empty: conversation.composer_is_empty(cx),
560 composer_empty: conversation.composer_is_empty(cx),
552 send_in_flight: conversation.send_in_flight(),
561 send_in_flight: conversation.send_in_flight(),
553 });
562 });
554 if idle {
563 // On Linux only the user restarts: the update dialog or the title bar button.
564 if idle && cfg!(not(target_os = "linux")) {
555 self.restart_into_update(cx);
565 self.restart_into_update(cx);
556 }
566 }
557 cx.notify();
567 cx.notify();
docs/decisions/0013-teams-icon-is-downloaded-not-shipped.md added +20 −0
@@ -0,0 +1,20 @@
1 ---
2 status: proposed
3 date: 2026-11-14
4 ---
5
6 # ADR 0013: The Microsoft Teams icon is downloaded on Linux, not shipped
7
8 ## Context
9
10 The "Microsoft Teams" app icon option embeds Microsoft's logo in the binary. For the Linux menu entry and tray we want the real Teams icon, but shipping Microsoft's trademark in our release assets is a risk. The options were: ship the PNG, use an icon theme name (depends on the user's theme), draw a look-alike (worse than either), or let the user's machine fetch the icon from Microsoft.
11
12 ## Decision
13
14 Linux builds do not embed `microsoft-teams-256.png`. On start the app downloads the favicon the Teams web client uses (`teams.public.onecdn.static.microsoft/.../microsoft_teams_logo_refresh_v2025.ico`, with the `<link id="teams-favicon">` of `teams.cloud.microsoft` as fallback) into `~/.local/share/icons/hicolor/<size>/apps/rusty-teams.png`. Once present it is the default app icon unless one was chosen in Appearance. Until then, and offline, the Rusty Teams logo is used. Windows and macOS keep the embedded icon.
15
16 ## Consequences
17
18 - No Microsoft logo in Linux release assets; the icon comes from Microsoft to the user directly.
19 - The first start shows the Rusty Teams logo for a moment; the title bar picks up the Teams icon on the next start.
20 - If Microsoft moves the file and the page stops naming it, the Rusty Teams logo stays.
@@ -0,0 +1,20 @@
1---
2status: proposed
3date: 2026-11-14
4---
5
6# ADR 0013: The Microsoft Teams icon is downloaded on Linux, not shipped
7
8## Context
9
10The "Microsoft Teams" app icon option embeds Microsoft's logo in the binary. For the Linux menu entry and tray we want the real Teams icon, but shipping Microsoft's trademark in our release assets is a risk. The options were: ship the PNG, use an icon theme name (depends on the user's theme), draw a look-alike (worse than either), or let the user's machine fetch the icon from Microsoft.
11
12## Decision
13
14Linux builds do not embed `microsoft-teams-256.png`. On start the app downloads the favicon the Teams web client uses (`teams.public.onecdn.static.microsoft/.../microsoft_teams_logo_refresh_v2025.ico`, with the `<link id="teams-favicon">` of `teams.cloud.microsoft` as fallback) into `~/.local/share/icons/hicolor/<size>/apps/rusty-teams.png`. Once present it is the default app icon unless one was chosen in Appearance. Until then, and offline, the Rusty Teams logo is used. Windows and macOS keep the embedded icon.
15
16## Consequences
17
18- No Microsoft logo in Linux release assets; the icon comes from Microsoft to the user directly.
19- The first start shows the Rusty Teams logo for a moment; the title bar picks up the Teams icon on the next start.
20- If Microsoft moves the file and the page stops naming it, the Rusty Teams logo stays.
docs/decisions/0014-linux-installs-and-updates-itself.md added +22 −0
@@ -0,0 +1,22 @@
1 ---
2 status: proposed
3 date: 2026-11-14
4 ---
5
6 # ADR 0014: The Linux binary installs and updates itself
7
8 ## Context
9
10 The Linux release is a bare binary in a tarball. Users had to copy a `.desktop` file and an icon by hand, and only Windows updated itself from GitHub releases. The options were: an AppImage (FUSE mount on every start, its own update tooling), distro packages (one per distro, repositories to run), or letting the binary install itself into the user's data folder and reuse the Windows updater.
11
12 ## Decision
13
14 On start the binary offers to install itself into `~/.local/share/applications/teams/teams` and writes `~/.local/share/applications/rusty-teams.desktop` (`StartupWMClass=rusty-teams`, matching the window's app id). Build output from a cargo `target/` folder is copied, anything else is moved. "Don't ask again" can be undone in Settings > General, which also has Install, Replace and Remove. The installed copy updates itself from the same GitHub releases as Windows (`release_feed.rs`, `updater.rs`), but always with consent (`linux_update.rs`): when Settings > General > Automatic updates is on (the default), a newer release is offered in a dialog; Update downloads the `rusty-teams-<tag>-linux-amd64` asset with progress and checks size, ELF header and the SHA-256 digest GitHub reports; Restart now swaps the file and relaunches. Not now holds for the running session; the next start asks again. There is no idle restart and no install on quit on Linux: a download left for later is offered again on the next start (Restart now, no second download). Settings > General > Check now runs the same flow on demand. A build compares releases against its release tag, or against the workspace version (kept equal to the latest release) when built locally. Binaries outside the install folder never replace themselves; Settings > General still shows the switch and Check now and explains that the app has to be installed first.
15
16 ## Consequences
17
18 - One binary, no root, no FUSE; menu entry and dock matching work after one click.
19 - Releases must keep publishing the bare `-linux-amd64` binary next to the tarball.
20 - Windows keeps its quiet download and idle restart; the two platforms differ on purpose.
21 - A self-built binary that is installed is offered releases newer than its workspace version; starting a newer build offers to replace the installed one.
22 - System packages (deb, rpm, Flatpak) stay possible and should simply not offer the install.
@@ -0,0 +1,22 @@
1---
2status: proposed
3date: 2026-11-14
4---
5
6# ADR 0014: The Linux binary installs and updates itself
7
8## Context
9
10The Linux release is a bare binary in a tarball. Users had to copy a `.desktop` file and an icon by hand, and only Windows updated itself from GitHub releases. The options were: an AppImage (FUSE mount on every start, its own update tooling), distro packages (one per distro, repositories to run), or letting the binary install itself into the user's data folder and reuse the Windows updater.
11
12## Decision
13
14On start the binary offers to install itself into `~/.local/share/applications/teams/teams` and writes `~/.local/share/applications/rusty-teams.desktop` (`StartupWMClass=rusty-teams`, matching the window's app id). Build output from a cargo `target/` folder is copied, anything else is moved. "Don't ask again" can be undone in Settings > General, which also has Install, Replace and Remove. The installed copy updates itself from the same GitHub releases as Windows (`release_feed.rs`, `updater.rs`), but always with consent (`linux_update.rs`): when Settings > General > Automatic updates is on (the default), a newer release is offered in a dialog; Update downloads the `rusty-teams-<tag>-linux-amd64` asset with progress and checks size, ELF header and the SHA-256 digest GitHub reports; Restart now swaps the file and relaunches. Not now holds for the running session; the next start asks again. There is no idle restart and no install on quit on Linux: a download left for later is offered again on the next start (Restart now, no second download). Settings > General > Check now runs the same flow on demand. A build compares releases against its release tag, or against the workspace version (kept equal to the latest release) when built locally. Binaries outside the install folder never replace themselves; Settings > General still shows the switch and Check now and explains that the app has to be installed first.
15
16## Consequences
17
18- One binary, no root, no FUSE; menu entry and dock matching work after one click.
19- Releases must keep publishing the bare `-linux-amd64` binary next to the tarball.
20- Windows keeps its quiet download and idle restart; the two platforms differ on purpose.
21- A self-built binary that is installed is offered releases newer than its workspace version; starting a newer build offers to replace the installed one.
22- System packages (deb, rpm, Flatpak) stay possible and should simply not offer the install.
docs/decisions/README.md +3 −1
@@ -28,5 +28,7 @@ Statuses: `proposed`, `accepted`, `superseded`.
28 28 | [0010](0010-preferred-external-browser.md) | Preferred browser for links and Google OAuth |
29 29 | [0011](0011-calendar-event-peek.md) | Calendar events open as a Teams-like peek |
30 30 | [0012](0012-linux-close-to-tray-closes-the-window.md) | On Linux, close to tray closes the main window |
31 | [0013](0013-teams-icon-is-downloaded-not-shipped.md) | The Microsoft Teams icon is downloaded on Linux, not shipped |
32 | [0014](0014-linux-installs-and-updates-itself.md) | The Linux binary installs and updates itself |
31 33
32 Records `0001` to `0010` are the decisions already shipped. `0011` stays `proposed` until the calendar-peek pull request merges, `0012` until the Linux tray pull request merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
34 Records `0001` to `0010` are the decisions already shipped. `0011` stays `proposed` until the calendar-peek pull request merges, `0012` to `0014` until the Linux tray and install pull request merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
@@ -28,5 +28,7 @@ Statuses: `proposed`, `accepted`, `superseded`.
28| [0010](0010-preferred-external-browser.md) | Preferred browser for links and Google OAuth |
28| [0010](0010-preferred-external-browser.md) | Preferred browser for links and Google OAuth |
29| [0011](0011-calendar-event-peek.md) | Calendar events open as a Teams-like peek |
29| [0011](0011-calendar-event-peek.md) | Calendar events open as a Teams-like peek |
30| [0012](0012-linux-close-to-tray-closes-the-window.md) | On Linux, close to tray closes the main window |
30| [0012](0012-linux-close-to-tray-closes-the-window.md) | On Linux, close to tray closes the main window |
31| [0013](0013-teams-icon-is-downloaded-not-shipped.md) | The Microsoft Teams icon is downloaded on Linux, not shipped |
32| [0014](0014-linux-installs-and-updates-itself.md) | The Linux binary installs and updates itself |
31
33
32Records `0001` to `0010` are the decisions already shipped. `0011` stays `proposed` until the calendar-peek pull request merges, `0012` until the Linux tray pull request merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
34Records `0001` to `0010` are the decisions already shipped. `0011` stays `proposed` until the calendar-peek pull request merges, `0012` to `0014` until the Linux tray and install pull request merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.