BlueGit

ict rusty-teams

feat(linux): tray, close to tray, self-install and updates

Tray
- StatusNotifierItem tray via ksni (KDE natively, GNOME with AppIndicator):
  left click shows/hides, menu Open, Mute sound, Do not disturb,
  Notifications, Quit; red dot for unread mentions
- Close to tray on Linux closes the main window for real and keeps the app
  running (QuitMode::Explicit); tray, second start or an incoming call open
  a new one. Notifications, call windows and activity outlive the window
  (KeptParts). GPUI cannot hide a Wayland window, see ADR 0012

Install
- On start the binary offers to install itself to
  ~/.local/share/applications/teams/teams and writes
  ~/.local/share/applications/rusty-teams.desktop (StartupWMClass matches
  the window); build output from target/ is copied, anything else moved
- Settings > General (Linux only): Install / Replace with this build /
  Remove, "Ask to install on start" to undo "Don't ask again"

Teams icon
- Linux builds no longer embed the Microsoft logo; it is downloaded from
  Microsoft's CDN into ~/.local/share/icons/hicolor and becomes the default
  app icon unless one was chosen, see ADR 0013

Updates
- The installed Linux copy updates from GitHub releases with consent:
  "Update available" dialog, download with progress, "Restart now"
  swaps the binary and relaunches. "Not now" holds for the session; a
  download left for later is offered again on the next start. No idle
  restart on Linux. Settings > General: "Automatic updates" switch and
  "Check now". Local builds compare against the workspace version
- release_feed/updater: per-platform asset (-linux-amd64), ELF check,
  executable bit, find/download split with progress
- CI publishes the bare rusty-teams-<tag>-linux-amd64 binary next to the
  tarball, see ADR 0014

Autostart and Windows behaviour are unchanged.

metis muharemovic · pushed by metis

Authored 2026-11-14 · 2 weeks ago

Hash
041aa463170a2fe8949a1db7be71c71c6e756eed
Parent
ba8e1484
28 files changed +2230 −100
.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
Cargo.lock +18 −0
@@ -318,6 +318,7 @@ dependencies = [
318 318 "futures-util",
319 319 "gpui-kit",
320 320 "image",
321 "ksni",
321 322 "libc",
322 323 "log",
323 324 "mcp",
@@ -5035,6 +5036,21 @@ dependencies = [
5035 5036 "libc",
5036 5037 ]
5037 5038
5039 [[package]]
5040 name = "ksni"
5041 version = "0.3.7"
5042 source = "registry+https://github.com/rust-lang/crates.io-index"
5043 checksum = "1bcc1cb43797140f74b711f1c4a49f48a7a7429f211c5fb78264e7bcd1e99caf"
5044 dependencies = [
5045 "arc-swap",
5046 "crossbeam-queue",
5047 "futures-util",
5048 "pastey 0.2.3",
5049 "serde",
5050 "tokio",
5051 "zbus",
5052 ]
5053
5038 5054 [[package]]
5039 5055 name = "kurbo"
5040 5056 version = "0.11.3"
@@ -9400,6 +9416,7 @@ dependencies = [
9400 9416 "signal-hook-registry",
9401 9417 "socket2",
9402 9418 "tokio-macros",
9419 "tracing",
9403 9420 "windows-sys 0.61.2",
9404 9421 ]
9405 9422
@@ -11778,6 +11795,7 @@ dependencies = [
11778 11795 "rustix 1.1.5",
11779 11796 "serde",
11780 11797 "serde_repr",
11798 "tokio",
11781 11799 "tracing",
11782 11800 "uds_windows",
11783 11801 "uuid",
@@ -318,6 +318,7 @@ dependencies = [
318 "futures-util",
318 "futures-util",
319 "gpui-kit",
319 "gpui-kit",
320 "image",
320 "image",
321 "ksni",
321 "libc",
322 "libc",
322 "log",
323 "log",
323 "mcp",
324 "mcp",
@@ -5035,6 +5036,21 @@ dependencies = [
5035 "libc",
5036 "libc",
5036]
5037]
5037
5038
5039[[package]]
5040name = "ksni"
5041version = "0.3.7"
5042source = "registry+https://github.com/rust-lang/crates.io-index"
5043checksum = "1bcc1cb43797140f74b711f1c4a49f48a7a7429f211c5fb78264e7bcd1e99caf"
5044dependencies = [
5045 "arc-swap",
5046 "crossbeam-queue",
5047 "futures-util",
5048 "pastey 0.2.3",
5049 "serde",
5050 "tokio",
5051 "zbus",
5052]
5053
5038[[package]]
5054[[package]]
5039name = "kurbo"
5055name = "kurbo"
5040version = "0.11.3"
5056version = "0.11.3"
@@ -9400,6 +9416,7 @@ dependencies = [
9400 "signal-hook-registry",
9416 "signal-hook-registry",
9401 "socket2",
9417 "socket2",
9402 "tokio-macros",
9418 "tokio-macros",
9419 "tracing",
9403 "windows-sys 0.61.2",
9420 "windows-sys 0.61.2",
9404]
9421]
9405
9422
@@ -11778,6 +11795,7 @@ dependencies = [
11778 "rustix 1.1.5",
11795 "rustix 1.1.5",
11779 "serde",
11796 "serde",
11780 "serde_repr",
11797 "serde_repr",
11798 "tokio",
11781 "tracing",
11799 "tracing",
11782 "uds_windows",
11800 "uds_windows",
11783 "uuid",
11801 "uuid",
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. 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. 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 +2 −1
@@ -34,7 +34,8 @@ Feature parity with the Microsoft Teams desktop client.
34 34 | Sign in on Windows through embedded WebView2, single sign-on | Done | |
35 35 | Start from the local cache, no spinner | Done | |
36 36 | Self-update | Done | |
37 | Tray icon, close to tray | 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 |
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 |
@@ -34,7 +34,8 @@ Feature parity with the Microsoft Teams desktop client.
34| Sign in on Windows through embedded WebView2, single sign-on | Done | |
34| Sign in on Windows through embedded WebView2, single sign-on | Done | |
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 | |
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 +2 −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"
@@ -38,6 +38,7 @@ rodio = { version = "0.22", default-features = false, features = ["playback", "m
38 38
39 39 [target.'cfg(target_os = "linux")'.dependencies]
40 40 x11rb = { version = "0.13", features = ["shape"] }
41 ksni = { version = "0.3", features = ["blocking"] }
41 42
42 43 [target.'cfg(windows)'.dependencies]
43 44 libc = "0.2"
@@ -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"
@@ -38,6 +38,7 @@ rodio = { version = "0.22", default-features = false, features = ["playback", "m
38
38
39[target.'cfg(target_os = "linux")'.dependencies]
39[target.'cfg(target_os = "linux")'.dependencies]
40x11rb = { version = "0.13", features = ["shape"] }
40x11rb = { version = "0.13", features = ["shape"] }
41ksni = { version = "0.3", features = ["blocking"] }
41
42
42[target.'cfg(windows)'.dependencies]
43[target.'cfg(windows)'.dependencies]
43libc = "0.2"
44libc = "0.2"
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 added +275 −0
@@ -0,0 +1,275 @@
1 //! Tray icon on Linux through the StatusNotifierItem D-Bus protocol (KDE Plasma
2 //! natively; GNOME with the AppIndicator extension).
3
4 use std::sync::Mutex;
5 use std::sync::mpsc::{Receiver, Sender, channel};
6
7 use ksni::blocking::{Handle, TrayMethods as _};
8 use ksni::menu::{CheckmarkItem, StandardItem};
9 use ksni::{Category, Icon, MenuItem, ToolTip};
10
11 use super::TrayCommand;
12 use crate::linux_desktop::DESKTOP_ID;
13
14 const TRAY_ICON_SIZES: [u32; 3] = [22, 32, 64];
15 const DOT_COLOR: [u8; 4] = [0xef, 0x44, 0x44, 0xff];
16
17 #[derive(Clone)]
18 struct Labels {
19 open: String,
20 mute_sound: String,
21 do_not_disturb: String,
22 notifications: String,
23 quit: String,
24 }
25
26 impl Labels {
27 fn current() -> Labels {
28 let tr = crate::ui_locale::tr;
29 Labels {
30 open: tr("tray.open"),
31 mute_sound: tr("tray.mute_sound"),
32 do_not_disturb: tr("tray.do_not_disturb"),
33 notifications: tr("tray.notifications"),
34 quit: tr("tray.quit"),
35 }
36 }
37 }
38
39 struct Item {
40 commands: Sender<TrayCommand>,
41 labels: Labels,
42 sound_on: bool,
43 do_not_disturb: bool,
44 mention: bool,
45 plain: Vec<Icon>,
46 dotted: Vec<Icon>,
47 }
48
49 impl Item {
50 fn send(&self, command: TrayCommand) {
51 let _ = self.commands.send(command);
52 }
53 }
54
55 /// Escapes the mnemonic underscores of a menu label.
56 fn menu_label(text: &str) -> String {
57 text.replace('_', "__")
58 }
59
60 impl ksni::Tray for Item {
61 fn id(&self) -> String {
62 DESKTOP_ID.to_owned()
63 }
64
65 fn title(&self) -> String {
66 crate::APP_NAME.to_owned()
67 }
68
69 fn category(&self) -> Category {
70 Category::Communications
71 }
72
73 fn icon_pixmap(&self) -> Vec<Icon> {
74 if self.mention {
75 self.dotted.clone()
76 } else {
77 self.plain.clone()
78 }
79 }
80
81 fn tool_tip(&self) -> ToolTip {
82 ToolTip {
83 title: crate::APP_NAME.to_owned(),
84 ..Default::default()
85 }
86 }
87
88 fn activate(&mut self, _x: i32, _y: i32) {
89 self.send(TrayCommand::Toggle);
90 }
91
92 fn menu(&self) -> Vec<MenuItem<Self>> {
93 vec![
94 StandardItem {
95 label: menu_label(&self.labels.open),
96 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Open)),
97 ..Default::default()
98 }
99 .into(),
100 MenuItem::Separator,
101 CheckmarkItem {
102 label: menu_label(&self.labels.mute_sound),
103 checked: !self.sound_on,
104 activate: Box::new(|item: &mut Self| item.send(TrayCommand::ToggleSound)),
105 ..Default::default()
106 }
107 .into(),
108 CheckmarkItem {
109 label: menu_label(&self.labels.do_not_disturb),
110 checked: self.do_not_disturb,
111 activate: Box::new(|item: &mut Self| item.send(TrayCommand::ToggleDoNotDisturb)),
112 ..Default::default()
113 }
114 .into(),
115 StandardItem {
116 label: menu_label(&self.labels.notifications),
117 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Settings)),
118 ..Default::default()
119 }
120 .into(),
121 MenuItem::Separator,
122 StandardItem {
123 label: menu_label(&self.labels.quit),
124 icon_name: "application-exit".into(),
125 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Quit)),
126 ..Default::default()
127 }
128 .into(),
129 ]
130 }
131 }
132
133 pub struct Tray {
134 handle: Handle<Item>,
135 commands: Mutex<Receiver<TrayCommand>>,
136 }
137
138 impl Tray {
139 /// `None` when there is no session bus or no tray host (no StatusNotifierWatcher).
140 pub fn new(sound_on: bool, do_not_disturb: bool, icon_png: &[u8]) -> Option<Self> {
141 let (plain, dotted) = tray_icons(icon_png)?;
142 let (sender, receiver) = channel();
143 let item = Item {
144 commands: sender,
145 labels: Labels::current(),
146 sound_on,
147 do_not_disturb,
148 mention: false,
149 plain,
150 dotted,
151 };
152 let handle = match item.spawn() {
153 Ok(handle) => handle,
154 Err(error) => {
155 log::warn!("no tray icon: {error}");
156 return None;
157 }
158 };
159 Some(Tray {
160 handle,
161 commands: Mutex::new(receiver),
162 })
163 }
164
165 pub fn relocalize(&self) {
166 let labels = Labels::current();
167 self.handle.update(move |item| item.labels = labels);
168 }
169
170 pub fn poll(&self) -> Vec<TrayCommand> {
171 let Ok(receiver) = self.commands.lock() else {
172 return Vec::new();
173 };
174 receiver.try_iter().collect()
175 }
176
177 pub fn set_app_icon(&mut self, icon_png: &[u8], mention: bool) {
178 let Some((plain, dotted)) = tray_icons(icon_png) else {
179 return;
180 };
181 self.handle.update(move |item| {
182 item.plain = plain;
183 item.dotted = dotted;
184 item.mention = mention;
185 });
186 }
187
188 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
189 let labels = Labels::current();
190 self.handle.update(move |item| {
191 item.labels = labels;
192 item.sound_on = sound_on;
193 item.do_not_disturb = do_not_disturb;
194 item.mention = mention;
195 });
196 }
197 }
198
199 impl Drop for Tray {
200 fn drop(&mut self) {
201 let _ = self.handle.shutdown();
202 }
203 }
204
205 /// The icon in every tray size, plain and with the unread dot, as ARGB32 big endian.
206 fn tray_icons(icon_png: &[u8]) -> Option<(Vec<Icon>, Vec<Icon>)> {
207 let decoded = image::load_from_memory(icon_png).ok()?;
208 let mut plain = Vec::new();
209 let mut dotted = Vec::new();
210 for size in TRAY_ICON_SIZES {
211 let resized = decoded
212 .resize_exact(size, size, image::imageops::FilterType::Lanczos3)
213 .to_rgba8();
214 let mut with_dot = resized.clone();
215 let radius = size as f32 * 0.22;
216 let center = size as f32 - radius - 0.5;
217 for (column, row, pixel) in with_dot.enumerate_pixels_mut() {
218 let distance = ((column as f32 + 0.5 - center).powi(2)
219 + (row as f32 + 0.5 - center).powi(2))
220 .sqrt();
221 if distance <= radius {
222 *pixel = image::Rgba(DOT_COLOR);
223 }
224 }
225 plain.push(argb_icon(size, resized.as_raw()));
226 dotted.push(argb_icon(size, with_dot.as_raw()));
227 }
228 Some((plain, dotted))
229 }
230
231 fn argb_icon(size: u32, rgba: &[u8]) -> Icon {
232 let data = rgba
233 .chunks_exact(4)
234 .flat_map(|pixel| [pixel[3], pixel[0], pixel[1], pixel[2]])
235 .collect();
236 Icon {
237 width: size as i32,
238 height: size as i32,
239 data,
240 }
241 }
242
243 #[cfg(test)]
244 mod tests {
245 use super::*;
246
247 #[test]
248 fn icons_come_in_every_size_as_argb() {
249 let png = crate::appearance::AppIcon::RustyTeams.png();
250 let (plain, dotted) = tray_icons(png).unwrap();
251 assert_eq!(plain.len(), TRAY_ICON_SIZES.len());
252 for (icon, size) in plain.iter().zip(TRAY_ICON_SIZES) {
253 assert_eq!((icon.width, icon.height), (size as i32, size as i32));
254 assert_eq!(icon.data.len(), (size * size * 4) as usize);
255 }
256 let last = dotted.last().unwrap();
257 let bottom_right = last.data.len() - 4 * (last.width as usize * 12 + 12);
258 assert_eq!(
259 &last.data[bottom_right..bottom_right + 4],
260 &[0xff, 0xef, 0x44, 0x44]
261 );
262 assert!(tray_icons(b"not a png").is_none());
263 }
264
265 #[test]
266 fn argb_moves_alpha_first() {
267 let icon = argb_icon(1, &[1, 2, 3, 4]);
268 assert_eq!(icon.data, vec![4, 1, 2, 3]);
269 }
270
271 #[test]
272 fn underscores_stay_visible_in_menu_labels() {
273 assert_eq!(menu_label("Do_not_disturb"), "Do__not__disturb");
274 }
275 }
@@ -0,0 +1,275 @@
1//! Tray icon on Linux through the StatusNotifierItem D-Bus protocol (KDE Plasma
2//! natively; GNOME with the AppIndicator extension).
3
4use std::sync::Mutex;
5use std::sync::mpsc::{Receiver, Sender, channel};
6
7use ksni::blocking::{Handle, TrayMethods as _};
8use ksni::menu::{CheckmarkItem, StandardItem};
9use ksni::{Category, Icon, MenuItem, ToolTip};
10
11use super::TrayCommand;
12use crate::linux_desktop::DESKTOP_ID;
13
14const TRAY_ICON_SIZES: [u32; 3] = [22, 32, 64];
15const DOT_COLOR: [u8; 4] = [0xef, 0x44, 0x44, 0xff];
16
17#[derive(Clone)]
18struct Labels {
19 open: String,
20 mute_sound: String,
21 do_not_disturb: String,
22 notifications: String,
23 quit: String,
24}
25
26impl Labels {
27 fn current() -> Labels {
28 let tr = crate::ui_locale::tr;
29 Labels {
30 open: tr("tray.open"),
31 mute_sound: tr("tray.mute_sound"),
32 do_not_disturb: tr("tray.do_not_disturb"),
33 notifications: tr("tray.notifications"),
34 quit: tr("tray.quit"),
35 }
36 }
37}
38
39struct Item {
40 commands: Sender<TrayCommand>,
41 labels: Labels,
42 sound_on: bool,
43 do_not_disturb: bool,
44 mention: bool,
45 plain: Vec<Icon>,
46 dotted: Vec<Icon>,
47}
48
49impl Item {
50 fn send(&self, command: TrayCommand) {
51 let _ = self.commands.send(command);
52 }
53}
54
55/// Escapes the mnemonic underscores of a menu label.
56fn menu_label(text: &str) -> String {
57 text.replace('_', "__")
58}
59
60impl ksni::Tray for Item {
61 fn id(&self) -> String {
62 DESKTOP_ID.to_owned()
63 }
64
65 fn title(&self) -> String {
66 crate::APP_NAME.to_owned()
67 }
68
69 fn category(&self) -> Category {
70 Category::Communications
71 }
72
73 fn icon_pixmap(&self) -> Vec<Icon> {
74 if self.mention {
75 self.dotted.clone()
76 } else {
77 self.plain.clone()
78 }
79 }
80
81 fn tool_tip(&self) -> ToolTip {
82 ToolTip {
83 title: crate::APP_NAME.to_owned(),
84 ..Default::default()
85 }
86 }
87
88 fn activate(&mut self, _x: i32, _y: i32) {
89 self.send(TrayCommand::Toggle);
90 }
91
92 fn menu(&self) -> Vec<MenuItem<Self>> {
93 vec![
94 StandardItem {
95 label: menu_label(&self.labels.open),
96 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Open)),
97 ..Default::default()
98 }
99 .into(),
100 MenuItem::Separator,
101 CheckmarkItem {
102 label: menu_label(&self.labels.mute_sound),
103 checked: !self.sound_on,
104 activate: Box::new(|item: &mut Self| item.send(TrayCommand::ToggleSound)),
105 ..Default::default()
106 }
107 .into(),
108 CheckmarkItem {
109 label: menu_label(&self.labels.do_not_disturb),
110 checked: self.do_not_disturb,
111 activate: Box::new(|item: &mut Self| item.send(TrayCommand::ToggleDoNotDisturb)),
112 ..Default::default()
113 }
114 .into(),
115 StandardItem {
116 label: menu_label(&self.labels.notifications),
117 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Settings)),
118 ..Default::default()
119 }
120 .into(),
121 MenuItem::Separator,
122 StandardItem {
123 label: menu_label(&self.labels.quit),
124 icon_name: "application-exit".into(),
125 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Quit)),
126 ..Default::default()
127 }
128 .into(),
129 ]
130 }
131}
132
133pub struct Tray {
134 handle: Handle<Item>,
135 commands: Mutex<Receiver<TrayCommand>>,
136}
137
138impl Tray {
139 /// `None` when there is no session bus or no tray host (no StatusNotifierWatcher).
140 pub fn new(sound_on: bool, do_not_disturb: bool, icon_png: &[u8]) -> Option<Self> {
141 let (plain, dotted) = tray_icons(icon_png)?;
142 let (sender, receiver) = channel();
143 let item = Item {
144 commands: sender,
145 labels: Labels::current(),
146 sound_on,
147 do_not_disturb,
148 mention: false,
149 plain,
150 dotted,
151 };
152 let handle = match item.spawn() {
153 Ok(handle) => handle,
154 Err(error) => {
155 log::warn!("no tray icon: {error}");
156 return None;
157 }
158 };
159 Some(Tray {
160 handle,
161 commands: Mutex::new(receiver),
162 })
163 }
164
165 pub fn relocalize(&self) {
166 let labels = Labels::current();
167 self.handle.update(move |item| item.labels = labels);
168 }
169
170 pub fn poll(&self) -> Vec<TrayCommand> {
171 let Ok(receiver) = self.commands.lock() else {
172 return Vec::new();
173 };
174 receiver.try_iter().collect()
175 }
176
177 pub fn set_app_icon(&mut self, icon_png: &[u8], mention: bool) {
178 let Some((plain, dotted)) = tray_icons(icon_png) else {
179 return;
180 };
181 self.handle.update(move |item| {
182 item.plain = plain;
183 item.dotted = dotted;
184 item.mention = mention;
185 });
186 }
187
188 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
189 let labels = Labels::current();
190 self.handle.update(move |item| {
191 item.labels = labels;
192 item.sound_on = sound_on;
193 item.do_not_disturb = do_not_disturb;
194 item.mention = mention;
195 });
196 }
197}
198
199impl Drop for Tray {
200 fn drop(&mut self) {
201 let _ = self.handle.shutdown();
202 }
203}
204
205/// The icon in every tray size, plain and with the unread dot, as ARGB32 big endian.
206fn tray_icons(icon_png: &[u8]) -> Option<(Vec<Icon>, Vec<Icon>)> {
207 let decoded = image::load_from_memory(icon_png).ok()?;
208 let mut plain = Vec::new();
209 let mut dotted = Vec::new();
210 for size in TRAY_ICON_SIZES {
211 let resized = decoded
212 .resize_exact(size, size, image::imageops::FilterType::Lanczos3)
213 .to_rgba8();
214 let mut with_dot = resized.clone();
215 let radius = size as f32 * 0.22;
216 let center = size as f32 - radius - 0.5;
217 for (column, row, pixel) in with_dot.enumerate_pixels_mut() {
218 let distance = ((column as f32 + 0.5 - center).powi(2)
219 + (row as f32 + 0.5 - center).powi(2))
220 .sqrt();
221 if distance <= radius {
222 *pixel = image::Rgba(DOT_COLOR);
223 }
224 }
225 plain.push(argb_icon(size, resized.as_raw()));
226 dotted.push(argb_icon(size, with_dot.as_raw()));
227 }
228 Some((plain, dotted))
229}
230
231fn argb_icon(size: u32, rgba: &[u8]) -> Icon {
232 let data = rgba
233 .chunks_exact(4)
234 .flat_map(|pixel| [pixel[3], pixel[0], pixel[1], pixel[2]])
235 .collect();
236 Icon {
237 width: size as i32,
238 height: size as i32,
239 data,
240 }
241}
242
243#[cfg(test)]
244mod tests {
245 use super::*;
246
247 #[test]
248 fn icons_come_in_every_size_as_argb() {
249 let png = crate::appearance::AppIcon::RustyTeams.png();
250 let (plain, dotted) = tray_icons(png).unwrap();
251 assert_eq!(plain.len(), TRAY_ICON_SIZES.len());
252 for (icon, size) in plain.iter().zip(TRAY_ICON_SIZES) {
253 assert_eq!((icon.width, icon.height), (size as i32, size as i32));
254 assert_eq!(icon.data.len(), (size * size * 4) as usize);
255 }
256 let last = dotted.last().unwrap();
257 let bottom_right = last.data.len() - 4 * (last.width as usize * 12 + 12);
258 assert_eq!(
259 &last.data[bottom_right..bottom_right + 4],
260 &[0xff, 0xef, 0x44, 0x44]
261 );
262 assert!(tray_icons(b"not a png").is_none());
263 }
264
265 #[test]
266 fn argb_moves_alpha_first() {
267 let icon = argb_icon(1, &[1, 2, 3, 4]);
268 assert_eq!(icon.data, vec![4, 1, 2, 3]);
269 }
270
271 #[test]
272 fn underscores_stay_visible_in_menu_labels() {
273 assert_eq!(menu_label("Do_not_disturb"), "Do__not__disturb");
274 }
275}
crates/app-base/src/notify/platform/mod.rs +4 −0
@@ -5,10 +5,14 @@ pub use windows_impl::*;
5 5
6 6 #[cfg(any(target_os = "linux", target_os = "macos"))]
7 7 mod linux_sound;
8 #[cfg(target_os = "linux")]
9 mod linux_tray;
8 10 #[cfg(not(windows))]
9 11 mod stub;
10 12 #[cfg(target_os = "linux")]
11 13 mod x11_input;
14 #[cfg(target_os = "linux")]
15 pub use linux_tray::Tray;
12 16 #[cfg(not(windows))]
13 17 pub use stub::*;
14 18
@@ -5,10 +5,14 @@ pub use windows_impl::*;
5
5
6#[cfg(any(target_os = "linux", target_os = "macos"))]
6#[cfg(any(target_os = "linux", target_os = "macos"))]
7mod linux_sound;
7mod linux_sound;
8#[cfg(target_os = "linux")]
9mod linux_tray;
8#[cfg(not(windows))]
10#[cfg(not(windows))]
9mod stub;
11mod stub;
10#[cfg(target_os = "linux")]
12#[cfg(target_os = "linux")]
11mod x11_input;
13mod x11_input;
14#[cfg(target_os = "linux")]
15pub use linux_tray::Tray;
12#[cfg(not(windows))]
16#[cfg(not(windows))]
13pub use stub::*;
17pub use stub::*;
14
18
crates/app-base/src/notify/platform/stub.rs +5 −1
@@ -7,7 +7,9 @@ use gpui_kit::Window;
7 7
8 8 use calling::ShareKind;
9 9
10 use super::{NativeHandle, ScreenRect, ShareGeometry, TrayCommand, WorkArea};
10 #[cfg(not(target_os = "linux"))]
11 use super::TrayCommand;
12 use super::{NativeHandle, ScreenRect, ShareGeometry, WorkArea};
11 13 use crate::notify::badge::Badge;
12 14
13 15 pub fn native_handle(_window: &Window) -> Option<NativeHandle> {
@@ -103,8 +105,10 @@ pub fn play_mp3(_bytes: Vec<u8>) {}
103 105 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
104 106 pub fn play_mp3_until(_bytes: Vec<u8>, _looped: bool, _stop: Arc<AtomicBool>) {}
105 107
108 #[cfg(not(target_os = "linux"))]
106 109 pub struct Tray;
107 110
111 #[cfg(not(target_os = "linux"))]
108 112 impl Tray {
109 113 pub fn new(_sound_on: bool, _do_not_disturb: bool, _icon_png: &[u8]) -> Option<Self> {
110 114 None
@@ -7,7 +7,9 @@ use gpui_kit::Window;
7
7
8use calling::ShareKind;
8use calling::ShareKind;
9
9
10use super::{NativeHandle, ScreenRect, ShareGeometry, TrayCommand, WorkArea};
10#[cfg(not(target_os = "linux"))]
11use super::TrayCommand;
12use super::{NativeHandle, ScreenRect, ShareGeometry, WorkArea};
11use crate::notify::badge::Badge;
13use crate::notify::badge::Badge;
12
14
13pub fn native_handle(_window: &Window) -> Option<NativeHandle> {
15pub fn native_handle(_window: &Window) -> Option<NativeHandle> {
@@ -103,8 +105,10 @@ pub fn play_mp3(_bytes: Vec<u8>) {}
103#[cfg(not(any(target_os = "linux", target_os = "macos")))]
105#[cfg(not(any(target_os = "linux", target_os = "macos")))]
104pub fn play_mp3_until(_bytes: Vec<u8>, _looped: bool, _stop: Arc<AtomicBool>) {}
106pub fn play_mp3_until(_bytes: Vec<u8>, _looped: bool, _stop: Arc<AtomicBool>) {}
105
107
108#[cfg(not(target_os = "linux"))]
106pub struct Tray;
109pub struct Tray;
107
110
111#[cfg(not(target_os = "linux"))]
108impl Tray {
112impl Tray {
109 pub fn new(_sound_on: bool, _do_not_disturb: bool, _icon_png: &[u8]) -> Option<Self> {
113 pub fn new(_sound_on: bool, _do_not_disturb: bool, _icon_png: &[u8]) -> Option<Self> {
110 None
114 None
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-state/src/activity/service.rs +5 −0
@@ -155,6 +155,11 @@ impl ActivityCenter {
155 155 .map(|selection| selection.conversation_id().to_owned())
156 156 }
157 157
158 /// Points at a main window reopened from the tray.
159 pub fn attach_main_window(&mut self, window: &Window) {
160 self.main_window = window.window_handle();
161 }
162
158 163 fn in_foreground(&self, conversation_id: &str, cx: &mut Context<Self>) -> bool {
159 164 self.selected_conversation(cx).as_deref() == Some(conversation_id)
160 165 && self
@@ -155,6 +155,11 @@ impl ActivityCenter {
155 .map(|selection| selection.conversation_id().to_owned())
155 .map(|selection| selection.conversation_id().to_owned())
156 }
156 }
157
157
158 /// Points at a main window reopened from the tray.
159 pub fn attach_main_window(&mut self, window: &Window) {
160 self.main_window = window.window_handle();
161 }
162
158 fn in_foreground(&self, conversation_id: &str, cx: &mut Context<Self>) -> bool {
163 fn in_foreground(&self, conversation_id: &str, cx: &mut Context<Self>) -> bool {
159 self.selected_conversation(cx).as_deref() == Some(conversation_id)
164 self.selected_conversation(cx).as_deref() == Some(conversation_id)
160 && self
165 && self
crates/app/src/call/overlay.rs +5 −0
@@ -168,6 +168,11 @@ fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
168 168 }
169 169
170 170 impl CallWindows {
171 /// Points at a main window reopened from the tray.
172 pub fn attach_main_window(&mut self, window: &Window) {
173 self.main_native = platform::native_handle(window);
174 }
175
171 176 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
172 177 let saved_position = |key: &str, cx: &App| {
173 178 app.read(cx)
@@ -168,6 +168,11 @@ fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
168}
168}
169
169
170impl CallWindows {
170impl CallWindows {
171 /// Points at a main window reopened from the tray.
172 pub fn attach_main_window(&mut self, window: &Window) {
173 self.main_native = platform::native_handle(window);
174 }
175
171 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
176 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
172 let saved_position = |key: &str, cx: &App| {
177 let saved_position = |key: &str, cx: &App| {
173 app.read(cx)
178 app.read(cx)
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 +58 −22
@@ -14,6 +14,11 @@ 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;
21 mod main_window;
17 22 pub mod notify;
18 23 mod settings;
19 24 mod views;
@@ -154,6 +159,18 @@ fn transport(
154 159 ))
155 160 }
156 161
162 fn main_window_options(cx: &App) -> WindowOptions {
163 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
164 let mut options = TitleBar::window_options();
165 options.window_bounds = Some(WindowBounds::Windowed(bounds));
166 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
167 options.app_id = Some(LINUX_APP_ID.to_owned());
168 if let Some(titlebar) = options.titlebar.as_mut() {
169 titlebar.title = Some(APP_NAME.into());
170 }
171 options
172 }
173
157 174 const STORE_OPEN_ATTEMPTS: u32 = 20;
158 175 const STORE_OPEN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
159 176
@@ -181,6 +198,8 @@ fn main() {
181 198 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
182 199 #[cfg(target_os = "linux")]
183 200 app_base::linux_fonts::hide_system_color_emoji();
201 #[cfg(target_os = "linux")]
202 linux_install::load_icon();
184 203 let arguments = parse_arguments();
185 204 if !arguments.demo && arguments.database.is_none() {
186 205 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
@@ -199,7 +218,7 @@ fn main() {
199 218 return;
200 219 }
201 220 }
202 #[cfg(windows)]
221 #[cfg(any(windows, target_os = "linux"))]
203 222 updater::clean_up_old_binary();
204 223 let mode = Mode {
205 224 demo: arguments.demo,
@@ -305,32 +324,49 @@ fn main() {
305 324 .detach();
306 325 }
307 326
308 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
309 let mut options = TitleBar::window_options();
310 options.window_bounds = Some(WindowBounds::Windowed(bounds));
311 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
312 options.app_id = Some(LINUX_APP_ID.to_owned());
313 if let Some(titlebar) = options.titlebar.as_mut() {
314 titlebar.title = Some(APP_NAME.into());
315 }
316 let open_target = arguments.open_target;
317 let startup = Startup {
318 switcher_query: arguments.switcher_query,
319 composer_text: arguments.composer_text,
320 reply_to_last: arguments.reply_to_last,
321 launched_by_autostart: arguments.autostart,
322 };
323 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
324 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
325 })
327 // The main window decides when to quit (see `main_window`): closing it into
328 // the tray leaves the app running without windows.
329 cx.set_quit_mode(QuitMode::Explicit);
330 // The command line only applies to the first window, not to one reopened from the tray.
331 let first_open = std::cell::Cell::new(Some((
332 arguments.open_target,
333 Startup {
334 switcher_query: arguments.switcher_query,
335 composer_text: arguments.composer_text,
336 reply_to_last: arguments.reply_to_last,
337 launched_by_autostart: arguments.autostart,
338 },
339 )));
340 main_window::install(
341 move |cx| {
342 let (open_target, startup) = first_open.take().unwrap_or_default();
343 let state = state.clone();
344 let opened =
345 gpui_kit::open_window(main_window_options(cx), cx, move |window, cx| {
346 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
347 });
348 match opened {
349 Ok((handle, _)) => Some(handle.into()),
350 Err(error) => {
351 log::error!("failed to open the main window: {error}");
352 None
353 }
354 }
355 },
356 cx,
357 )
326 358 .expect("failed to open window");
327 let main_window_id = main_window.window_id();
328 cx.on_window_closed(move |cx, closed| {
329 if closed == main_window_id {
359 cx.on_window_closed(|cx, closed| {
360 if main_window::note_closed(closed, cx) {
330 361 cx.quit();
331 362 }
332 363 })
333 364 .detach();
365 #[cfg(target_os = "linux")]
366 if !arguments.demo {
367 linux_install::start(cx);
368 linux_update::start(cx);
369 }
334 370 if !arguments.autostart {
335 371 cx.activate(true);
336 372 }
@@ -14,6 +14,11 @@ 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;
21mod main_window;
17pub mod notify;
22pub mod notify;
18mod settings;
23mod settings;
19mod views;
24mod views;
@@ -154,6 +159,18 @@ fn transport(
154 ))
159 ))
155}
160}
156
161
162fn main_window_options(cx: &App) -> WindowOptions {
163 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
164 let mut options = TitleBar::window_options();
165 options.window_bounds = Some(WindowBounds::Windowed(bounds));
166 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
167 options.app_id = Some(LINUX_APP_ID.to_owned());
168 if let Some(titlebar) = options.titlebar.as_mut() {
169 titlebar.title = Some(APP_NAME.into());
170 }
171 options
172}
173
157const STORE_OPEN_ATTEMPTS: u32 = 20;
174const STORE_OPEN_ATTEMPTS: u32 = 20;
158const STORE_OPEN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
175const STORE_OPEN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
159
176
@@ -181,6 +198,8 @@ fn main() {
181 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
198 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
182 #[cfg(target_os = "linux")]
199 #[cfg(target_os = "linux")]
183 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();
184 let arguments = parse_arguments();
203 let arguments = parse_arguments();
185 if !arguments.demo && arguments.database.is_none() {
204 if !arguments.demo && arguments.database.is_none() {
186 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
205 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
@@ -199,7 +218,7 @@ fn main() {
199 return;
218 return;
200 }
219 }
201 }
220 }
202 #[cfg(windows)]
221 #[cfg(any(windows, target_os = "linux"))]
203 updater::clean_up_old_binary();
222 updater::clean_up_old_binary();
204 let mode = Mode {
223 let mode = Mode {
205 demo: arguments.demo,
224 demo: arguments.demo,
@@ -305,32 +324,49 @@ fn main() {
305 .detach();
324 .detach();
306 }
325 }
307
326
308 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
327 // The main window decides when to quit (see `main_window`): closing it into
309 let mut options = TitleBar::window_options();
328 // the tray leaves the app running without windows.
310 options.window_bounds = Some(WindowBounds::Windowed(bounds));
329 cx.set_quit_mode(QuitMode::Explicit);
311 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
330 // The command line only applies to the first window, not to one reopened from the tray.
312 options.app_id = Some(LINUX_APP_ID.to_owned());
331 let first_open = std::cell::Cell::new(Some((
313 if let Some(titlebar) = options.titlebar.as_mut() {
332 arguments.open_target,
314 titlebar.title = Some(APP_NAME.into());
333 Startup {
315 }
334 switcher_query: arguments.switcher_query,
316 let open_target = arguments.open_target;
335 composer_text: arguments.composer_text,
317 let startup = Startup {
336 reply_to_last: arguments.reply_to_last,
318 switcher_query: arguments.switcher_query,
337 launched_by_autostart: arguments.autostart,
319 composer_text: arguments.composer_text,
338 },
320 reply_to_last: arguments.reply_to_last,
339 )));
321 launched_by_autostart: arguments.autostart,
340 main_window::install(
322 };
341 move |cx| {
323 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
342 let (open_target, startup) = first_open.take().unwrap_or_default();
324 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
343 let state = state.clone();
325 })
344 let opened =
345 gpui_kit::open_window(main_window_options(cx), cx, move |window, cx| {
346 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
347 });
348 match opened {
349 Ok((handle, _)) => Some(handle.into()),
350 Err(error) => {
351 log::error!("failed to open the main window: {error}");
352 None
353 }
354 }
355 },
356 cx,
357 )
326 .expect("failed to open window");
358 .expect("failed to open window");
327 let main_window_id = main_window.window_id();
359 cx.on_window_closed(|cx, closed| {
328 cx.on_window_closed(move |cx, closed| {
360 if main_window::note_closed(closed, cx) {
329 if closed == main_window_id {
330 cx.quit();
361 cx.quit();
331 }
362 }
332 })
363 })
333 .detach();
364 .detach();
365 #[cfg(target_os = "linux")]
366 if !arguments.demo {
367 linux_install::start(cx);
368 linux_update::start(cx);
369 }
334 if !arguments.autostart {
370 if !arguments.autostart {
335 cx.activate(true);
371 cx.activate(true);
336 }
372 }
crates/app/src/main_window.rs added +114 −0
@@ -0,0 +1,114 @@
1 //! Owns the main window so it can be closed into the tray and opened again.
2 //!
3 //! GPUI cannot hide a window on Wayland, so on Linux "close to tray" really closes
4 //! the main window while the app (tray, notifications, calls) keeps running; the tray
5 //! or a second start opens a fresh one. Windows hides the window natively instead.
6
7 use std::rc::Rc;
8
9 use gpui_kit::*;
10
11 type Opener = Rc<dyn Fn(&mut App) -> Option<AnyWindowHandle>>;
12
13 pub struct MainWindow {
14 handle: Option<AnyWindowHandle>,
15 open: Opener,
16 hiding: bool,
17 }
18
19 impl Global for MainWindow {}
20
21 /// Opens the first main window with `open` and remembers how to open the next one.
22 pub fn install(
23 open: impl Fn(&mut App) -> Option<AnyWindowHandle> + 'static,
24 cx: &mut App,
25 ) -> Option<AnyWindowHandle> {
26 let open: Opener = Rc::new(open);
27 cx.set_global(MainWindow {
28 handle: None,
29 open: open.clone(),
30 hiding: false,
31 });
32 let handle = open(cx);
33 cx.global_mut::<MainWindow>().handle = handle;
34 handle
35 }
36
37 fn main_mut(cx: &mut App) -> Option<&mut MainWindow> {
38 cx.has_global::<MainWindow>()
39 .then(|| cx.global_mut::<MainWindow>())
40 }
41
42 pub fn current(cx: &App) -> Option<AnyWindowHandle> {
43 cx.try_global::<MainWindow>().and_then(|main| main.handle)
44 }
45
46 /// The next close of the main window goes to the tray instead of quitting.
47 pub fn mark_hiding(cx: &mut App) {
48 if let Some(main) = main_mut(cx) {
49 main.hiding = true;
50 }
51 }
52
53 /// Closes the main window into the tray. Deferred: the window's views may be on the stack.
54 pub fn hide(cx: &mut App) {
55 let Some(handle) = current(cx) else {
56 return;
57 };
58 mark_hiding(cx);
59 cx.defer(move |cx| {
60 if handle
61 .update(cx, |_, window, _| window.remove_window())
62 .is_err()
63 {
64 note_closed(handle.window_id(), cx);
65 }
66 });
67 }
68
69 /// Brings the main window to the front, opening a new one if it was closed into the tray.
70 /// Deferred: building the shell updates entities that may be on the stack.
71 pub fn show(cx: &mut App) {
72 cx.defer(|cx| {
73 if let Some(handle) = current(cx)
74 && handle
75 .update(cx, |_, window, _| window.activate_window())
76 .is_ok()
77 {
78 return;
79 }
80 let Some(open) = cx.try_global::<MainWindow>().map(|main| main.open.clone()) else {
81 return;
82 };
83 let handle = open(cx);
84 if let Some(main) = main_mut(cx) {
85 main.handle = handle;
86 main.hiding = false;
87 }
88 if let Some(handle) = handle {
89 handle
90 .update(cx, |_, window, _| window.activate_window())
91 .ok();
92 }
93 cx.activate(true);
94 });
95 }
96
97 /// Call from `on_window_closed`. Returns true when the app should quit: the main
98 /// window closed and it was not closed into the tray.
99 pub fn note_closed(window_id: WindowId, cx: &mut App) -> bool {
100 let Some(main) = main_mut(cx) else {
101 return false;
102 };
103 if main.handle.map(|handle| handle.window_id()) != Some(window_id) {
104 return false;
105 }
106 main.handle = None;
107 !std::mem::take(&mut main.hiding)
108 }
109
110 /// Whether the main window is currently closed into the tray.
111 pub fn is_hidden(cx: &App) -> bool {
112 cx.try_global::<MainWindow>()
113 .is_some_and(|main| main.handle.is_none())
114 }
@@ -0,0 +1,114 @@
1//! Owns the main window so it can be closed into the tray and opened again.
2//!
3//! GPUI cannot hide a window on Wayland, so on Linux "close to tray" really closes
4//! the main window while the app (tray, notifications, calls) keeps running; the tray
5//! or a second start opens a fresh one. Windows hides the window natively instead.
6
7use std::rc::Rc;
8
9use gpui_kit::*;
10
11type Opener = Rc<dyn Fn(&mut App) -> Option<AnyWindowHandle>>;
12
13pub struct MainWindow {
14 handle: Option<AnyWindowHandle>,
15 open: Opener,
16 hiding: bool,
17}
18
19impl Global for MainWindow {}
20
21/// Opens the first main window with `open` and remembers how to open the next one.
22pub fn install(
23 open: impl Fn(&mut App) -> Option<AnyWindowHandle> + 'static,
24 cx: &mut App,
25) -> Option<AnyWindowHandle> {
26 let open: Opener = Rc::new(open);
27 cx.set_global(MainWindow {
28 handle: None,
29 open: open.clone(),
30 hiding: false,
31 });
32 let handle = open(cx);
33 cx.global_mut::<MainWindow>().handle = handle;
34 handle
35}
36
37fn main_mut(cx: &mut App) -> Option<&mut MainWindow> {
38 cx.has_global::<MainWindow>()
39 .then(|| cx.global_mut::<MainWindow>())
40}
41
42pub fn current(cx: &App) -> Option<AnyWindowHandle> {
43 cx.try_global::<MainWindow>().and_then(|main| main.handle)
44}
45
46/// The next close of the main window goes to the tray instead of quitting.
47pub fn mark_hiding(cx: &mut App) {
48 if let Some(main) = main_mut(cx) {
49 main.hiding = true;
50 }
51}
52
53/// Closes the main window into the tray. Deferred: the window's views may be on the stack.
54pub fn hide(cx: &mut App) {
55 let Some(handle) = current(cx) else {
56 return;
57 };
58 mark_hiding(cx);
59 cx.defer(move |cx| {
60 if handle
61 .update(cx, |_, window, _| window.remove_window())
62 .is_err()
63 {
64 note_closed(handle.window_id(), cx);
65 }
66 });
67}
68
69/// Brings the main window to the front, opening a new one if it was closed into the tray.
70/// Deferred: building the shell updates entities that may be on the stack.
71pub fn show(cx: &mut App) {
72 cx.defer(|cx| {
73 if let Some(handle) = current(cx)
74 && handle
75 .update(cx, |_, window, _| window.activate_window())
76 .is_ok()
77 {
78 return;
79 }
80 let Some(open) = cx.try_global::<MainWindow>().map(|main| main.open.clone()) else {
81 return;
82 };
83 let handle = open(cx);
84 if let Some(main) = main_mut(cx) {
85 main.handle = handle;
86 main.hiding = false;
87 }
88 if let Some(handle) = handle {
89 handle
90 .update(cx, |_, window, _| window.activate_window())
91 .ok();
92 }
93 cx.activate(true);
94 });
95}
96
97/// Call from `on_window_closed`. Returns true when the app should quit: the main
98/// window closed and it was not closed into the tray.
99pub fn note_closed(window_id: WindowId, cx: &mut App) -> bool {
100 let Some(main) = main_mut(cx) else {
101 return false;
102 };
103 if main.handle.map(|handle| handle.window_id()) != Some(window_id) {
104 return false;
105 }
106 main.handle = None;
107 !std::mem::take(&mut main.hiding)
108}
109
110/// Whether the main window is currently closed into the tray.
111pub fn is_hidden(cx: &App) -> bool {
112 cx.try_global::<MainWindow>()
113 .is_some_and(|main| main.handle.is_none())
114}
crates/app/src/notify/center.rs +41 −5
@@ -313,20 +313,40 @@ impl NotificationCenter {
313 313 cx.notify();
314 314 }
315 315
316 pub fn start_in_background(&self, window: &mut Window) {
316 /// Points at a main window reopened from the tray.
317 pub fn attach_main_window(&mut self, window: &mut Window) {
318 self.main_window = window.window_handle();
319 self.main_native = platform::native_handle(window);
320 platform::set_window_icon(window, self.app_icon.png());
321 }
322
323 pub fn start_in_background(&self, window: &mut Window, cx: &mut App) {
317 324 match (&self.tray, self.main_native) {
318 325 (Some(_), Some(native)) => platform::hide_window(native),
326 #[cfg(target_os = "linux")]
327 (Some(_), None) => crate::main_window::hide(cx),
319 328 _ => window.minimize_window(),
320 329 }
330 let _ = cx;
321 331 }
322 332
323 pub fn intercept_close(&self, _cx: &App) -> bool {
333 /// True when the close is handled here (window hidden natively). On Linux the
334 /// window closes for real and the app stays in the tray.
335 pub fn intercept_close(&self, cx: &mut App) -> bool {
324 336 match (self.settings.close_to_tray, &self.tray, self.main_native) {
325 337 (true, Some(_), Some(native)) => {
326 338 platform::hide_window(native);
327 339 true
328 340 }
329 _ => false,
341 #[cfg(target_os = "linux")]
342 (true, Some(_), None) => {
343 crate::main_window::mark_hiding(cx);
344 false
345 }
346 _ => {
347 let _ = cx;
348 false
349 }
330 350 }
331 351 }
332 352
@@ -1158,6 +1178,9 @@ impl NotificationCenter {
1158 1178 if self.main_window_active(cx) {
1159 1179 if let Some(native) = self.main_native {
1160 1180 platform::hide_window(native);
1181 } else {
1182 #[cfg(target_os = "linux")]
1183 crate::main_window::hide(cx);
1161 1184 }
1162 1185 } else {
1163 1186 self.raise_main_window(cx);
@@ -1171,6 +1194,11 @@ impl NotificationCenter {
1171 1194 }
1172 1195
1173 1196 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
1197 #[cfg(target_os = "linux")]
1198 if crate::main_window::is_hidden(cx) {
1199 crate::main_window::show(cx);
1200 return;
1201 }
1174 1202 if let Some(native) = self.main_native {
1175 1203 platform::restore_and_raise(native);
1176 1204 }
@@ -1179,10 +1207,18 @@ impl NotificationCenter {
1179 1207 .ok();
1180 1208 }
1181 1209
1210 /// Applies the icon again even if the choice is unchanged: its image changed.
1211 pub fn reapply_app_icon(&mut self, cx: &mut Context<Self>) {
1212 self.show_app_icon(active_appearance::current(cx).app_icon, cx);
1213 }
1214
1182 1215 fn apply_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1183 if icon == self.app_icon {
1184 return;
1216 if icon != self.app_icon {
1217 self.show_app_icon(icon, cx);
1185 1218 }
1219 }
1220
1221 fn show_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1186 1222 self.app_icon = icon;
1187 1223 let mention = !self.unread_mentions.is_empty();
1188 1224 if let Some(tray) = &mut self.tray {
@@ -313,20 +313,40 @@ impl NotificationCenter {
313 cx.notify();
313 cx.notify();
314 }
314 }
315
315
316 pub fn start_in_background(&self, window: &mut Window) {
316 /// Points at a main window reopened from the tray.
317 pub fn attach_main_window(&mut self, window: &mut Window) {
318 self.main_window = window.window_handle();
319 self.main_native = platform::native_handle(window);
320 platform::set_window_icon(window, self.app_icon.png());
321 }
322
323 pub fn start_in_background(&self, window: &mut Window, cx: &mut App) {
317 match (&self.tray, self.main_native) {
324 match (&self.tray, self.main_native) {
318 (Some(_), Some(native)) => platform::hide_window(native),
325 (Some(_), Some(native)) => platform::hide_window(native),
326 #[cfg(target_os = "linux")]
327 (Some(_), None) => crate::main_window::hide(cx),
319 _ => window.minimize_window(),
328 _ => window.minimize_window(),
320 }
329 }
330 let _ = cx;
321 }
331 }
322
332
323 pub fn intercept_close(&self, _cx: &App) -> bool {
333 /// True when the close is handled here (window hidden natively). On Linux the
334 /// window closes for real and the app stays in the tray.
335 pub fn intercept_close(&self, cx: &mut App) -> bool {
324 match (self.settings.close_to_tray, &self.tray, self.main_native) {
336 match (self.settings.close_to_tray, &self.tray, self.main_native) {
325 (true, Some(_), Some(native)) => {
337 (true, Some(_), Some(native)) => {
326 platform::hide_window(native);
338 platform::hide_window(native);
327 true
339 true
328 }
340 }
329 _ => false,
341 #[cfg(target_os = "linux")]
342 (true, Some(_), None) => {
343 crate::main_window::mark_hiding(cx);
344 false
345 }
346 _ => {
347 let _ = cx;
348 false
349 }
330 }
350 }
331 }
351 }
332
352
@@ -1158,6 +1178,9 @@ impl NotificationCenter {
1158 if self.main_window_active(cx) {
1178 if self.main_window_active(cx) {
1159 if let Some(native) = self.main_native {
1179 if let Some(native) = self.main_native {
1160 platform::hide_window(native);
1180 platform::hide_window(native);
1181 } else {
1182 #[cfg(target_os = "linux")]
1183 crate::main_window::hide(cx);
1161 }
1184 }
1162 } else {
1185 } else {
1163 self.raise_main_window(cx);
1186 self.raise_main_window(cx);
@@ -1171,6 +1194,11 @@ impl NotificationCenter {
1171 }
1194 }
1172
1195
1173 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
1196 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
1197 #[cfg(target_os = "linux")]
1198 if crate::main_window::is_hidden(cx) {
1199 crate::main_window::show(cx);
1200 return;
1201 }
1174 if let Some(native) = self.main_native {
1202 if let Some(native) = self.main_native {
1175 platform::restore_and_raise(native);
1203 platform::restore_and_raise(native);
1176 }
1204 }
@@ -1179,10 +1207,18 @@ impl NotificationCenter {
1179 .ok();
1207 .ok();
1180 }
1208 }
1181
1209
1210 /// Applies the icon again even if the choice is unchanged: its image changed.
1211 pub fn reapply_app_icon(&mut self, cx: &mut Context<Self>) {
1212 self.show_app_icon(active_appearance::current(cx).app_icon, cx);
1213 }
1214
1182 fn apply_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1215 fn apply_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1183 if icon == self.app_icon {
1216 if icon != self.app_icon {
1184 return;
1217 self.show_app_icon(icon, cx);
1185 }
1218 }
1219 }
1220
1221 fn show_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1186 self.app_icon = icon;
1222 self.app_icon = icon;
1187 let mention = !self.unread_mentions.is_empty();
1223 let mention = !self.unread_mentions.is_empty();
1188 if let Some(tray) = &mut self.tray {
1224 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 +72 −16
@@ -166,6 +166,24 @@ fn watch_releases(running_tag: &'static str, cx: &mut App) {
166 166
167 167 const DEMO_UPDATE_VARIABLE: &str = "TEAMS_DEMO_UPDATE";
168 168
169 /// Entities created with the first main window that a reopened one takes over.
170 #[derive(Clone)]
171 struct KeptParts {
172 activity: Entity<ActivityCenter>,
173 notifications: Entity<NotificationCenter>,
174 call_windows: Entity<CallWindows>,
175 }
176
177 impl Global for KeptParts {}
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
169 187 pub struct AppShell {
170 188 state: Entity<AppState>,
171 189 rail: Entity<RailView>,
@@ -240,9 +258,20 @@ impl AppShell {
240 258 window: &mut Window,
241 259 cx: &mut Context<Self>,
242 260 ) -> Self {
243 let call_media = cx.new(|_| CallMedia);
244 state.update(cx, |state, _| state.call_media = Some(call_media.clone()));
245 let activity = cx.new(|cx| ActivityCenter::new(state.clone(), window, cx));
261 let kept = cx.try_global::<KeptParts>().cloned();
262 let reopened = kept.is_some();
263 let activity = match &kept {
264 Some(kept) => {
265 kept.activity
266 .update(cx, |activity, _| activity.attach_main_window(window));
267 kept.activity.clone()
268 }
269 None => {
270 let call_media = cx.new(|_| CallMedia);
271 state.update(cx, |state, _| state.call_media = Some(call_media.clone()));
272 cx.new(|cx| ActivityCenter::new(state.clone(), window, cx))
273 }
274 };
246 275 let activity_panel = cx.new(|cx| ActivityPanel::new(state.clone(), activity.clone(), cx));
247 276 let quick_pane = cx.new(|cx| QuickViewPane::new(state.clone(), activity.clone(), cx));
248 277 let manage_team_page = cx.new(|cx| ManageTeamPage::new(state.clone(), window, cx));
@@ -361,9 +390,29 @@ impl AppShell {
361 390 });
362 391 let focus_handle = cx.focus_handle();
363 392 window.focus(&focus_handle, cx);
364 let notifications =
365 cx.new(|cx| NotificationCenter::new(state.clone(), activity.clone(), window, cx));
366 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
393 // The tray, notifications and calls outlive a main window closed into the tray.
394 let (notifications, call_windows) = match kept {
395 Some(kept) => {
396 kept.notifications.update(cx, |notifications, _| {
397 notifications.attach_main_window(window)
398 });
399 kept.call_windows.update(cx, |call_windows, _| {
400 call_windows.attach_main_window(window)
401 });
402 (kept.notifications, kept.call_windows)
403 }
404 None => {
405 let notifications = cx
406 .new(|cx| NotificationCenter::new(state.clone(), activity.clone(), window, cx));
407 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
408 cx.set_global(KeptParts {
409 activity: activity.clone(),
410 notifications: notifications.clone(),
411 call_windows: call_windows.clone(),
412 });
413 (notifications, call_windows)
414 }
415 };
367 416 let user_input = cx.global::<UserInputHandle>().0.clone();
368 417 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
369 418 this.user_input.touch();
@@ -385,7 +434,9 @@ impl AppShell {
385 434 }
386 435 });
387 436 let closing = notifications.clone();
388 window.on_window_should_close(cx, move |_, cx| !closing.read(cx).intercept_close(cx));
437 window.on_window_should_close(cx, move |_, cx| {
438 !closing.update(cx, |notifications, cx| notifications.intercept_close(cx))
439 });
389 440 let mut shell = AppShell {
390 441 state,
391 442 rail,
@@ -434,14 +485,17 @@ impl AppShell {
434 485 reply_to_last,
435 486 launched_by_autostart,
436 487 } = startup;
437 if shell
438 .notifications
439 .read(cx)
440 .startup()
441 .starts_hidden(launched_by_autostart)
488 if !reopened
489 && shell
490 .notifications
491 .read(cx)
492 .startup()
493 .starts_hidden(launched_by_autostart)
442 494 {
443 495 cx.defer_in(window, |this, window, cx| {
444 this.notifications.read(cx).start_in_background(window)
496 this.notifications.update(cx, |notifications, cx| {
497 notifications.start_in_background(window, cx)
498 })
445 499 });
446 500 }
447 501 if let Some(query) = switcher_query {
@@ -459,7 +513,7 @@ impl AppShell {
459 513 });
460 514 });
461 515 }
462 #[cfg(windows)]
516 #[cfg(any(windows, target_os = "linux"))]
463 517 cx.spawn_in(window, async move |this, cx| {
464 518 loop {
465 519 cx.background_executor().timer(updater::POLL_INTERVAL).await;
@@ -472,6 +526,7 @@ impl AppShell {
472 526 }
473 527 })
474 528 .detach();
529 // Linux asks before downloading (`linux_update`); Windows downloads quietly.
475 530 #[cfg(windows)]
476 531 if let Some(running_tag) = app_base::version::release_tag() {
477 532 watch_releases(running_tag, cx);
@@ -479,7 +534,7 @@ impl AppShell {
479 534 shell
480 535 }
481 536
482 #[cfg_attr(not(windows), allow(dead_code))]
537 #[cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))]
483 538 fn poll_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
484 539 if matches!(
485 540 self.update,
@@ -505,7 +560,8 @@ impl AppShell {
505 560 composer_empty: conversation.composer_is_empty(cx),
506 561 send_in_flight: conversation.send_in_flight(),
507 562 });
508 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")) {
509 565 self.restart_into_update(cx);
510 566 }
511 567 cx.notify();
@@ -166,6 +166,24 @@ fn watch_releases(running_tag: &'static str, cx: &mut App) {
166
166
167const DEMO_UPDATE_VARIABLE: &str = "TEAMS_DEMO_UPDATE";
167const DEMO_UPDATE_VARIABLE: &str = "TEAMS_DEMO_UPDATE";
168
168
169/// Entities created with the first main window that a reopened one takes over.
170#[derive(Clone)]
171struct KeptParts {
172 activity: Entity<ActivityCenter>,
173 notifications: Entity<NotificationCenter>,
174 call_windows: Entity<CallWindows>,
175}
176
177impl Global for KeptParts {}
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
169pub struct AppShell {
187pub struct AppShell {
170 state: Entity<AppState>,
188 state: Entity<AppState>,
171 rail: Entity<RailView>,
189 rail: Entity<RailView>,
@@ -240,9 +258,20 @@ impl AppShell {
240 window: &mut Window,
258 window: &mut Window,
241 cx: &mut Context<Self>,
259 cx: &mut Context<Self>,
242 ) -> Self {
260 ) -> Self {
243 let call_media = cx.new(|_| CallMedia);
261 let kept = cx.try_global::<KeptParts>().cloned();
244 state.update(cx, |state, _| state.call_media = Some(call_media.clone()));
262 let reopened = kept.is_some();
245 let activity = cx.new(|cx| ActivityCenter::new(state.clone(), window, cx));
263 let activity = match &kept {
264 Some(kept) => {
265 kept.activity
266 .update(cx, |activity, _| activity.attach_main_window(window));
267 kept.activity.clone()
268 }
269 None => {
270 let call_media = cx.new(|_| CallMedia);
271 state.update(cx, |state, _| state.call_media = Some(call_media.clone()));
272 cx.new(|cx| ActivityCenter::new(state.clone(), window, cx))
273 }
274 };
246 let activity_panel = cx.new(|cx| ActivityPanel::new(state.clone(), activity.clone(), cx));
275 let activity_panel = cx.new(|cx| ActivityPanel::new(state.clone(), activity.clone(), cx));
247 let quick_pane = cx.new(|cx| QuickViewPane::new(state.clone(), activity.clone(), cx));
276 let quick_pane = cx.new(|cx| QuickViewPane::new(state.clone(), activity.clone(), cx));
248 let manage_team_page = cx.new(|cx| ManageTeamPage::new(state.clone(), window, cx));
277 let manage_team_page = cx.new(|cx| ManageTeamPage::new(state.clone(), window, cx));
@@ -361,9 +390,29 @@ impl AppShell {
361 });
390 });
362 let focus_handle = cx.focus_handle();
391 let focus_handle = cx.focus_handle();
363 window.focus(&focus_handle, cx);
392 window.focus(&focus_handle, cx);
364 let notifications =
393 // The tray, notifications and calls outlive a main window closed into the tray.
365 cx.new(|cx| NotificationCenter::new(state.clone(), activity.clone(), window, cx));
394 let (notifications, call_windows) = match kept {
366 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
395 Some(kept) => {
396 kept.notifications.update(cx, |notifications, _| {
397 notifications.attach_main_window(window)
398 });
399 kept.call_windows.update(cx, |call_windows, _| {
400 call_windows.attach_main_window(window)
401 });
402 (kept.notifications, kept.call_windows)
403 }
404 None => {
405 let notifications = cx
406 .new(|cx| NotificationCenter::new(state.clone(), activity.clone(), window, cx));
407 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
408 cx.set_global(KeptParts {
409 activity: activity.clone(),
410 notifications: notifications.clone(),
411 call_windows: call_windows.clone(),
412 });
413 (notifications, call_windows)
414 }
415 };
367 let user_input = cx.global::<UserInputHandle>().0.clone();
416 let user_input = cx.global::<UserInputHandle>().0.clone();
368 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
417 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
369 this.user_input.touch();
418 this.user_input.touch();
@@ -385,7 +434,9 @@ impl AppShell {
385 }
434 }
386 });
435 });
387 let closing = notifications.clone();
436 let closing = notifications.clone();
388 window.on_window_should_close(cx, move |_, cx| !closing.read(cx).intercept_close(cx));
437 window.on_window_should_close(cx, move |_, cx| {
438 !closing.update(cx, |notifications, cx| notifications.intercept_close(cx))
439 });
389 let mut shell = AppShell {
440 let mut shell = AppShell {
390 state,
441 state,
391 rail,
442 rail,
@@ -434,14 +485,17 @@ impl AppShell {
434 reply_to_last,
485 reply_to_last,
435 launched_by_autostart,
486 launched_by_autostart,
436 } = startup;
487 } = startup;
437 if shell
488 if !reopened
438 .notifications
489 && shell
439 .read(cx)
490 .notifications
440 .startup()
491 .read(cx)
441 .starts_hidden(launched_by_autostart)
492 .startup()
493 .starts_hidden(launched_by_autostart)
442 {
494 {
443 cx.defer_in(window, |this, window, cx| {
495 cx.defer_in(window, |this, window, cx| {
444 this.notifications.read(cx).start_in_background(window)
496 this.notifications.update(cx, |notifications, cx| {
497 notifications.start_in_background(window, cx)
498 })
445 });
499 });
446 }
500 }
447 if let Some(query) = switcher_query {
501 if let Some(query) = switcher_query {
@@ -459,7 +513,7 @@ impl AppShell {
459 });
513 });
460 });
514 });
461 }
515 }
462 #[cfg(windows)]
516 #[cfg(any(windows, target_os = "linux"))]
463 cx.spawn_in(window, async move |this, cx| {
517 cx.spawn_in(window, async move |this, cx| {
464 loop {
518 loop {
465 cx.background_executor().timer(updater::POLL_INTERVAL).await;
519 cx.background_executor().timer(updater::POLL_INTERVAL).await;
@@ -472,6 +526,7 @@ impl AppShell {
472 }
526 }
473 })
527 })
474 .detach();
528 .detach();
529 // Linux asks before downloading (`linux_update`); Windows downloads quietly.
475 #[cfg(windows)]
530 #[cfg(windows)]
476 if let Some(running_tag) = app_base::version::release_tag() {
531 if let Some(running_tag) = app_base::version::release_tag() {
477 watch_releases(running_tag, cx);
532 watch_releases(running_tag, cx);
@@ -479,7 +534,7 @@ impl AppShell {
479 shell
534 shell
480 }
535 }
481
536
482 #[cfg_attr(not(windows), allow(dead_code))]
537 #[cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))]
483 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>) {
484 if matches!(
539 if matches!(
485 self.update,
540 self.update,
@@ -505,7 +560,8 @@ impl AppShell {
505 composer_empty: conversation.composer_is_empty(cx),
560 composer_empty: conversation.composer_is_empty(cx),
506 send_in_flight: conversation.send_in_flight(),
561 send_in_flight: conversation.send_in_flight(),
507 });
562 });
508 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")) {
509 self.restart_into_update(cx);
565 self.restart_into_update(cx);
510 }
566 }
511 cx.notify();
567 cx.notify();
docs/decisions/0012-linux-close-to-tray-closes-the-window.md added +21 −0
@@ -0,0 +1,21 @@
1 ---
2 status: proposed
3 date: 2026-11-14
4 ---
5
6 # ADR 0012: On Linux, close to tray closes the main window
7
8 ## Context
9
10 "Close to tray" hides the main window on Windows (`ShowWindow`). GPUI has no call to hide a window on Wayland, and an `xdg_toplevel` cannot be unmapped without patching the GPUI Linux backend. The options were: minimize instead (the window stays in the task manager), force XWayland so X11 unmapping works (blurry with fractional scaling, loses Wayland screen share), patch GPUI to destroy and recreate the toplevel role, or close the window for real and open a new one from the tray.
11
12 ## Decision
13
14 On Linux, with a tray host present, closing the main window closes it for real while the app keeps running (`QuitMode::Explicit`, `main_window.rs`). The tray icon, a second start or an incoming call open a new main window. The entities that must outlive the window (notifications with the tray, call windows, activity) are created with the first window and handed to every later one (`KeptParts` in `views/shell.rs`). Without a tray host, closing quits as before.
15
16 ## Consequences
17
18 - Works the same on Wayland and X11, and the window really leaves the task manager.
19 - A reopened window starts from the cached state, not from the exact previous UI: open dialogs and scroll positions are gone, the selected chat and drafts stay.
20 - Anything new that has to survive a closed main window must live in `KeptParts` or outside the shell, not in a view created by `AppShell::new`.
21 - We do not patch GPUI.
@@ -0,0 +1,21 @@
1---
2status: proposed
3date: 2026-11-14
4---
5
6# ADR 0012: On Linux, close to tray closes the main window
7
8## Context
9
10"Close to tray" hides the main window on Windows (`ShowWindow`). GPUI has no call to hide a window on Wayland, and an `xdg_toplevel` cannot be unmapped without patching the GPUI Linux backend. The options were: minimize instead (the window stays in the task manager), force XWayland so X11 unmapping works (blurry with fractional scaling, loses Wayland screen share), patch GPUI to destroy and recreate the toplevel role, or close the window for real and open a new one from the tray.
11
12## Decision
13
14On Linux, with a tray host present, closing the main window closes it for real while the app keeps running (`QuitMode::Explicit`, `main_window.rs`). The tray icon, a second start or an incoming call open a new main window. The entities that must outlive the window (notifications with the tray, call windows, activity) are created with the first window and handed to every later one (`KeptParts` in `views/shell.rs`). Without a tray host, closing quits as before.
15
16## Consequences
17
18- Works the same on Wayland and X11, and the window really leaves the task manager.
19- A reopened window starts from the cached state, not from the exact previous UI: open dialogs and scroll positions are gone, the selected chat and drafts stay.
20- Anything new that has to survive a closed main window must live in `KeptParts` or outside the shell, not in a view created by `AppShell::new`.
21- We do not patch GPUI.
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 +4 −1
@@ -27,5 +27,8 @@ Statuses: `proposed`, `accepted`, `superseded`.
27 27 | [0009](0009-bundled-google-oauth-client.md) | Bundled Google OAuth Desktop client |
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 | [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 |
30 33
31 Records `0001` to `0010` are the decisions already shipped. `0011` stays `proposed` until the calendar-peek 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`.
@@ -27,5 +27,8 @@ Statuses: `proposed`, `accepted`, `superseded`.
27| [0009](0009-bundled-google-oauth-client.md) | Bundled Google OAuth Desktop client |
27| [0009](0009-bundled-google-oauth-client.md) | Bundled Google OAuth Desktop client |
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 |
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 |
30
33
31Records `0001` to `0010` are the decisions already shipped. `0011` stays `proposed` until the calendar-peek 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`.