BlueGit

ict rusty-teams

feat(linux): tray icon and close to tray

Adds a StatusNotifierItem tray on Linux (ksni): KDE Plasma natively, GNOME
with the AppIndicator extension. Left click toggles the main window; the menu
has Open, Mute sound, Do not disturb, Notifications and Quit.

GPUI cannot hide a Wayland window, so with "Close to tray" the main window
closes for real while the app keeps running (QuitMode::Explicit). The tray, a
second start or an incoming call open a new main window, which takes over the
notification center, call windows and activity center (KeptParts). Without a
tray host, closing quits as before. See ADR 0012.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis muharemovic · pushed by metis

Authored 2026-11-14 · 2 weeks ago

Hash
09e746989ad0c5f34e4a414d561ab5f7051573a6
Parent
3ecaf27a
15 files changed +590 −41
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",
@@ -5036,6 +5037,21 @@ dependencies = [
5036 5037 "libc",
5037 5038 ]
5038 5039
5040 [[package]]
5041 name = "ksni"
5042 version = "0.3.7"
5043 source = "registry+https://github.com/rust-lang/crates.io-index"
5044 checksum = "1bcc1cb43797140f74b711f1c4a49f48a7a7429f211c5fb78264e7bcd1e99caf"
5045 dependencies = [
5046 "arc-swap",
5047 "crossbeam-queue",
5048 "futures-util",
5049 "pastey 0.2.3",
5050 "serde",
5051 "tokio",
5052 "zbus",
5053 ]
5054
5039 5055 [[package]]
5040 5056 name = "kurbo"
5041 5057 version = "0.11.3"
@@ -9401,6 +9417,7 @@ dependencies = [
9401 9417 "signal-hook-registry",
9402 9418 "socket2",
9403 9419 "tokio-macros",
9420 "tracing",
9404 9421 "windows-sys 0.61.2",
9405 9422 ]
9406 9423
@@ -11779,6 +11796,7 @@ dependencies = [
11779 11796 "rustix 1.1.5",
11780 11797 "serde",
11781 11798 "serde_repr",
11799 "tokio",
11782 11800 "tracing",
11783 11801 "uds_windows",
11784 11802 "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",
@@ -5036,6 +5037,21 @@ dependencies = [
5036 "libc",
5037 "libc",
5037]
5038]
5038
5039
5040[[package]]
5041name = "ksni"
5042version = "0.3.7"
5043source = "registry+https://github.com/rust-lang/crates.io-index"
5044checksum = "1bcc1cb43797140f74b711f1c4a49f48a7a7429f211c5fb78264e7bcd1e99caf"
5045dependencies = [
5046 "arc-swap",
5047 "crossbeam-queue",
5048 "futures-util",
5049 "pastey 0.2.3",
5050 "serde",
5051 "tokio",
5052 "zbus",
5053]
5054
5039[[package]]
5055[[package]]
5040name = "kurbo"
5056name = "kurbo"
5041version = "0.11.3"
5057version = "0.11.3"
@@ -9401,6 +9417,7 @@ dependencies = [
9401 "signal-hook-registry",
9417 "signal-hook-registry",
9402 "socket2",
9418 "socket2",
9403 "tokio-macros",
9419 "tokio-macros",
9420 "tracing",
9404 "windows-sys 0.61.2",
9421 "windows-sys 0.61.2",
9405]
9422]
9406
9423
@@ -11779,6 +11796,7 @@ dependencies = [
11779 "rustix 1.1.5",
11796 "rustix 1.1.5",
11780 "serde",
11797 "serde",
11781 "serde_repr",
11798 "serde_repr",
11799 "tokio",
11782 "tracing",
11800 "tracing",
11783 "uds_windows",
11801 "uds_windows",
11784 "uuid",
11802 "uuid",
README.md +1 −1
@@ -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`. Copy `crates/app/assets/linux/rusty-teams.desktop` to `~/.local/share/applications/` and `crates/app/assets/icon/teams-fast-256.png` to `~/.local/share/icons/hicolor/256x256/apps/rusty-teams.png` so the dock can match it. Tray icon through StatusNotifierItem (KDE Plasma natively, GNOME with the AppIndicator extension); with "Close to tray" the window closes and the app keeps running in the tray, which opens a new window. Built-in login without Chrome is planned |
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).
@@ -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`. Copy `crates/app/assets/linux/rusty-teams.desktop` to `~/.local/share/applications/` and `crates/app/assets/icon/teams-fast-256.png` to `~/.local/share/icons/hicolor/256x256/apps/rusty-teams.png` so the dock can match it. Tray icon through StatusNotifierItem (KDE Plasma natively, GNOME with the AppIndicator extension); with "Close to tray" the window closes and the app keeps running in the tray, which opens a new window. Built-in login without Chrome is planned |
93| 🍎 macOS | Starts Google Chrome or Chromium on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
93| 🍎 macOS | Starts Google Chrome or Chromium on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
94
94
95The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
95The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
ROADMAP.md +1 −1
@@ -34,7 +34,7 @@ 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 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 39 | Single instance, second start brings the window to front | Done | |
40 40 | Sign in on macOS without starting Chrome by hand | Done | Same managed Chrome as on Linux, profile in Application Support |
@@ -34,7 +34,7 @@ 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| 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 |
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| Single instance, second start brings the window to front | Done | |
39| 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 |
40| Sign in on macOS without starting Chrome by hand | Done | Same managed Chrome as on Linux, profile in Application Support |
crates/app-base/Cargo.toml +1 −0
@@ -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"
@@ -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/src/notify/platform/linux_tray.rs added +277 −0
@@ -0,0 +1,277 @@
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
13 /// The window and desktop entry id (`rusty-teams.desktop`).
14 const DESKTOP_ID: &str = "rusty-teams";
15
16 const TRAY_ICON_SIZES: [u32; 3] = [22, 32, 64];
17 const DOT_COLOR: [u8; 4] = [0xef, 0x44, 0x44, 0xff];
18
19 #[derive(Clone)]
20 struct Labels {
21 open: String,
22 mute_sound: String,
23 do_not_disturb: String,
24 notifications: String,
25 quit: String,
26 }
27
28 impl Labels {
29 fn current() -> Labels {
30 let tr = crate::ui_locale::tr;
31 Labels {
32 open: tr("tray.open"),
33 mute_sound: tr("tray.mute_sound"),
34 do_not_disturb: tr("tray.do_not_disturb"),
35 notifications: tr("tray.notifications"),
36 quit: tr("tray.quit"),
37 }
38 }
39 }
40
41 struct Item {
42 commands: Sender<TrayCommand>,
43 labels: Labels,
44 sound_on: bool,
45 do_not_disturb: bool,
46 mention: bool,
47 plain: Vec<Icon>,
48 dotted: Vec<Icon>,
49 }
50
51 impl Item {
52 fn send(&self, command: TrayCommand) {
53 let _ = self.commands.send(command);
54 }
55 }
56
57 /// Escapes the mnemonic underscores of a menu label.
58 fn menu_label(text: &str) -> String {
59 text.replace('_', "__")
60 }
61
62 impl ksni::Tray for Item {
63 fn id(&self) -> String {
64 DESKTOP_ID.to_owned()
65 }
66
67 fn title(&self) -> String {
68 crate::APP_NAME.to_owned()
69 }
70
71 fn category(&self) -> Category {
72 Category::Communications
73 }
74
75 fn icon_pixmap(&self) -> Vec<Icon> {
76 if self.mention {
77 self.dotted.clone()
78 } else {
79 self.plain.clone()
80 }
81 }
82
83 fn tool_tip(&self) -> ToolTip {
84 ToolTip {
85 title: crate::APP_NAME.to_owned(),
86 ..Default::default()
87 }
88 }
89
90 fn activate(&mut self, _x: i32, _y: i32) {
91 self.send(TrayCommand::Toggle);
92 }
93
94 fn menu(&self) -> Vec<MenuItem<Self>> {
95 vec![
96 StandardItem {
97 label: menu_label(&self.labels.open),
98 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Open)),
99 ..Default::default()
100 }
101 .into(),
102 MenuItem::Separator,
103 CheckmarkItem {
104 label: menu_label(&self.labels.mute_sound),
105 checked: !self.sound_on,
106 activate: Box::new(|item: &mut Self| item.send(TrayCommand::ToggleSound)),
107 ..Default::default()
108 }
109 .into(),
110 CheckmarkItem {
111 label: menu_label(&self.labels.do_not_disturb),
112 checked: self.do_not_disturb,
113 activate: Box::new(|item: &mut Self| item.send(TrayCommand::ToggleDoNotDisturb)),
114 ..Default::default()
115 }
116 .into(),
117 StandardItem {
118 label: menu_label(&self.labels.notifications),
119 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Settings)),
120 ..Default::default()
121 }
122 .into(),
123 MenuItem::Separator,
124 StandardItem {
125 label: menu_label(&self.labels.quit),
126 icon_name: "application-exit".into(),
127 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Quit)),
128 ..Default::default()
129 }
130 .into(),
131 ]
132 }
133 }
134
135 pub struct Tray {
136 handle: Handle<Item>,
137 commands: Mutex<Receiver<TrayCommand>>,
138 }
139
140 impl Tray {
141 /// `None` when there is no session bus or no tray host (no StatusNotifierWatcher).
142 pub fn new(sound_on: bool, do_not_disturb: bool, icon_png: &[u8]) -> Option<Self> {
143 let (plain, dotted) = tray_icons(icon_png)?;
144 let (sender, receiver) = channel();
145 let item = Item {
146 commands: sender,
147 labels: Labels::current(),
148 sound_on,
149 do_not_disturb,
150 mention: false,
151 plain,
152 dotted,
153 };
154 let handle = match item.spawn() {
155 Ok(handle) => handle,
156 Err(error) => {
157 log::warn!("no tray icon: {error}");
158 return None;
159 }
160 };
161 Some(Tray {
162 handle,
163 commands: Mutex::new(receiver),
164 })
165 }
166
167 pub fn relocalize(&self) {
168 let labels = Labels::current();
169 self.handle.update(move |item| item.labels = labels);
170 }
171
172 pub fn poll(&self) -> Vec<TrayCommand> {
173 let Ok(receiver) = self.commands.lock() else {
174 return Vec::new();
175 };
176 receiver.try_iter().collect()
177 }
178
179 pub fn set_app_icon(&mut self, icon_png: &[u8], mention: bool) {
180 let Some((plain, dotted)) = tray_icons(icon_png) else {
181 return;
182 };
183 self.handle.update(move |item| {
184 item.plain = plain;
185 item.dotted = dotted;
186 item.mention = mention;
187 });
188 }
189
190 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
191 let labels = Labels::current();
192 self.handle.update(move |item| {
193 item.labels = labels;
194 item.sound_on = sound_on;
195 item.do_not_disturb = do_not_disturb;
196 item.mention = mention;
197 });
198 }
199 }
200
201 impl Drop for Tray {
202 fn drop(&mut self) {
203 let _ = self.handle.shutdown();
204 }
205 }
206
207 /// The icon in every tray size, plain and with the unread dot, as ARGB32 big endian.
208 fn tray_icons(icon_png: &[u8]) -> Option<(Vec<Icon>, Vec<Icon>)> {
209 let decoded = image::load_from_memory(icon_png).ok()?;
210 let mut plain = Vec::new();
211 let mut dotted = Vec::new();
212 for size in TRAY_ICON_SIZES {
213 let resized = decoded
214 .resize_exact(size, size, image::imageops::FilterType::Lanczos3)
215 .to_rgba8();
216 let mut with_dot = resized.clone();
217 let radius = size as f32 * 0.22;
218 let center = size as f32 - radius - 0.5;
219 for (column, row, pixel) in with_dot.enumerate_pixels_mut() {
220 let distance = ((column as f32 + 0.5 - center).powi(2)
221 + (row as f32 + 0.5 - center).powi(2))
222 .sqrt();
223 if distance <= radius {
224 *pixel = image::Rgba(DOT_COLOR);
225 }
226 }
227 plain.push(argb_icon(size, resized.as_raw()));
228 dotted.push(argb_icon(size, with_dot.as_raw()));
229 }
230 Some((plain, dotted))
231 }
232
233 fn argb_icon(size: u32, rgba: &[u8]) -> Icon {
234 let data = rgba
235 .chunks_exact(4)
236 .flat_map(|pixel| [pixel[3], pixel[0], pixel[1], pixel[2]])
237 .collect();
238 Icon {
239 width: size as i32,
240 height: size as i32,
241 data,
242 }
243 }
244
245 #[cfg(test)]
246 mod tests {
247 use super::*;
248
249 #[test]
250 fn icons_come_in_every_size_as_argb() {
251 let png = crate::appearance::AppIcon::RustyTeams.png();
252 let (plain, dotted) = tray_icons(png).unwrap();
253 assert_eq!(plain.len(), TRAY_ICON_SIZES.len());
254 for (icon, size) in plain.iter().zip(TRAY_ICON_SIZES) {
255 assert_eq!((icon.width, icon.height), (size as i32, size as i32));
256 assert_eq!(icon.data.len(), (size * size * 4) as usize);
257 }
258 let last = dotted.last().unwrap();
259 let bottom_right = last.data.len() - 4 * (last.width as usize * 12 + 12);
260 assert_eq!(
261 &last.data[bottom_right..bottom_right + 4],
262 &[0xff, 0xef, 0x44, 0x44]
263 );
264 assert!(tray_icons(b"not a png").is_none());
265 }
266
267 #[test]
268 fn argb_moves_alpha_first() {
269 let icon = argb_icon(1, &[1, 2, 3, 4]);
270 assert_eq!(icon.data, vec![4, 1, 2, 3]);
271 }
272
273 #[test]
274 fn underscores_stay_visible_in_menu_labels() {
275 assert_eq!(menu_label("Do_not_disturb"), "Do__not__disturb");
276 }
277 }
@@ -0,0 +1,277 @@
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;
12
13/// The window and desktop entry id (`rusty-teams.desktop`).
14const DESKTOP_ID: &str = "rusty-teams";
15
16const TRAY_ICON_SIZES: [u32; 3] = [22, 32, 64];
17const DOT_COLOR: [u8; 4] = [0xef, 0x44, 0x44, 0xff];
18
19#[derive(Clone)]
20struct Labels {
21 open: String,
22 mute_sound: String,
23 do_not_disturb: String,
24 notifications: String,
25 quit: String,
26}
27
28impl Labels {
29 fn current() -> Labels {
30 let tr = crate::ui_locale::tr;
31 Labels {
32 open: tr("tray.open"),
33 mute_sound: tr("tray.mute_sound"),
34 do_not_disturb: tr("tray.do_not_disturb"),
35 notifications: tr("tray.notifications"),
36 quit: tr("tray.quit"),
37 }
38 }
39}
40
41struct Item {
42 commands: Sender<TrayCommand>,
43 labels: Labels,
44 sound_on: bool,
45 do_not_disturb: bool,
46 mention: bool,
47 plain: Vec<Icon>,
48 dotted: Vec<Icon>,
49}
50
51impl Item {
52 fn send(&self, command: TrayCommand) {
53 let _ = self.commands.send(command);
54 }
55}
56
57/// Escapes the mnemonic underscores of a menu label.
58fn menu_label(text: &str) -> String {
59 text.replace('_', "__")
60}
61
62impl ksni::Tray for Item {
63 fn id(&self) -> String {
64 DESKTOP_ID.to_owned()
65 }
66
67 fn title(&self) -> String {
68 crate::APP_NAME.to_owned()
69 }
70
71 fn category(&self) -> Category {
72 Category::Communications
73 }
74
75 fn icon_pixmap(&self) -> Vec<Icon> {
76 if self.mention {
77 self.dotted.clone()
78 } else {
79 self.plain.clone()
80 }
81 }
82
83 fn tool_tip(&self) -> ToolTip {
84 ToolTip {
85 title: crate::APP_NAME.to_owned(),
86 ..Default::default()
87 }
88 }
89
90 fn activate(&mut self, _x: i32, _y: i32) {
91 self.send(TrayCommand::Toggle);
92 }
93
94 fn menu(&self) -> Vec<MenuItem<Self>> {
95 vec![
96 StandardItem {
97 label: menu_label(&self.labels.open),
98 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Open)),
99 ..Default::default()
100 }
101 .into(),
102 MenuItem::Separator,
103 CheckmarkItem {
104 label: menu_label(&self.labels.mute_sound),
105 checked: !self.sound_on,
106 activate: Box::new(|item: &mut Self| item.send(TrayCommand::ToggleSound)),
107 ..Default::default()
108 }
109 .into(),
110 CheckmarkItem {
111 label: menu_label(&self.labels.do_not_disturb),
112 checked: self.do_not_disturb,
113 activate: Box::new(|item: &mut Self| item.send(TrayCommand::ToggleDoNotDisturb)),
114 ..Default::default()
115 }
116 .into(),
117 StandardItem {
118 label: menu_label(&self.labels.notifications),
119 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Settings)),
120 ..Default::default()
121 }
122 .into(),
123 MenuItem::Separator,
124 StandardItem {
125 label: menu_label(&self.labels.quit),
126 icon_name: "application-exit".into(),
127 activate: Box::new(|item: &mut Self| item.send(TrayCommand::Quit)),
128 ..Default::default()
129 }
130 .into(),
131 ]
132 }
133}
134
135pub struct Tray {
136 handle: Handle<Item>,
137 commands: Mutex<Receiver<TrayCommand>>,
138}
139
140impl Tray {
141 /// `None` when there is no session bus or no tray host (no StatusNotifierWatcher).
142 pub fn new(sound_on: bool, do_not_disturb: bool, icon_png: &[u8]) -> Option<Self> {
143 let (plain, dotted) = tray_icons(icon_png)?;
144 let (sender, receiver) = channel();
145 let item = Item {
146 commands: sender,
147 labels: Labels::current(),
148 sound_on,
149 do_not_disturb,
150 mention: false,
151 plain,
152 dotted,
153 };
154 let handle = match item.spawn() {
155 Ok(handle) => handle,
156 Err(error) => {
157 log::warn!("no tray icon: {error}");
158 return None;
159 }
160 };
161 Some(Tray {
162 handle,
163 commands: Mutex::new(receiver),
164 })
165 }
166
167 pub fn relocalize(&self) {
168 let labels = Labels::current();
169 self.handle.update(move |item| item.labels = labels);
170 }
171
172 pub fn poll(&self) -> Vec<TrayCommand> {
173 let Ok(receiver) = self.commands.lock() else {
174 return Vec::new();
175 };
176 receiver.try_iter().collect()
177 }
178
179 pub fn set_app_icon(&mut self, icon_png: &[u8], mention: bool) {
180 let Some((plain, dotted)) = tray_icons(icon_png) else {
181 return;
182 };
183 self.handle.update(move |item| {
184 item.plain = plain;
185 item.dotted = dotted;
186 item.mention = mention;
187 });
188 }
189
190 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
191 let labels = Labels::current();
192 self.handle.update(move |item| {
193 item.labels = labels;
194 item.sound_on = sound_on;
195 item.do_not_disturb = do_not_disturb;
196 item.mention = mention;
197 });
198 }
199}
200
201impl Drop for Tray {
202 fn drop(&mut self) {
203 let _ = self.handle.shutdown();
204 }
205}
206
207/// The icon in every tray size, plain and with the unread dot, as ARGB32 big endian.
208fn tray_icons(icon_png: &[u8]) -> Option<(Vec<Icon>, Vec<Icon>)> {
209 let decoded = image::load_from_memory(icon_png).ok()?;
210 let mut plain = Vec::new();
211 let mut dotted = Vec::new();
212 for size in TRAY_ICON_SIZES {
213 let resized = decoded
214 .resize_exact(size, size, image::imageops::FilterType::Lanczos3)
215 .to_rgba8();
216 let mut with_dot = resized.clone();
217 let radius = size as f32 * 0.22;
218 let center = size as f32 - radius - 0.5;
219 for (column, row, pixel) in with_dot.enumerate_pixels_mut() {
220 let distance = ((column as f32 + 0.5 - center).powi(2)
221 + (row as f32 + 0.5 - center).powi(2))
222 .sqrt();
223 if distance <= radius {
224 *pixel = image::Rgba(DOT_COLOR);
225 }
226 }
227 plain.push(argb_icon(size, resized.as_raw()));
228 dotted.push(argb_icon(size, with_dot.as_raw()));
229 }
230 Some((plain, dotted))
231}
232
233fn argb_icon(size: u32, rgba: &[u8]) -> Icon {
234 let data = rgba
235 .chunks_exact(4)
236 .flat_map(|pixel| [pixel[3], pixel[0], pixel[1], pixel[2]])
237 .collect();
238 Icon {
239 width: size as i32,
240 height: size as i32,
241 data,
242 }
243}
244
245#[cfg(test)]
246mod tests {
247 use super::*;
248
249 #[test]
250 fn icons_come_in_every_size_as_argb() {
251 let png = crate::appearance::AppIcon::RustyTeams.png();
252 let (plain, dotted) = tray_icons(png).unwrap();
253 assert_eq!(plain.len(), TRAY_ICON_SIZES.len());
254 for (icon, size) in plain.iter().zip(TRAY_ICON_SIZES) {
255 assert_eq!((icon.width, icon.height), (size as i32, size as i32));
256 assert_eq!(icon.data.len(), (size * size * 4) as usize);
257 }
258 let last = dotted.last().unwrap();
259 let bottom_right = last.data.len() - 4 * (last.width as usize * 12 + 12);
260 assert_eq!(
261 &last.data[bottom_right..bottom_right + 4],
262 &[0xff, 0xef, 0x44, 0x44]
263 );
264 assert!(tray_icons(b"not a png").is_none());
265 }
266
267 #[test]
268 fn argb_moves_alpha_first() {
269 let icon = argb_icon(1, &[1, 2, 3, 4]);
270 assert_eq!(icon.data, vec![4, 1, 2, 3]);
271 }
272
273 #[test]
274 fn underscores_stay_visible_in_menu_labels() {
275 assert_eq!(menu_label("Do_not_disturb"), "Do__not__disturb");
276 }
277}
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-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
@@ -169,6 +169,11 @@ fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
169 169 }
170 170
171 171 impl CallWindows {
172 /// Points at a main window reopened from the tray.
173 pub fn attach_main_window(&mut self, window: &Window) {
174 self.main_native = platform::native_handle(window);
175 }
176
172 177 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
173 178 let saved_position = |key: &str, cx: &App| {
174 179 app.read(cx)
@@ -169,6 +169,11 @@ fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
169}
169}
170
170
171impl CallWindows {
171impl CallWindows {
172 /// Points at a main window reopened from the tray.
173 pub fn attach_main_window(&mut self, window: &Window) {
174 self.main_native = platform::native_handle(window);
175 }
176
172 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
177 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
173 let saved_position = |key: &str, cx: &App| {
178 let saved_position = |key: &str, cx: &App| {
174 app.read(cx)
179 app.read(cx)
crates/app/src/main.rs +46 −21
@@ -14,6 +14,7 @@ mod inline_video;
14 14 mod layout_guard;
15 15 #[cfg(any(target_os = "linux", target_os = "macos"))]
16 16 mod linux_browser;
17 mod main_window;
17 18 pub mod notify;
18 19 mod settings;
19 20 mod views;
@@ -154,6 +155,18 @@ fn transport(
154 155 ))
155 156 }
156 157
158 fn main_window_options(cx: &App) -> WindowOptions {
159 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
160 let mut options = TitleBar::window_options();
161 options.window_bounds = Some(WindowBounds::Windowed(bounds));
162 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
163 options.app_id = Some(LINUX_APP_ID.to_owned());
164 if let Some(titlebar) = options.titlebar.as_mut() {
165 titlebar.title = Some(APP_NAME.into());
166 }
167 options
168 }
169
157 170 const STORE_OPEN_ATTEMPTS: u32 = 20;
158 171 const STORE_OPEN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
159 172
@@ -305,28 +318,40 @@ fn main() {
305 318 .detach();
306 319 }
307 320
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 })
321 // The main window decides when to quit (see `main_window`): closing it into
322 // the tray leaves the app running without windows.
323 cx.set_quit_mode(QuitMode::Explicit);
324 // The command line only applies to the first window, not to one reopened from the tray.
325 let first_open = std::cell::Cell::new(Some((
326 arguments.open_target,
327 Startup {
328 switcher_query: arguments.switcher_query,
329 composer_text: arguments.composer_text,
330 reply_to_last: arguments.reply_to_last,
331 launched_by_autostart: arguments.autostart,
332 },
333 )));
334 main_window::install(
335 move |cx| {
336 let (open_target, startup) = first_open.take().unwrap_or_default();
337 let state = state.clone();
338 let opened =
339 gpui_kit::open_window(main_window_options(cx), cx, move |window, cx| {
340 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
341 });
342 match opened {
343 Ok((handle, _)) => Some(handle.into()),
344 Err(error) => {
345 log::error!("failed to open the main window: {error}");
346 None
347 }
348 }
349 },
350 cx,
351 )
326 352 .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 {
353 cx.on_window_closed(|cx, closed| {
354 if main_window::note_closed(closed, cx) {
330 355 cx.quit();
331 356 }
332 357 })
@@ -14,6 +14,7 @@ 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;
17mod main_window;
17pub mod notify;
18pub mod notify;
18mod settings;
19mod settings;
19mod views;
20mod views;
@@ -154,6 +155,18 @@ fn transport(
154 ))
155 ))
155}
156}
156
157
158fn main_window_options(cx: &App) -> WindowOptions {
159 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
160 let mut options = TitleBar::window_options();
161 options.window_bounds = Some(WindowBounds::Windowed(bounds));
162 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
163 options.app_id = Some(LINUX_APP_ID.to_owned());
164 if let Some(titlebar) = options.titlebar.as_mut() {
165 titlebar.title = Some(APP_NAME.into());
166 }
167 options
168}
169
157const STORE_OPEN_ATTEMPTS: u32 = 20;
170const STORE_OPEN_ATTEMPTS: u32 = 20;
158const STORE_OPEN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
171const STORE_OPEN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
159
172
@@ -305,28 +318,40 @@ fn main() {
305 .detach();
318 .detach();
306 }
319 }
307
320
308 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
321 // The main window decides when to quit (see `main_window`): closing it into
309 let mut options = TitleBar::window_options();
322 // the tray leaves the app running without windows.
310 options.window_bounds = Some(WindowBounds::Windowed(bounds));
323 cx.set_quit_mode(QuitMode::Explicit);
311 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
324 // 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());
325 let first_open = std::cell::Cell::new(Some((
313 if let Some(titlebar) = options.titlebar.as_mut() {
326 arguments.open_target,
314 titlebar.title = Some(APP_NAME.into());
327 Startup {
315 }
328 switcher_query: arguments.switcher_query,
316 let open_target = arguments.open_target;
329 composer_text: arguments.composer_text,
317 let startup = Startup {
330 reply_to_last: arguments.reply_to_last,
318 switcher_query: arguments.switcher_query,
331 launched_by_autostart: arguments.autostart,
319 composer_text: arguments.composer_text,
332 },
320 reply_to_last: arguments.reply_to_last,
333 )));
321 launched_by_autostart: arguments.autostart,
334 main_window::install(
322 };
335 move |cx| {
323 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
336 let (open_target, startup) = first_open.take().unwrap_or_default();
324 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
337 let state = state.clone();
325 })
338 let opened =
339 gpui_kit::open_window(main_window_options(cx), cx, move |window, cx| {
340 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
341 });
342 match opened {
343 Ok((handle, _)) => Some(handle.into()),
344 Err(error) => {
345 log::error!("failed to open the main window: {error}");
346 None
347 }
348 }
349 },
350 cx,
351 )
326 .expect("failed to open window");
352 .expect("failed to open window");
327 let main_window_id = main_window.window_id();
353 cx.on_window_closed(|cx, closed| {
328 cx.on_window_closed(move |cx, closed| {
354 if main_window::note_closed(closed, cx) {
329 if closed == main_window_id {
330 cx.quit();
355 cx.quit();
331 }
356 }
332 })
357 })
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 +31 −3
@@ -315,20 +315,40 @@ impl NotificationCenter {
315 315 cx.notify();
316 316 }
317 317
318 pub fn start_in_background(&self, window: &mut Window) {
318 /// Points at a main window reopened from the tray.
319 pub fn attach_main_window(&mut self, window: &mut Window) {
320 self.main_window = window.window_handle();
321 self.main_native = platform::native_handle(window);
322 platform::set_window_icon(window, self.app_icon.png());
323 }
324
325 pub fn start_in_background(&self, window: &mut Window, cx: &mut App) {
319 326 match (&self.tray, self.main_native) {
320 327 (Some(_), Some(native)) => platform::hide_window(native),
328 #[cfg(target_os = "linux")]
329 (Some(_), None) => crate::main_window::hide(cx),
321 330 _ => window.minimize_window(),
322 331 }
332 let _ = cx;
323 333 }
324 334
325 pub fn intercept_close(&self, _cx: &App) -> bool {
335 /// True when the close is handled here (window hidden natively). On Linux the
336 /// window closes for real and the app stays in the tray.
337 pub fn intercept_close(&self, cx: &mut App) -> bool {
326 338 match (self.settings.close_to_tray, &self.tray, self.main_native) {
327 339 (true, Some(_), Some(native)) => {
328 340 platform::hide_window(native);
329 341 true
330 342 }
331 _ => false,
343 #[cfg(target_os = "linux")]
344 (true, Some(_), None) => {
345 crate::main_window::mark_hiding(cx);
346 false
347 }
348 _ => {
349 let _ = cx;
350 false
351 }
332 352 }
333 353 }
334 354
@@ -1174,6 +1194,9 @@ impl NotificationCenter {
1174 1194 if self.main_window_active(cx) {
1175 1195 if let Some(native) = self.main_native {
1176 1196 platform::hide_window(native);
1197 } else {
1198 #[cfg(target_os = "linux")]
1199 crate::main_window::hide(cx);
1177 1200 }
1178 1201 } else {
1179 1202 self.raise_main_window(cx);
@@ -1187,6 +1210,11 @@ impl NotificationCenter {
1187 1210 }
1188 1211
1189 1212 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
1213 #[cfg(target_os = "linux")]
1214 if crate::main_window::is_hidden(cx) {
1215 crate::main_window::show(cx);
1216 return;
1217 }
1190 1218 if let Some(native) = self.main_native {
1191 1219 platform::restore_and_raise(native);
1192 1220 }
@@ -315,20 +315,40 @@ impl NotificationCenter {
315 cx.notify();
315 cx.notify();
316 }
316 }
317
317
318 pub fn start_in_background(&self, window: &mut Window) {
318 /// Points at a main window reopened from the tray.
319 pub fn attach_main_window(&mut self, window: &mut Window) {
320 self.main_window = window.window_handle();
321 self.main_native = platform::native_handle(window);
322 platform::set_window_icon(window, self.app_icon.png());
323 }
324
325 pub fn start_in_background(&self, window: &mut Window, cx: &mut App) {
319 match (&self.tray, self.main_native) {
326 match (&self.tray, self.main_native) {
320 (Some(_), Some(native)) => platform::hide_window(native),
327 (Some(_), Some(native)) => platform::hide_window(native),
328 #[cfg(target_os = "linux")]
329 (Some(_), None) => crate::main_window::hide(cx),
321 _ => window.minimize_window(),
330 _ => window.minimize_window(),
322 }
331 }
332 let _ = cx;
323 }
333 }
324
334
325 pub fn intercept_close(&self, _cx: &App) -> bool {
335 /// True when the close is handled here (window hidden natively). On Linux the
336 /// window closes for real and the app stays in the tray.
337 pub fn intercept_close(&self, cx: &mut App) -> bool {
326 match (self.settings.close_to_tray, &self.tray, self.main_native) {
338 match (self.settings.close_to_tray, &self.tray, self.main_native) {
327 (true, Some(_), Some(native)) => {
339 (true, Some(_), Some(native)) => {
328 platform::hide_window(native);
340 platform::hide_window(native);
329 true
341 true
330 }
342 }
331 _ => false,
343 #[cfg(target_os = "linux")]
344 (true, Some(_), None) => {
345 crate::main_window::mark_hiding(cx);
346 false
347 }
348 _ => {
349 let _ = cx;
350 false
351 }
332 }
352 }
333 }
353 }
334
354
@@ -1174,6 +1194,9 @@ impl NotificationCenter {
1174 if self.main_window_active(cx) {
1194 if self.main_window_active(cx) {
1175 if let Some(native) = self.main_native {
1195 if let Some(native) = self.main_native {
1176 platform::hide_window(native);
1196 platform::hide_window(native);
1197 } else {
1198 #[cfg(target_os = "linux")]
1199 crate::main_window::hide(cx);
1177 }
1200 }
1178 } else {
1201 } else {
1179 self.raise_main_window(cx);
1202 self.raise_main_window(cx);
@@ -1187,6 +1210,11 @@ impl NotificationCenter {
1187 }
1210 }
1188
1211
1189 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
1212 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
1213 #[cfg(target_os = "linux")]
1214 if crate::main_window::is_hidden(cx) {
1215 crate::main_window::show(cx);
1216 return;
1217 }
1190 if let Some(native) = self.main_native {
1218 if let Some(native) = self.main_native {
1191 platform::restore_and_raise(native);
1219 platform::restore_and_raise(native);
1192 }
1220 }
crates/app/src/views/shell.rs +59 −13
@@ -166,6 +166,16 @@ 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
169 179 pub struct AppShell {
170 180 state: Entity<AppState>,
171 181 rail: Entity<RailView>,
@@ -240,9 +250,20 @@ impl AppShell {
240 250 window: &mut Window,
241 251 cx: &mut Context<Self>,
242 252 ) -> 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));
253 let kept = cx.try_global::<KeptParts>().cloned();
254 let reopened = kept.is_some();
255 let activity = match &kept {
256 Some(kept) => {
257 kept.activity
258 .update(cx, |activity, _| activity.attach_main_window(window));
259 kept.activity.clone()
260 }
261 None => {
262 let call_media = cx.new(|_| CallMedia);
263 state.update(cx, |state, _| state.call_media = Some(call_media.clone()));
264 cx.new(|cx| ActivityCenter::new(state.clone(), window, cx))
265 }
266 };
246 267 let activity_panel = cx.new(|cx| ActivityPanel::new(state.clone(), activity.clone(), cx));
247 268 let quick_pane = cx.new(|cx| QuickViewPane::new(state.clone(), activity.clone(), cx));
248 269 let manage_team_page = cx.new(|cx| ManageTeamPage::new(state.clone(), window, cx));
@@ -361,9 +382,29 @@ impl AppShell {
361 382 });
362 383 let focus_handle = cx.focus_handle();
363 384 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));
385 // The tray, notifications and calls outlive a main window closed into the tray.
386 let (notifications, call_windows) = match kept {
387 Some(kept) => {
388 kept.notifications.update(cx, |notifications, _| {
389 notifications.attach_main_window(window)
390 });
391 kept.call_windows.update(cx, |call_windows, _| {
392 call_windows.attach_main_window(window)
393 });
394 (kept.notifications, kept.call_windows)
395 }
396 None => {
397 let notifications = cx
398 .new(|cx| NotificationCenter::new(state.clone(), activity.clone(), window, cx));
399 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
400 cx.set_global(KeptParts {
401 activity: activity.clone(),
402 notifications: notifications.clone(),
403 call_windows: call_windows.clone(),
404 });
405 (notifications, call_windows)
406 }
407 };
367 408 let user_input = cx.global::<UserInputHandle>().0.clone();
368 409 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
369 410 this.user_input.touch();
@@ -385,7 +426,9 @@ impl AppShell {
385 426 }
386 427 });
387 428 let closing = notifications.clone();
388 window.on_window_should_close(cx, move |_, cx| !closing.read(cx).intercept_close(cx));
429 window.on_window_should_close(cx, move |_, cx| {
430 !closing.update(cx, |notifications, cx| notifications.intercept_close(cx))
431 });
389 432 let mut shell = AppShell {
390 433 state,
391 434 rail,
@@ -434,14 +477,17 @@ impl AppShell {
434 477 reply_to_last,
435 478 launched_by_autostart,
436 479 } = startup;
437 if shell
438 .notifications
439 .read(cx)
440 .startup()
441 .starts_hidden(launched_by_autostart)
480 if !reopened
481 && shell
482 .notifications
483 .read(cx)
484 .startup()
485 .starts_hidden(launched_by_autostart)
442 486 {
443 487 cx.defer_in(window, |this, window, cx| {
444 this.notifications.read(cx).start_in_background(window)
488 this.notifications.update(cx, |notifications, cx| {
489 notifications.start_in_background(window, cx)
490 })
445 491 });
446 492 }
447 493 if let Some(query) = switcher_query {
@@ -166,6 +166,16 @@ 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
169pub struct AppShell {
179pub struct AppShell {
170 state: Entity<AppState>,
180 state: Entity<AppState>,
171 rail: Entity<RailView>,
181 rail: Entity<RailView>,
@@ -240,9 +250,20 @@ impl AppShell {
240 window: &mut Window,
250 window: &mut Window,
241 cx: &mut Context<Self>,
251 cx: &mut Context<Self>,
242 ) -> Self {
252 ) -> Self {
243 let call_media = cx.new(|_| CallMedia);
253 let kept = cx.try_global::<KeptParts>().cloned();
244 state.update(cx, |state, _| state.call_media = Some(call_media.clone()));
254 let reopened = kept.is_some();
245 let activity = cx.new(|cx| ActivityCenter::new(state.clone(), window, cx));
255 let activity = match &kept {
256 Some(kept) => {
257 kept.activity
258 .update(cx, |activity, _| activity.attach_main_window(window));
259 kept.activity.clone()
260 }
261 None => {
262 let call_media = cx.new(|_| CallMedia);
263 state.update(cx, |state, _| state.call_media = Some(call_media.clone()));
264 cx.new(|cx| ActivityCenter::new(state.clone(), window, cx))
265 }
266 };
246 let activity_panel = cx.new(|cx| ActivityPanel::new(state.clone(), activity.clone(), cx));
267 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));
268 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));
269 let manage_team_page = cx.new(|cx| ManageTeamPage::new(state.clone(), window, cx));
@@ -361,9 +382,29 @@ impl AppShell {
361 });
382 });
362 let focus_handle = cx.focus_handle();
383 let focus_handle = cx.focus_handle();
363 window.focus(&focus_handle, cx);
384 window.focus(&focus_handle, cx);
364 let notifications =
385 // 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));
386 let (notifications, call_windows) = match kept {
366 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
387 Some(kept) => {
388 kept.notifications.update(cx, |notifications, _| {
389 notifications.attach_main_window(window)
390 });
391 kept.call_windows.update(cx, |call_windows, _| {
392 call_windows.attach_main_window(window)
393 });
394 (kept.notifications, kept.call_windows)
395 }
396 None => {
397 let notifications = cx
398 .new(|cx| NotificationCenter::new(state.clone(), activity.clone(), window, cx));
399 let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
400 cx.set_global(KeptParts {
401 activity: activity.clone(),
402 notifications: notifications.clone(),
403 call_windows: call_windows.clone(),
404 });
405 (notifications, call_windows)
406 }
407 };
367 let user_input = cx.global::<UserInputHandle>().0.clone();
408 let user_input = cx.global::<UserInputHandle>().0.clone();
368 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
409 let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
369 this.user_input.touch();
410 this.user_input.touch();
@@ -385,7 +426,9 @@ impl AppShell {
385 }
426 }
386 });
427 });
387 let closing = notifications.clone();
428 let closing = notifications.clone();
388 window.on_window_should_close(cx, move |_, cx| !closing.read(cx).intercept_close(cx));
429 window.on_window_should_close(cx, move |_, cx| {
430 !closing.update(cx, |notifications, cx| notifications.intercept_close(cx))
431 });
389 let mut shell = AppShell {
432 let mut shell = AppShell {
390 state,
433 state,
391 rail,
434 rail,
@@ -434,14 +477,17 @@ impl AppShell {
434 reply_to_last,
477 reply_to_last,
435 launched_by_autostart,
478 launched_by_autostart,
436 } = startup;
479 } = startup;
437 if shell
480 if !reopened
438 .notifications
481 && shell
439 .read(cx)
482 .notifications
440 .startup()
483 .read(cx)
441 .starts_hidden(launched_by_autostart)
484 .startup()
485 .starts_hidden(launched_by_autostart)
442 {
486 {
443 cx.defer_in(window, |this, window, cx| {
487 cx.defer_in(window, |this, window, cx| {
444 this.notifications.read(cx).start_in_background(window)
488 this.notifications.update(cx, |notifications, cx| {
489 notifications.start_in_background(window, cx)
490 })
445 });
491 });
446 }
492 }
447 if let Some(query) = switcher_query {
493 if let Some(query) = switcher_query {
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/README.md +2 −1
@@ -27,5 +27,6 @@ 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 |
30 31
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`.
32 Records `0001` to `0010` are the decisions already shipped. `0011` stays `proposed` until the calendar-peek pull request merges, `0012` until the Linux tray pull request merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
@@ -27,5 +27,6 @@ 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 |
30
31
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`.
32Records `0001` to `0010` are the decisions already shipped. `0011` stays `proposed` until the calendar-peek pull request merges, `0012` until the Linux tray pull request merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.